2

我有监控目录(/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;
        }

    }

}
4

3 回答 3

4

inotify_add_watch不监听子目录的变化。您必须检测这些子目录的创建时间以及inotify_add_watch它们。

最需要注意的是,在创建子目录后,您会收到相应的通知,但在您收到通知时,文件和子目录可能已经在该目录中创建,因此您将“丢失“这些事件,因为您还没有机会为新的子目录添加手表。

避免此问题的一种方法是在收到通知后扫描目录内容,以便您可以看到其中的真实内容。这为为他们添加更多手表创造了机会。

于 2012-09-03T07:22:04.093 回答
0

您可以尝试删除子文件夹,而不是每次需要在其中添加内容时重新创建它。

于 2012-01-20T11:04:07.167 回答
0

在 inotify 中,每个目录都需要一个 watch。对于全局通知,有 fanotify 左右。

于 2012-01-18T11:05:42.953 回答