我正在使用Popen
启动子进程,我希望它能完成退出。但是,这个过程不仅没有退出,而且向它发送sigkill仍然让它活着!下面是一个演示:
from subprocess import Popen
import os
import time
import signal
command = ["python","--version"]
process = Popen(command)
pid = process.pid
time.sleep(5) #ample time to finish
print pid
print "Sending sigkill"
os.kill(pid,signal.SIGKILL)
try:
#Kill with signal 0 just checks whether process exists
os.kill(pid,0)
print "Process still alive immediately after (not so bad...)!"
except Exception as e:
print "Succeeded in terminating child quickly!"
time.sleep(20) #Give it ample time to die
#Kill with signal 0 just checks whether process exists
try:
os.kill(pid,0)
print "Process still alive! That's bad!"
except Exception as e:
print "Succeeded in terminating child!"
对我来说,打印:
77881
Python 2.7.10
Sending sigkill
Process still alive immediately after (not so bad...)!
Process still alive! That's bad!
这个脚本不仅可以验证孩子在完成后仍然活着,但是我可以在打印的进程ID上使用ps
并看到它仍然存在。奇怪的是,ps将进程名称列为(Python)
(注意括号)。
答案 0 :(得分:3)
您需要拨打process.wait()
或使用signal.signal(signal.SIGCHLD, signal.SIG_IGN)
一次表示您不打算等待任何孩子。前者是便携式的;后者仅适用于Unix(但POSIX-standard)。如果你不做这些事情,那么在Unix上,这个过程就像僵尸一样,以及Windows has a similar behavior if you keep the process handle open。