文件操作拓展-inotify

1. 文件监控

man inotify - monitoring filesystem events

inotify提供了监控文件事件的机制,可监控单个文件或目录。当监控目录时,inotify会返回目录本身事件和目录内文件事件。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <assert.h>

int main(int argc, char *argv[])
{
    int ifd = -1;
    int wd = -1;
    int n = 0, total = 0, delta = 0;    
    char buf[1024];
    struct inotify_event *p;

    ifd = inotify_init();
    assert(ifd >= 0);

#ifndef DEBUG
    wd = inotify_add_watch(ifd, ".", IN_CREATE | IN_DELETE);
#else 
    wd = inotify_add_watch(ifd, "wang", IN_ALL_EVENTS);
#endif

    assert(wd >= 0);

    while(1){
        n = read(ifd, buf, 1024);
        p = (struct inotify_event *)buf;

        total = 0;
        while(total < n){
            if(p->mask == IN_CREATE){
                if(p->len != 0){
                    printf("%s create.\n", p->name);
                }
            } else if(p->mask == IN_DELETE){
                if(p->len != 0){
                    printf("%s delete.\n", p->name);
                }
            } else {
            
                printf("should not be here. =>%#x<=\n", p->mask);
            }
            
            delta = sizeof(struct inotify_event) + p->len;
            total += delta;
            p = (struct inotify_event *)((char *)p + delta);
        }
        printf("=============one read==========\n");
    }

    return 0;
}

 参考:linux 文件监控之 inotify

注:配置文件修改后通知应用加载(热加载)有两种方案:1)inotify监控配置文件的修改;2)基于信号实现,当配置修改后,kill信号到配置解析进程,重新解析配置文件。

 

posted @ 2015-12-14 20:57  yuxi_o  阅读(265)  评论(0编辑  收藏  举报