inotify监测文件及文件夹

linux下可以利用inotify来监测文件以及文件夹

详细的说明可以参考:

http://www.ibm.com/developerworks/cn/linux/l-inotifynew/

需要注意的是inotify读取的结构体中最后一个成员是不定长的。因此读取事件后需要强转类型,以下为测试代码:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/inotify.h>
char *files[]={
	"t1","t2","t3"
};
struct st_files{
	char *filename;
	int wd;
};
struct st_files file_wd[3];
char * event_array[]={
	"File was accessed",
	"File was modified",
	"File attributes were changed",
	"writtable file closed",
	"unwrittable file closed",
	"File was opened",
	"File was moved from X",
	"File was moved to Y",
	"Subfile was created",
	"Subfile was deleted",
	"Self was deleted",
	"Self was moved",
	"",
	"Backing fs was unmounted",
	"Event queued overflowed",
	"File was ignored"
};
int main(void){
	int fd;
	int wd;
	char buffer[1024];
	char *offset=NULL;
	struct inotify_event *event=NULL;
	int len,tmp_len;
	int i;
	fd=inotify_init();//初始化inotify程序
	for(i=0;i<3;i++){
		wd=inotify_add_watch(fd,files[i],IN_ALL_EVENTS);//添加需要监测的文件与相应的行为,每个文件对应一个wd
		if(wd<0) perror("inotify_add_watch failed");
		file_wd[i].filename=files[i];
		file_wd[i].wd=wd;
	}
	while(len=read(fd,buffer,1024)){//读取相关事件,read为阻塞
		offset=buffer;
		printf("some event happens, len = %d.\n",len);
		event=(struct inotify_event *)buffer;
		while((char *)event-buffer<len){
			//offset=buffer;
			//event=(struct inotify_event*)buffer;
			for(i=0;i<3;i++){
				if(event->wd!=file_wd[i].wd) continue;
				printf("file %s is %d\n",file_wd[i].filename,i);
				break;
			}
			for(i=0;i<16;i++){
				if(event_array[i][0]=='\0') continue;
				if(event->mask&(1<<i)){
					printf("%s\n",event_array[i]);//输出触发的行为
				}
			}
			tmp_len=sizeof(struct inotify_event)+event->len;
			event=(struct inotify_event*)(offset+tmp_len);
			offset+=tmp_len;
		}
	}
	return 0;
}
posted @ 2011-06-28 16:35  akawhy  阅读(2341)  评论(0编辑  收藏  举报