7

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?

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
| improve this answer | |
  • 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 '19 at 7:09
0

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

| improve this answer | |
  • 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 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/… – Tenders McChiken Jul 23 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.