1

I have been programming using python for the raspberryPi for several months now and I am trying to make my scripts "well behaved" and wrap up (close files and make sure no writes to SD are being perfomed) upon reception of SIGTERM.

Following advice on SO (1, 2) I am able to handle SIGTERM if I kill the process manually (i.e. kill {process number}) but if I send the shutdown command (i.e. shutdown -t 30 now) my handler never gets called.

I also tried registering for all signals and checking the signal being send on the shutdown event but I am not getting any.

Here's simple example code:

import time
import signal
import sys


def myHandler(signum, frame):
    print "Signal #, ", signum
    sys.exit()

for i in [x for x in dir(signal) if x.startswith("SIG")]:
    try:
        signum = getattr(signal, i)
        signal.signal(signum, myHandler)
        print "Handler added for {}".format(i)
    except RuntimeError,m:
        print "Skipping %s"%i
    except ValueError:
        break
while True:
    print "goo"
    time.sleep(1)

Any ideas will be greatly appreciated .. =)

Community
  • 1
  • 1
  • 2
    it's possible that on `shutdown` you get `SIGTERM`, but the script isn't able to output to the screen. Append to a log file, then check the log when the machine comes back. – johntellsall Jun 09 '14 at 20:24
  • Good point. I will try it and report my findings – CesarChavez Jun 10 '14 at 00:14
  • 1
    @shavenwarthog: When I try the `shutdown` command with `-t` (as far as I understand is the time between `SIGTERM` and `SIGKILL`) I can configure a reasonable amount of time to see the output to the screen. Anyway is a valid point. – CesarChavez Jun 10 '14 at 00:22

1 Answers1

0

this code works for me on the raspberry pi, i can see the correct output in the file output.log after the restart:

logging.basicConfig(level=WARNING,
                    filename='output.log',
                    format='%(message)s')   
def quit():
    #cleaning code here
    logging.warning('exit')
    sys.exit(0)

def handler(signum=None, frame=None):
    quit()

for sig in [signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT, signal.SIGKILL]:
    signal.signal(sig, handler)

def restart():
    command = '/sbin/shutdown -r now'
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]
    logging.warning('%s'%output)

restart()

maybe your terminal handles the signal before the python script does, so you can't actually see anything. Try to see the output in a file (with the logging module or the way as you like).

GiulioG
  • 81
  • 5