python - How to process SIGTERM signal gracefully? -


let's assume have such trivial daemon written in python:

def mainloop():     while true:         # 1.         # 2.         # 3. important         # 4. job         # 5. sleep  mainloop() 

and daemonize using start-stop-daemon default sends sigterm (term) signal on --stop.

let's suppose current step performed #2. , @ moment we're sending term signal.

what happens execution terminates immediately.

i've found can handle signal event using signal.signal(signal.sigterm, handler) thing still interrupts current execution , passes control handler.

so, question - possible not interrupt current execution handle term signal in separated thread (?) able set shutdown_flag = true mainloop() had chance stop gracefully?

a class based clean 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 true:     time.sleep(1)     print("doing in loop ...")     if killer.kill_now:       break    print "end of program. killed gracefully :)" 

Comments

Popular posts from this blog

design - Custom Styling Qt Quick Controls -

Unable to remove the www from url on https using .htaccess -