C 使用 Inotify 监控目录和文件

31 篇文章 0 订阅

1. 监控路径并打印所有发生在该路径的事件. 

代码如下:

/*****************************************************************************
 *  Copyright          :  All Rights Reserved.
 *
 *  Date               :  2013-03-01 13:11:22
 *  Author/Corporation :  Dengzhaoqun
 *  Email              :  dengzhaoqun@163.com
 *****************************************************************************/
#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",
	"IN_MOVED_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;
	}
	
	wd = inotify_add_watch(fd, argv[1], IN_ALL_EVENTS);
	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;
}

运行 inotify_watch 监控一个目录:

$ ./inotify_watch test/
...
  --- IN_OPEN
  --- IN_CLOSE_NOWRITE
.tmp.swp --- IN_CREATE
.tmp.swp --- IN_OPEN
.tmp.swpx --- IN_CREATE
.tmp.swpx --- IN_OPEN
.tmp.swpx --- IN_CLOSE_WRITE
.tmp.swpx --- IN_DELETE
.tmp.swp --- IN_CLOSE_WRITE
.tmp.swp --- IN_DELETE
.tmp.swp --- IN_CREATE
.tmp.swp --- IN_OPEN
.tmp.swp --- IN_MODIFY
  --- IN_OPEN
  --- IN_CLOSE_NOWRITE
.tmp.swp --- IN_MODIFY
...

从上面的结果可以看到在 test 目录中使用 vim 创建一个 tmp 文件, 产生很多的冗杂事件. 因此需要对监控的事件做出小范围的选择而不是 IN_ALL_EVENTS .




2. IN_MOVE_SELF 和 IN_DELETE_SELF 事件

由于个人水平, 曾经对这两个事件的含义并没有理解正确. 当监控 path 时( path可以是文件或目录), 

$ ./inotify_watch path
执行 
$ rm -f path
则发生 IN_DELETE_SELF 事件;

执行

mv path path2
则发生 IN_MOVE_SELF 事件.




3. 监控目录和文件

监控目录中内容改变应监控的事件: 

IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVDED_TO

监控文件内容的改变应监控的事件: 

IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值