AF_UNIX套接字:我可以在进程之间传递套接字句柄吗?

发布于 2024-08-09 16:22:04 字数 737 浏览 6 评论 0 原文

假设我创建了一个 socketpair() 并将其中一个套接字的句柄传递给生成的进程 (popen),进程能够与父进程通信吗?

我看到的示例是使用 fork() 应用的,这超出了我当前项目的范围。

更新:我尝试了一个简单的测试:

  1. 客户端:socketpair与套接字[0]

  2. 从客户端使用 posix_spawn 和套接字1 作为命令行参数

  3. Client: write 到套接字 ... 客户端退出时没有任何警告...

看来此方法有问题。

更新:我还发现了这个注意

管道和套接字对仅限于具有共同祖先的进程之间的通信。

Let's say I create a socketpair() and I pass the handle of one of the socket to a spawned process (popen), will the said process be able to communicate back with the parent?

The examples I saw are applied using fork() which is out of scope for my current project.

Updated: I tried a simple test:

  1. Client: socketpair with sockets[0]

  2. From Client use posix_spawn with sockets1 as command-line argument

  3. Client: write to socket ... Client exits without any warning...

It would appear that there is a problem with this method.

UPDATED: I also found this note:

Pipes and socketpairs are limited to communication between processes with a common ancestor.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

和我恋爱吧 2024-08-16 16:22:04

execve 的手册页指出:

 File descriptors open in the calling process image remain open in the new
 process image, except for those for which the close-on-exec flag is set
 (see close(2) and fcntl(2)).  Descriptors that remain open are unaffected
 by execve().

由于像 popen 这样的函数是基于 execve 的,所以从 socketpair 函数获得的文件描述符应该在两个进程中都很好,而且我不明白为什么你不能以任何方式传递描述符方式让你高兴。我假设在这种情况下您的意思是将其转换为字符串并将其通过 STDIN 设置到子进程,这会将其转换回 int 以用作文件描述符。

为其编写一些试用代码当然是值得的。

The man page for execve states:

 File descriptors open in the calling process image remain open in the new
 process image, except for those for which the close-on-exec flag is set
 (see close(2) and fcntl(2)).  Descriptors that remain open are unaffected
 by execve().

Since functions like popen are based on execve, then the file descriptors that you got from your socketpair function should be good across both processes, and I don't see why you can't pass the descriptor in whatever manner pleases you. I'm assuming that in this case you mean to convert it to a string and set it over STDIN to the sub-process, which would convert it back to an int to use as a file descriptor.

It would certainly be worth writing some trial code for.

来日方长 2024-08-16 16:22:04

是的,您可以将其传递给子进程。诀窍在于,socketpair() 为您提供了一对连接的套接字 - 确保子级保留一个,父级保留另一个(父级应关闭子级,反之亦然)。

但大多数情况下使用一对管道。

Yes, you can pass it to the child process. The trick is really that socketpair() gives you a pair of connected sockets - make sure that the child keeps one and the parent keeps the other (the parent should close the child's and vice versa).

Most cases use a pair of pipes instead though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文