No, as the kernel does not provide any sort of "going to sleep" signal before freezing all processes, there is no distribution-agnostic way to detect it.
That said, pretty much all suspend requests – including lid-close – tend to go through a few userspace APIs: eventually, they either call systemd-logind's Suspend()
function via D-Bus, or spawn the pm-suspend
command. Both have various kinds of "hooks" which can be used for this.
(Note that no matter what you do, a direct echo mem > /sys/power/state
remains nearly invisible to userspace, short of watching for sudden clock jumps...)
So, if you use systemd as init:
Install xss-lock
and make your desktop environment start it on login (via ~/.xinitrc
, via ~/.config/autostart/
, or via whatever):
xss-lock xlock &
This will handle systemd's pre-suspend notifications, as well as manual loginctl lock-sessions
calls should you ever need those.
Create a pm-utils hook script at /etc/pm/sleep.d/50lock
:
#!/bin/sh
loginctl lock-sessions
(Don't forget to chmod +x
.) You don't need this for regular systemd suspend, but it will send out a notification to xss-lock whenever you manually run pm-suspend
.
If you're using another init system:
If you're using pm-suspend
, I suppose you could run xlock
directly from the pm/sleep.d hook script. That would require you to also directly set DISPLAY
and XAUTHORITY
environment variables, which is kinda awful since they can vary from boot to boot (although some people hardcode :0
there...)
Overall, in that situation, desktop-environment-specific methods might work better.