python中的子进程终止

时间:2016-10-20 23:44:33

标签: python subprocess

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

1 个答案:

答案 0 :(得分:2)

目前,如果脚本A使用B杀死os.kill,则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))