已編寫 USB 鼠標驅動,通過 Input 子系統上報事件,hexdump /dev/input/eventX 驗證正常。現需編寫應用程序讀取該事件流。
Linux 中 Input 事件設備即字符設備文件(/dev/input/event*),應用層可直接 open()、read() 獲取 struct input_event 結構體數組。
#include <linux/input.h>
#include <fcntl.h>
#include <unistd.h>
int fd = open("/dev/input/event2", O_RDONLY);
struct input_event ev;
while (read(fd, &ev, sizeof(ev)) == sizeof(ev)) {
if (ev.type == EV_REL) { // 相對移動
if (ev.code == REL_X) printf("X: %d\n", ev.value);
if (ev.code == REL_Y) printf("Y: %d\n", ev.value);
} else if (ev.type == EV_KEY) { // 按鍵
printf("Btn %d %s\n", ev.code, ev.value ? "down" : "up");
}
}
close(fd);
libevdev 等封裝庫簡化解析。