在C中使用inotify文件

我试图在C中运行inotify的例子但是它不起作用。 我想监视对文件的修改(文件是tmp.cfg),但它不起作用..我不知道我是否正确运行它,因为我理解如何监视目录,但不是一个file这是一个例子:

#include  #include  #include  #include  #include  #include  #define EVENT_SIZE ( sizeof (struct inotify_event) ) #define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) int main( int argc, char **argv ) { int length, i = 0; int fd; int wd; char buffer[BUF_LEN]; fd = inotify_init(); if ( fd < 0 ) { perror( "inotify_init" ); } wd = inotify_add_watch( fd, "/home/name/tmp.cfg", IN_MODIFY | IN_CREATE | IN_DELETE ); length = read( fd, buffer, BUF_LEN ); if ( length < 0 ) { perror( "read" ); } while ( i mask & IN_CREATE ) { printf( "The file %s was created.\n", event->name ); } else if ( event->mask & IN_DELETE ) { printf( "The file %s was deleted.\n", event->name ); } else if ( event->mask & IN_MODIFY ) { printf( "The file %s was modified.\n", event->name ); } i += EVENT_SIZE + event->len; } ( void ) inotify_rm_watch( fd, wd ); ( void ) close( fd ); return 0; } 

一旦我运行它,如果我在文件上写一些东西,然后保存它,没有任何反应。 我试过调试它..问题似乎是if(event-> mask&IN_MODIFY),因为它不认识它作为修改

你有2个问题。 首先,据我所知,inotify并不真正适用于文件 – 它需要目录名称才能观看。

第二,你错过if (event->len) { inside while循环。

此代码适用于创建,删除和修改当前目录中的文件:

 #include  #include  #include  #include  #include  #include  #define EVENT_SIZE (sizeof(struct inotify_event)) #define BUF_LEN (1024 * (EVENT_SIZE + 16)) int main(int argc, char **argv) { int length, i = 0; int fd; int wd; char buffer[BUF_LEN]; fd = inotify_init(); if (fd < 0) { perror("inotify_init"); } wd = inotify_add_watch(fd, ".", IN_MODIFY | IN_CREATE | IN_DELETE); length = read(fd, buffer, BUF_LEN); if (length < 0) { perror("read"); } while (i < length) { struct inotify_event *event = (struct inotify_event *) &buffer[i]; if (event->len) { if (event->mask & IN_CREATE) { printf("The file %s was created.\n", event->name); } else if (event->mask & IN_DELETE) { printf("The file %s was deleted.\n", event->name); } else if (event->mask & IN_MODIFY) { printf("The file %s was modified.\n", event->name); } } i += EVENT_SIZE + event->len; } (void) inotify_rm_watch(fd, wd); (void) close(fd); return 0; } 

我认为你没有使用你的用户名 ,这是你的主目录,你没有检查inotify_add_watch的返回可能会失败:

 "/home/name/tmp.cfg" 

编辑:好的第二个问题,你不应该打印name因为

名称字段仅在为监视目录内的文件返回事件时才出现;

Edit2:第三个问题,在你运行程序之前文件必须存在,因为你在文件上添加了一个监视器,我建议你从inotify_add_watch检查错误

在观看文件时,如果文件由编辑器操作,您可以编辑它并创建更改,则可能会执行一些操作,导致您要求观看的原始文件被删除。 因此,如果您只观看一个文件,通知将停止。

它不适用于单个文件,因为当我们使用编辑器修改文件时,编辑器会打开文件的副本,当我们从文本编辑器中保存编辑后的版本时,现有文件将被删除,并且新文件将被删除。使用修改创建相同的名称。

删除旧文件后,在该文件上创建的监视将变为无效,并自动删除。

如果监视父目录,则可以看到旧文件被新文件替换。

有两种方法可以解决它,监视父目录并在对要监视的特定内容进行修改时打印消息。

否则,只要进行修改,就会在文件上创建一个新手表。 删除旧文件时​​,将触发IN_DELETE_SELF事件。

event-> name仅在您查看目录时才为非空,因为它将包含在监视目录中发生事件的文件的名称。