I want to detect that system is restarting before it terminates my program on Linux. I tried using /var/run/utmp file to detect runlevel, put inotify on its changes but seems like system is closing this program before I get signal. I catch shutdown with it if I set runlevel with telinit command, but dont catch if I just restart with button on top-right corner in Ubuntu.
Any idea how can it be done?
Catch the
SIGTERMsignal and be quick with saving/doing whatever and then exit. You've got approximately 10 seconds before you'll getSIGKILLwhich you can't catch, and you'll be force terminated.If the system isn't sending you a
SIGTERMto allow proper shutdown, change your system to something proper, this is the standard way of doing it.See
man 7 signalandman 3 sigactionfor signal handling.(Note that I don't know of a standard way to check if a system is rebooting or not, I don't think such thing exists. But as mentioned above, a proper system will send you
SIGTERMand let you do your cleanup/exit. Hard reboot excluded, because thats almost equivalent of pulling the power cord.)