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
|
#include <stdio.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <malloc.h>
#include <error.h>
#include <errno.h>
#define fail(msg) error(1, errno, msg)
#ifndef PATH_MAX
# define PATH_MAX 4096
#endif
struct ev {
int val;
char *name;
};
#define STRVAL(val) #val
#define IN(name) {IN_##name, STRVAL(name)}
struct ev events[] = {
IN(CLOSE_WRITE),
IN(CLOSE_NOWRITE),
IN(OPEN),
{0, NULL}
};
int main(int argc, char **argv) {
int i, ifd, wfd, mask;
int wfds[argc - 1];
if (argc < 2) {
fprintf(stderr, "Usage: %s file_to_watch ...\n", argv[0]);
return 1;
}
for (i=1; i<argc; i++) {
printf("file = %s\n", argv[i]);
}
ifd = inotify_init();
if (ifd == -1) fail("inotify_init");
printf("ifd = %i\n", ifd);
mask = 0;
struct ev *event = events;
while (event->name != NULL) {
mask |= event->val;
printf("event IN_%-16s = %8x\n", event->name, event->val);
++event;
}
for (i=1; i<argc; i++) {
wfd = inotify_add_watch(ifd, argv[i], mask);
if (wfd == -1) fail("inotify_add_watch");
printf("wfd = %i\n", wfd);
wfds[i - 1] = wfd;
}
int iev_size = sizeof(struct inotify_event) + PATH_MAX + 1;
struct inotify_event *iev = malloc(iev_size);
if (!iev) fail("malloc");
putchar('\n');
int j = 100;
while (--j) {
char *file;
if (read(ifd, iev, iev_size) == -1) {
perror("read");
break;
}
for (i=0; i<argc-1; i++) {
if (wfds[i] == iev->wd) {
file = argv[i + 1];
break;
}
}
printf("wd = %i, mask = %x, name = %s\tfile = %s\n",
iev->wd, iev->mask, iev->name,
file);
}
free(iev);
for (i=0; i<argc-1; i++) {
wfd = wfds[i];
if (inotify_rm_watch(ifd, wfd) == -1) fail("inotify_rm_watch");
}
close(ifd);
return 0;
}
|