#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;
}
转载于:https://www.cnblogs.com/zelos/archive/2011/08/01/2123596.html