python - 如何避免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 制作孤儿进程?
解决方案
推荐阅读
- c# - ASP.NET Core 依赖注入:在运行时传递参数
- javascript - How do I align th and td content of a table using Bootstrap 4?
- c++ - Running gcc 5.2 build on gcc 4.4.7 Red Hat 6.6
- mysql - MySQL 分组查询
- c# - c#,在子类中强制实现方法
- uitableview - 如何实现类似的过渡?
- makefile - makefile 定义中的逗号是什么意思?
- python - 如何忽略或修复 RuntimeWarning:编译时版本
- javascript - Start Drag On Click (Angular draggable droppable)
- android - Android读取webview html并将数据发送到java