linux下文件或目录被访问等事件监听

linux系统下文件或目录事件监听,如一个文件被创建、修改、被访问、移动等事件,要想捕捉到这些事件。就可以借助于linux下inotify功能。这个是在linux内核里面的函数。

下面是一个示例。

#include <stdio .h>
#include <stdlib .h>
#include <sys /types.h>
#include <linux /inotify.h>
 
#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )
 
int main(int argc, char **argv) {
    int length, i = 0;
    int fd;
    int wd;
    char buffer[EVENT_BUF_LEN];
 
    /*初始化实例*/
    fd = inotify_init();
 
    /*checking for error*/
    if (fd < 0) {
        perror("inotify_init");
    }
 
    /**
     * 添加事件监听类别
     */
    wd = inotify_add_watch(fd, "/home/liyajie/t", IN_ACCESS);
    /**
     * 读取事件
     */
    length = read(fd, buffer, EVENT_BUF_LEN);
 
    /*checking for error*/
    if (length < 0) {
        perror("read");
    }
 
    /**
     * Wait until the event happened
     */
    while (i < length) {
        struct inotify_event *event = (struct inotify_event *) &buffer[i];
        if (event->len) {
            if (event->mask & IN_CREATE) {
                if (event->mask & IN_ISDIR) {
                    printf("New directory %s created.\n", event->name);
                } else {
                    printf("New file %s created.\n", event->name);
                }
            } else if (event->mask & IN_DELETE) {
                if (event->mask & IN_ISDIR) {
                    printf("Directory %s deleted.\n", event->name);
                } else {
                    printf("File %s deleted.\n", event->name);
                }
            } else {
                printf("The file is accessed the event_name: %s \n",event->name);
            }
        }
        i += EVENT_SIZE + event->len;
    }
    /*从事件组中移出所添加的监听器*/
    inotify_rm_watch(fd, wd);
 
    /*closing the INOTIFY instance*/
    close(fd);
}
 
posted @ 2012-07-03 10:16  xianyuan  阅读(651)  评论(0编辑  收藏  举报