首页 > 解决方案 > 如何避免python中的孤儿进程多处理和子进程?

问题描述

我的函数entry_function()首先使用ProcessPool(from pebble) 来同时处理多个任务。每个任务都包括调用外部 jar 文件subprocess.run()

不幸的是,外部 jar 不稳定;有时它会崩溃。如果任何外部 jar 崩溃,我想停止一切并entry_function()使用正确的退出代码退出。这是因为每次执行外部 jar 都需要很多时间,我想尽可能地节省时间。

问题是,当我调用future.cancel()ProcessPool 调用的进程时,它不会终止它们的子进程(即外部 jar)。结果,外部 jar 的进程成为孤儿进程。

这是我的代码的摘要:

import subprocess
from pebble import ProcessPool

def entry_function():
    with ProcessPool() as pool:
    future = pool.map(worker, iterables)

    try:
        for res in future.result():
        collected_res += res

    except subprocess.CalledProcessError as e:
        print("CalledProcessError: %s" % e.cmd)
        future.cancel()  # this terminates (and cancels) worker processes
        return None

    return collected_res

def worker(item):
    # prepare cmd
    p = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3600)  # this process is not killed and becomes an orphan process
    p.check_returncode()

    # do something with p.stdout
    return res

在这种情况下,如何避免为外部 jar 制作孤儿进程?

标签: pythonpython-3.xmultiprocessingsubprocess

解决方案


推荐阅读