[英]exit and clean up python fork
i am trying to code socket server with fork in python. 我正在尝试用python中的fork对套接字服务器进行编码。 somehow a new fork will be created when a client is connected and this fork process will handle the connection including send/receive. 连接客户端时,将以某种方式创建新的派生,并且该派生过程将处理连接,包括发送/接收。
i ran this script on Linux centOS
and monitor resources with htop/top
to see how many forks (task) are shown. 我在Linux centOS
上运行了此脚本,并使用htop/top
监视资源以查看显示了多少个fork(任务)。 the problem is when i kill some fork by using os._exit(0)
htop won't be changed (naturally it has to be decreased by killing forks) and when i close python script every thing will be back to normal ( Ram usage and tasks ). 问题是当我使用os._exit(0)
杀死一些叉子时,htop不会被更改(自然必须通过杀死叉子来减少),而当我关闭python脚本时,所有事情都会恢复正常(Ram用法和任务 )。
so what i have to do that when i kill some fork by using os._exit(0)
, it effects on htop
in other hand releases all resources and do not wait until its own parent is killed ? 因此,当我使用os._exit(0)
杀死一些fork时,我该怎么做,另一方面,它对htop
影响会释放所有资源,而不是等到其父os._exit(0)
被杀死os._exit(0)
执行此操作?
here it's the code to create forks: 这是创建派生代码的代码:
def test(sock):
//handle socket then return
for i in range (1000):
sock,addr=socket.accept()
pid=os.fork()
if pid==0:
test(sock)
os._exit(0)
elif pid !=-1:
os.waitpid(-1, os.WNOHANG)
The parent process needs to wait for the child in order for the child process' resources to be released. 父进程需要等待子进程,以便释放子进程的资源。 Until then the process still exists in a "zombie" state, and it will still appear in ps
and top
etc. 在此之前,该进程仍然以“僵尸”状态存在,并且仍将以ps
和top
等形式出现。
You can call one of os.wait()
, os.waitpid()
, os.wait3()
, or os.wait4()
. 您可以调用os.wait()
, os.waitpid()
, os.wait3()
或os.wait4()
。
os.wait3()
with the os.WNOHANG
option might be most useful to you as it will wait for any child process and the parent will not block until a child terminates (or it's state changes - wait
will return child processes that have been stopped or restarted too). 带有os.WNOHANG
选项的os.wait3()
对您来说可能最有用,因为它将等待任何子进程,并且父进程不会阻塞,直到子进程终止(或者状态改变- wait
将返回已停止的子进程)或也重新启动)。
More details on the underlying system calls can be found in the Linux man page: man 2 wait
. 有关底层系统调用的更多详细信息,请参见Linux手册页: man 2 wait
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.