【问题标题】:How to kill a python child process created with subprocess.check_output() when the parent dies?当父进程死亡时,如何杀死使用 subprocess.check_output() 创建的 python 子进程?
【发布时间】:2013-10-27 04:13:03
【问题描述】:

我正在一台 linux 机器上运行一个 python 脚本,它使用 subprocess.check_output() 创建一个子进程,如下所示:

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

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

【问题讨论】:

标签: python linux subprocess


【解决方案1】:

从 Python 3.2 开始,有一种非常简单的方法可以做到这一点:

from subprocess import Popen

with Popen(["sleep", "60"]) as process:
    print(f"Just launched server with PID {process.pid}")

我认为这对于大多数用例来说都是最好的,因为它简单且可移植,并且避免了对全局状态的任何依赖。

如果此解决方案不够强大,那么我建议您查看有关此问题或 Python: how to kill child process(es) when parent dies? 的其他答案和讨论,因为有很多巧妙的方法可以解决提供不同权衡的问题围绕便携性、弹性和简单性。 ?

【讨论】:

    【解决方案2】:

    是的,您可以通过两种方法实现这一点。它们都要求您使用Popen 而不是check_output。第一种是比较简单的方法,使用try..finally,如下:

    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))
    

    【讨论】:

    • 如果需要命令的输出,可以使用p.stdout.read()p.stdout.readlines()
    • 第一个方法刚刚启动并且立即杀死子进程,你应该在Popen()调用之后添加p.communicate()/p.wait()The 2nd method works only on Linux
    • @JF,你是对的,从我的例子中并不清楚程序的代码应该在finally 语句之前,适当缩进try.. 我认为它是现在更清楚了。无论如何,从问题中不清楚父母如何在孩子之前死去(除非被杀),所以我不能假设实际的命令是ls,或者应该等待孩子(可能是某种服务器?)。至于您的第二条评论,问题表明系统是 linux。
    【解决方案3】:

    您的问题在于使用 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)
    

    【讨论】:

    • 好吧,我没有意识到communication()实际上是在等待子进程完成。只需要一个返回输出和错误的 fct 并等待子进程完成,并在父进程死亡时杀死子进程。
    • 如果父进程崩溃,则不能保证会调用atexit 处理程序。顺便说一句,如果你有 proc 对象;您可以直接调用proc.kill()(无需先提取pid)
    • @J.F. Sebastian:如果父级崩溃,那么任何机制都可能不会被调用,除非它是由第三方完成的(然后可能会崩溃)。必须承认我忘了proc.kill() - 好点。
    • @cdarke:见prctl()-based solution(第三方是内核)。
    • 现在可以将其用作装饰器(它看起来很奇怪,因为 cmets 中没有格式):@atexit.register def kill_child(): ..
    【解决方案4】:

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

    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.kill http://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid http://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill

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

    重写 check_output:

    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
    

    然后随心所欲地使用它,也许将活动执行存储在一个临时变量中,并在退出时用信号或其他拦截主循环错误/关闭的方式终止它们。

    最后,您仍然需要在主应用程序中捕获终止以安全地杀死任何孩子,解决此问题的最佳方法是使用 try &amp; exceptsignal

    【讨论】:

      【解决方案5】:

      您可以手动执行此操作:

      ps aux | grep &lt;process name&gt;

      获取 PID(第二列)和

      kill -9 &lt;PID&gt; -9 是强制杀死它

      【讨论】:

      • 我希望能够通过获取子进程的 pid 或其他技巧以编程方式进行。另外,我什至不能手动杀死孩子,因为我没有它的 pid。
      • 它与上面评论中的链接相同 - 使用 Popen 您可以取回子进程的 pid,而我使用 check_output 时没有。
      • @Clara 你也可以使用Popen 获取输出,subprocess.Popen(...).communicate()[0]
      最近更新 更多