在接受连接之前或之后分叉? [英] Fork before or after accepting connections?

查看:50
本文介绍了在接受连接之前或之后分叉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段创建了4个进程,所有进程都共享同一个侦听套接字.

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

推荐答案

您可以使用任何一种方法来实现.

You can do it either way.

您注意到,接受之后的派生是每个客户端/连接一个孩子.在接受之前(但在监听之后)进行分叉通常称为预分叉.每个子级都等待接受,无论哪个子级,传入的连接都会对其进行处理.只要接受是由内核完成的(我认为)任何现代 unix 都会这样做,这就是安全的.如果不是,则必须在接受周围放置某种IPC(互斥量等)锁.预分叉的优点是,您无需为每个连接花费分叉的费用,因为您已经有一个现有的池.

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.

这篇关于在接受连接之前或之后分叉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆