C-最好实现下面的民意调查,挖掘或其他任何事情



假设以下代码在等待从设备读取输入的pthread中调用,但是该设备本身最初在启动期间不可用,并通过USB端口插入[SAS SAS键盘]。

有比使用do..while更好的等待方法吗?我看到do..while CPU利用率很高,直到获取文件描述符为止。

#define DEV "/dev/input/event2"
int fd; 
fd = open(DEV, O_RDONLY);
if (fd == -1) {
    fprintf(stderr, "Cannot open %s: %s.n", dev, strerror(errno));
    //return EXIT_FAILURE;
    do{     
        fd = open(dev, O_RDONLY);
    }       
    while(fd < 0);
}
while (1)
{
    //Logic to read from say keyboard device
}

您可以使用libudev的通知功能:

http://www.signal11.us/oss/udev/

https://www.freedesktop.org/software/systemd/man/libudev.html

You can use inotify as:
Create inotify object: 
    fd=inotify_init();
Add your path in watcher list:
    inotify_add_watch(fd,<YOUR_PATH>, IN_CREATE | IN_DELETE)<0)
Continuously watch in infinite loop and use select for timeout and wait  for event  on fd.
    ret = pselect(fd+1, &fds, NULL, NULL, &tv, NULL);
When the event will occur, read the event.
    rsize = read(fd, buf, BUF_LEN);
    event=(struct inotify_event *)buf;
Check for event:
if((event->mask & IN_CREATE)){
    //USB added
}else if((event->mask & IN_DELETE)){
    //USB deleted
}

我希望这有所帮助。

相关内容

  • 没有找到相关文章

最新更新