inotify实例

1604阅读 0评论2009-12-29 ubuntuer
分类:LINUX

#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <sys/inotify.h>

typedef struct wd_name {
    int wd;
    char * name;
}WD;

#define MONITOR_NUM 3
char* files[MONITOR_NUM] = {
    "./a",
    "./b",
    "./c"
};

WD wd_array[MONITOR_NUM];

static void inotify_event_handler(struct inotify_event *event)
{
    int i = 0;
    if (event->mask & IN_ISDIR)
     printf("Object type: %s\n", "Direcotory");
    else
    printf("Object type: %s\n", "file");
    
    for (i=0; i<MONITOR_NUM; i++)
     {
        if (event->wd != wd_array[i].wd)
            continue;
        printf("Object name: %s\n", wd_array[i].name);
        break;
     }
    
     if ( event->mask & IN_CREATE )
         {
     if ( event->mask & IN_ISDIR )
      printf( "The directory %s was created.\n", event->name );
     else
      printf( "The file %s was created.\n", event->name );
    }
   else if ( event->mask & IN_DELETE )
    {
     if ( event->mask & IN_ISDIR )
       printf( "The directory %s was deleted.\n", event->name );
     else
       printf( "The file %s was deleted.\n", event->name );
    }
   else if ( event->mask & IN_MODIFY )
       {
     if ( event->mask & IN_ISDIR )
       printf( "The directory %s was modified.\n", event->name );
     else
       printf( "The file %s was modified.\n", event->name );
    }
}

int main(int argc, char **argv)
{
 int fd = 0;
 int wd = 0;
 int i = 0;
 int len = 0;
 int index = 0;
    
 unsigned char buf[1024] = {0};
 struct inotify_event *event = {0};
 
 fd = inotify_init();
 if (fd < 0) {
        printf("Fail to initialize inotify.\n");
        return -1;
    }
    
 for (i=0; i<MONITOR_NUM; i++) {
        wd_array[i].name = files[i];
        wd = inotify_add_watch(fd, wd_array[i].name, IN_CREATE | IN_MODIFY | IN_DELETE);
        if (wd < 0) {
            printf("Can't add watch for %s.\n", wd_array[i].name);
            return -1;
        }
        wd_array[i].wd = wd;
    }
    
 
 for (;;)
 {
     index = 0;
     len = 0;
     while (((len = read(fd, &buf, sizeof(buf))) < 0) && (errno == EINTR));
  
  while (index < len)
          {
              event = (struct inotify_event *)(buf + index);
              inotify_event_handler(event);
              index += sizeof(struct inotify_event) + event->len;
          }
     }    
  
 
 for (i=0; i<MONITOR_NUM; i++)
     inotify_rm_watch(fd, wd_array[i].wd);

 close(fd);
 
 return 0;
}

 


 

上一篇:Linux 信号signal处理机制包括定时器
下一篇:内核模块遍历进程--内核PS