zoukankan      html  css  js  c++  java
  • inotify使用代码

    #include <stdio.h>
    #include <sys/epoll.h>
    #include <stdlib.h>
    #include <sys/inotify.h>
    
    #define FDMAXNUM (1024)
    #define MAXEVENTS (64)
    #define FAILURE_EXIT (-1)
    #define INOTIFYEVENTBUFSIZE (1024)
    
    int main(int argc, char**argv){
    
        int ifd = inotify_init();
        if(ifd==-1){
    	perror("inotify_init failed");
    	exit(FAILURE_EXIT);
        }
        char ibuf[INOTIFYEVENTBUFSIZE] __attribute__((aligned(4))) = {0} ;
    
        int efd=epoll_create(FDMAXNUM);
        if(efd==-1){
    	perror("epoll_createfailed");
    	exit(FAILURE_EXIT);
        }
        
        int ret = -1;
        struct epoll_event event;
        event.data.fd = ifd;
        event.events = EPOLLIN; 
    
        ret = epoll_ctl(efd, EPOLL_CTL_ADD, ifd, &event);
        if(ret==-1) {
    	perror("epoll_ctl failed");
    	exit(FAILURE_EXIT);
        }
    
        int wd = inotify_add_watch(ifd, "/home/yaozh/Videos",IN_ACCESS);
        if (wd==-1) {
    	perror("inotify_add_watch failed");
    	exit(FAILURE_EXIT);
        }
    
        //wait for change event to come
        int eventnum = -1;
        struct epoll_event *events = malloc(sizeof(struct epoll_event) * MAXEVENTS);
        do {
    	eventnum = epoll_wait(efd, events, MAXEVENTS, -1);
    	if (eventnum==-1){
    	    perror("epoll_wait failed");
    	    free(events);
    	    exit(FAILURE_EXIT);
    	}
    	int len = 0;
    	len = read(ifd, ibuf,INOTIFYEVENTBUFSIZE);
    	while (len) {
    	    int i=0;
    	    while(i<len) {
    		struct inotify_event *event = (struct inotify_event*)(ibuf+i);
    		if(event->len) {
    		    printf("name is %s\n", event->name);
    		}
    		i += sizeof(struct inotify_event) + event->len;
    	    }
    	    len = read(ifd, ibuf, INOTIFYEVENTBUFSIZE);
    	}
        } while (eventnum);
    	
        free(events);
    
        ret = close(efd);
        if(ret==-1) {
    	perror("close epoll fd failed");
    	exit(FAILURE_EXIT);
        }
        ret = close(ifd);
        if(ret==-1) {
    	perror("close inotify fd failed");
    	exit(FAILURE_EXIT);
        }
    
        return 0;
    }
    
  • 相关阅读:
    Hive 导入、导出数据
    mysql 命令行参数说明
    mysql 查看表信息
    python之冒泡排序
    python之选择排序
    python之快速排序
    光荣之路测试开发面试linux考题之四:性能命令
    测试开发linux面试之三:后台进程之操作
    测试开发面试的Linux面试题总结之二:常用命令
    测试开发面试的Linux面试题总结之一:vim使用方法
  • 原文地址:https://www.cnblogs.com/zelos/p/2123596.html
Copyright © 2011-2022 走看看