/* * inotify.c のサンプル * * Copyright (C) NAKAMURA Minoru * * gcc -Wall -o inotify inotify.c */ #include #include #include #include /* for offsetof */ #include /* for memmove */ #include #include #include #define MAX_WATCHPOINT_DIRS (32) static void display_inotify_event(struct inotify_event *inotify_p); static int wd_array[MAX_WATCHPOINT_DIRS]; int main(int argc, char **argv) { int i, max_wd; if (argc < 2) { printf("Usage: [directory-to-watch1 [directory-to-watch2 ...]]\n"); exit(EXIT_SUCCESS); } int fd = inotify_init(); if (fd == -1) { perror("inotify_init"); exit(EXIT_FAILURE); } max_wd = (MAX_WATCHPOINT_DIRS > argc - 1) ? argc - 1 : MAX_WATCHPOINT_DIRS; /* * 監視対象とするディレクトリを指定。 * 監視対象ディレクトリは複数設定することも可能。 */ for (i=0 ; ilen; if (ret < i + size) { /* inotify イベントの可変部分が読み込めていない。 */ aux = ret - i; memmove(buffer, buffer + i, aux); goto reread; } /* イベントの解析 */ display_inotify_event(inotify_p); i += size; } } for (i=0 ; imask; // File was accessed (read) (*). if (mask & IN_ACCESS) ret += sprintf(buffer + ret, "ACCESS "); // Metadata changed if (mask & IN_ATTRIB) ret += sprintf(buffer + ret, "ATTRIB "); // File opened for writing was closed (*). if (mask & IN_CLOSE_WRITE) ret += sprintf(buffer + ret, "CLOSE_WRITE "); // File not opened for writing was closed (*). if (mask & IN_CLOSE_NOWRITE) ret += sprintf(buffer + ret, "CLOSE_NOWRITE "); // File/directory created in watched directory (*). if (mask & IN_CREATE) ret += sprintf(buffer + ret, "CREATE "); // File/directory deleted from watched directory (*). if (mask & IN_DELETE) ret += sprintf(buffer + ret, "DELETE "); // Watched file/directory was itself deleted. if (mask & IN_DELETE_SELF) ret += sprintf(buffer + ret, "DELETE_SELF "); // File was modified (*). if (mask & IN_MODIFY) ret += sprintf(buffer + ret, "MODIFY "); // Watched file/directory was itself moved. if (mask & IN_MOVE_SELF) ret += sprintf(buffer + ret, "MODIFY_SELF "); // File moved out of watched directory (*). if (mask & IN_MOVED_FROM) ret += sprintf(buffer + ret, "MOVE_FROM "); // File moved into watched directory (*). if (mask & IN_MOVED_TO) ret += sprintf(buffer + ret, "MOVE_TO "); // File was opened (*). if (mask & IN_OPEN) ret += sprintf(buffer + ret, "OPEN "); // Watch was removed explicitly (inotify_rm_watch(2)) or // automatically (file was deleted, or file system was // unmounted). if (mask & IN_IGNORED) ret += sprintf(buffer + ret, "IGNORED "); // Subject of this event is a directory. if (mask & IN_ISDIR) ret += sprintf(buffer + ret, "ISDIR "); // Event queue overflowed (wd is -1 for this event). if (mask & IN_Q_OVERFLOW) ret += sprintf(buffer + ret, "Q_OVERFLOW "); // File system containing watched object was unmounted. if (mask & IN_UNMOUNT) ret += sprintf(buffer + ret, "Q_UNMOUNT "); printf("%d %x %u %u \"%s\" [%s]\n", inotify_p->wd, inotify_p->mask, inotify_p->cookie, inotify_p->len, &inotify_p->name, buffer); }