c - 使用 inotify 优化程序

标签 c linux inotify

我通过inotify编写了一个程序来检查循环中的文件更改以获取对此的任何更改。 但我认为这可以做得更好。 有人能更好地编写这段代码吗?

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>
#include <sys/select.h>
#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )
int event_check (int fd)
{
  fd_set rfds;
  FD_ZERO (&rfds);
  FD_SET (fd, &rfds);
  /* Wait until an event happens or we get interrupted 
     by a signal that we catch */
  return select (FD_SETSIZE, &rfds, NULL, NULL, NULL);
  }

int main( )
{
  int length, i = 0;
  int fd;
  int wd;
while(1){
i=0;
  fd = inotify_init();

  if ( fd < 0 ) {
    perror( "inotify_init" );
  }

  wd = inotify_add_watch( fd, "/tmp/test", IN_CLOSE_WRITE);
    if (event_check (fd) > 0)
    {
        char buffer[EVENT_BUF_LEN];
        int count = 0;
        length = read( fd, buffer, EVENT_BUF_LEN ); 
        if ( length < 0 ) {
            perror( "read" );
          } 
         while ( i < length ) {     struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ]; 
            printf( "New file %s Editted.\n", event->name );
            i += EVENT_SIZE + event->len;
          }
    }
}
    inotify_rm_watch( fd, wd );
   close( fd );
}

最佳答案

我认为一个程序只需要一个inotify_init,一个目录只需要一个inotify_add_watch。 您能否粘贴您所说不起作用的“init 和 add_watch 外部循环”版本?

关于c - 使用 inotify 优化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3389114/

相关文章:

linux - C 程序使用 inotify 监视多个目录和子目录?

python - iNotify 收到事件后如何关闭文件句柄

c - C17 要我如何初始化我的原子?

c - OpenCV 傅立叶幅度 - 似乎不正确

c - 想知道此声明与代码中的注释相比有什么问题吗? - 初学者在这里

PHP odbc 驱动程序作为共享扩展

linux - 被动操作系统指纹更改为 MacOS

c - 嵌套结构的动态数组成员

linux - Bash脚本复制无名文件夹

c - 使用 inotify 检查监视文件夹中的文件是否被覆盖