【问题标题】:Python - How to restart a child process on early exit?Python - 如何在提前退出时重新启动子进程?
【发布时间】:2021-10-31 15:56:39
【问题描述】:

假设我有一个应用程序需要永远运行子进程,并且只会在出错时退出。 (假设流程被命名为 Q1 和 Q2)。

Q1 和 Q2 应该永远运行。但是,它们可能会因错误而终止。在这种情况下,主进程应该只重启被终止的进程。

如何查找任何已终止的进程并重新启动它们,而不会出现任何阻塞?

其他参考1

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: python concurrency multiprocessing python-multiprocessing


【解决方案1】:

你可以这样做:

from multiprocessing import Pool
from time import sleep

def foo():
    print("foo here")
    sleep(3)
    raise Exception

def bar():
    print("bar here")
    while True:
        sleep(5)
        print("'bar'-process still alive")

if __name__ == "__main__":
    restarts = foo, bar
    results = {func: None for func in restarts}
    with Pool(processes=2) as p:
        while True:
            for func in restarts:
                results[func] = p.apply_async(func)
                print(f"'{func.__name__}'-process (re)started")
            sleep(1)
            restarts = (
                func
                for func, result in results.items()
                if result.ready() and not result.successful()
            )

【讨论】:

  • 谢谢,这似乎完全符合我的需要。不过我有一个后续问题,第 25 行有一个func。我不明白它的用途,请你解释一下。
  • 重新实现代码后,我看到了它是如何使用的,并理解了我之前的问题。请忽略它。谢谢!
  • @adam 感谢您的反馈。 (我可能应该使用简单的循环而不是理解。)
猜你喜欢
  • 2014-04-06
  • 2013-08-05
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
相关资源
最近更新 更多