OSA B18

 B18. Write a daemon process that monitors a directory and reports the changes in directory contents.(e.g. addition of new files, directory access times etc)


Program:


#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/types.h>
#include<linux/inotify.h>
#define EVENT_SIZE (sizeof (struct inotify_event))
#define EVENT_BUF_LEN (1024*(EVENT_SIZE+16))
int main()
{
        int length,i=0;
        int fd;
        int wd;
        char buffer[EVENT_BUF_LEN];


while(1)
{
        i=0;
        fd=inotify_init();

        if(fd<0)
        {
                perror("inotify_init");

 }

        wd=inotify_add_watch(fd,"/home/vivek/mydir",IN_CREATE|IN_DELETE|IN_MODIFY);

        length = read(fd,buffer,EVENT_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)
                        {
                if(event->mask & IN_ISDIR)
        {
        printf("new directory %s created.\n", event->name);
        }
else
        {
        printf("new file %s created.\n ", event->name);
        }
        }
        else if(event->mask & IN_DELETE)
{
if(event->mask & IN_ISDIR)

        {
        printf("directory %s deleted.\n",event->name);
        }
        else
        {
        printf("file %s deleted.\n",event->name);
        }
        }
        if(event->mask & IN_MODIFY)
        {
        if(event->mask & IN_ISDIR)
        {
        printf("directory %s modified.\n",event->name);
        }
 else
        {
        printf( "file %s modified.\n",event->name);
        }
        }
        }
        i += EVENT_SIZE + event->len;
        }
}
inotify_rm_watch(fd,wd);
close(fd);
}

0 comments:

Post a Comment