假设我创建了一个 socketpair()
并将其中一个套接字的句柄传递给生成的进程 (popen
),进程能够与父进程通信吗?
我看到的示例是使用 fork()
应用的,这超出了我当前项目的范围。
更新:我尝试了一个简单的测试:
-
客户端:socketpair
与套接字[0]
-
从客户端使用 posix_spawn
和套接字1 作为命令行参数
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:
-
Client: socketpair
with sockets[0]
-
From Client use posix_spawn
with sockets1 as command-line argument
-
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.
发布评论
评论(2)
execve 的手册页指出:
由于像 popen 这样的函数是基于 execve 的,所以从 socketpair 函数获得的文件描述符应该在两个进程中都很好,而且我不明白为什么你不能以任何方式传递描述符方式让你高兴。我假设在这种情况下您的意思是将其转换为字符串并将其通过 STDIN 设置到子进程,这会将其转换回 int 以用作文件描述符。
为其编写一些试用代码当然是值得的。
The man page for execve states:
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.
是的,您可以将其传递给子进程。诀窍在于,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.