假设我正在使用读取和发送系统调用将文件从服务器发送到客户端。 现在,我想使用 mmap 系统调用在客户端接收数据。我该怎么做?
给出以下 send_file 函数(服务器端): (sd是与客户端关联的套接字描述符)
int send_file (int sd, const char* file_name) {
int fd;
char buf[1024];
if ( (fd =get_fd(file_name)) > 0) {
while (read(fd, buf, sizeof buf) > 0) {
if (send(sd, buf, sizeof buf, 0) < 0) {
perror("send");
return -1;
}
}
close(fd);
return 0;
}
return -1;
}
同样,我想在客户端创建文件,然后使用 MMAP 存储来自服务器的文件。 我怎么做?希望得到一些建议。
提前致谢
最佳答案
您无法使用mmap
从套接字接收文件。 mmap
用于将文件(或匿名内存)映射到进程虚拟地址空间。引用手册页
mmap() creates a new mapping in the virtual address space of the calling process.
所以你必须使用“套接字调用”来在客户端接收文件。
不确定为什么要这样做,这是一种使用 mmap 在客户端写入文件的方法。首先,您必须使用fopen()
。然后,您可以使用 lseek 来“放大”文件:
The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subse‐ quent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.
最后你可以映射它并复制通过网络接收到的内容。
关于c - 使用mmap从服务器接收文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22478322/