我在Linux机器上运行一个python脚本,该脚本使用subprocess.check_output()创建一个子进程,如下所示:
subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)
问题是,即使父进程死亡,子进程仍在运行。父母去世后,我还有什么办法可以杀死子进程?
您的问题是使用subprocess.check_output-是正确的,您无法使用该接口获取子PID。改用Popen:
subprocess.check_output
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
为确保您在出口处杀死孩子:
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)