在 Linux 的事件循环中使用 select() 系统调用

问题描述 投票:0回答:1

我希望我的程序等待几秒钟以允许目录/文件更改,这样如果满足一个条件并且执行代码,事件循环保持打开状态以允许更多文件/目录更改,但我现在只在一个事件后退出循环运行。我遇到了 select() 系统调用,但我不知道如何插入到我的程序中以实现我的目标,

下面是我在 http://www.thegeekstuff.com/2010/04/inotify-c-program-example/ 上找到的一段代码,可能有助于说明我想要做的事情(我的 while 循环比这里的它看起来不会难看)

/*This is the sample program to notify us for the file creation and file deletion takes place in “/tmp” directory*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

int main( )
{
  int length, i = 0;
  int fd;
  int wd;
  char buffer[EVENT_BUF_LEN];

  /*creating the INOTIFY instance*/
  fd = inotify_init();

  /*checking for error*/
  if ( fd < 0 ) {
    perror( "inotify_init" );
  }

  /*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/
  wd = inotify_add_watch( fd, "/tmp/foo", IN_CREATE | IN_DELETE );

  /*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/ 

  length = read( fd, buffer, EVENT_BUF_LEN ); 

  /*checking for error*/
  if ( length < 0 ) {
    perror( "read" );
  }  
  /*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/
  while ( i < length ) {
    struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
     if ( event->len ) {
      if ( event->mask & IN_CREATE ) {
        if ( event->mask & IN_ISDIR ) {
          printf( "New directory %s created.\n", event->name );
        }
        else {
          printf( "New file %s created.\n", event->name );
        }
      }
      else if ( event->mask & IN_DELETE ) {
        if ( event->mask & IN_ISDIR ) {
          printf( "Directory %s deleted.\n", event->name );
        }
        else {
          printf( "File %s deleted.\n", event->name );
        }
      }
    }
    i += EVENT_SIZE + event->len;
  }
  /*removing the “/tmp” directory from the watch list.*/
   inotify_rm_watch( fd, wd );

  /*closing the INOTIFY instance*/
   close( fd );

}
c linux-kernel operating-system filesystems posix-select
1个回答
0
投票

如果我理解正确,看起来您可以简单地将

read()
while()
语句放在循环中。例如

while ((length = read(...)) >= 0) {
    while (i < length) {
        ...
    }
}

read()
将阻塞,直到有可用的东西为止。

© www.soinside.com 2019 - 2024. All rights reserved.