C program using inotify to monitor multiple directories along with sub-directories?

Posted by lakshmipathi on Stack Overflow See other posts from Stack Overflow or by lakshmipathi
Published on 2010-01-19T04:53:26Z Indexed on 2010/03/19 18:01 UTC
Read the original article Hit count: 247

Filed under:
|

I have program which monitors a directory (/test) and notify me. I want to improve this to monitor another directory (say /opt). And also how to monitor it's subdirectories , current i'll get notified if any changes made to files under /test . but i'm not getting any inotifcation if changes made sub-directory of /test, that is touch /test/sub-dir/files.txt ..

Here my current code - hope this will help

/*

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;
        }

    }

}

© Stack Overflow or respective owner

Related posts about linux

Related posts about inotify