How to process SIGTERM signal gracefully?

前端 未结 7 556
刺人心
刺人心 2020-11-22 16:02

Let\'s assume we have such a trivial daemon written in python:

def mainloop():
    while True:
        # 1. do
        # 2. some
        # 3. important
              


        
相关标签:
7条回答
  • 2020-11-22 16:48

    A class based clean to use solution:

    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 not killer.kill_now:
        time.sleep(1)
        print("doing something in a loop ...")
    
      print("End of the program. I was killed gracefully :)")
    
    0 讨论(0)
提交回复
热议问题