我使用的多道庫產卵兩個子進程。我想確保只要父進程還活着,如果子進程死了(接收SIGKILL或SIGTERM),它們就會自動重啓。另一方面,如果父進程收到一個SIGTERM/SIGINT,我希望它終止所有的子進程然後退出。Python的多 - 捕捉信號重新啓動子進程或關閉父進程
這是我走近這個問題:
import sys
import time
from signal import signal, SIGINT, SIGTERM, SIGQUIT, SIGCHLD, SIG_IGN
from functools import partial
import multiprocessing
import setproctitle
class HelloWorld(multiprocessing.Process):
def __init__(self):
super(HelloWorld, self).__init__()
# ignore, let parent handle it
signal(SIGTERM, SIG_IGN)
def run(self):
setproctitle.setproctitle("helloProcess")
while True:
print "Hello World"
time.sleep(1)
class Counter(multiprocessing.Process):
def __init__(self):
super(Counter, self).__init__()
self.counter = 1
# ignore, let parent handle it
signal(SIGTERM, SIG_IGN)
def run(self):
setproctitle.setproctitle("counterProcess")
while True:
print self.counter
time.sleep(1)
self.counter += 1
def signal_handler(helloProcess, counterProcess, signum, frame):
print multiprocessing.active_children()
print "helloProcess: ", helloProcess
print "counterProcess: ", counterProcess
if signum == 17:
print "helloProcess: ", helloProcess.is_alive()
if not helloProcess.is_alive():
print "Restarting helloProcess"
helloProcess = HelloWorld()
helloProcess.start()
print "counterProcess: ", counterProcess.is_alive()
if not counterProcess.is_alive():
print "Restarting counterProcess"
counterProcess = Counter()
counterProcess.start()
else:
if helloProcess.is_alive():
print "Stopping helloProcess"
helloProcess.terminate()
if counterProcess.is_alive():
print "Stopping counterProcess"
counterProcess.terminate()
sys.exit(0)
if __name__ == '__main__':
helloProcess = HelloWorld()
helloProcess.start()
counterProcess = Counter()
counterProcess.start()
for signame in [SIGINT, SIGTERM, SIGQUIT, SIGCHLD]:
signal(signame, partial(signal_handler, helloProcess, counterProcess))
multiprocessing.active_children()
如果我發送SIGKILL到counterProcess,它會正常重新啓動。但是,向helloProcess發送SIGKILL也會重新啓動counterProcess而不是helloProcess?
如果我發送一個SIGTERM父進程,父將退出,但子進程成爲孤兒和繼續。我如何糾正這種行爲?
'signal.SIGCHLD'處理器和'multiprocessing.Process'不能很好地工作一起。在'signal.SIGCHLD'處理程序中,即使在子結束之後,Process.is_alive也返回True。 –