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 回答