Search code examples
linuxserviceembedded-linuxsystemd

How to detect shutdown triggered on Linux via dbus


I need to perform some task before system will be shut down. I can't do it in class destructor because my service can be stopped not only because of shut down

My service already uses dbus to communicate to other services in the system, so I'd prefer to have some dbus signal that will notify about system shutdown

I thought to do the task in destructor, but the context of destructor doesn't fit - I need to perform asynchronous task.

I expect some dbus signal to be able to subscribe on it


Solution

  • Use the systemd-logind Inhibit() API via D-Bus to obtain a delay-type inhibitor. You'll receive a file descriptor as part of the call result, so make sure your D-Bus bindings support that.

    Shutdowns initiated by users through systemd-logind will broadcast a PrepareForSleep signal via D-Bus, and the actual shutdown will be delayed until you close() the previously received file descriptor (although only up to a few seconds).

    See the xss-lock project for an example.