父子在同一端口上侦听时会发生什么? [英] What happens when parent-child listen on the same port?

查看:113
本文介绍了父子在同一端口上侦听时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父级,当它启动时,它启动一个线程,该线程创建一个侦听端口X的TCP Server实例.此后,父级开始派生子进程(该进程不执行任何操作并退出).请注意,这些子进程从父进程继承fds,因此最终在端口X上侦听.

I have a parent which when it starts, kicks off a thread that creates an instance of TCP Server that listens on port X. After this, the parent starts forking off child processes (which do few things and exit). Note that these child processes inherit fds from parent and hence end up listening on port X.

父程序有一个处理程序,用于处理来自端口X的请求,但子进程没有这样的处理程序(它是os.execv()-ed C ++程序)

The parent program has a handler for requests coming in on port X but the child process has no such handler (it is a os.execv()-ed C++ program)

我知道子进程可以关闭所有fds,在这种情况下不会出现上述情况.端口X上的传入请求会如何处理?如何处理?

I know that child process could close all fds, in which case the above situation will not arise. What happens to a incoming request on port X? How is it processed?

这是我到目前为止观察到的... 父级中的tcp请求处理程序在收到请求时执行command.getstatusoutput(..).在大多数情况下,它的行为符合预期(或我预期的方式)-执行上述命令而没有任何错误...但偶尔我会得到

Here's what i have observed so far... The tcp request handler in the parents executes commands.getstatusoutput(..) when it receives a request. Most of the times, it behaves as expected (or the way i expected) - execution of the above command without any errors ...but occasionally i get

File "/home/y/lib/python2.7/commands.py", line 61, in getstatusoutput
    sts = pipe.close()
IOError: [Errno 10] No child processes

推荐答案

在操作系统级别上,这应该没有任何问题.本质上,这是预分支服务器的工作方式:

At the operating-system level, there shouldn't be any problem with this. This is essentially the way that pre-forked servers work:

  1. 在主线程中创建套接字
  2. 将套接字绑定到一个地址
  3. 调用listen()将套接字置于侦听模式-此时,操作系统将接受所有连接请求并将它们排入队列
  4. 分叉一堆孩子,每个孩子都继承开放的套接字
  5. 然后,子进程处理每个调用accept()的过程,该调用将阻塞,直到存在要处理的连接为止.

如果孩子选择不在侦听套接字上调用accept()(因为您的执行过程不会),那么该进程或仍在接受连接的进程就不会有任何问题

If a child chooses not to call accept() on the listening socket, (as your exec'ed proccess won't) then there shouldn't be any issues for that process, or for the ones who are still accepting connections.

我能看到的唯一麻烦是无法关闭套接字-为了使操作系统真正关闭套接字,所有引用该套接字的进程都必须对其调用close(),从而将其关闭打开描述符倒数到零.

The only complication that I can see is that the socket can't be closed -- in order for the operating system to actually close it, all processes with a reference to it have to call close() on it, bringing its open descriptor count down to zero.

在您的情况下,最好是,如果这种行为干扰了应用程序的其余部分,则在派生之后但在调用exec之前,关闭子级中的侦听套接字.

It is probably best, in your case, if that behaviour is interfering with the rest of your application, to close the listening socket in the child -- after you fork, but before you call exec.

这篇关于父子在同一端口上侦听时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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