Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4823694
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: LINUX

2009-12-29 12:09:40

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

 


 

阅读(1606) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~