码迷,mamicode.com
首页 > 其他好文 > 详细

inotify和epoll

时间:2019-03-18 11:52:00      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:could   sys   main   watch   result   roc   span   pre   create   

参考EventHub.cpp

1、初始化inotify

int mINotifyFd = inotify_init();

2、将要监测的目录添加到inotify

int result = inotify_add_watch(mINotifyFd, argv[1], IN_DELETE | IN_CREATE);

3、读inotify有没有event

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

int read_process_inotify_fd(int fd)
{
    int res;
    char event_buf[512];
    int event_size;
    int event_pos = 0;
    struct inotify_event *event;
      res = read(fd, event_buf, sizeof(event_buf));
      if(res < (int)sizeof(*event)) {
              if(errno == EINTR)
                  return 0;
              printf("could not get event, %s\n", strerror(errno));
              return -1;
      }
      while(res >= (int)sizeof(*event)) {
        event = (struct inotify_event *)(event_buf + event_pos);
        //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
        if(event->len) {
           
            if(event->mask & IN_CREATE) {
                printf("create file: %s\n", event->name);
            } else {
                printf("delete file: %s\n", event->name);
            }
        }
        event_size = sizeof(*event) + event->len;
        res -= event_size;
        event_pos += event_size;
    }
    return 0;
      
}

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

    int mINotifyFd = inotify_init();
    int result = inotify_add_watch(mINotifyFd, argv[1], IN_DELETE | IN_CREATE);
    if (result < 0) {
        printf("inotify_add_watch error\n");
        return -1;
    }
    while (1) {
         ret = read_process_inotify_fd(mINotifyFd);
         if (ret) {
             printf("read_process_inotify_fd error\n");
             return -1;
         }
    }

    return 0;
}

 

inotify和epoll

标签:could   sys   main   watch   result   roc   span   pre   create   

原文地址:https://www.cnblogs.com/zhu-g5may/p/10551055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!