Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top