-1

私は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 );
}
4

2 に答える 2

1

1 つのプログラムに 1 つの inotify_init だけが必要で、1 つのディレクトリに 1 つの inotify_add_watch だけが必要だと思います。あなたが言った「ループ外のinitとadd_watch」バー​​ジョンを貼り付けてください。

于 2011-12-04T23:11:43.840 に答える
0

私は inotify を使用したことがないので、これが間違っている可能性がありますが、コードを「改善」すると思われるいくつかの変更を次に示します。

  1. inotify_initまたはinotify_add_watchをループの中に入れる理由はないと思います。ループの前に、この初期化作業を 1 回だけ実行してください。

  2. なぜ関数を作成したのかわかりませんevent_check。タイムアウトを指定しておらず、単一のファイル記述子のみを使用しているため、 read でも同じ機能が得られると思います。

于 2010-08-02T16:09:50.630 に答える