Is there a way to make os.killpg not kill the script that calls it?
python, subprocess
Solution
A bit late to answer, but since google took me here while looking for a related problem: the reason your script gets killed is because its children will, by default, inherit its group id. But you can tell `subprocess.Popen` to create a new process group for your subprocess. Though it's a bit tricky: you have to pass in `os.setpgrp` for the `preexec_fn` parameter. This will call setpgrp (without any arguments) in the newly created (forked) process (before that does the exec) which will set the `gid` of the new process to the `pid` of the new process (thus creating a new group). The documentation mentions that it can deadlock in multi-threaded code. As an alternative, you can use `start_new_session=True`, but that would create not only a new process group but a new session. (And that would mean that if you close your terminal session while your script is running, the children would not be terminated. It may or may not be a problem.)
As a side note, if you are on windows, you can simply pass `subprocess.CREATE_NEW_PROCESS_GROUP` in the `creationflag` parameter.
Here is what it looks like in detail:
subOut = subprocess.Popen(['your', 'subprocess', ...], preexec_fn=os.setpgrp)
# when it's time to kill
os.killpg(os.getpgid(subOut.pid), signal.SIGTERM)
Problem
I have a subprocess which I open, which calls other processes. I use `os.killpg(os.getpgid(subOut.pid), signal.SIGTERM)` to kill the entire group, but this kills the python script as well. Even when I call a python script with `os.killpg` from a second python script, this kills the second script as well. Is there a way to make `os.killpg` not stop the script? Another solution would be to individually kill every child 1process. However, even using ``` p = psutil.Process(subOut.pid) child_pid = p.children(recursive=True) for pid in child_pid: os.kill(pid.pid, signal.SIGTERM) ``` does not correctly give me all the pids of the children. And you know what they say... don't kill the script that calls you...