【问题标题】:using select() system call in event loop in Linux在 Linux 的事件循环中使用 select() 系统调用
【发布时间】:2014-06-29 07:15:06
【问题描述】:

我希望我的程序等待几秒钟以允许更改目录/文件,这样如果满足一个条件并执行代码,则事件循环保持打开状态以允许更多文件/目录更改,但我现在只在之后退出一个事件循环运行。我遇到了 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 select linux-kernel operating-system filesystems


【解决方案1】:

如果我理解正确,看起来您可以简单地将 read()while() 语句括在一个循环中。例如

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 2013-10-24
    • 2015-12-22
    相关资源
    最近更新 更多