簡體   English   中英

如何殺死 subprocess.Popen() 進程產生的子進程?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM