AF_UNIX socket: can I pass socket handle between processes?
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 argumentClient:
write
to socket ... Client exits without any warning...
It would appear that there is a problem with this method.
UPDATED: I also found thi开发者_开发技巧s note:
Pipes and socketpairs are limited to communication between processes with a common ancestor.
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.
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.
精彩评论