使用input.h Linux无法生成写入设备内核的击键

时间:2014-09-27 11:34:26

标签: linux kernel linux-device-driver keystroke

我正在尝试生成击键并使用输入库将它们写入Linux中的内核。我找到了一个示例表单http://rico-studio.com/linux/read-and-write-to-a-keyboard-device/并制作了一个小测试程序。它应该只打印一堆t,但只有当我自己敲击一个键(例如空格)时才这样做。

#include <linux/input.h>
#include <linux/uinput.h>

#include <fcntl.h>
#include <string.h>

#include <stdio.h>
#include <unistd.h>

#define EV_PRESSED 1
#define EV_RELEASED 0
#define EV_REPEAT 2



int main() {

    int fd = 0;

    /*In my case event3 handles the keyboard. This can be checked typing     
     *   cat /proc/bus/input/devices in the terminal
     */
    char *device = "/dev/input/event3";

    struct input_event event;

    memset(&event, 0, sizeof(event));

    gettimeofday(&event.time, NULL);
    if( (fd = open(device,  O_RDWR |  O_NONBLOCK )) < 0 )
    {
        printf("not opened "); // Read or Write to device
        return 0;
    }

    for(int i=0;i <500 ;i++)
    {
//      usleep(1000);
        event.type = EV_KEY;
        // Press the key down
        event.value = EV_PRESSED;
        event.code = KEY_T;

        write(fd, &event, sizeof(struct input_event));
//      usleep(1000);

        // Release the key
        event.value = EV_RELEASED;
        event.code = KEY_T;
        write(fd, &event, sizeof(struct input_event));
        usleep(100000);

    }
    close(fd);

    return 0;
}

也许这个按键可以刷新内存以及写入设备内存的t生成的按键?所以我想知道我错过了什么让它产生一个击键并将其全部写入内核。

1 个答案:

答案 0 :(得分:1)

如果您运行xxd /dev/input3并拆分输出,则可以看到键盘在每次更改密钥后也发送EV_SYNSYN_REPORT个事件以标记分组集的结尾事件。要做同样的事情:

event.type = EV_SYN;
event.code = SYN_REPORT;
event.value = 0;
write(fd, &event, sizeof(struct input_event));