Tôi đang sử dụng thư viện đa xử lý để sinh ra hai tiến trình con. Tôi muốn đảm bảo rằng miễn là quá trình cha mẹ còn sống, nếu quá trình con chết (nhận được SIGKILL hoặc SIGTERM), chúng sẽ được khởi động lại tự động. Mặt khác, nếu tiến trình cha nhận được một SIGTERM/SIGINT, tôi muốn nó chấm dứt tất cả các tiến trình con rồi thoát ra.Đa xử lý Python - Chụp tín hiệu để khởi động lại quá trình con hoặc tắt quy trình cha
Đây là cách tôi tiếp cận vấn đề:
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()
Nếu tôi gửi một SIGKILL đến counterProcess, nó sẽ khởi động lại một cách chính xác. Tuy nhiên, việc gửi SIGKILL đến helloProcess cũng khởi động lại bộ đếm ngược thay vì helloProcess?
Nếu tôi gửi SIGTERM đến tiến trình cha mẹ, cha mẹ sẽ thoát, nhưng quá trình con trở thành trẻ mồ côi và tiếp tục. Tôi làm cách nào để khắc phục hành vi này?
'signal.SIGCHLD' handler và' multiprocessing.Process' không hoạt động tốt cùng với nhau. Trong trình xử lý 'signal.SIGCHLD',' Process.is_alive' trả về 'True' ngay cả sau khi con chấm dứt. –