用子进程杀死python中的子进程的子进程
python是否提供了一种方法来查找使用子进程生成的子进程的子进程,以便我可以正确地杀死它们?如果不是,有什么好办法可以确保孩子的孩子被杀害?
Does python provide a way to find the children of a child process spawned using subprocess, so that I can kill them properly? If not, what is a good way of ensuring that the children of a child are killed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下内容仅适用于 Unix:
在子进程将使其成为新会话的会话领导者和新进程的进程组领导者组。向进程组发送 SIGTERM 将会向该子进程可能生成的所有子进程发送 SIGTERM。
您可以使用 subprocess.Popen(..., preexec_fn=os.setsid) 来完成此操作。例如:
运行此命令将不会显示任何输出,但
ps ax
将显示子进程,并且它生成的ls -laR
已终止。但如果你注释掉
,
ps ax
将显示类似So without
os.setsid
,ls -laR
的内容,并且生成它的 shell 仍然是跑步。一定要杀死他们:The following applies to Unix only:
Calling os.setsid() in the child process will make it the session leader of a new session and the process group leader of a new process group. Sending a SIGTERM to the process group will send a SIGTERM to all the subprocess that this child process might have spawned.
You could do this using
subprocess.Popen(..., preexec_fn=os.setsid)
. For example:Running this will show no output, but
ps ax
will show the subprocess and thels -laR
that it spawns are terminated.But if you comment out
then
ps ax
will show something likeSo without
os.setsid
,ls -laR
and the shell that spawned it are still running. Be sure to kill them:这并不容易,但如果您的应用程序在 Linux 中运行,您可以遍历 /proc 文件系统并构建所有 PPID(父 PID)与您的子进程相同的 PID 列表。
Not exactly easy, but if your application runs in Linux, you could walk through the /proc filesystem and build a list of all PIDs whose PPID (parent PID) is the same as your subprocess'.