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;
}

转载于:https://www.cnblogs.com/aLittleBitCool/archive/2011/06/28/2092417.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值