suspend AND lock screen on closing lid in arch/systemd
There are a couple of examples in the Arch Wiki.
Basically, it involves creating a service file for your screen locker and ensuring it is hooked to either the suspend
, hibernate
or sleep
targets.
If you use a simple screen locker like slock, /etc/systemd/system/lock.service
would look like this:
[Unit]
Description=Lock the screen on resume from suspend
[Service]
User=jason
Environment=DISPLAY=:0
ExecStart=/usr/bin/slock
[Install]
WantedBy=suspend.target
Other examples on the wiki have more complex options, including shutting down and bringing up other services, etc.
While jasonwryan's reply is correct, it is incomplete. In order to safely lock after suspending, instead of before - where a non-root process may prevent the kernel from suspending, you must add a Before= instance which forces systemd to wait for the ExecStart call to slock to start before suspending. Using sleep.target covers suspend, hibernate, and hybrid sleep.
[Unit]
Description=Lock
+Before=sleep.target
[Service]
User=mustapha
Environment=DISPLAY=:0
ExecStart=/usr/local/bin/slock
[Install]
-WantedBy=suspend.target
+WantedBy=sleep.target
If you use openrc
with elogind
is there an alternative solution (which is not systemd dependent):
#!/bin/sh
#
# /lib/elogind/system-sleep/lock.sh
# Lock before suspend integration with elogind
username=lerax
userhome=/home/$username
export XAUTHORITY="$userhome/.Xauthority"
export DISPLAY=":0.0"
case "${1}" in
pre)
su $username -c "/usr/bin/slock" &
sleep 1s;
;;
esac
ref: https://gist.github.com/ryukinix/bd0c1ddcbbafdb4149ae70e41b7c822b
I'm posting this because was very difficult to find it a proper way that it works and this thread appears on first results of google about "lock after suspend" or whatever.