]> git.scottworley.com Git - keystroke-timestamps/blob - keystroke-timestamps.c
6cb49731cba993b270561b790e55fed2f4f5657f
[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 open_fd = open(device, O_RDONLY);
33 if (open_fd < 0) {
34 err(EX_NOINPUT, "Could not open keyboard event file");
35 }
36 int maxfd = open_fd;
37 free(device);
38 struct input_event i;
39 fd_set all_inputs, ready_inputs;
40 FD_ZERO(&all_inputs);
41 FD_SET(open_fd, &all_inputs);
42 while (1) {
43 ready_inputs = all_inputs;
44 if (select(maxfd+1, &ready_inputs, NULL, NULL, NULL) != 1) {
45 err(EX_IOERR, "select");
46 }
47 for (int fd=0; fd <= maxfd; fd++) {
48 if (FD_ISSET(fd, &ready_inputs)) {
49 int read_return = read(fd, &i, sizeof(i));
50 if (read_return == -1) {
51 err(EX_IOERR, "read");
52 }
53 if (read_return != sizeof(i)) {
54 errx(EX_IOERR, "Unexpected EOF");
55 }
56 if (i.type == 1 && i.value == 1) {
57 if (print_usec) {
58 printf("%ld.%06ld\n", i.time.tv_sec, i.time.tv_usec);
59 } else {
60 printf("%ld\n", i.time.tv_sec);
61 }
62 fflush(stdout);
63 }
64 }
65 }
66 }
67 return 0;
68 }