zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    sql server 2008数据库 降为 sql server 2005数据库 最终方案总结
    android 单元测试
    C# 5.0中引入了async 和 await
    Android之NDK开发
    Java NIO原理 图文分析及代码实现
    【第六篇】Volley之https相关
    【第五篇】Volley代码修改之图片二级缓存以及相关源码阅读(重写ImageLoader.ImageCache)
    【第四篇】Volley修改之GsonRequest
    java复习 --集合类
    android 图片加载优化,避免oom问题产生
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/2092417.html
Copyright © 2011-2022 走看看