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;
    }
    
  • 相关阅读:
    hdu--4487--dp
    gitLab重新配置ssh
    图片在DIV中垂直居中的显示方法
    Git教程学习 -- 第六篇 标签管理
    Git教程学习 -- 第五篇 Bug分支
    Git教程学习 --第四篇 分支管理
    Git 教程学习--第三篇
    Git 教程学习--第二篇
    Git 教程学习--第一篇
    动态修改title标题
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/2092417.html
Copyright © 2011-2022 走看看