]> git.scottworley.com Git - keystroke-timestamps/blob - keystroke-timestamps.c
Use select() to wait for data
[keystroke-timestamps] / keystroke-timestamps.c
1 #include <err.h>
2 #include <fcntl.h>
3 #include <getopt.h>
4 #include <linux/input.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sysexits.h>
9 #include <sys/select.h>
10 #include <unistd.h>
11
12 int main (int argc, char **argv)
13 {
14 int print_usec = 0;
15 char* device = strdup("/dev/input/by-path/platform-i8042-serio-0-event-kbd");
16 struct option long_options[] = {
17 {"device", required_argument, 0, 'd' },
18 {"usec", no_argument, &print_usec, 1 },
19 {0, 0, 0, 0 },
20 };
21 while (1) {
22 int c = getopt_long(argc, argv, "", long_options, NULL);
23 if (c == -1) break;
24 if (c == 'd') {
25 free(device);
26 device = strdup(optarg);
27 continue;
28 }
29 if (c != 0) exit(EX_USAGE);
30 }
31
32 int fd = open(device, O_RDONLY);
33 if (fd < 0) {
34 err(EX_NOINPUT, "Could not open keyboard event file");
35 }
36 free(device);
37 struct input_event i;
38 fd_set all_inputs, ready_inputs;
39 FD_ZERO(&all_inputs);
40 FD_SET(fd, &all_inputs);
41 while (1) {
42 ready_inputs = all_inputs;
43 if (select(fd+1, &ready_inputs, NULL, NULL, NULL) != 1) {
44 err(EX_IOERR, "select");
45 }
46 if (read(fd, &i, sizeof(i)) != sizeof(i)) {
47 break;
48 }
49 if (i.type == 1 && i.value == 1) {
50 if (print_usec) {
51 printf("%ld.%06ld\n", i.time.tv_sec, i.time.tv_usec);
52 } else {
53 printf("%ld\n", i.time.tv_sec);
54 }
55 fflush(stdout);
56 }
57 }
58 return 0;
59 }