开发者

Fork before or after accepting connections?

开发者 https://www.devze.com 2022-12-07 23:46 出处:网络
The following snippet of code creates 4 processes, all sharing the same listening socket. Is there any danger in doing th开发者_开发知识库is?Should I always have one listening process and fork after

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

Is there any danger in doing th开发者_开发知识库is? 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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消