当然需要使用 select函数。
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(void)
{
int kbd_fd = open("/dev/input/event3", O_RDONLY);
if(kbd_fd < 0)
{
printf("fail to open file. error: %s\n", strerror(errno));
return -1;
}
fd_set rset;
FD_ZERO(&rset);
FD_SET(kbd_fd, &rset);
int count = 0;
while(1)
{
if( select(kbd_fd + 1, &rset, NULL, NULL, NULL) == -1)
{
printf("error occurs\n");
}
else if(FD_ISSET(kbd_fd, &rset))
{
char buf[100];
read(kbd_fd, buf, 100);
printf("there is key input:%d\n", count++);
}
}
return 0;
input event后面的数字可能随不通的系统不通类型的设备而不同。
可以通过下面的命令查看对应的设备类型:
$ cat /proc/bus/input/devices | grep -A 7 -B 2 keyboard
I: Bus=0011 Vendor=0001 Product=0001 Version=ab54
N: Name="AT Translated Set 2 keyboard"
P: Phys=isa0060/serio0/input0
S: Sysfs=/devices/platform/i8042/serio0/input/input3
U: Uniq=
H: Handlers=sysrq kbd event3 leds
B: PROP=0
B: EV=120013
B: KEY=4 2000000 3803078 f800d001 feffffdf ffefffff ffffffff fffffffe
$ ls /dev/input/by-path/ -l | grep kbd
lrwxrwxrwx 1 root root 9 Nov 30 22:34 platform-i8042-serio-0-event-kbd -> ../event3