我正在尝试检测python脚本中的系统关闭,在该脚本中我需要正常停止线程 它只会在我杀死-15 pid时捕获它,但是当我执行shutdown -P或shutdown -r时它不会捕获信号
import time
import threading
import signal
class Job(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.shutdown_flag = threading.Event()
def run(self):
while not self.shutdown_flag.is_set():
time.sleep(0.5)
f = open('threads.log', 'a')
f.write('%s Thread #%s stopped\n' % self.ident)
f.close()
class ServiceExit(Exception):
pass
def service_shutdown(signum, frame):
print('Caught signal %d' % signum)
raise ServiceExit
def main():
signal.signal(signal.SIGTERM, service_shutdown)
signal.signal(signal.SIGINT, service_shutdown)
try:
j1 = Job()
j2 = Job()
j1.start()
j2.start()
while True:
time.sleep(0.5)
except ServiceExit:
j1.shutdown_flag.set()
j2.shutdown_flag.set()
j1.join()
j2.join()
print('Exiting main program')
答案 0 :(得分:0)
不是它没有捕获信号,而是那个时候没有发送信号。您必须配置systemd才能为您的程序做到这一点。