Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fork before or after accepting connections?

The following snippet of code creates 4 processes, all sharing the same listening socket.

Is there any danger in doing this? Should I always have one listening process and fork after connections are accepted, in the conventional manner?

for (p = 0; p < 3; p++) {
  pid = fork();
  if (pid == 0) break;
}
while (1) { 
  unsigned int clientlen = sizeof(echoclient);
  /* Wait for client connection */
  if ((clientsock = 
       accept(serversock, (struct sockaddr *) &echoclient,
              &clientlen)) < 0) { 
    die("Failed to accept client connection");
  } 
  fprintf(stdout, "Process No. %d - Client connected: %s\n",
                  p,
                  inet_ntoa(echoclient.sin_addr));
  handle_client(clientsock);
}

(I understand that forking after accepting allows a programme to make a process per connection. I'm playing around with proto-threads and various async stuff, so I'm just looking at having one process per core.)

like image 481
fadedbee Avatar asked Oct 14 '09 20:10

fadedbee


1 Answers

You can do it either way.

As you note, forking after the accept is one child per client/connection. Forking before the accept (but after the listen) is generally known as pre-forking. Each of the children wait on the accept and whatever child gets the incoming connection processes it. This is safe so long as the accept is done by the kernel which (I think) any modern unix does. If not, you have to put some kind of IPC (mutex, etc.) lock around the accept. The advantage to pre-forking is that you don't need to go through the expense of a fork for each connection, you already have an existing pool.

like image 128
Duck Avatar answered Sep 28 '22 04:09

Duck