如何优雅地处理SIGTERM信号?

不中断当前的执行,而是在一个单独的线程中处理signal,以便mainloop()有机会优雅地停止?

import signal
import time

class GracefulKiller:
  kill_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self,signum, frame):
    self.kill_now = True

if __name__ == '__main__':
  killer = GracefulKiller()
  while True:
    time.sleep(1)
    print("doing something in a loop ...")
    if killer.kill_now:
      break

  print "End of the program. I was killed gracefully :)"

 

posted @ 2019-03-25 11:09  twoseee  阅读(1515)  评论(0编辑  收藏  举报