父母去世时如何杀死用subprocess.check_output()创建的python子进程? [英] How to kill a python child process created with subprocess.check_output() when the parent dies?
本文介绍了父母去世时如何杀死用subprocess.check_output()创建的python子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在linux机器上运行一个python脚本,该脚本使用subprocess.check_output()创建一个子进程,如下所示:
I am running on a linux machine a python script which creates a child process using subprocess.check_output() as it follows:
subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)
问题在于,即使父进程死亡,子进程仍在运行. 父母去世后,我还有什么办法可以杀死子进程?
The problem is that even if the parent process dies, the child is still running. Is there any way I can kill the child process as well when the parent dies?
推荐答案
您的问题出在使用subprocess.check_output
-您是正确的,无法使用该接口获取子PID.改用Popen:
Your problem is with using subprocess.check_output
- you are correct, you can't get the child PID using that interface. Use Popen instead:
proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE)
# Here you can get the PID
global child_pid
child_pid = proc.pid
# Now we can wait for the child to complete
(output, error) = proc.communicate()
if error:
print "error:", error
print "output:", output
为确保在出口处杀死孩子,
To make sure you kill the child on exit:
import os
import signal
def kill_child():
if child_pid is None:
pass
else:
os.kill(child_pid, signal.SIGTERM)
import atexit
atexit.register(kill_child)
这篇关于父母去世时如何杀死用subprocess.check_output()创建的python子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文