/* * inotify-watchdir.c * * Watch a file or directory for changes using inotify * * Copyright (c) 2008-2009 Tobias Klauser * * All rights reserved. */ #include #include #include #include #include #include struct mask2string { uint32_t mask; const char *desc; }; static const struct mask2string events[] = { { IN_ACCESS, "ACCESS" }, { IN_MODIFY, "MODIFY" }, { IN_ATTRIB, "ATTRIB" }, { IN_CLOSE_WRITE, "CLOSE_WRITE" }, { IN_CLOSE_NOWRITE, "CLOSE_NOWRITE" }, { IN_OPEN, "OPEN" }, { IN_MOVED_FROM, "MOVED_FROM" }, { IN_MOVED_TO, "MOVED_TO" }, { IN_CREATE, "CREATE" }, { IN_DELETE, "DELETE" }, { IN_DELETE_SELF, "DELETE_SELF" }, { IN_MOVE_SELF, "MOVE_SELF" }, { IN_UNMOUNT, "UNMOUNT" }, { IN_Q_OVERFLOW, "Q_OVERFLOW" }, { IN_IGNORED, "IGNORED" }, /* special flags */ { IN_ONLYDIR, "ONLYDIR" }, { IN_DONT_FOLLOW, "DONT_FOLLOW" }, { IN_MASK_ADD, "MASK_ADD" }, { IN_ONESHOT, "ONESHOT" }, /* end of array */ { -1, NULL } }; static void inotify_print_event(struct inotify_event *inev) { 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; events[i].desc; 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 ...\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; }