在不同进程之间传递文件描述符的可移植方式
在大多数 UNIX 系统上,通过 fork() 可以轻松地在子进程/父进程之间传递打开的文件; 然而,我需要在孩子已经分叉“之后”分享一个 fd 。
我发现了一些 网页告诉我 sendmsg() 可能适用于任意进程; 但这似乎非常依赖操作系统并且很复杂。 portlisten 似乎是我能找到的最好的例子,但我更喜欢像 libevent 这样的好的包装库,它隐藏了 kqueue、池的所有魔力……
有谁知道是否有一些库(和可移植的方式)可以做到这一点?
On most UNIX systems passing an open file between processes can be easily done for child/parent processes by fork(); however I need to share a fd "after" the child was already forked.
I've found some webpages telling me that sendmsg() may work for arbitary processes; but that seems very OS dependent and complex. The portlisten seems like the best example I can find, but I'd prefer a good wrapper library like libevent that hides all the magic of kqueue, pool, ....
Does anyone know if there's some library (and portable way) to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的选择是尝试通过 Unix 域套接字发送文件描述符。 Stephens 和网络上的一些地方对此进行了描述,但如果您提出好意,我可以为您挖掘代码。
如今这将非常便携; 很多以前被认为是“不可移植”的东西(例如
mmap
!)现在已经非常普遍了。 如果您需要比“当今大多数系统”更具可移植性,那么您将面临很多有趣的问题,但如果您告诉我们更多有关您正在做什么以及您正在使用什么平台的信息,那么您可能会遇到很多有趣的问题(也许非 Unix POSIX 平台?)我们也许可以提供帮助。Your best bet is to try sending the file descriptor over a Unix domain socket. This is described in Stephens, and in a few places on the web, but I can dig up code for you if you ask nicely.
This will be pretty portable these days; a lot of the things considered "non-portable" way back when (such as
mmap
!) are extremely common now. If you need to be more portable than "most systems these days," you've got a lot of interesting issues ahead of you, but possibly if you tell us more about what you're doing and what platforms you're working on (perhaps non-Unix POSIX platforms?) we might be able to help out.有一种基于 Unix 域套接字的机制,用于使用
sendmsg()
系统调用在进程之间传输文件描述符(例如套接字 - 当然,它不能进行内存映射)。您可以在 Stevens(正如 Curt Sampson 提到的)中找到更多信息,也可以在维基百科。
您可以在 通过 Linux 套接字发送文件描述符< /a>.
There is a Unix domain socket-based mechanism for transferring file descriptors (such as sockets - which cannot be memory mapped, of course) between processes - using the
sendmsg()
system call.You can find more in Stevens (as mentioned by Curt Sampson), and also at Wikipedia.
You can find a much more recent question with working code at Sending file descriptor by Linux socket.