简体   繁体   English

停止python子进程,留下死掉的“ python”进程

[英]Stop python sub-process leaving behind dead 'python' process

I am working on a python program which has to run a (possibly large) number of other python programs (for some load testing). 我正在开发一个python程序,该程序必须运行(可能是大量)其他python程序(用于某些负载测试)。 Some of these are short-lived and others keep going for longer. 其中一些是短暂的,而另一些则持续更长的时间。 I want the short-lived ones to terminate and disappear when they are done, but each one seems to leave behind a dead "(Python)" process until the original program finishes. 我希望短命的终止并在完成后消失,但是每个似乎都留下了一个死掉的“(Python)”进程,直到原始程序完成为止。

Platform is OSX, Python 2.7.6. 平台是OSX,Python 2.7.6。

Here are simple demo programs that show the issue: 这是显示问题的简单演示程序:

#!/usr/bin/env python
# Child Process: Started by parent...
import time
print "Hello from child!"
time.sleep(10)
print "Child finished."
exit(0)

And the parent program: 和父程序:

#!/usr/bin/env python
# Parent process:
import subprocess, time
print "Starting Child..."
child = subprocess.Popen( "./child.py" )
print "Parent Process... hanging around."
time.sleep(30)
exit(0)

I run the "parent" program from the terminal with "./parent.py". 我从终端使用“ ./parent.py”运行“父”程序。 Here's the output (as expected): 这是输出(按预期):

Starting Child...
Parent Process... hanging around.
Hello from child!
Child finished.

Initially the 'ps' command shows this: 最初,“ ps”命令显示以下内容:

'ps' command shows this: 'ps'命令显示如下:

782 ttys002    0:00.03 python ./parent.py
783 ttys002    0:00.02 python ./child.py

This makes sense... the parent has launched the child process. 这是有道理的...父级已启动子级进程。

After 10 seconds, the child finishes as expected, and 'ps' then shows: 10秒后,孩子完成预期的操作,然后“ ps”显示:

782 ttys002    0:00.03 python ./parent.py
783 ttys002    0:00.00 (Python)

'783' then hangs around until the parent process finishes, even though the python program has already done "exit(0)". 然后,即使python程序已经完成“ exit(0)”,“ 783”也会一直挂到父进程完成为止。

Is there any way to actually terminate / get rid of this process once it's done? 完成后,是否有任何方法可以实际终止/摆脱此过程? I'm thinking it might be an issue if I launch hundreds or even thousands of short-lived processes over a long time. 我认为如果长时间启动数百个甚至数千个短生命周期的进程可能会成为问题。

I've experimented with subprocess(), Popen (as shown), and also using fork() and then execl(), but they always end up with the same behaviour. 我已经尝试了subprocess(),Popen(如图所示),还使用了fork()然后是execl(),但是它们总是以相同的方式结束。

您应该在某个时候致电child.wait。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM