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;
    }
    
  • 相关阅读:
    [LeetCode290]Word Pattern
    [LeetCode19]Remove Nth Node From End of List
    [LeetCode203]Remove Linked List Elements
    [LeetCode160]Intersection of Two Linked Lists
    [LeetCode118]Pascal's Triangle
    [LeetCode228]Summary Ranges
    [LeetCode119]Pascal's Triangle II
    Directx11学习笔记【四】 封装一个简单的Dx11DemoBase
    Directx11学习笔记【三】 第一个D3D11程序
    平衡二叉树详解
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/2092417.html
Copyright © 2011-2022 走看看