views:

327

answers:

2

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 sockets[1] 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.

+2  A: 

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.

Joshua D. Boyd
`popen` will not close existing file descriptors, except: "The *popen()* function shall ensure that any streams from previous *popen()* calls that remain open in the parent process are closed in the new child process." http://www.opengroup.org/onlinepubs/009695399/functions/popen.html
ephemient
Just to clarify, please note that file descriptors that are opened *after* the child has been forked (and sent stringified to the child's STDIN) will not be open in the child. Only fds already open at the time the execve call is made will be open in the child as well, and usually such fds will be communicated to the child via command line arguments. I can see no reason to involve a pipe.
Inshallah
A: 

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.

MarkR
see updated section in question. I did that to no avail. I created the child process through `posix_spawn`: could that be the problem?
jldupont