Is there a way for multiple processes to share a listening socket?

You can share a socket between two (or more) processes in Linux and even Windows.

Under Linux (Or POSIX type OS), using fork() will cause the forked child to have copies of all the parent’s file descriptors. Any that it does not close will continue to be shared, and (for example with a TCP listening socket) can be used to accept() new sockets for clients. This is how many servers, including Apache in most cases, work.

On Windows the same thing is basically true, except there is no fork() system call so the parent process will need to use CreateProcess or something to create a child process (which can of course use the same executable) and needs to pass it an inheritable handle.

Making a listening socket an inheritable handle is not a completely trivial activity but not too tricky either. DuplicateHandle() needs to be used to create a duplicate handle (still in the parent process however), which will have the inheritable flag set on it. Then you can give that handle in the STARTUPINFO structure to the child process in CreateProcess as a STDIN, OUT or ERR handle (assuming you didn’t want to use it for anything else).

EDIT:

Reading the MDSN library , it appears that WSADuplicateSocket is a more robust or correct mechanism of doing this; it is still nontrivial because the parent/child processes need to work out which handle needs to be duplicated by some IPC mechanism (although this could be as simple as a file in the filesystem)

CLARIFICATION:

In answer to the OP’s original question, no, multiple processes cannot bind(); just the original parent process would call bind(), listen() etc, the child processes would just process requests by accept(), send(), recv() etc.

Leave a Comment