Unix 上不使用文件系统的 0 副本进程间通信
如果我必须在两个进程之间移动适量的内存,我可以执行以下操作:
- 创建一个文件,用于将
- ftruncate 写入所需大小的
- mmap 并取消链接它
- 根据需要使用
当另一个进程需要该数据时,它:
- 连接到第一个进程通过 unix 套接字,
- 第一个进程通过 unix 套接字消息发送文件的 fd
- fd
- mmap根据需要使用
这允许我们在进程之间移动内存而无需任何副本 - 但创建的文件必须位于内存安装的文件系统上,否则我们可能会得到一张磁盘命中,这会降低性能。有没有一种方法可以在不使用文件系统的情况下执行类似的操作?一个类似 malloc 的函数返回一个 fd 和一个指针就可以做到这一点。
[编辑] 拥有文件描述符还提供了由内核维护的引用计数机制。
If I have to move a moderate amount of memory between two processes, I can do the following:
- create a file for writing
- ftruncate to desired size
- mmap and unlink it
- use as desired
When another process requires that data, it:
- connects to the first process through a unix socket
- the first process sends the fd of the file through a unix socket message
- mmap the fd
- use as desired
This allows us to move memory between processes without any copy - but the file created must be on a memory-mounted filesystem, otherwise we might get a disk hit, which would degrade performance. Is there a way to do something like that without using a filesystem? A malloc-like function that returned a fd along with a pointer would do it.
[Edit] Having a file descriptor provides also a reference count mechanism that is maintained by the kernel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
System V 或 POSIX 共享内存(这有点不同,但最终得到相同的结果)?对于任何这样的系统,您都必须担心进程访问内存时的协调问题,内存映射文件也是如此。
Is there anything wrong with System V or POSIX shared memory (which are somewhat different, but end up with the same result)? With any such system, you have to worry about coordination between the processes as they access the memory, but that is true with memory-mapped files too.