How do you get Ubuntu to automatically run a program every time the screen is unlocked?

5,805

Solution 1

It is possible, albeit a bit tricky. GnomeScreensaver documentation states:

Is there a way to perform actions when the screensaver activates or deactivates? Or when the session becomes idle?

One way is to watch for the D-Bus signals from gnome-screensaver. Here's an example of how to perform actions when the session becomes idle or is no longer idle using the Perl language:

my $cmd = "dbus-monitor --session \"type='signal',interface='org.gnome.ScreenSaver',member='SessionIdleChanged'\"";

open (IN, "$cmd |");

while (<IN>) {
    if (m/^\s+boolean true/) {
        print "*** Session is idle ***\n";
    } elsif (m/^\s+boolean false/) {
        print "*** Session is no longer idle ***\n";
    }
}

Although when I examined using dbus-monitor and proceeded to lock/unlock the screen the signal emitted was

path=/org/gnome/ScreenSaver; interface=org.gnome.ScreenSaver; member=ActiveChanged
boolean true

when screen was locked and

path=/org/gnome/ScreenSaver; interface=org.gnome.ScreenSaver; member=ActiveChanged
boolean false

When unlocked.

So altering the above script,

my $cmd = "dbus-monitor --session \"type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'\"";

open (IN, "$cmd |");

while (<IN>) {
    if (m/^\s+boolean false/) {
        exec('/path/to/your/script');
    } 
}

should do it.

Solution 2

Building on the bash shell script Michael wrote:

#!/usr/bin/env bash
dbus-monitor --session "type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'" | while read line ; do 
    if [ x"$(echo "$line" | grep 'boolean true')" != x ] ; then 
        # runs once when screensaver comes on...
    fi
    if [ x"$(echo "$line" | grep 'boolean false')" != x ] ; then 
        # runs once when screensaver goes off...
    fi
done

Solution 3

Doing it in bash to share the same external script:

#!/usr/bin/env bash
dbus-monitor --session "type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'" | while read line ; do 
        if [ x"$(echo "$line" | grep 'boolean false')" != x ] ; then 
               # do whatever you want here
        fi
done
Share:
5,805

Related videos on Youtube

Corey T Foote
Author by

Corey T Foote

Updated on September 17, 2022

Comments

  • Corey T Foote
    Corey T Foote over 1 year

    I have a script I would like to have automatically invoked every time the screen is unlocked. Does Ubuntu provide some support for users who wish to do this?

    • Zoredache
      Zoredache over 13 years
      I am not aware of anything. I suspect you would have to some hacking/patching of your favorite screen saver application.