]> git.scottworley.com Git - keystroke-timestamps/blob - keystroke-timestamps.c
Don't copy the device argument
[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 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 device = optarg;
26 continue;
27 }
28 if (c != 0) exit(EX_USAGE);
29 }
30
31 fd_set all_inputs;
32 FD_ZERO(&all_inputs);
33 int maxfd = 0;
34 glob_t glob_result;
35 int glob_return = glob(device, GLOB_ERR | GLOB_NOSORT, NULL, &glob_result);
36 if (glob_return == GLOB_NOMATCH) {
37 errx(EX_NOINPUT, "Could not find keyboard event file(s): %s", device);
38 }
39 if (glob_return != 0) {
40 err(EX_NOINPUT, "Could not glob keyboard event file(s): %s", device);
41 }
42 for (unsigned i = 0; i < glob_result.gl_pathc; i++) {
43 int open_fd = open(glob_result.gl_pathv[i], O_RDONLY);
44 if (open_fd < 0) {
45 err(EX_NOINPUT, "Could not open keyboard event file: %s", glob_result.gl_pathv[i]);
46 }
47 if (open_fd > maxfd) {
48 maxfd = open_fd;
49 }
50 FD_SET(open_fd, &all_inputs);
51 }
52 globfree(&glob_result);
53
54 struct input_event i;
55 while (1) {
56 fd_set ready_inputs = all_inputs;
57 if (select(maxfd+1, &ready_inputs, NULL, NULL, NULL) != 1) {
58 err(EX_IOERR, "select");
59 }
60 for (int fd=0; fd <= maxfd; fd++) {
61 if (FD_ISSET(fd, &ready_inputs)) {
62 int read_return = read(fd, &i, sizeof(i));
63 if (read_return == -1) {
64 err(EX_IOERR, "read");
65 }
66 if (read_return != sizeof(i)) {
67 errx(EX_IOERR, "Unexpected EOF");
68 }
69 if (i.type == 1 && i.value == 1) {
70 if (print_usec) {
71 printf("%ld.%06ld\n", i.time.tv_sec, i.time.tv_usec);
72 } else {
73 printf("%ld\n", i.time.tv_sec);
74 }
75 fflush(stdout);
76 }
77 }
78 }
79 }
80 return 0;
81 }