Python -如何在提前退出时重启子进程?



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

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

我怎么能找到任何终止的进程并重新启动它们,没有任何阻塞?

其他参考文献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()
)

最新更新