10

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?

4

2 Answers 2

3

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).

3
  • I need to distinguish also reboot vs poweroff/halt. From the systemctl's point of view it's "stopping" in all cases.
    – VPfB
    Jul 23, 2020 at 11:23
  • @VPfB In that case, you probably want to evaluate which target is active. It's hacky but it works: stackoverflow.com/questions/25166085/… Jul 23, 2020 at 13:09
  • One word of caution: the value returned by systemctl is-system-running may not always be consistent from one systemd version to another. For instance, I discovered that in RHEL 8 and 9, returns stopping fairly quickly after shutdown -r, but in RHEL 7, you get "running" until much later in the shutdown process. This is not really a bug; the exact behavior is simply undefined. Jan 15 at 6:10
1

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
1
  • 1
    Thank you. The link to this was already posted in the comments. While this is helpful, the best solution for me would allow the ExecStop command of the running service to check in which situation it was called.
    – VPfB
    Jun 2, 2019 at 7:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .