how to kill process and child processes from python?
Another solution if your process is not a process group and you don't want to use psutil, is to run this shell command:
pkill -TERM -P 12345
For instance with
os.system('pkill -TERM -P {pid}'.format(pid=12345))
If the parent process is not a "process group" but you want to kill it with the children, you can use psutil (https://psutil.readthedocs.io/en/latest/#processes). os.killpg cannot identify pid of a non-process-group.
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()
When you pass a negative PID to kill
, it actually sends the signal to the process group by that (absolute) number. You do the equivalent with os.killpg()
in Python.