python - 如何杀死由 subprocess.Popen() 进程产生的子进程?
问题描述
我subprocess.Popen
用来产生一个新的子进程 - 在这种情况下git clone
。
问题是它git clone
本身会产生子进程,当我尝试Popen.kill()
仅使用父进程 ( git clone
) 杀死它们时,它会被杀死,而不是它的子进程。
一个孩子的例子是:
79191 /usr/lib/git-core/git fetch-pack --stateless-rpc --stdin --lock-pack --include-tag --thin --cloning --depth=1 https://example.com/scm/adoha/adoha_digit_interpretation.git/
我怎样才能杀死所有的进程 -git clone
及其子进程?
注意:我考虑过将这些进程放在他们自己的进程组中,但随后主进程也被杀死了。
# execute a child process using os.execvp()
p = subprocess.Popen(shlex.split(f'git clone --bare --depth=1 -v \'{url}\' \'{temp_dir}\''),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
ret_code = p.wait(timeout)
except subprocess.TimeoutExpired as exc:
p.kill()
shutil.rmtree(temp_dir)
raise common.exc.WatchdogException(f'Failed to clone repository: Timeout.'
f'\n{timeout=}\n{url=}') from exc
解决方案
您可以使用以下代码段终止进程及其子进程:
import psutil
def kill_process_and_children(pid: int, sig: int = 15):
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess as e:
# Maybe log something here
return
for child_process in proc.children(recursive=True):
child_process.send_signal(sig)
proc.send_signal(sig)
kill_process_and_children(p.pid)
推荐阅读
- google-cloud-platform - GCP Dataflow 未在 UI 中获取步骤日志。使用 python SDK
- asp.net-core - .net core Custom oauth2 login 和 Google login api 一起出现错误
- html - div-content 可见thought div-height = 0
- mysql - 如何编写我的 sql 查询来拆分列?
- c++ - 为什么从基类继承的成员函数未定义?
- css - 何时编译 SASS
- javascript - 具有较高角度的圆圈周围的项目
- android - Android中的密钥库问题
- java - 如何将我的项目转换回 IntelliJ 项目?
- java - JavaFX Ant 构建失败,JDK 10.0.2 Eclipse Photon