我使用的多道库产卵两个子进程。我想确保只要父进程还活着,如果子进程死了(接收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。 –