#include #include #include #include #include #include #include /* Allow for 1024 simultanious events */ #define BUFF_SIZE ((sizeof(struct inotify_event)+FILENAME_MAX)*1024) /* IN_CREATE, IN_DELETE, IN_DELETE_SELF, * IN_OPEN, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE, * IN_ACCESS, IN_MODIFY, IN_ATTRIB, * IN_MOVE_SELF, IN_MOVED_FROM, IN_MOVED_TO, */ #define MY_MASK (IN_CREATE | IN_DELETE | IN_DELETE_SELF) static void handle_error(int err) { fprintf (stderr, "Error: %s\n", strerror(err)); } void get_inotify_event(int fd, const char * target) { ssize_t len, i = 0; char action[81+FILENAME_MAX] = {0}; char buff[BUFF_SIZE] = {0}; len = read(fd, buff, BUFF_SIZE); while (i < len) { struct inotify_event *pevent = (struct inotify_event *)&buff[i]; char action[81+FILENAME_MAX] = {0}; unsigned int mask = pevent->mask & MY_MASK; if (!mask) goto skip; if (pevent->len) strcpy(action, pevent->name); else strcpy(action, target); /* if (mask & IN_ACCESS) strcat(action, " was read"); if (mask & IN_ATTRIB) strcat(action, " Metadata changed"); if (mask & IN_MODIFY) strcat(action, " was modified"); */ /* if (mask & IN_OPEN) strcat(action, " was opened"); if (mask & IN_CLOSE_WRITE) strcat(action, " opened for writing was closed"); if (mask & IN_CLOSE_NOWRITE) strcat(action, " not opened for writing was closed"); */ if (mask & IN_CREATE) strcat(action, " created in watched directory"); if (mask & IN_DELETE) strcat(action, " deleted from watched directory"); if (mask & IN_DELETE_SELF) strcat(action, "Watched file/directory was itself deleted"); /* if (mask & IN_MOVE_SELF) strcat(action, "Watched file/directory was itself moved"); if (mask & IN_MOVED_FROM) strcat(action, " moved out of watched directory"); if (mask & IN_MOVED_TO) strcat(action, " moved into watched directory"); */ printf("wd=%d mask=%d cookie=%d len=%d dir=%s\n", pevent->wd, pevent->mask, pevent->cookie, pevent->len, (pevent->mask & IN_ISDIR)?"yes":"no"); printf("%s\n", action); skip: i += sizeof(struct inotify_event) + pevent->len; } } int main(int argc, char *argv[]) { char target[FILENAME_MAX]; int result; int fd; int wd; /* watch descriptor */ if (argc < 2) { fprintf(stderr, "Watching the current directory\n"); strcpy(target, "."); } else { fprintf(stderr, "Watching %s\n", argv[1]); strcpy(target, argv[1]); } fd = inotify_init(); if (fd < 0) { handle_error(errno); return 1; } wd = inotify_add_watch(fd, target, IN_ALL_EVENTS); if (wd < 0) { handle_error(errno); return 1; } while (1) { get_inotify_event(fd, target); } return 0; }