Linux系统编程之获取/dev/input目录下的event对应的键盘设备

我们在Linux操作系统下使用input子系统时,键盘会有一个对应的/dev/input/event接口。可以通过ioctl函数来读取键盘设备名,因为每一个设备名是固定的,再根据设备名区分event。我的系统是Fedora 32,共有20个event接口,如下:

[root@fedora Workspace]# ls /dev/input/event*
/dev/input/event0   /dev/input/event15  /dev/input/event4
/dev/input/event1   /dev/input/event16  /dev/input/event5
/dev/input/event10  /dev/input/event17  /dev/input/event6
/dev/input/event11  /dev/input/event18  /dev/input/event7
/dev/input/event12  /dev/input/event19  /dev/input/event8
/dev/input/event13  /dev/input/event2   /dev/input/event9
/dev/input/event14  /dev/input/event3

下面就用键盘设备名,查找其对应的event接口。代码如下:

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

int main(void)
{
	int i, fd;
	char path[BUFSIZ], buf[BUFSIZ];

	for (i = 0; i < 20; i++)
	{
		sprintf(path, "/dev/input/event%d", i);
		
		if ((fd = open(path, O_RDONLY)) < 0)
		{
			perror("open");
			exit(1);
		}

		ioctl(fd, EVIOCGNAME(sizeof(buf)), buf);

		if(strstr(buf, "keyboard"))
		{
			printf("File Path: %s\n", path);
			printf("Dev Name: %s\n", buf);
		}
		
		close(fd);
        }

    return 0;
}

运行结果如下:

[root@fedora Workspace]# gcc -o demo demo.c
[root@fedora Workspace]# ./demo
File Path: /dev/input/event4
Dev Name: AT Translated Set 2 keyboard

Leave a Reply

Your email address will not be published. Required fields are marked *