Python中的子进程终止

3

我有一个Python脚本,使用subprocess.Popen()启动另一个Python脚本的子进程。这个子进程又使用Popen来启动另一个子进程(另一个Python脚本)。 脚本A调用脚本B,脚本B调用脚本C。 如果我使用os.kill()杀死脚本B的进程,会终止运行脚本C的进程吗? 如果不是的话,有什么方法可以实现?

1个回答

2
目前来看,如果脚本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会是一个好主意,因为它会杀死所有子进程。 - J. P. Petersen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接