I'm using a third party library that starts various sub processes. When there's an exception I'd like to kill all the child processes. How can I get a list of child pids?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can't always log all the sub-processes as they are created, since they can in turn create new processes that you are not aware of. However, it's pretty simple to use psutil to find them:
import psutil
current_process = psutil.Process()
children = current_process.children(recursive=True)
for child in children:
print('Child pid is {}'.format(child.pid))
回答2:
It's usually safer to log the pids of all your child processes when you create them. There isn't a posix compliant way to list child PIDs. I know this can be done with the PS tool.
回答3:
Using psutil you can get all children process (even recursive process) look at https://psutil.readthedocs.io/en/latest/#psutil.Process.children