Created
December 2, 2014 17:25
-
-
Save arkq/eac2649ea6f77c7040f1 to your computer and use it in GitHub Desktop.
Check for given key event on the hardware level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* kbcheck.c - Check for given key event on the hardware level | |
* Copyright (c) 2014 Arkadiusz Bokowy | |
* | |
* This projected is licensed under the terms of the MIT license. | |
* | |
* Compilation: | |
* gcc -Wall -Wextra -o kbcheck kbcheck.c | |
* | |
* Exemplary usage: | |
* kbcheck -t 500 /dev/input/event4 0x7d # check for Win key | |
* | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <poll.h> | |
#include <time.h> | |
#include <linux/input.h> | |
/* Get time in microseconds (maximal time delta is 255 seconds). */ | |
long timeu(const struct timespec *ts) { | |
struct timespec _ts; | |
if (ts == NULL) { | |
clock_gettime(CLOCK_BOOTTIME, &_ts); | |
ts = &_ts; | |
} | |
return (ts->tv_sec & 0xFF) * 1000000 + ts->tv_nsec / 1000; | |
} | |
int main(int argc, char *argv[]) { | |
int opt; | |
int timeout = 50; | |
while ((opt = getopt(argc, argv, "ht:")) != -1) | |
switch (opt) { | |
case 'h': | |
return_usage: | |
printf("usage: %s [options] <kbdev> <keycode>\n" | |
" -t NUM\ttimeout value in ms (default: %d)\n", | |
argv[0], timeout); | |
return EXIT_SUCCESS; | |
case 't': | |
timeout = atoi(optarg); | |
break; | |
default: | |
printf("Try `%s -h` for more informations.\n", argv[0]); | |
return EXIT_FAILURE; | |
} | |
/* it should be two arguments */ | |
if (optind + 2 != argc) | |
goto return_usage; | |
char *kbdevice = argv[optind]; | |
int keycode = strtol(argv[optind + 1], NULL, 0); | |
struct pollfd fds; | |
struct input_event ev; | |
if ((fds.fd = open(kbdevice, O_RDONLY)) == -1) { | |
perror("error: unable to open event device"); | |
return EXIT_FAILURE; | |
} | |
fds.events = POLLIN; | |
/* get our staring time to correctly handling timeout */ | |
long start = timeu(NULL); | |
int _timeout; | |
while ((_timeout = timeout - (timeu(NULL) - start) / 1000) > 0) { | |
if (poll(&fds, 1, _timeout) <= 0) | |
/* timeout or error, we don't care */ | |
break; | |
ev.type = 0; | |
read(fds.fd, &ev, sizeof(ev)); | |
if (ev.type == 1 && ev.code == keycode) | |
/* we've got our key press/release event */ | |
return EXIT_SUCCESS; | |
} | |
return EXIT_FAILURE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment