2

ディレクトリの変更をリッスンするコードがあります。実行すると、ファイルに何も書き込まれず、端末にも表示されません。

特定のテキストファイルで変更が行われるのを聞くのを手伝ってもらえますか? タイムスタンプとどのような変更が行われたかを保存したい。

コードは次のとおりです。

/*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];
  char str[] = "This is tutorialspoint.com";
  FILE* fp=NULL;;
  fp=fopen("f1.txt","rw+");

  /*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", 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.1\n", event->name );
      fwrite(str , 1 , sizeof(str) , fd );
        }
        else {
          printf( "New file %s created.\n2", event->name );
      fwrite(str , 1 , sizeof(str) , fd );
        }
      }
      else if ( event->mask & IN_DELETE ) {
        if ( event->mask & IN_ISDIR ) {
          fwrite(str , 1 , sizeof(str) , fd );
          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 );
   fclose(fd);
  /*closing the INOTIFY instance*/
   close( fd );

}
4

1 に答える 1

1

私の推測では、それは単にread呼び出しをブロックするだけです。その上のコメントから:

実際には、この読み取りは変更イベントが発生するまでブロックされます

待っているイベントが発生していないだけで、発生するreadまでこの呼び出しはブロックされます。

このプログラムをある端末で実行し、別の端末で実行することをお勧めします。

$ touch /tmp/foo
于 2013-05-24T17:49:58.927 に答える