I am writing a crossplatform, multiprocess and multithreaded server using the "pre forking model" and the C language. Depending on the mode (multiprocess or multithread), the server just started, creates a set of processes/threads whose task is to process the requests of clients that are accepted by the main server. Because child processes are created before accepting a socket, they obviously do not inherit the accepted socket. In win32 I solved, duplicating the socket. How can I do in C linux?
Use an Unix domain socket instead of a pipe for any control communication between the parent and the child. Unlike pipes, they are bidirectional. If you use a datagram socket, each send()
corresponds to one recv()
and vice versa (ie. message boundaries are retained), which makes passing structures and such easier.
The point is, you can pass descriptors between processes using an Unix domain socket. The cmsg man page has example code.
Essentially, before you fork the child processes, you create an Unix domain socket pair, unique for each child process, for control communication between the parent and the child. I recommend using an Unix domain datagram socket.
When the parent process wishes to hand off a connection to a child process, it sends the child a message, with an SCM_RIGHTS
ancillary message containing the connected socket descriptor. (The kernel will handle the details of copying the descriptor over; just note that the descriptor number may differ in the receiving process.)
This approach works not only in Linux, but in BSDs also.