2 gcc kqdir.c -o kqdir -Wall -W -Wextra -ansi -pedantic */
8 #include <string.h> /* for strerror () */
10 #include <sys/event.h>
12 #define MAX_ENTRIES 256
14 /* function prototypes */
15 void diep(const char *s
);
17 int main(int argc
, char *argv
[])
19 struct kevent evlist
[MAX_ENTRIES
]; /* events we want to monitor */
20 struct kevent chlist
[MAX_ENTRIES
]; /* events that were triggered */
24 int fdlist
[MAX_ENTRIES
], cnt
, i
, kq
, nev
;
26 /* check argument count */
28 fprintf(stderr
, "Usage: %s directory\n", argv
[0]);
32 /* create a new kernel event queue */
33 if ((kq
= kqueue()) == -1)
36 /* open directory named by argv[1], associate a directory stream
37 with it and return a pointer to it
39 if ((pdir
= opendir(argv
[1])) == NULL
)
42 /* skip . and .. entries */
44 while((pdent
= readdir(pdir
)) != NULL
&& cnt
++ < 2)
47 /* get all directory entries and for each one of them,
48 initialise a kevent structure
51 while((pdent
= readdir(pdir
)) != NULL
) {
52 /* check whether we have exceeded the max number of
53 entries that we can monitor
55 if (cnt
> MAX_ENTRIES
- 1) {
56 fprintf(stderr
, "Max number of entries exceeded\n");
57 goto CLEANUP_AND_EXIT
;
60 /* check path length */
61 if (strlen(argv
[1] + strlen(pdent
->d_name
) + 1) > 256) {
62 fprintf(stderr
,"Max path length exceeded\n");
63 goto CLEANUP_AND_EXIT
;
65 strcpy(fullpath
, argv
[1]);
66 strcat(fullpath
, "/");
67 strcat(fullpath
, pdent
->d_name
);
69 /* open directory entry */
70 if ((fdlist
[cnt
] = open(fullpath
, O_RDONLY
)) == -1) {
72 goto CLEANUP_AND_EXIT
;
75 /* initialise kevent structure */
76 EV_SET(&chlist
[cnt
], fdlist
[cnt
], EVFILT_VNODE
,
77 EV_ADD
| EV_ENABLE
| EV_ONESHOT
,
78 NOTE_DELETE
| NOTE_EXTEND
| NOTE_WRITE
| NOTE_ATTRIB
,
86 nev
= kevent(kq
, chlist
, cnt
, evlist
, cnt
, NULL
);
91 for (i
= 0; i
< nev
; i
++) {
92 if (evlist
[i
].flags
& EV_ERROR
) {
93 fprintf(stderr
, "EV_ERROR: %s\n", strerror(evlist
[i
].data
));
94 goto CLEANUP_AND_EXIT
;
97 if (evlist
[i
].fflags
& NOTE_DELETE
) {
98 printf("fd: %d Deleted\n", evlist
[i
].ident
);
100 else if (evlist
[i
].fflags
& NOTE_EXTEND
||
101 evlist
[i
].fflags
& NOTE_WRITE
) {
102 printf("fd: %d Modified\n", evlist
[i
].ident
);
104 else if (evlist
[i
].fflags
& NOTE_ATTRIB
) {
105 printf("fd: %d Attributes modified\n", evlist
[i
].ident
);
111 /* close open file descriptors, directory stream and kqueue */
113 for (i
= 0; i
< cnt
; i
++)
121 void diep(const char *s
)