什么是更好的实现以下 - 民意调查,inotify或其他任何东西

时间:2018-02-06 11:49:25

标签: c linux polling inotify

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

有没有比使用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
}

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

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
}

我希望这会有所帮助。

相关问题