Skip to content

Instantly share code, notes, and snippets.

@parrotmac
Created February 4, 2020 18:23
Show Gist options
  • Select an option

  • Save parrotmac/1261c88a131e45004f9f52ca2ffcda2f to your computer and use it in GitHub Desktop.

Select an option

Save parrotmac/1261c88a131e45004f9f52ca2ffcda2f to your computer and use it in GitHub Desktop.
Read Linux Key Events
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <string.h>
#include <stdio.h>
/*
* Mostly a copy from https://stackoverflow.com/a/20946151
* Demo of reading from /dev/input/event* devices
* Compile for ARM: arm-linux-gnueabihf-gcc -static -march=armv7 main.c -o keyevents-arm
*/
static const char *const evval[3] = {
"RELEASED",
"PRESSED ",
"REPEATED"
};
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "please specify only the input event path to listen on (e.g. /dev/input/event0).\n");
return EXIT_FAILURE;
}
fprintf(stdout, "listening to %s\n", argv[1]);
fflush(stdout);
char *dev = argv[1];
struct input_event ev;
ssize_t n;
int fd;
fd = open(dev, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Cannot open %s: %s.\n", dev, strerror(errno));
return EXIT_FAILURE;
}
while (1) {
n = read(fd, &ev, sizeof ev);
if (n == (ssize_t) -1) {
if (errno == EINTR)
continue;
else
break;
} else if (n != sizeof ev) {
errno = EIO;
break;
}
if (ev.type == EV_KEY && ev.value >= 0 && ev.value <= 2) {
fprintf(stdout, "%s 0x%04x (%d)\n", evval[ev.value], (int) ev.code, (int) ev.code);
fflush(stdout);
}
}
fflush(stdout);
fprintf(stderr, "%s.\n", strerror(errno));
return EXIT_FAILURE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment