Run script on wake assistance

Always good to explain what I am hoping to accomplish, as I maybe asking the wrong question.

I am running SDDM instead of GDM.

Because of that I use i3lock to lock my PC as GDM is required to lock modern GNOME systems.

I have sorted my keyboard shortcut META+L and it works perfectly, however I sometimes put my PC to sleep and I want it to lock automatically on resume.

Following this: I have a shell script in

/lib/systemd/system-sleep/
#!/bin/sh
export DISPLAY=:0

case $1/$2 in
  pre/*)
    echo "Going to $2..."
    # Place your pre suspend commands here, or `exit 0` if no pre suspend action required
    exit 0
    ;;
  post/*)
    echo "Waking up from $2..."
    # Place your post suspend (resume) commands here, or `exit 0` if no post suspend action required
    i3lock -c 000000 -n
    ;;
esac

The display 0 line is because nothing happens and checking the log of

journalctl -b -u systemd-suspend.service

I can see:

Jun 08 18:13:10 fedora systemd-sleep[12070]: System returned from sleep state.
Jun 08 18:13:10 fedora systemd-sleep[12232]: No protocol specified
Jun 08 18:13:10 fedora systemd-sleep[12232]: i3lock: Could not connect to X11, maybe you need to set DISPLAY?
Jun 08 18:13:10 fedora [12226]: /usr/lib/systemd/system-sleep/on-wakeup.sh failed with exit status 1.
Jun 08 18:13:10 fedora systemd[1]: systemd-suspend.service: Deactivated successfully.
Jun 08 18:13:10 fedora systemd[1]: Finished systemd-suspend.service - System Suspend.

I have tried adding DISPLAY to =:0 which didn’t help, and also tried enabling a service which also didn’t help.

The service in question was
/etc/systemd/system/onwakeup.service

[Unit]
Description=Run On Wakeup Script
After=suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target


[Service]
ExecStart=Shell script above
#User=my_user_name
Environment=DISPLAY=:0

[Install]
WantedBy=suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target

Once enabled with

sudo systemctl enable onwakeup

It doesn’t even show up on logs.

Any advice?

I have solved using the following tutorial but adapting Before to After as I want it to run After resuming.

Create a file using sudo at /etc/systemd/system/wakelock@.service, with the following content:

[Unit]
Description=Lock the screen on resume from suspend
After=sleep.target suspend.target

[Service]
User=%i
Type=forking
Environment=DISPLAY=:0
ExecStart=i3lock -c 000000 -n

[Install]
WantedBy=sleep.target suspend.target
Step 3: Enable the systemd module
Enable the systemd module you just created with:

sudo systemctl enable wakelock@<YOUR-USER-NAME> --now
i3lock will now run once as a demo, then when you wake from suspend, i3lock will automatically start.

That's it! If you make any changes and want them reflected immediately without restart, simply do:

sudo systemctl restart wakelock@<YOUR-USER-NAME>
1 Like