1 /************************************************************************* 2 > File Name: inotify.c 3 > 监测一个目录下的文件变化,增加或删除提示 4 > Created Time: Thu 21 Sep 2017 02:41:48 PM CST 5 ************************************************************************/ 6 7 #include8 #include 9 #include 10 #include 11 #include 12 13 int read_process_inotify_fd(int inotify_fd)14 {15 int res;16 char event_buf[512];17 int event_size;18 int event_pos = 0;19 struct inotify_event *event;20 res = read(inotify_fd, event_buf, sizeof(event_buf));21 if(res < sizeof(struct inotify_event))22 {23 if(errno == EINTR)24 {25 return 0;26 }27 printf("can not get event ,%s\n",strerror(errno));28 return -1;29 }30 31 while(res >= (int)sizeof(*event)) {32 event = (struct inotify_event *)(event_buf + event_pos); //指向下一个结构体33 if(event->len) {34 if(event->mask & IN_CREATE) {35 printf("Add device '%s' due to inotify event\n", event->name);36 } else {37 printf("Removing device '%s' due to inotify event\n", event->name);38 }39 }40 event_size = sizeof(*event) + event->len;41 res -= event_size;42 event_pos += event_size; //跳转到下一个结构体 43 }44 return 0;45 }46 47 int main(int argc ,char **argv)48 {49 int fd;50 if(argc < 2)51 {52 printf("Usage: %s \n",argv[0]);53 return -1;54 }55 // inotify_init56 fd = inotify_init();57 // add watch58 //添加监控:argv[1]监控目录,IN_DELETE|IN_CREATE 监控 创建和删除59 inotify_add_watch(fd, argv[1], IN_DELETE|IN_CREATE); 60 // read61 while(1)62 {63 read_process_inotify_fd(fd);64 }65 return 0;66 }