我试图在C中运行inotify的例子但是它不起作用.我想监视对文件的修改(文件是tmp.cfg),但它不起作用..我不知道我是否正确运行它,因为我了解如何监视目录,但不是一个file这是一个例子:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <unistd.h>
#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 < length ) {
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
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;
}
Run Code Online (Sandbox Code Playgroud)
一旦我运行它,如果我在文件上写了一些然后保存它,没有任何反应.我试过调试它..问题似乎是if(event-> mask&IN_MODIFY),因为它不认识它作为修改
你有2个问题。首先,据我所知,inotify 并不能真正处理文件——它需要目录名来观察。
其次,你错过了if (event->len) {while 循环。
此代码适用于我创建、删除和修改当前目录中的文件:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <unistd.h>
#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;
}
Run Code Online (Sandbox Code Playgroud)
它不适用于单个文件,因为当我们使用编辑器修改文件时,编辑器会打开文件的副本,当我们从文本编辑器保存编辑后的版本时,现有文件将被删除,并生成一个新文件通过修改创建相同的名称。
删除旧文件后,在该文件上创建的监视将失效并自动删除。
如果监视父目录,您可以看到旧文件被新文件替换。
有两种方法可以解决这个问题,监视父目录并在对您想要观看的特定内容进行修改时打印消息。
否则,每当进行修改时都会在文件上创建一个新的监视。当旧文件被删除时,会触发 IN_DELETE_SELF 事件。
仅当您监视目录时,event->name 才为非空,因为它将包含监视目录中发生事件的文件的名称。
我认为您没有使用您的用户名,这是您的主目录,并且您没有检查其返回inotify_add_watch可能会失败:
"/home/name/tmp.cfg"
Run Code Online (Sandbox Code Playgroud)
编辑:好的第二个问题,你不应该打印,name因为
仅当为监视目录中的文件返回事件时,名称字段才会出现;
Edit2:第三个问题,在运行程序之前该文件必须存在,因为您在文件上添加了监视,我建议您检查错误inotify_add_watch