I\'m trying to detect shut down or reboot from Linux in my c program. I found that program can use signal(SIGTERM, handler) (SIGKILL, handler). But these two will trigger if
Catch SIGTERM. In the handler, read the /var/run/utmp
file to get the runlevel. See the source code of the runlevel(8)
command for reference.
Your assumptions are mistaken. There is no way to catch SIGKILL
; it terminates the process with no chance to respond to it.
With that said, I may have a solution: you can catch SIGTERM
, and if you install the signal handler with sigaction
and the SA_SIGINFO
flag, you should be able to determine which process sent you the SIGTERM
signal. If it came from init
(pid 1), it's a shutdown. This is mildly hackish but might work for your purposes.