基本概念:
Inotify 是一个 Linux特性,它监控文件系统操作,比如读取、写入和创建。Inotify 反应灵敏,用法非常简单,并且比 cron 任务的繁忙轮询高效得多。
需求:
1.有一个文件采集进程,需要对日志文件进行采集,日志文件可能会被删除,可能会被移动。
2.我们都知道文件一旦被删除或者移动,那么进程使用原有打开的文件fd就无法继续读取文件数据。
3.那么就需要监控文件的创建,移动,删除等状态,以便重新打开文件,所以需要使用Inotify来做这件事。
源码inotfy.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_NUM 12
char *event_str[EVENT_NUM] =
{
"IN_ACCESS",
"IN_MODIFY", //文件修改
"IN_ATTRIB",
"IN_CLOSE_WRITE",
"IN_CLOSE_NOWRITE",
"IN_OPEN",
"IN_MOVED_FROM", //文件移动from
"IN_MOVED_TO", //文件移动to
"IN_CREATE", //文件创建
"IN_DELETE", //文件删除
"IN_DELETE_SELF",
"IN_MOVE_SELF"
};
int main(int argc, char *argv[])
{
int fd;
int wd;
int len;
int nread;
char buf[BUFSIZ];
struct inotify_event *event;
int i;
// 判断输入参数
if (argc < 2) {
fprintf(stderr, "%s path\n", argv[0]);
return -1;
}
// 初始化
fd = inotify_init();
if (fd < 0) {
fprintf(stderr, "inotify_init failed\n");
return -1;
}
/* 增加监听事件
* 监听所有事件:IN_ALL_EVENTS
* 监听文件是否被创建,删除,移动:IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO
*/
wd = inotify_add_watch(fd, argv[1], IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO);
if(wd < 0) {
fprintf(stderr, "inotify_add_watch %s failed\n", argv[1]);
return -1;
}
buf[sizeof(buf) - 1] = 0;
while( (len = read(fd, buf, sizeof(buf) - 1)) > 0 ) {
nread = 0;
while(len> 0) {
event = (struct inotify_event *)&buf[nread];
for(i=0; i<EVENT_NUM; i++) {
if((event->mask >> i) & 1) {
if(event->len > 0)
fprintf(stdout, "%s --- %s\n", event->name, event_str[i]);
else
fprintf(stdout, "%s --- %s\n", " ", event_str[i]);
}
}
nread = nread + sizeof(struct inotify_event) + event->len;
len = len - sizeof(struct inotify_event) - event->len;
}
}
return 0;
}
编译运行:
gcc inotfy.c
// 监控当前目录的文件变化
./a.out ./
测试结果:
小结:
1.可以根据需要对代码进行调整测试
2.参考:http://www.ibm.com/developerworks/cn/linux/l-inotify/
3.参考:http://www.jb51.net/article/37420.htm
End;