Skip to content

Instantly share code, notes, and snippets.

@omnidan
Created October 3, 2012 17:56
Show Gist options
  • Save omnidan/3828609 to your computer and use it in GitHub Desktop.
Save omnidan/3828609 to your computer and use it in GitHub Desktop.
Capture key events from a keyboard/input device.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <termios.h>
#include <signal.h>
void handler(int sig) {
printf("\nEXIT(%d)\n", sig);
exit(0);
}
void perror_exit(char *error) {
perror(error);
handler(9);
}
int main (int argc, char *argv[]) {
struct input_event ev[64];
int fd, rd, value, size = sizeof (struct input_event);
char name[256] = "Unknown";
char *device = NULL;
if (argv[1] == NULL) {
printf("Usage: %s [INPUT_DEVICE]\n", argv[0]);
exit(0);
}
if ((getuid ()) == 0) printf("ROOT = TRUE\n");
else printf("ROOT = FALSE [!]\n");
device = argv[1];
if ((fd = open (device, O_RDONLY)) == -1) printf("INVALID_DEVICE(%s) [!]\n", device);
ioctl(fd, EVIOCGNAME (sizeof (name)), name);
printf("READ(%s) [%s]\n", device, name);
while (1) {
if ((rd=read(fd, ev, size * 64)) < size) perror_exit("READ_ERROR");
value = ev[0].value;
if (value != ' ' && ev[1].value == 1 && ev[1].type == 1) {
printf ("KEY(%d)\n", ev[1].code);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment