inotify example

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

#include <time.h>
#include <fcntl.h>

static void
_inotify_event_handler(struct inotify_event *event ,int fd)
{

  const char* action = NULL;
  puts("***************handler event****************************/n");
  printf("event->mask: 0x%08x", event->mask);
  printf("/t/tevent->name: %s/n", event->name);

  if(event->mask & IN_ISDIR) 
    {
        if(event->mask & IN_DELETE)
        {
            printf("%s dir delete./n",event->name);
        }
        else if(event->mask & IN_CREATE)
        {
            printf("%s dir create./n",event->name);
            inotify_add_watch(fd, event->name, IN_ALL_EVENTS);
        }
        return ;
    }

  switch(event->mask)

    { 

        case IN_MODIFY:

        { 

            action = "IN_MODIFY";

            break;

        }

        case IN_CREATE:

        {

            action = "IN_CREATE";

            break;

        }

        case IN_DELETE:

        {

            action = "IN_DELETE";

            break;

        }

        case IN_MOVED_FROM:

        {

            action = "IN_MOVED_FROM";

            break;

        }

        case IN_MOVED_TO:

        {

            action = "IN_MOVED_TO";

            break;

        break;

        }

        default:break;

    }

    printf("/nevent->name=%s/t/taction=%s/n",event->name,action);
}

int
main(int argc, char **argv)
{
  if (argc != 2) {
    printf("Usage: %s <file/dir>/n", argv[0]);
    return -1;
  }

  int fd;
  int wd;
  struct timeval time;
  int ret;
  time.tv_sec = 10;
  time.tv_usec = 0;


  unsigned char buf[1024] = {0};
  struct inotify_event *event = {0};
   fd = inotify_init();
   wd = inotify_add_watch(fd, argv[1], IN_ALL_EVENTS);

  for (;;) {
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(fd, &fds);
    if ((ret=select(fd + 1, &fds, NULL, NULL, &time)) > 0) {
      int len, index = 0;
      while (((len = read(fd, &buf, sizeof(buf))) < 0) && (errno == EINTR));
      while (index < len) {
        event = (struct inotify_event *)(buf + index);
        _inotify_event_handler(event,fd);
        index += sizeof(struct inotify_event) + event->len;
      }
    }
 
    else if (!ret)
   { puts("time out/n");}

    else if(ret<0)
    {perror("select ");}
   
  }

  inotify_rm_watch(fd, wd);

  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值