Linux编程基础之inotify机制简析

来源:互联网 发布:vc界面编程入门 编辑:程序博客网 时间:2024/06/03 14:57

本文实现一个inotify的小例子,功能:指定一个目录,当目录中创建文件或者删除文件时,把相应的通知信息打印出来。

一、inotify机制和API

1、inotify机制

inotify可以用来监视文件系统的变化,它不仅可以监视文件的变化,还可以监视文件夹的变化。当有变化发生时,它就会返回相应的变化事件。关于inotify机制的详细信息可以参考相关数据或者资料。

2、inotify涉及的API

a、int inotify_init(void);
初始化一个inotify的实例并返回一个和文件描述符作为该inotify事件队列的句柄。

b、int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
向该inotify实例中添加一个监视的文件或者目录。

fd : inotify实例

pathname : 要监视的文件或者文件夹名称

mask : 要监视事件的屏蔽位,它的具体可用参数如下所示:

IN_ACCESS         File was accessed (read) (*).IN_ATTRIB         Metadata  changed,  e.g.,  permissions,  timestamps,  extended  attributes,  link count (since Linux                             2.6.25), UID, GID, etc. (*).IN_CLOSE_WRITE    File opened for writing was closed (*).IN_CLOSE_NOWRITE  File not opened for writing was closed (*).IN_CREATE         File/directory created in watched directory (*).IN_DELETE         File/directory deleted from watched directory (*).IN_DELETE_SELF    Watched file/directory was itself deleted.IN_MODIFY         File was modified (*).IN_MOVE_SELF      Watched file/directory was itself moved.IN_MOVED_FROM     File moved out of watched directory (*).IN_MOVED_TO       File moved into watched directory (*).IN_OPEN           File was opened (*).

cint inotify_rm_watch(int fd, int wd);
移除要监视的文件或者文件夹。


二、测试

实现一个简单的小例子进行测试,当指定目录中有文件创建或者删除时把相应的信息打印出来。

程序的完整代码实现如下:

#include <stdio.h>#include <sys/inotify.h>#include <unistd.h>#include <string.h>/*指定一个目录,当目录中创建或者删除文件时,把相应的信息打印出来 *Usage : inotify <dir> */int main(int argc, char *argv[]){int fd;int result;char event_buf[512];int event_pos = 0;int event_size;struct inotify_event *event;if(2 != argc){printf("Usage : %s <dir>\n", argv[0]);return -1;}/* 初始化一个inotify的实例,获得一个该实例的文件描述符 */fd = inotify_init();/* 添加一个用于监视的目录:主要监视该目录中文件的添加和移除 */result = inotify_add_watch(fd, argv[1], IN_DELETE | IN_CREATE);if(-1 == result){printf("inotify_add_watch error!\n");return -1;}/* 不停的监视当前目录中是否有添加或者删除文件 */while(1){/* 读取inotify的监视事件的信息 */memset(event_buf, 0, 512);result = read(fd, event_buf, sizeof(event_buf));    if(result < (int)sizeof(*event)) {        printf("could not get event!\n");        return -1;    }event_pos = 0;// 每次读取数据时复位位置信息/* 将获得的inotify信息打印出来 */while(result >= (int)sizeof(*event)) {        event = (struct inotify_event *)(event_buf + event_pos);        if(event->len) {            if(event->mask & IN_CREATE) // 创建一个文件时{                printf("create : file is %s\n", event->name);            } else // 删除一个文件时            {                printf("delete : file is %s\n", event->name);            }        }/* 更新位置信息,以便获得下一个 inotify_event 对象的首地址*/        event_size = sizeof(*event) + event->len;        result -= event_size;        event_pos += event_size;    }}/* 关闭这个文件描述符 */close(fd);return 0;}

编译并运行上面代码结果如下:





0 0