inotify监测实例

 1 /*************************************************************************
 2     > File Name: inotify.c
 3     > 监测一个目录下的文件变化,增加或删除提示
 4     > Created Time: Thu 21 Sep 2017 02:41:48 PM CST
 5  ************************************************************************/
 6 
 7 #include <stdio.h>
 8 #include <sys/inotify.h>
 9 #include <string.h>
10 #include <errno.h>
11 #include <fcntl.h>
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
",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
", event->name);
36             } else {
37                 printf("Removing device '%s' due to inotify event
", 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 <dir>
",argv[0]);
53         return -1;
54     }
55     // inotify_init
56     fd = inotify_init();
57     // add watch
58     //添加监控:argv[1]监控目录,IN_DELETE|IN_CREATE 监控 创建和删除
59     inotify_add_watch(fd, argv[1], IN_DELETE|IN_CREATE); 
60     // read
61     while(1)
62     {
63         read_process_inotify_fd(fd);
64     }
65     return 0;
66 }
View Code

原文地址:https://www.cnblogs.com/winfu/p/7569170.html