c - 使用mmap从服务器接收文件

标签 c sockets networking mmap

假设我正在使用读取和发送系统调用将文件从服务器发送到客户端。 现在,我想使用 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/

相关文章:

networking - 从 Windows 主机连接到 WSL2 上的服务器不起作用

macos - OSX 每个应用程序通过 nettop 的网络吞吐量

c - 以 printf 作为参数的 for 循环

python - 将 C 代码中的字符串发送到 Flask

java - 在java中调用close()方法后操作系统需要多长时间才能关闭套接字?

sockets - select() 使用如此多的 CPU 能力有什么问题?

c - 如何使用 memset 设置填充数组

c - 如何使用功能停止golang gRPC服务器?

c - 当我用数组初始化指针时会发生什么?

python - 将 tun0(TUN 接口(interface))与 Scrapy 一起使用