![](/img/trans.png)
[英]Kill Terminal/tcpdump spawned by subprocess.Popen (Python)
[英]How can I kill child processes spawned by the subprocess.Popen() process?
我使用subprocess.Popen
来生成一个新的子进程 - 在这种情况下是git clone
。
问题是git clone
本身会产生子Popen.kill()
,当我尝试使用Popen.kill()
杀死它们时,只有父Popen.kill()
( git clone
) 被杀死,而不是它的子Popen.kill()
。
一个孩子的例子是:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.