0

I'm new to working with forking and I am having a trouble understanding how to achieve what I want. I'll try to explain as best I can.

I have Process A which is a functional Berkeley socket server running on Linux.

I need Process A to load a program from the disk into a separate non-blocking process (Process B) in a background state. Then Process A needs to pass Process B control of Process A's sockets. Lastly Process A needs to end, leaving process B running.

I'm unclear on whats needed to pass the sockets to a new process if the old one ends, and the best way to create a non-blocking new process that allows the original process to end.

  • Is A getting the socket before or after it starts B? – Barmar Jan 04 '13 at 22:55
  • I'm curious if there's a way to share file handles between processes. But let me ask this: Have you considered combining the two programs and just use threads to shared data and socket handles between the two code paths? – selbie Jan 04 '13 at 23:00
  • Possible duplicate question of: http://stackoverflow.com/questions/909064/portable-way-to-pass-file-descriptor-between-different-processes – selbie Jan 04 '13 at 23:01

2 Answers2

3

There's nothing special you need to do. Just make sure the close on exec flag is cleared for any file descriptors you want process B to inherit and set for any file descriptors you don't want process B to inherit. Then call exec to replace process A with process B. Process B will start with all inheritable file descriptors intact.

Community
  • 1
  • 1
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • And how will B know which file descriptors to use? You need to pass this information separately. – Barmar Jan 04 '13 at 23:02
  • @Barmar: There are a few good ways. One is by prior agreement. For example, if it's only getting one TCP connection, it can be agreed that this will be file descriptor 3. You can use `dup2` to put it there before calling `exec`. (This is how standard in, out, and error work, right?) Another way is using command line arguments to B. – David Schwartz Jan 04 '13 at 23:38
  • I know, those are the "something special you need to do". I didn't have time to write an answer, I was trying to push you to improve your answer. – Barmar Jan 05 '13 at 04:14
  • This was the solution I ended up using. And I did have to pass the socket fds. I ended up writing them to a file, then passing an argument by execl to read back in a list of FD's. Turning off the close on exec flag turned out to be missing piece I needed to pass the sockets. – user1908813 Jan 06 '13 at 02:18
0

If you need to pass an open file (such as a socket) without using inheritance-through-fork, you use ioctl with I_SENDFD. Here is a very detailed description. (There is a corresponding mechanism for receiving it.) You can do this with a named pipe which connects the processes, or via a variation, with a Unix domain socket.

bmargulies
  • 97,814
  • 39
  • 186
  • 310