TransWikia.com

How can a systemd service detect that system is going to power off?

Unix & Linux Asked by VPfB on December 8, 2021

I have a systemd service controlling some hardware, let’s take lamps as a good example. It is OK to restart the service, or reboot the PC, because it is safe that the lamps are left switched on for some while.

However if (and only if) the system is going to halt (power off), I want to do not only the regular cleanup, but also to switch the lights off, i.e. to stop the service in a sligthly different way.

In all mentioned cases (service restart, reboot, halt) the ExecStop command is executed the same way. How can I distinguish between these cases or otherwise know if systemd is doing poweroff or not?

2 Answers

It turns out that you can determine the status of the system by checking the output of

systemctl is-system-running      # See man 1 systemctl for more info

In your case, I recommend wrapping the part responsible for turning off your lamps with:

if [[ "$(systemctl is-system-running || true)" == "stopping" ]]; then
    # RUN THE COMMANDS OR EXECUTABLES FOR TURNING OFF THE LAMP HERE
fi

Of course, you could always inline the check directly in ExecStop if you don't want to maintain a separate wrapper (i.e ExecStop=sh -c 'if ... fi).

Answered by Tenders McChiken on December 8, 2021

This answer explain how to use the power target

You can add a service that will trigger a command on power-off event, something like

[Unit]
Description=My command on power event
Before=shutdown.target
DefaultDependencies=no

[Service]
ExecStart=/some/thing/to/execute
Type=oneshot
RemainAfterExit=yes

[Install]
WantedBy=shutdown.target

Answered by intika on December 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP