How to identify shutdown event in linux

In my Ubuntu application, I wanted to perform certain finalization for my application before the system is being shutdown. For that, I need to identify the shutdown event in my application.

From what I have read online, there are mainly two major solutions, that are being suggested.

  1. using the ‘PrepareForShutdown’ dbus signal.
  2. trapping the SIGTERM signal that is send to the running applications prior to shutdown.

However, I have tried both the ways and they don’t seem to work for me. The handler that I m registering for ‘PrepareForShutdown’ never gets invoked.

For method 2, I have observed that my application does not receive SIGTERM signal, instead it receives some other signal a moment before being terminated using SIGKILL.

Can someone help me out, what should I be using to identify the shutdown correctly? I do not intend to read it from certain OS files, please provide an event based solution.

I’m not familiar with this signal, but here’s a guess: that signal is for letting you know that a shutdown is scheduled to occur at a future time, and doesn’t run at all when a shutdown is actually happening?

Hi, the default upstream behavior of systemd is to send SIGTERM first, then SIGKILL next. In Fedora, we do SIGTERM → SIGABRT (to generate a core dump) → SIGKILL. I cannot think of why you might be receiving a different signal before SIGTERM. But also, you can’t use SIGTERM to identify that the system is shutting down because there could be many possible reasons for that signal to be sent.

Maybe something like this would work for you?

Sorry, I was wrong. The docs indicate this should work. I wonder if your system is configured with a very short timeout such that your application just doesn’t have time to receive the signal? Alternatively, perhaps the message bus itself is being killed too soon and doesn’t have time to relay the signal? I have no clue what might be going wrong. Sorry for not being much help.

Hi,

If your application uses Gtk.Application then you can connect to the Gtk.Application::query-end signal to detect session logout.