linux系统调用read读取event键盘输入。

#include<string.h>
#include<fcntl.h>
#include<linux/input.h>
#include<unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#define CHECK_POINT
int main(){
        int fd = open("/dev/input/event2",O_RDONLY);
        #ifdef CHECK_POINT
        printf("fd = %d\n",fd);
        #endif
        struct input_event t;
        printf("size of t = %d\n",sizeof(t));
        while(1)
        {
                printf("while -\n");
                sleep(1);
                int len = read(fd, &t, sizeof(t));
                if(len == sizeof(t))
                {
                        printf("read over\n");
                        if(t.type==EV_KEY)
                                if(t.value==0 || t.value==1)
                                {
                                        printf("key %d %s\n", t.code, (t.value) ? "Pressed" : "Released");
                                        if(t.code == KEY_ESC)
                                                break;
                              }
                }
                #ifdef CHECK_POINT
                printf("len = %d\n",len);
                #endif
        }
        return 0;
}

我的代码在第20行,系统调用read()这里会阻塞,但是我按下键盘按键也没有任何反应,没有读取到键盘按键。只能ctrl+c退出程序。请大佬指点。

阅读 4.2k
1 个回答

键盘设备不一定关联到/dev/input/event2
得看看cat /proc/bus/input/devices

I: Bus=0011 Vendor=0001 Product=0001 Version=ab41
N: Name="AT Translated Set 2 keyboard"
P: Phys=isa0060/serio0/input0
S: Sysfs=/devices/platform/i8042/serio0/input/input1
int fd = open("/dev/input/event1",O_RDONLY);
    if(fd < 0){
        perror("open event fail:");
        return -1;
    }

    struct input_event t;
    while(1){
        if(read(fd, &t, sizeof(t)) == sizeof(t)){

            if(t.type==EV_KEY && (t.value==0 || t.value==1)){

                printf("key %d %s\n", t.code, (t.value) ? "Pressed" : "Released");
                if(t.code == KEY_ESC)
                    break;
            }
        }

    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题