我正在为一个游戏库创建一个 Linux 模块,它可以让你热插拔多个游戏杆,它使用 inotify 来观看/dev/input
.
我正在用 3 个操纵杆对其进行测试:
- 首先,我连接了 2 个操纵杆。
- 然后我启动应用程序,操纵杆工作,我没有收到错误。
- 之后我连接第三个操纵杆,
perror
给出:/dev/input/js1: Permission denied
。 - 当我检查
ls -l /proc/<pid-of-process>/fd
它列出/dev/input/js0
和/dev/input/js2
.
当我以 root 身份运行时,所有的操纵杆都可以正常工作。
这是它的初始化方式:
static void createGamepad(char *locName){
char dirName[30];
int fd;
snprintf(dirName, 30, "/dev/input/%s", locName);
fd = open(dirName, O_RDONLY | O_NONBLOCK, 0);
if(fd < 0){
perror(dirName);
}
}
struct dirent *dir;
DIR *d;
int i, notifyfd, watch;
// Attach notifications to check if a device connects/disconnects
notifyfd = inotify_init();
watch = inotify_add_watch(notifyfd, "/dev/input", IN_CREATE | IN_DELETE);
d = opendir("/dev/input");
i = 0;
while((dir = readdir(d)) != NULL){
if(*dir->d_name == 'j' && *(dir->d_name + 1) == 's'){
createGamepad(dir->d_name, i);
i++;
}
}
closedir(d);
之后 inotify 在while(1)
循环中像这样处理它:
static bool canReadINotify(){
fd_set set;
struct timeval timeout;
FD_ZERO(&set);
FD_SET(notifyfd, &set);
timeout.tv_sec = 0;
timeout.tv_usec = 0;
return select(notifyfd + 1, &set, NULL, NULL, &timeout) > 0 &&
FD_ISSET(notifyfd, &set);
}
// Inside the event loop
struct inotify_event ne;
while(canReadINotify()){
if(read(notifyfd, &ne, sizeof(struct inotify_event) + 16) >= 0){
if(*ne.name != 'j' || *(ne.name + 1) != 's'){
continue;
}
if(ne.mask & IN_CREATE){
createGamepad(ne.name);
}
}
}
甚至可以使用 inotify 还是应该使用 udev?如果可能的话,我该如何解决这个问题?