Tho*_*ers 30
当您将负 PID 传递给kill它时,它实际上通过该(绝对)数字将信号发送到进程组.你os.killpg()在Python中做了相同的事情.
jun*_*hew 26
如果父进程不是"进程组"但您想要使用子进程终止它,则可以使用psutil(https://pythonhosted.org/psutil/#processes).os.killpg无法识别非进程组的pid.
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()
Run Code Online (Sandbox Code Playgroud)
如果您的进程不是进程组并且您不想使用psutil,则另一种解决方案是运行此shell命令:
pkill -TERM -P 12345
Run Code Online (Sandbox Code Playgroud)
比如说
os.system('pkill -TERM -P {pid}'.format(pid=12345))
Run Code Online (Sandbox Code Playgroud)