/* watch: Watch a given file for changes and run a given command. Syntax: watch file-name command The command is run whenever the file is modified, moved, or deleted. Written and copyrighted by Dmitri Pavlov in 2011. Distributed under the terms of GNU General Public License version 3. Feedback welcome via SMTP: host math.berkeley.edu, user pavlov. */ #include #include #include #include #include void affirm(int a, const char *s) { if (!a) { perror(s); exit(1); } } int main(int argc, char **argv) { int verbose = getenv("VERBOSE") != NULL; if (argc != 3) { fprintf(stderr, "Usage: watch file command\n"); return 1; } int d = inotify_init(); affirm(d != -1, "inotify_init"); affirm(inotify_add_watch(d, argv[1], IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF) != -1, "inotify_add_watch (initial call)"); struct inotify_event e; while (read(d, &e, sizeof(struct inotify_event)) > 0) { if (verbose) { if (e.mask & IN_DELETE_SELF) fprintf(stderr, "deleted\n"); if (e.mask & IN_MOVE_SELF) fprintf(stderr, "moved\n"); if (e.mask & IN_MODIFY) fprintf(stderr, "modified\n"); } if (e.mask & IN_IGNORED) affirm(inotify_add_watch(d, argv[1], IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF) != -1, "inotify_add_watch (subsequent call)"); if (e.mask & (IN_IGNORED | IN_MODIFY)) affirm(system(argv[2]) != -1, "system"); } affirm(0, "read"); }