子进程变得不存在,`communic()`挂起

时间:2018-06-01 15:09:15

标签: python python-2.7 subprocess defunct

在Ubuntu 14.04的python 2.7中,我启动了一个这样的过程:

bag_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for i in range(5):
    print "Countdown: {}".format(5 - i - 1)
    time.sleep(1)
print "Sending SIGINT to PID {}".format(bag_process.pid)
bag_process.send_signal(signal.SIGINT)
(bag_out, bag_err) = bag_process.communicate()

程序挂在communicate()行。当我打开另一个终端时,我运行ps -ef | grep ###来查找子流程的pid,我看到了<defunct>

为什么子程序变得不存在,父程序挂在communicate()上?如果孩子在收到SIGINT后真正退出,我怎样才能使父程序可靠地处理而不挂?

1 个答案:

答案 0 :(得分:0)

问题是:不要杀死这样的进程:

bag_process.send_signal(signal.SIGINT)

相反,杀死进程及其所有子进程,如下所示:

parent = psutil.Process(bag_process.pid)
for child in parent.get_children(recursive=True):
    child.send_signal(signal.SIGINT)
bag_process.send_signal(signal.SIGINT)