Skip to content
Advertisement

How can my Linux program get a computer-is-about-to-go-to-sleep notification, without modifying any system config files?

I wrote a Linux program that creates some persistent TCP connections, and I would like my program to close() those TCP sockets just before the Linux-computer goes to sleep, so that the remote peer isn’t left with a non-responsive “zombie” TCP connection.

According to this answer, one way to do that is to modify the /etc/pm/sleep.d file to run a special notification app, but I’d prefer not to do it that way since modifying system config files is risky (and in many cases not possible if my program does not have permissions to do so).

Windows and MacOS/X have C-based notification APIs for this sort of thing; is there anything similar in Linux-land?

Advertisement

Answer

You can use systemd-logind a tiny daemon that manages user logins and provides both a C library interface as well as a D-Bus interface. You can subscribe to the following signals:

The PrepareForShutdown() resp. PrepareForSleep() signals are sent right before (with the argument True) and after (with the argument False) the system goes down for reboot/poweroff, resp. suspend/hibernate. This may be used by applications for saving data on disk, releasing memory or doing other jobs that shall be done shortly before shutdown/sleep, in conjunction with delay inhibitor locks. After completion of this work they should release their inhibition locks in order not to delay the operation any further.

You can also take a look at this sample program written in Python that uses D-Bus and the PrepareForSleep() signal.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement