用子进程杀死python中的子进程的子进程

发布于 2025-01-01 10:27:35 字数 78 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤寂小茶 2025-01-08 10:27:35

以下内容仅适用于 Unix:

在子进程将使其成为新会话的会话领导者和新进程的进程组领导者组。向进程组发送 SIGTERM 将会向该子进程可能生成的所有子进程发送 SIGTERM。

您可以使用 subprocess.Popen(..., preexec_fn=os.setsid) 来完成此操作。例如:

import signal
import os
import subprocess
import time
PIPE = subprocess.PIPE
proc = subprocess.Popen('ls -laR /', shell=True,
                        preexec_fn=os.setsid,
                        stdout=PIPE, stderr=PIPE)
time.sleep(2)
os.killpg(proc.pid, signal.SIGTERM)

运行此命令将不会显示任何输出,但 ps ax 将显示子进程,并且它生成的 ls -laR 已终止。

但如果你注释掉

preexec_fn=os.setsid

ps ax 将显示类似

% ps ax | grep "ls -la"
 5409 pts/3    S      0:00 /bin/sh -c ls -laR /
 5410 pts/3    R      0:05 ls -laR /

So without os.setsid, ls -laR 的内容,并且生成它的 shell 仍然是跑步。一定要杀死他们:

% kill 5409
% kill 5410

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:

import signal
import os
import subprocess
import time
PIPE = subprocess.PIPE
proc = subprocess.Popen('ls -laR /', shell=True,
                        preexec_fn=os.setsid,
                        stdout=PIPE, stderr=PIPE)
time.sleep(2)
os.killpg(proc.pid, signal.SIGTERM)

Running this will show no output, but ps ax will show the subprocess and the ls -laR that it spawns are terminated.

But if you comment out

preexec_fn=os.setsid

then ps ax will show something like

% ps ax | grep "ls -la"
 5409 pts/3    S      0:00 /bin/sh -c ls -laR /
 5410 pts/3    R      0:05 ls -laR /

So without os.setsid, ls -laR and the shell that spawned it are still running. Be sure to kill them:

% kill 5409
% kill 5410
半夏半凉 2025-01-08 10:27:35

这并不容易,但如果您的应用程序在 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'.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文