假设在等待从设备读取输入的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
}
答案 0 :(得分:2)
您可以使用libudev的通知功能:
http://www.signal11.us/oss/udev/
https://www.freedesktop.org/software/systemd/man/libudev.html
答案 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
}
我希望这会有所帮助。