]> git.scottworley.com Git - keystroke-timestamps/blob - keystroke-timestamps.c
Merge
[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 /* Open output file */
38 FILE *output_file;
39 if (output == NULL) {
40 output_file = stdout;
41 } else {
42 output_file = fopen(output, "a");
43 if (output_file == NULL) {
44 err(EX_CANTCREAT, "Could not open output file: %s", output);
45 }
46 }
47
48 /* Open device inputs */
49 fd_set all_inputs;
50 FD_ZERO(&all_inputs);
51 int maxfd = 0;
52 glob_t glob_result;
53 int glob_return = glob(device, GLOB_ERR | GLOB_NOSORT, NULL, &glob_result);
54 if (glob_return == GLOB_NOMATCH) {
55 errx(EX_NOINPUT, "Could not find keyboard event file(s): %s", device);
56 }
57 if (glob_return != 0) {
58 err(EX_NOINPUT, "Could not glob keyboard event file(s): %s", device);
59 }
60 for (unsigned i = 0; i < glob_result.gl_pathc; i++) {
61 int device_fd = open(glob_result.gl_pathv[i], O_RDONLY);
62 if (device_fd < 0) {
63 err(EX_NOINPUT, "Could not open keyboard event file: %s", glob_result.gl_pathv[i]);
64 }
65 if (device_fd > maxfd) {
66 maxfd = device_fd;
67 }
68 FD_SET(device_fd, &all_inputs);
69 }
70 globfree(&glob_result);
71
72 /* Report keystroke timestamps */
73 struct input_event i;
74 while (1) {
75 fd_set ready_inputs = all_inputs;
76 if (select(maxfd+1, &ready_inputs, NULL, NULL, NULL) != 1) {
77 err(EX_IOERR, "select");
78 }
79 for (int fd=0; fd <= maxfd; fd++) {
80 if (FD_ISSET(fd, &ready_inputs)) {
81 int read_return = read(fd, &i, sizeof(i));
82 if (read_return == -1) {
83 err(EX_IOERR, "read");
84 }
85 if (read_return != sizeof(i)) {
86 errx(EX_IOERR, "Unexpected EOF");
87 }
88 if (i.type == 1 && i.value == 1) {
89 if (print_usec) {
90 fprintf(output_file, "%ld.%06ld\n", i.time.tv_sec, i.time.tv_usec);
91 } else {
92 fprintf(output_file, "%ld\n", i.time.tv_sec);
93 }
94 fflush(output_file);
95 }
96 }
97 }
98 }
99 return 0;
100 }