简体   繁体   English

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

[英]Killing children of children in python with subprocess

Does python provide a way to find the children of a child process spawned using subprocess, so that I can kill them properly? python是否提供一种方法来查找使用子进程生成的子进程的子进程,以便我可以正确地杀死它们? If not, what is a good way of ensuring that the children of a child are killed? 如果不是,那么确保孩子的孩子被杀的好方法是什么?

The following applies to Unix only: 以下内容仅适用于Unix:

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 . 在子进程中调用os.setsid()将使其成为新会话的会话负责人和新流程组的流程负责人。 Sending a SIGTERM to the process group will send a SIGTERM to all the subprocess that this child process might have spawned. 将SIGTERM发送到进程组会将SIGTERM发送到该子进程可能已产生的所有子进程。

You could do this using subprocess.Popen(..., preexec_fn=os.setsid) . 您可以使用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. 运行此命令将不显示任何输出,但是ps ax将显示该子ls -laR ,并且其产生的ls -laR被终止。

But if you comment out 但是如果你注释掉

preexec_fn=os.setsid

then ps ax will show something like 然后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 and the shell that spawned it are still running. 因此,如果没有os.setsidls -laR和产生它的shell仍在运行。 Be sure to kill them: 确保杀死它们:

% kill 5409
% kill 5410

并不是很容易,但是如果您的应用程序在Linux上运行,则可以遍历/ proc文件系统并构建其PPID(父PID)与子进程相同的所有PID的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM