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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
/*
* inotify-watch.c
*
* Watch a file or directory for changes using inotify
*
* Copyright (c) 2008-2009 Tobias Klauser <tklauser@distanz.ch>
*
* All rights reserved.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/inotify.h>
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*x))
struct mask2string {
uint32_t mask;
const char *desc;
};
#define DECLARE_M2STR(x) { x, #x }
static const struct mask2string events[] = {
DECLARE_M2STR(IN_ACCESS),
DECLARE_M2STR(IN_MODIFY),
DECLARE_M2STR(IN_ATTRIB),
DECLARE_M2STR(IN_CLOSE_WRITE),
DECLARE_M2STR(IN_CLOSE_NOWRITE),
DECLARE_M2STR(IN_OPEN),
DECLARE_M2STR(IN_MOVED_FROM),
DECLARE_M2STR(IN_MOVED_TO),
DECLARE_M2STR(IN_CREATE),
DECLARE_M2STR(IN_DELETE),
DECLARE_M2STR(IN_DELETE_SELF),
DECLARE_M2STR(IN_MOVE_SELF),
DECLARE_M2STR(IN_UNMOUNT),
DECLARE_M2STR(IN_Q_OVERFLOW),
DECLARE_M2STR(IN_IGNORED),
/* special flags */
DECLARE_M2STR(IN_ONLYDIR),
DECLARE_M2STR(IN_DONT_FOLLOW),
DECLARE_M2STR(IN_MASK_ADD),
DECLARE_M2STR(IN_ONESHOT),
};
static void inotify_print_event(struct inotify_event *inev)
{
unsigned int i;
/* stat? */
printf("(%s) wd=%04x, cookie=%04x, len=%04x, name=\"%s\" :",
inev->mask & IN_ISDIR ? "dir" : "file",
inev->wd, inev->cookie, inev->len,
inev->len > 0 ? inev->name : "");
for (i = 0; i < ARRAY_SIZE(events); i++)
if (inev->mask & events[i].mask)
printf(" %s", events[i].desc);
printf("\n");
}
int main(int argc, char *argv[])
{
int fd, len;
int *watches;
struct inotify_event *inev;
char buf[1024];
if (argc < 2) {
printf("Usage: %s <path> ...\n", *argv);
exit(EXIT_FAILURE);
}
++argv;
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
watches = malloc((argc - 1) * sizeof(int));
if (!watches) {
perror("malloc");
exit(EXIT_FAILURE);
}
while (*argv) {
*watches = inotify_add_watch(fd, *argv, IN_ALL_EVENTS|IN_UNMOUNT);
if (*watches < 0) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
++watches;
++argv;
}
while (1) {
len = read(fd, buf, sizeof(buf));
inev = (struct inotify_event *) &buf;
while (len > 0) {
inotify_print_event(inev);
len -= sizeof(struct inotify_event) + inev->len;
inev = (struct inotify_event *) ((char *) inev
+ sizeof(struct inotify_event) + inev->len);
}
}
return 0;
}
|