所以我有一个脚本,它使用 Subprocess 模块创建一个子进程。 然后,该子进程还会创建子进程,并且可以持续一段时间。有没有办法在不知道子进程的父进程链有多深的情况下杀死它的整个链?
我试过:
os.kill(os.getppid(), signal.SIGTERM)
但这只会杀死子进程的直接父进程。我想一直到达链的顶部并杀死向下的进程。
此代码将检索所提供的父进程的所有子进程。
children(recursive=True)
方法递归地获取所有子进程。然后信号被发送到所有子进程。
import os
import signal
import psutil
def kill_process_tree(pid, sig=signal.SIGTERM, include_parent=False):
parent = psutil.Process(pid)
children = parent.children(recursive=True)
if include_parent:
children.append(parent)
for process in children:
process.send_signal(sig)
# Get the current process ID
current_pid = os.getpid()
# Call the function to kill the process tree
kill_process_tree(current_pid)