使用监听套接字分叉 [英] Forking with a listening socket

查看:47
本文介绍了使用监听套接字分叉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我尝试在套接字上使用 accept() 的方式的正确性.

I'd like to make sure about the correctness of the way I try to use accept() on a socket.

我知道在 Linux 中,在套接字上 listen() 是安全的,fork() N 个孩子,然后 recv()所有这些数据包都没有来自用户端的任何同步(数据包在子级之间或多或少地实现负载平衡).但那是 UDP.

I know that in Linux it's safe to listen() on a socket, fork() N children and then recv() the packets in all of them without any synchronisation from the user side (the packets get more or less load-balanced between the children). But that's UDP.

TCP 和 listen()fork()accept() 是否具有相同的属性?我是否可以假设可以接受父创建的共享套接字,即使其他孩子也这样做?POSIX、BSD 套接字或任何其他标准是否在某处对其进行了定义?

Does the same property hold for TCP and listen(), fork(), accept()? Can I just assume that it's ok to accept on a shared socket created by the parent, even when other children do the same? Is POSIX, BSD sockets or any other standard defining it somewhere?

推荐答案

如果在子进程中 fork() 然后 accept() 只有一个子进程会在连接上调用 accept() 然后处理它.这是预分叉,连接不会在孩子之间共享.

If you fork() and then accept() in your children only one child process is going to call accept() on a connection and then process it. This is pre-forking and the connections won't be shared among the children.

您可以通过颠倒顺序并接受和分叉来执行每个连接方案的标准一个孩子.然而,这两种技术都是为了效率、平衡等,而不是为了共享特定的连接.

You can do a standard one child per connection scheme by reversing the order and accepting and forking. However both of these techniques are for efficiency, balancing, etc., not for sharing a particular connection.

TCP 与 UDP 不同.在 TCP 中这样做是不可取的,因为你几乎肯定会以一团糟结束.给定的接收消息可以分布在一个或多个数据包上,多个进程协调比让一个子进程处理连接更痛苦.

TCP is different from UDP. It would be inadvisable to do that in TCP as you will almost certainly end up with a mess. A given received message can be spread over one or more packets and it would be more of a pain for multiple process to coordinate than would be to have one child handle the connection.

这篇关于使用监听套接字分叉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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