linuxrhelsystemd

how can a systemd controlled service distinguish between shutdown and reboot?


I have a Linux process that runs on RHEL7 and is started by systemd. When the process is stopped, I need to know if it is being stopped because of a system shutdown or reboot, and I need to be able to distinguish between the two.

Previously, under init on RHEL6, I was able to do this by looking at the pathname used to invoke my init script, and sent the process a different signal accordingly, i.e.:

case "$0" in 
    *rc0\.d*|*rc1\.d*)     #shutdown
    sig=USR1
    ;;
    *rc6\.d*)              #reboot
    sig=USR2
    ;;
    *)
    sig=TERM
    ;;
esac

This doesnt work with systemd...although my init script gets called at the right time, $0 is always the same (/etc/init.d/scriptname).

Is there some way under systemd to know if you are being called because of a system shutdown or reboot? I'm happy to get rid of the init script and configure it as a systemd target instead, but from the documentation I can't see a way to do what I want.


Solution

  • CameronNemo's comment is on the right track. The special systemd targets are described in man systemd.special or http://linuxmanpages.net/manpages/fedora14/man7/systemd.special.7.html and the reboot target is active on a reboot. However, the shutdown target is active on any form of system termination, whether reboot or halt, so it doesn't help to discriminate. For other targets of interest see man telinit. I've had success with the following type of code:

    /usr/bin/systemctl list-jobs | egrep -q 'shutdown.target.*start' && echo "shutting down" || echo "not shutting down"
    /usr/bin/systemctl list-jobs | egrep -q 'reboot.target.*start' && echo "-> rebooting" || echo "-> not rebooting"
    /usr/bin/systemctl list-jobs | egrep -q 'halt.target.*start' && echo "-> halting" || echo "-> not halting"
    /usr/bin/systemctl list-jobs | egrep -q 'poweroff.target.*start' && echo "-> powering down" || echo "-> not powering down"
    

    When shutting down the system it will always say "shutting down" and then depending on reboot or poweroff also "rebooting" or "powering down". /sbin/halt will result in a "halting". shutdown -h now converts into powering off when I try it, but that may depend on virtual vs. physical environment. I've tested in EC2 us-east using Fedora 20 (ami-21362b48) and CentOS7 (ami-96a818fe). If you come across a situation where this doesn't work please leave a comment and I'll try to fix!