How can I pass a socket from parent to child processes

user1995143 picture user1995143 · Jan 20, 2013 · Viewed 9.6k times · Source

I'm stuck on a problem in a C program on Linux.

I know that when a processes is forked the child process inherits some things from the parent, including open file descriptors.

The problem is that I'm writing a multi-process server application with a master process that accepts new connections and puts the descriptors into shared memory.

When the child process attempts to read from one of these descriptors from the shared memory, on select() i got an EBADF error!

How can the child process read and use a socket (or any file descriptor in general) created by a parent process after it has been forked?

Answer

Robert S. Barnes picture Robert S. Barnes · Jan 20, 2013

When you call fork, the child process inherits copies of all open file descriptors. The typical way of doing this is for a parent process to open a listening socket, call accept which blocks until a connection arrives and then calls fork after receiving the connection. The parent then closes it's copy of the file descriptor, while the new child process can keep using the file descriptor and do any processing which is needed. Once the child is done it also closes the socket. It's important to remember two things: 1. The file descriptor / socket is a resource in the operating system and after the fork the parent and child each have a handle to that resource, which is kind of like a reference counted smart pointer. I explain this in more detail here. The second thing is that only file descriptors which are opened before calling fork are shared, because after forking parent and child are completely separate processes, even though they may share some resources like file descriptors which existed prior to the fork. If you're using a model where you want to have a parent handing out work to worker processes, it may be better for you to consider using threads, and a thread pool.

By the way, you can download allot of nice examples of servers and clients from Unix Network Programming website.