![](/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.