简体   繁体   中英

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? If not, what is a good way of ensuring that the children of a child are killed?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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