Handling signal TERM in Python

I had an issue with the lights staying on after stopping the python script using start-stop-daemon, because I wasn’t handling the terminate signal that it passes to the script.

By default, when you call start-stop-daemon with –stop argument it sends a signal TERM (terminate). To handle this signal I created a class that registers a callback method for signal.SIGTERM. That method then sets a flag. So when start-stop-daemon is called with the –stop argument it will call the method and set the flag. In my main while loop I now check that flag and if it is set then I quit the code and clear the GPIO pins.

class CancellationToken:
    cancel_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.cancel_now = True

while not request.cancel_now:
    #do stuff here... and stop once the service receives
    # a TERM signal

Leave a Reply

Your email address will not be published. Required fields are marked *