dnotify监控文件行为

来源:互联网 发布:adidas跑鞋系列 知乎 编辑:程序博客网 时间:2024/06/07 23:28
 #include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <sys/inotify.h>

static void   _inotify_event_handler(struct inotify_event *event)      //从buf中取出一个事件。
{
    printf("event->mask: 0x%08x\n", event->mask);
    printf("event->name: %s\n", event->name);
}

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

    unsigned char buf[1024] = {0};
    struct inotify_event *event = NULL;


    int fd = inotify_init();                 //初始化监视器
    int wd = inotify_add_watch(fd, argv[1], IN_ALL_EVENTS);                  //监控指定文件的ALL_EVENTS。

    for (;;)

    {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        if (select(fd + 1, &fds, NULL, NULL, NULL) > 0)                //监控fd的事件。当有事件发生时,返回值>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);                                             //获取事件。
                index += sizeof(struct inotify_event) + event->len;             //移动index指向下一个事件。
            }
        }
    }

    inotify_rm_watch(fd, wd);              //删除对指定文件的监控。

    return 0;
}

0 0
原创粉丝点击