Home > Software design >  python program won't handle systemd KillSignal at reboot
python program won't handle systemd KillSignal at reboot

Time:11-16

I have a set of LEDs that I start and turn into a specific colour when the machine starts up and during other events. At power-off/reboot I want the LEDs to reset to the default colour.

To achieve this I start a systemd service that starts up the LED code and have a handle for the signal in the python code. Unfortunately I'm not either receiving the signal or the signal is not getting handled.

import signal
from threading import Event

stop_event = Event()

def read_led_status():
    while True:
        #do stuff (read from pipe and update LED status)
        stop_event.wait(0.5)


def system_exit():
    stop_event.set()
    #set default colour


if __name__ == "__main__":
    #handle kill signal
    signal.signal(signal.SIGTERM, system_exit)
    signal.signal(signal.SIGINT, system_exit)
    signal.signal(signal.SIGHUP, system_exit)

    read_led_status()

The system service

[Unit]
Description=LED
ConditionPathExistsGlob=/dev/ttyUSB*
Before=startup.service

[Service]
Type=simple
User=admin
ExecStart=sudo python3 /led/led_start.py
KillSignal=SIGTERM
StandardOutput=syslog
StandardError=syslog
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

What am I doing wrong here? It's running on Ubuntu. Any help would be appreciated.

CodePudding user response:

The callback executed by signal expects two arguments. Your implementation does not take any. The right prototype is:

def system_exit(signum, frame):
    stop_event.set()

This might have thrown a TypeError upon signal receive and execution. As you forward your logs output to syslog, then the journalctl should have kept a track of this.

Using the above prototype should make your script properly catch and handle the SIGTERM signal (i.e.: the signal registered in the systemd service definition).

  • Related