How to properly handle and save system shutdown (and SIGTERM) to finish work in Python?

Basic need: I have a Python daemon that calls another program through os.system. My desire is to be able to handle the shutdown of the system or SIGTERM correctly so that the called program returns and then exits.

What I already tried: I tried the approach using the signal:

import signal, time def handler(signum = None, frame = None): print 'Signal handler called with signal', signum time.sleep(3) #here check if process is done print 'Wait done' signal.signal(signal.SIGTERM , handler) while True: time.sleep(6) 

Using time.sleep does not work, and the second print is never called.

I read a few words about atexit.register (handler) instead of signal.signal (signal.SIGTERM, handler), but nothing gets called when kill.

+6
source share
1 answer

Your code almost works, except that you forgot to exit after cleaning.

We often need to catch various other signals, such as INT, HUP and QUIT, but not so much with demons.

 import sys, signal, time def handler(signum = None, frame = None): print 'Signal handler called with signal', signum time.sleep(1) #here check if process is done print 'Wait done' sys.exit(0) for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]: signal.signal(sig, handler) while True: time.sleep(6) 

In many systems, conventional processes do not have much time to clean during shutdown. To be safe, you can write an init.d script to stop your daemon and wait for it.

+9
source

Source: https://habr.com/ru/post/904393/


All Articles