Kill Process Tree docs should provide hint about os.killpg
Summary
- OS: Linux
- Type: doc
Description
The https://psutil.readthedocs.io/en/latest/index.html#kill-process-tree docs should provide a hint that there is a simpler way to kill a subprocess tree that is often good enough and does not require psutil, namely creating a built-in subprocess.Popen object with process_group=0 and then using the built-in os.killpg().
Less experienced Python users at several firms I've worked at are finding incomplete advice on the internet (such as the top answer on https://stackoverflow.com/questions/6549669/how-to-kill-process-and-child-processes-from-python), then taking a dependency on psutil and (if they're at least a little more thorough) copy/pasting the kill_proc_tree() implementation out of the psutil docs (rather than the worse code on Stackoverflow), when instead they should just be using os.killpg().
I can submit a PR with a small docs update if you agree.
Thanks for the great work on psutil.
Mmmm I'm not sure killpg would have the same effect. Doesn't it require to pre-emptively use setpgid first? The solution shown in the doc is supposed to work for any PID (not only os.getpid()) and be cross-platform (e.g. Windows has no killpg).
Here is a demonstration of what I described in the issue description: https://github.com/ctcjab/killpg-demo
The solution shown in the doc is supposed to work for any PID (not only os.getpid()) and be cross-platform (e.g. Windows has no killpg).
Right, what I'm proposing in this issue is for https://psutil.readthedocs.io/en/latest/index.html#kill-process-tree to actually say what you just said, and that for the special case where you're running on Unix, then this can be accomplished using the standard library as shown above.
Every time I've encountered code that uses psutil's kill_proc_tree() recipe, it didn't need to because it was actually this special case, which is very common (likely more common?), but developers just didn't realize this due to not finding docs that explained this. Figured I'd try to do something to help by opening this issue.
One more advantage of the killpg approach over the psutil kill_process_tree() recipe is that it still cleans up all the descendent processes even if an intermediate one has exited while some of its descendants are still running.
This limitation is documented in psutil here, but it's easy to miss that when looking at the current https://psutil.readthedocs.io/en/latest/index.html#kill-process-tree docs.
How would you modify it? No need to make a PR just yet. You can write it here.