-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor_dir_inotify.c
65 lines (55 loc) · 1.75 KB
/
monitor_dir_inotify.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <errno.h>
#include <linux/inotify.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
int main() {
int length, i = 0;
int fd;
int wd;
char buffer[EVENT_BUF_LEN];
/*creating the INOTIFY instance*/
fd = inotify_init();
/*checking for error*/
if (fd < 0) {
perror("inotify_init");
}
/*adding the “/tmp” directory into watch list. Here, the suggestion is to
* validate the existence of the directory before adding into monitoring
* list.*/
wd = inotify_add_watch(fd, "/tmp", IN_CREATE | IN_DELETE);
/*read to determine the event change happens on “/tmp” directory. Actually
* this read blocks until the change event occurs*/
length = read(fd, buffer, EVENT_BUF_LEN);
/*checking for error*/
if (length < 0) {
perror("read");
}
/*actually read return the list of change events happens. Here, read the
* change event one by one and process it accordingly.*/
while (i < length) {
struct inotify_event *event = (struct inotify_event *)&buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
if (event->mask & IN_ISDIR) {
printf("New directory %s created.\n", event->name);
} else {
printf("New file %s created.\n", event->name);
}
} else if (event->mask & IN_DELETE) {
if (event->mask & IN_ISDIR) {
printf("Directory %s deleted.\n", event->name);
} else {
printf("File %s deleted.\n", event->name);
}
}
}
i += EVENT_SIZE + event->len;
}
/*removing the “/tmp” directory from the watch list.*/
inotify_rm_watch(fd, wd);
/*closing the INOTIFY instance*/
close(fd);
}