我有一个监视目录(
/test
)并通知我的程序。
我想改进它以监视另一个目录(比如/opt)。
以及如何监控它的子目录,目前我会收到对 /test
下的文件所做的任何更改的通知。但是如果在 /test
的子目录中进行更改,我不会收到任何通知,例如:
touch /test/sub-dir/files.txt
这是我当前的代码 - 希望这会有所帮助
/*
Simple example for inotify in Linux.
inotify has 3 main functions.
inotify_init1 to initialize
inotify_add_watch to add monitor
then inotify_??_watch to rm monitor.you the what to replace with ??.
yes third one is inotify_rm_watch()
*/
#include <sys/inotify.h>
int main(){
int fd,wd,wd1,i=0,len=0;
char pathname[100],buf[1024];
struct inotify_event *event;
fd=inotify_init1(IN_NONBLOCK);
/* watch /test directory for any activity and report it back to me */
wd=inotify_add_watch(fd,"/test",IN_ALL_EVENTS);
while(1){
//read 1024 bytes of events from fd into buf
i=0;
len=read(fd,buf,1024);
while(i<len){
event=(struct inotify_event *) &buf[i];
/* check for changes */
if(event->mask & IN_OPEN)
printf("%s :was opened\n",event->name);
if(event->mask & IN_MODIFY)
printf("%s : modified\n",event->name);
if(event->mask & IN_ATTRIB)
printf("%s :meta data changed\n",event->name);
if(event->mask & IN_ACCESS)
printf("%s :was read\n",event->name);
if(event->mask & IN_CLOSE_WRITE)
printf("%s :file opened for writing was closed\n",event->name);
if(event->mask & IN_CLOSE_NOWRITE)
printf("%s :file opened not for writing was closed\n",event->name);
if(event->mask & IN_DELETE_SELF)
printf("%s :deleted\n",event->name);
if(event->mask & IN_DELETE)
printf("%s :deleted\n",event->name);
/* update index to start of next event */
i+=sizeof(struct inotify_event)+event->len;
}
}
}
inotify_add_watch
不监听子目录的变化。您必须检测何时创建这些子目录,以及inotify_add_watch
它们。
最需要注意的是,创建子目录后,您会得到相应的通知,但在您收到通知时,可能已经在该子目录中创建了文件和子目录,因此您将“丢失”这些事件,因为您还没有机会为新的子目录添加监视。
避免这个问题的一种方法是在收到通知后扫描目录内容,这样你就可以看到里面到底有什么。这创造了为他们添加更多手表的机会。
在 inotify 中,每个目录需要一个 watch。全局通知,有fanotify之类的
您可以尝试删除子文件夹,而不是每次需要在其中添加内容时重新创建它。