为什么`ioctl(fd,EVIOCGRAB,1)`有时会导致关键垃圾邮件? [英] Why does `ioctl(fd, EVIOCGRAB, 1)` cause key spam sometimes?

查看:258
本文介绍了为什么`ioctl(fd,EVIOCGRAB,1)`有时会导致关键垃圾邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写自己的键盘驱动程序"(实际上并未编写内核模块), 通过抓住我认为是用户界面中最低的抽象级别的键盘:/dev/input/event*.

I'm trying to write my own "keyboard driver" (without actually writing a kernel module), by grabbing the keyboard at what I assume is the lowest level of abstraction in userland: /dev/input/event*.

如果您更改ioctl(fd, EVIOCGRAB, UNGRAB)的第一次出现,以下代码将进行抓取 到ioctl(fd, EVIOCGRAB, GRAB).

The following code does the grabbing, provided you change the first ocurrence of ioctl(fd, EVIOCGRAB, UNGRAB) to ioctl(fd, EVIOCGRAB, GRAB).

// gcc main.c -o main

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <linux/input.h>
#include <fcntl.h>
#include <errno.h>

#define EXIT_KEY  KEY_ESC
#define UNGRAB    0
#define GRAB      1

const char* kbd_device = "/dev/input/event4";

// ------------------------------------------------------------------------------------------------
int main(void){
  int fd = open(kbd_device, O_RDONLY);
  if(fd == -1){
    printf("Cannot open %s. %s.\n", kbd_device, strerror(errno));
    return -1;
  }

  if(ioctl(fd, EVIOCGRAB, UNGRAB))
    printf("Couldn't grab %s. %s.\n", kbd_device, strerror(errno));
  else
    printf("Grabbed %s!\n", kbd_device);

  while(1){
    struct input_event event;
    read(fd, &event, sizeof(event));
    if (event.type == EV_KEY && event.value >= 0 && event.value <= 2){
      printf("%d %3d\n", event.value, event.code);

      if(event.code == EXIT_KEY){
        ioctl(fd, EVIOCGRAB, UNGRAB);
        close(fd);
        return 0;
      }

    }
  }
}

问题

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆