tags:

views:

673

answers:

3

If I am working in an application and I press key from keyboard, how can I capture that key (or string), including the source application's name, in C, under GNU/LINUX, in userland, without X11 :)

Thanks.

A: 

One possibility: find and take a look at the source for 'sudosh', the 'sudo shell' (or one of its replacements since that has not been modified in a while; Google is your friend).

It messes with pseudo-ttys and tracks all the input and output by also recording the information to file.

Whether that is precise enough for you is perhaps more debatable; it would log all keystrokes for all applications. I'm also not certain how it works with X11 - if it works with X11.

Jonathan Leffler
A: 

You can read data from one of the files in /dev/input. Which one depends on your system. It might be /dev/input/event0 or /dev/input/by-path/platform-i8042-serio-0-event-kbd or something else. The format is specified in the kernel header input.h. It is

struct input_event {
        struct timeval time;
        __u16 type;
        __u16 code;
        __s32 value;
};

You can run

od -tx2 FILENAME

and type something to see what happens.

As for finding out which application received the key event, I'm not sure. You could try checking which one is reading from the main tty.

Kim
+1  A: 

Well, without X11 this problem is way more difficult.
For the keystroke part you can use a code similar to this one, but you have to pass as an argument the device that you are reading (keyboard, usually /dev/input/event0 )

#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int fd;
    if(argc < 2) {
     printf("usage: %s <device>\n", argv[0]);
     return 1;
    }
    fd = open(argv[1], O_RDONLY);
    struct input_event ev;

    while (1)
    {
    read(fd, &ev, sizeof(struct input_event));

    if(ev.type == 1)
     printf("key %i state %i\n", ev.code, ev.value);

    }
}

Credits do not go to me, this code is taken from the Ventriloctrl hack to get keystrokes. http://public.callutheran.edu/~abarker/ventriloctrl-0.4.tar.gz

Hope I am of some help.

aemus