Hi, I am working on an app where I need to detect 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. What I want to know is if there is someway 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 shutdowm. 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.
When the system shuts down, the rc.d
scripts are called.
Maybe you can add a script there that sends some special signal to your program.
However, I doubt you can stop the system shutdown that way.
Making your application responding differently to some SIGTERM signals than others seems opaque and potentially confusing. It's arguable that you should always respond the same way to a given signal. Adding unusual conditions makes it harder to understand and test application behavior.
Adding an rc script that handles shutdown (by sending a special signal) is a completely standard way to handle such a problem; if this script is installed as part of a standard package (make install
or rpm/deb packaging) there should be no worries about control of user machines.
There is no way to determine if a SIGTERM is a part of a shutdown sequence. To detect a shutdown sequence you can either use use rc.d scripts like ereOn and Eric Sepanson suggested or use mechanisms like DBus. However, from a design point of view it makes sense to not ignore SIGTERM even if it is not part of shutdown. SIGTERM's primary purpose is to politely ask apps to exit cleanly and it is not likely that someone with enough privileges will issue a SIGTERM if he/she does not want the app to exit.