Zhani Baramidze
Zhani Baramidze

Reputation: 1497

How to detect restart before terminating program on Linux

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?

Upvotes: 0

Views: 896

Answers (1)

Jite
Jite

Reputation: 4368

Catch the SIGTERM signal and be quick with saving/doing whatever and then exit. You've got approximately 10 seconds before you'll get SIGKILL which you can't catch, and you'll be force terminated.

If the system isn't sending you a SIGTERM to allow proper shutdown, change your system to something proper, this is the standard way of doing it.

See man 7 signal and man 3 sigaction for 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 SIGTERM and let you do your cleanup/exit. Hard reboot excluded, because thats almost equivalent of pulling the power cord.)

Upvotes: 3

Related Questions