微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的代码无法使用uinput创建简单的输入设备?

如何解决为什么我的代码无法使用uinput创建简单的输入设备?

我正在尝试学习在Linux中使用 / dev / uinput ,并从 kernel.org/doc/html/v4.12/input/uinput.html 复制了简单的代码>如下:

#include <linux/uinput.h>

void emit(int fd,int type,int code,int val)
{
   struct input_event ie;

   ie.type = type;
   ie.code = code;
   ie.value = val;
   /* timestamp values below are ignored */
   ie.time.tv_sec = 0;
   ie.time.tv_usec = 0;

   write(fd,&ie,sizeof(ie));
}

int main(void)
{
   struct uinput_setup usetup;

   int fd = open("/dev/uinput",O_WRONLY | O_NONBLOCK);


   /*
    * The ioctls below will enable the device that is about to be
    * created,to pass key events,in this case the space key.
    */
   ioctl(fd,UI_SET_EVBIT,EV_KEY);
   ioctl(fd,UI_SET_KEYBIT,KEY_SPACE);

   memset(&usetup,sizeof(usetup));
   usetup.id.bustype = BUS_USB;
   usetup.id.vendor = 0x1234; /* sample vendor */
   usetup.id.product = 0x5678; /* sample product */
   strcpy(usetup.name,"Example device");

   ioctl(fd,UI_DEV_SETUP,&usetup);
   ioctl(fd,UI_DEV_CREATE);

   /*
    * On UI_DEV_CREATE the kernel will create the device node for this
    * device. We are inserting a pause here so that userspace has time
    * to detect,initialize the new device,and can start listening to
    * the event,otherwise it will not notice the event we are about
    * to send. This pause is only needed in our example code!
    */
   sleep(1);

   /* Key press,report the event,send key release,and report again */
   emit(fd,EV_KEY,KEY_SPACE,1);
   emit(fd,EV_SYN,SYN_REPORT,0);
   emit(fd,0);

   /*
    * Give userspace some time to read the events before we destroy the
    * device with UI_DEV_DESTOY.
    */
   sleep(1);

   //ioctl(fd,UI_DEV_DESTROY);
   close(fd);

   return 0;
}

它可以编译并成功运行而没有错误。但是我在终端中找不到使用此命令xinput创建的任何设备。我还检查了 / dev / input / 的内部内容,但执行该程序后未发现任何更改。

我在Kali的Ubuntu上尝试过。我想念的是什么?

解决方法

也许可以帮助别人。

int i=0;
while(i<100){
i++;
sleep(1);
   emit(fd,EV_KEY,KEY_SPACE,1);
   emit(fd,EV_SYN,SYN_REPORT,0);
   emit(fd,0);
}

我发现在循环程序时会创建设备。在此期间,您可以使用xinput命令进行检查。程序结束后,即使我不调用ioctl(fd,UI_DEV_DESTROY),设备也会被破坏。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。