如何在父进程死亡时终止使用subprocess.check_output()创建的python子进程?

2024-04-27 09:42:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在linux机器上运行一个python脚本,它使用subprocess创建一个子进程

subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)

问题是,即使父进程死亡,子进程仍在运行。 当父进程死亡时,是否有任何方法可以杀死子进程?


Tags: 方法脚本机器output进程linuxcheckstderr
3条回答

是的,你可以通过两种方法来实现。两者都要求您使用Popen,而不是check_output。第一种是更简单的方法,使用try..最后,如下所示:

from contextlib import contextmanager

@contextmanager
def run_and_terminate_process(*args, **kwargs):
try:
    p = subprocess.Popen(*args, **kwargs)
    yield p        
finally:
    p.terminate() # send sigterm, or ...
    p.kill()      # send sigkill

def main():
    with run_and_terminate_process(args) as running_proc:
        # Your code here, such as running_proc.stdout.readline()

这将捕获sigint(键盘中断)和sigterm,但不会捕获sigkill(如果使用-9终止脚本)。

另一种方法比较复杂,使用ctypes的prctl PR_SET_PDEATHSIG。一旦父进程因任何原因退出(甚至sigkill),系统将向子进程发送一个信号。

import signal
import ctypes
libc = ctypes.CDLL("libc.so.6")
def set_pdeathsig(sig = signal.SIGTERM):
    def callable():
        return libc.prctl(1, sig)
    return callable
p = subprocess.Popen(args, preexec_fn = set_pdeathsig(signal.SIGTERM))

不知道具体细节,但最好的方法仍然是用信号捕捉错误(甚至可能是所有错误),并终止任何剩余的进程。

import signal
import sys
import subprocess
import os

def signal_handler(signal, frame):
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

a = subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)

while 1:
    pass # Press Ctrl-C (breaks the application and is catched by signal_handler()

这只是一个模型,你需要捕捉的不仅仅是SIGINT,但这个想法可能会让你开始,你还需要检查生成的进程。

http://docs.python.org/2/library/os.html#os.killhttp://docs.python.org/2/library/subprocess.html#subprocess.Popen.pidhttp://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill

我建议重写check_output的个性化版本,因为我刚刚意识到check_输出实际上只是为了简单的调试等,因为在执行过程中不能与它进行太多交互。。

重写检查输出:

from subprocess import Popen, PIPE, STDOUT
from time import sleep, time

def checkOutput(cmd):
    a = Popen('ls -l', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    print(a.pid)
    start = time()
    while a.poll() == None or time()-start <= 30: #30 sec grace period
        sleep(0.25)
    if a.poll() == None:
        print('Still running, killing')
        a.kill()
    else:
        print('exit code:',a.poll())
    output = a.stdout.read()
    a.stdout.close()
    a.stdin.close()
    return output

使用它做任何你想做的事情,也许将活动的执行存储在一个临时变量中,并在退出时用信号或其他方法隐藏主循环的错误/关闭来杀死它们。

最后,您仍然需要在主应用程序中捕获终止符,以便安全地杀死任何child,最好的方法是使用try & exceptsignal

您的问题是使用subprocess.check_output-您是正确的,您无法使用该接口获取子PID。改为使用Popen:

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)

相关问题 更多 >