2017-07-27 100 views
0

我正在啓動一個Popen的子過程,我期望它完成退出。然而,這個過程不僅不能退出,而且發送sigkill仍然會使它活着!下面是一個腳本演示:爲什麼Popen子進程不會死?

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! 

這不僅可以腳本驗證孩子還活着就應該已經完成​​之後,但我可以用ps在打印的進程ID上看到它仍然存在。奇怪的是,ps列出進程名稱爲(Python)(注意括號)。

+1

爲什麼不''process.terminate()'? – zwer

+2

這是一個殭屍程序。它不會消失,直到你調用['os.wait()'](https://docs.python.org/2/library/os.html#os.wait)。 – Kevin

+0

@凱文:是的,就是這樣!如果您將此作爲答案發布,我會選擇它。 – augray

回答