how to detect Linux shutdown/reboot

前端 未结 2 1561
余生分开走
余生分开走 2020-12-17 23:44

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

相关标签:
2条回答
  • 2020-12-18 00:29

    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.

    0 讨论(0)
  • 2020-12-18 00:45

    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.

    0 讨论(0)
提交回复
热议问题