Fork before or after accepting connections?

后端 未结 1 2101
陌清茗
陌清茗 2021-02-15 01:27

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

相关标签:
1条回答
  • 2021-02-15 01:49

    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 讨论(0)
提交回复
热议问题