简体   繁体   中英

How to properly handle and retain system shutdown (and SIGTERM) in order to finish its job in Python?

Basic need : I've a Python daemon that's calling another program through os.system. My wish is to be able to properly to handle system shutdown or SIGTERM in order to let the called program return and then exiting.

What I've already tried: I've tried an approach using 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)

The usage of time.sleep doesn't seems to work and the second print is never called.

I've read few words about atexit.register(handler) instead of signal.signal(signal.SIGTERM, handler) but nothing is called on kill.

Your code does almost work, except you forgot to exit after cleaning up.

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

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)

On many systems, ordinary processes don't have much time to clean up during shutdown. To be safe, you could write an init.d script to stop your daemon and wait for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM