简体   繁体   English

在接受连接之前或之后分叉?

[英]Fork before or after accepting connections?

The following snippet of code creates 4 processes, all sharing the same listening socket. 以下代码片段创建了4个进程,所有进程共享相同的侦听套接字。

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.) (我知道接受后分叉允许一个程序为每个连接创建一个进程。我正在玩原型线程和各种异步的东西,所以我只想看每个核心有一个进程。)

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. 这是安全的,只要接受是由内核完成的(我认为)任何现代的unix都可以。 If not, you have to put some kind of IPC (mutex, etc.) lock around the accept. 如果没有,你必须在接受周围放置某种IPC(互斥等)。 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. 预分叉的优点是您不需要为每个连接花费一个分支,您已经有一个现有的池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM