マルチプロセスライブラリを使用して2つの子プロセスを生成しています。私は、親プロセスが生存している限り、子プロセスが死んだ場合(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()
私はcounterProcessにSIGKILLを送信した場合、それが正しく再起動します。ただし、helloProcessにSIGKILLを送信すると、helloProcessではなくcounterProcessが再起動されます。
親プロセスにSIGTERMを送信すると、親プロセスは終了しますが、子プロセスは孤児になって処理を続行します。この動作を修正するにはどうすればよいですか?
'signal.SIGCHLD'ハンドラと' multiprocessing.Process'がうまく動作しない仕事に
Process.terminate
、そのデフォルト値にリセットする必要があります一緒に。 'signal.SIGCHLD'ハンドラでは、' Process.is_alive'は子プロセスが終了した後でも 'True'を返します。 –