evdev 设备queue events 直到你read() 他们,所以在大多数情况下打开设备,执行ioctl() 并立即开始从中读取事件应该可以工作。如果驱动程序从队列中删除了一些事件,它是sends you a SYN_DROPPED event,因此您可以检测到发生这种情况的情况。 The libevdev documentation 对如何处理这种情况有一些想法;按照我的阅读方式,您应该简单地重试,即删除所有待处理的事件,然后重做ioctl(),直到没有更多的SYN_DROPPED 事件。
我使用这段代码来验证这种方法是否有效:
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <string.h>
#define EVDEV "/dev/input/event9"
int main(int argc, char **argv) {
unsigned char key_states[KEY_MAX/8 + 1];
struct input_event evt;
int fd;
memset(key_states, 0, sizeof(key_states));
fd = open(EVDEV, O_RDWR);
ioctl(fd, EVIOCGKEY(sizeof(key_states)), key_states);
// Create some inconsistency
printf("Type (lots) now to make evdev drop events from the queue\n");
sleep(5);
printf("\n");
while(read(fd, &evt, sizeof(struct input_event)) > 0) {
if(evt.type == EV_SYN && evt.code == SYN_DROPPED) {
printf("Received SYN_DROPPED. Restart.\n");
fsync(fd);
ioctl(fd, EVIOCGKEY(sizeof(key_states)), key_states);
}
else if(evt.type == EV_KEY) {
// Ignore repetitions
if(evt.value > 1) continue;
key_states[evt.code / 8] ^= 1 << (evt.code % 8);
if((key_states[evt.code / 8] >> (evt.code % 8)) & 1 != evt.value) {
printf("Inconsistency detected: Keycode %d is reported as %d, but %d is stored\n", evt.code, evt.value,
(key_states[evt.code / 8] >> (evt.code % 8)) & 1);
}
}
}
}
程序启动后故意等待5秒。在那个时候按下一些键来填充缓冲区。在我的系统上,我需要输入大约 70 个字符才能触发SYN_DROPPED。 EV_KEY 处理代码检查事件是否与EVIOCGKEY ioctl 报告的状态一致。