C程序使用inotify监视多个目录以及子目录?

时间:2010-01-19 04:53:27

标签: linux inotify

我有监控目录(/ test)的程序并通知我。 我想改进它来监视另一个目录(比如说/ opt)。 以及如何监控它的子目录,如果对/ test下的文件进行任何更改,当前我将收到通知。但是如果更改了/ test的子目录,那就是触摸/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;
        }

    }

}

3 个答案:

答案 0 :(得分:4)

inotify_add_watch不会监听子目录中的更改。您必须检测何时创建这些子目录,以及inotify_add_watch它们。

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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