1

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?

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • I'm a bit confused by the question. Did your code create a number of threads or did it create a number of processes.? Note: a number of threads would be much easier to work with since the code could create a 'thread pool'. If you meant the codfe created a number of processes, then the socket used to communicate with the client would be a meaningless number in another process – user3629249 Jan 22 '19 at 16:27

1 Answers1

1

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.

Nominal Animal
  • 38,216
  • 5
  • 59
  • 86