views:

232

answers:

1

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.)

+6  A: 

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.

Duck
I though it is thr kernel duty to perform accept a tcp connection behind the hood (aka tree way handle shake) in the TCP layer. I was sure no kind of IPC was needed here. Does someone on SO know a platorm where it is ?
yves Baumes
According to Stevens, BSD derived kernels always did it. Some older SysV systems implemented accept in a library and locking was required. It's doubtful anyone is running a production OS that old but I suppose you never know.
Duck