如何在Python中终止进程及其子进程?
比如在bash中:
kill -9 -PID
os.kill(pid, signal.SIGKILL)
这个命令只会结束父进程。
7 个回答
6
如果你的进程不是一个进程组,而且你不想使用 psutil这个库,另一种解决办法就是运行这个命令:
pkill -TERM -P 12345
比如说用
os.system('pkill -TERM -P {pid}'.format(pid=12345))
57
如果父进程不是一个“进程组”,但你想要连同它一起结束,可以使用 psutil 这个库(https://psutil.readthedocs.io/en/latest/#processes)。因为 os.killpg 这个方法无法识别不是进程组的进程 ID。
import psutil
parent_pid = 30437 # my example
parent = psutil.Process(parent_pid)
for child in parent.children(recursive=True): # or parent.children() for recursive=False
child.kill()
parent.kill()
39
当你给 kill
命令传递一个 负数 的进程ID(PID)时,它实际上是把信号发送给那个(绝对值)数字对应的进程 组。在Python中,你可以用 os.killpg()
来实现同样的效果。