【问题标题】:optimize a program with inotify使用 inotify 优化程序
【发布时间】:2010-08-02 15:17:07
【问题描述】:

我通过 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 );
}

【问题讨论】:

  • 当你说你希望代码更好时,你能定义你的意思吗?在哪些方面更好?
  • 我能写得更好吗?极有可能。你有什么特别想要的吗?
  • 只需正确地重新缩进代码就会让它“更好”。

标签: c linux inotify


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我从未使用过 inotify,因此这可能是错误的,但我认为这里有一些更改可能会“改进”您的代码。

    1. 我认为没有任何理由将inotify_initinotify_add_watch 放入循环中。只需在循环之前执行一次初始化工作。

    2. 我不确定您为什么要创建 event_check 函数。你没有指定超时,你只使用一个文件描述符,所以我认为 read 会给你同样的功能。

    【讨论】:

    • 还要去掉select中的FD_SETSIZE。
    猜你喜欢
    • 2012-02-05
    • 1970-01-01
    • 2015-07-05
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多