]> git.scottworley.com Git - keystroke-timestamps/blob - keystroke-timestamps.c
5a27279660103f6503cfc8066be0096d24f1f235
[keystroke-timestamps] / keystroke-timestamps.c
1 #include <err.h>
2 #include <fcntl.h>
3 #include <glob.h>
4 #include <getopt.h>
5 #include <linux/input.h>
6 #include <stdio.h>
7 #include <stdlib.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 = "/dev/input/by-path/*kbd*";
16 char* output = NULL;
17 struct option long_options[] = {
18 {"device", required_argument, 0, 'd' },
19 {"output", required_argument, 0, 'o' },
20 {"usec", no_argument, &print_usec, 1 },
21 {0, 0, 0, 0 },
22 };
23 while (1) {
24 int c = getopt_long(argc, argv, "", long_options, NULL);
25 if (c == -1) break;
26 if (c == 'd') {
27 device = optarg;
28 continue;
29 }
30 if (c == 'o') {
31 output = optarg;
32 continue;
33 }
34 if (c != 0) exit(EX_USAGE);
35 }
36
37 FILE *output_file;
38 if (output == NULL) {
39 output_file = stdout;
40 } else {
41 output_file = fopen(output, "a");
42 if (output_file == NULL) {
43 err(EX_CANTCREAT, "Could not open output file: %s", output);
44 }
45 }
46
47 fd_set all_inputs;
48 FD_ZERO(&all_inputs);
49 int maxfd = 0;
50 glob_t glob_result;
51 int glob_return = glob(device, GLOB_ERR | GLOB_NOSORT, NULL, &glob_result);
52 if (glob_return == GLOB_NOMATCH) {
53 errx(EX_NOINPUT, "Could not find keyboard event file(s): %s", device);
54 }
55 if (glob_return != 0) {
56 err(EX_NOINPUT, "Could not glob keyboard event file(s): %s", device);
57 }
58 for (unsigned i = 0; i < glob_result.gl_pathc; i++) {
59 int device_fd = open(glob_result.gl_pathv[i], O_RDONLY);
60 if (device_fd < 0) {
61 err(EX_NOINPUT, "Could not open keyboard event file: %s", glob_result.gl_pathv[i]);
62 }
63 if (device_fd > maxfd) {
64 maxfd = device_fd;
65 }
66 FD_SET(device_fd, &all_inputs);
67 }
68 globfree(&glob_result);
69
70 struct input_event i;
71 while (1) {
72 fd_set ready_inputs = all_inputs;
73 if (select(maxfd+1, &ready_inputs, NULL, NULL, NULL) != 1) {
74 err(EX_IOERR, "select");
75 }
76 for (int fd=0; fd <= maxfd; fd++) {
77 if (FD_ISSET(fd, &ready_inputs)) {
78 int read_return = read(fd, &i, sizeof(i));
79 if (read_return == -1) {
80 err(EX_IOERR, "read");
81 }
82 if (read_return != sizeof(i)) {
83 errx(EX_IOERR, "Unexpected EOF");
84 }
85 if (i.type == 1 && i.value == 1) {
86 if (print_usec) {
87 fprintf(output_file, "%ld.%06ld\n", i.time.tv_sec, i.time.tv_usec);
88 } else {
89 fprintf(output_file, "%ld\n", i.time.tv_sec);
90 }
91 fflush(output_file);
92 }
93 }
94 }
95 }
96 return 0;
97 }