【问题标题】:what is better to achieve the below - poll, inotify or anything else什么是更好的实现以下 - poll,inotify 或其他任何东西
【发布时间】:2018-02-06 11:49:25
【问题描述】:

假设下面的代码在等待从设备读取输入的 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
}

【问题讨论】:

  • 你真的应该检查 what 错误open 有。这可能是无法真正恢复的东西。
  • 至少,您应该睡眠一段时间,以防止 CPU 使用率过高(而不是内存)。
  • @Aconcagua,谢谢你纠正我。也很想知道在睡眠到位的情况下幕后会发生什么。任何指向它的指针都表示赞赏。
  • @shwink 粗略地 描述:拥有比 CPU 内核更多的线程,当然,线程需要共享内核。所以操作系统在它们之间切换,为它们中的每一个分配一定的时间,它可以使用特定的 CPU,然后让其他线程再次运行,而前一个线程必须等待再次轮到它。这称为调度。在休眠时间过去之前,不会考虑调度休眠线程......因此,休眠线程也不会消耗 CPU 资源(除了调度程序检查它是否再次可用)。

标签: c linux polling inotify


【解决方案1】:
【解决方案2】:
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
}

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-06
    • 2012-08-27
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多