Python中的子进程终止
问题描述:
我有一个Python脚本,它使用subprocess.Popen()启动另一个Python脚本的子进程。这个子进程使用Popen启动另一个子进程(另一个Python脚本)。 脚本A调用脚本B调用脚本C. 如果我使用os.kill()终止进程脚本B,它会终止运行脚本C的进程。 如果没有任何方法可以做到这一点。Python中的子进程终止
答
现在,如果脚本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))
也许这将是一个想法,这里使用'os.killpg',因为它会杀死所有的孩子们。 –