I am working on an application where I need to detect a system shutdown. However, I have not found any reliable way get a notification on this event.
I know that on shutdown, my app will receive a SIGTERM
signal followed by a SIGKILL
. I want to know if there is any way to query if a SIGTERM
is part of a shutdown sequence?
Does any one know if there is a way to query that programmatically (C API)?
As far as I know, the system does not provide any other method to query for an impending shutdown. If it does, that would solve my problem as well. I have been trying out runlevels
as well, but change in runlevels
seem to be instantaneous and without any prior warnings.
Maybe a little bit late. Yes, you can determine if a SIGTERM is in a shutting down process by invoking the runlevel command. Example:
#!/bin/bash
trap "runlevel >$HOME/run-level; exit 1" term
read line
echo "Input: $line"
save it as, say, term.sh
and run it. By executing killall term.sh
, you should able to see and investigate the run-level
file in your home directory. By executing any of the following:
sudo reboot
sudo halt -p
sudo shutdown -P
and compare the difference in the file. Then you should have the idea on how to do it.