Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting keyboard, mouse activity in linux

Or simply use the command xprintidle which returns the idle time in milliseconds.

It has been packaged for debian based systems. (the source is not available any more on the original site dtek.chalmers.se/~henoch but you can get it at packages.ubuntu.com)

more info on freshmeat.net


Complete c solution : (cut & paste the whole code in a terminal)

cat>/tmp/idletime.c<<EOF
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/scrnsaver.h>

int GetIdleTime () {
        time_t idle_time;
        static XScreenSaverInfo *mit_info;
        Display *display;
        int screen;
        mit_info = XScreenSaverAllocInfo();
        if((display=XOpenDisplay(NULL)) == NULL) { return(-1); }
        screen = DefaultScreen(display);
        XScreenSaverQueryInfo(display, RootWindow(display,screen), mit_info);
        idle_time = (mit_info->idle) / 1000;
        XFree(mit_info);
        XCloseDisplay(display); 
        return idle_time;
}

int main() {
        printf("%d\n", GetIdleTime());
        return 0;
}
EOF

gcc -Wall /tmp/idletime.c -o /tmp/idletime -L/usr/X11R6/lib/ -lX11 -lXext -lXss 
DISPLAY=:0 /tmp/idletime

(the main part is coming from X11::IdleTime perl module)


Don't poll when there's better methods available.

You don't specify the environment, but since you mention the mouse, I'm going to assume modern X11.

xidle uses the MIT-SCREEN-SAVER extension to determine whether the user is idle or not -- you can use xidle directly, or read its source code to learn how to use the XScreenSaver(3) yourself.

Edit

man 3 XScreenSaver -- just use the idle-reporting/notification portions of it, since there is no more XIDLE extension since X11R6.


My aproach is to use ad-hoc perl module :

# cpan -i X11::IdleTime; sleep 2; perl -MX11::IdleTime -e 'print GetIdleTime(), $/;'

This is an example how to check that an user is idle for 5 minutes using xprintidle and shell script:

#!/bin/sh
idletime=$(xprintidle)
threshold=300000 # 5 min = 5 * 60 * 1000 ms
if [ "$idletime" -gt "$threshold" ]; then
  echo "idle"
fi

xprintidle returns time in milliseconds.

This script does not do any polling or the like. It only executes some code if user is idle and does nothing otherwise.


Try executing who -u -H at the command line. It will tell you who's logged in and how long they've been idle. At least users logged in to a terminal; I don't think it works at all in X. Anyhow, with this information you can tell who's idle or not and take actions appropriately.

If you're in X you could create a script to run as a screen saver or something like that.