【问题标题】:Subprocess termination in pythonpython中的子进程终止
【发布时间】:2016-10-20 23:44:33
【问题描述】:

我有一个 Python 脚本,它使用 subprocess.Popen() 启动另一个 Python 脚本的子进程。这个子进程使用 Popen 启动另一个子进程(另一个 Python 脚本)。 脚本 A 调用脚本 B,脚本 B 调用脚本 C。 如果我使用 os.kill() 杀死进程脚本 B,它将终止运行脚本 C 的进程。 如果没有,有没有办法做到这一点。

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    就目前而言,如果脚本A 使用os.kill 杀死B,那么C 本身不会被杀死。

    为了确保这一点,脚本B 可以在退出时负责杀死C

    # this is in script B
    import functools, atexit
    
    def kill_children(*pids):
        import os, signal
    
        for pid in pids or []:
            os.kill(pid, signal.SIGTERM)
    
    # we start a process for C
    c_pid = ...
    
    # kill C when we we exit
    atexit.register(functools.partial(kill_children, c_pid)) 
    

    【讨论】:

    • 也许在这里使用os.killpg 是个好主意,因为它会杀死所有的孩子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2018-03-11
    • 1970-01-01
    • 2011-01-21
    • 2012-09-19
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多