linux uinput:简单的例子?

时间:2014-11-01 21:11:12

标签: linux uinput

使用uinput工作时,我在使用两个方面遇到了一些问题。

基于Getting started with uinput: the user level input subsystem [死链接; archived] 我将以下编写器放在一起(减去错误处理):

int main(int ac, char **av)
{
    int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
    int ret = ioctl(fd, UI_SET_EVBIT, EV_ABS);
    ret = ioctl(fd, UI_SET_ABSBIT, ABS_X);

    struct uinput_user_dev uidev = {0};
    snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "uinput-rotary");
    uidev.absmin[ABS_X] = 0;
    uidev.absmax[ABS_X] = 255;
    ret = write(fd, &uidev, sizeof(uidev));
    ret = ioctl(fd, UI_DEV_CREATE);

    struct input_event ev = {0};
    ev.type = EV_ABS;
    ev.code = ABS_X;
    ev.value = 42;

    ret = write(fd, &ev, sizeof(ev));

    getchar();

    ret = ioctl(fd, UI_DEV_DESTROY);
    return EXIT_SUCCESS;
}

这似乎有效,至少似乎写了完整的input_event结构。

然后我写了最天真的读者我可以提出的事件:

int main(int ac, char **av)
{
    int fd = open(av[1], O_RDONLY);

    char name[256] = "unknown";
    ioctl(fd, EVIOCGNAME(sizeof(name)), name);
    printf("reading from %s\n", name);

    struct input_event ev = {0};
    int ret = read(fd, &ev, sizeof(ev));
    printf("Read an event! %i\n", ret);
    printf("ev.time.tv_sec: %li\n", ev.time.tv_sec);
    printf("ev.time.tv_usec: %li\n", ev.time.tv_usec);
    printf("ev.type: %hi\n", ev.type);
    printf("ev.code: %hi\n", ev.code);
    printf("ev.value: %li\n", ev.value);

    return EXIT_SUCCESS;
}

不幸的是,读者方根本不起作用;每次只能设法读取8个字节,这几乎不是一个完整的input_event结构。

我犯了什么愚蠢的错误?

1 个答案:

答案 0 :(得分:5)

您还应该在实际事件之后编写同步事件。在你的作家方代码中:

struct input_event ev = {0};
ev.type = EV_ABS;
ev.code = ABS_X;
ev.value = 42;

usleep(1500);

memset(&ev, 0, sizeof(ev));
ev.type = EV_SYN;
ev.code = 0;
ev.value = 0;

ret = write(fd, &ev, sizeof(ev));

getchar();