Watching a directory with inotify

From WTFwiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Here's a thing one can compile to use inotify(7) to watch for files being created and deleted in a directory:

#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <unistd.h>

#define EVENT_SIZE     (sizeof (struct inotify_event))
#define EVENT_BUF_LEN  (1024 * (EVENT_SIZE + 16))

int main(int argc, char **argv) {
       int fd, ret, i;
       char buffer[EVENT_BUF_LEN];
       struct inotify_event *event;

       if (argc < 2) {
               printf("Usage: %s <dir>\n", argv[0]);
               return 1;
       }

       fd = inotify_init();
       if (fd == -1) {
               perror("inotify_init");
               return 1;
       }

       ret = inotify_add_watch(fd, argv[1], IN_CREATE | IN_DELETE);
       if (ret == -1) {
               perror("inotify_add_watch");
               return 1;
       }

       while (1) {
               ret = read(fd, buffer, EVENT_BUF_LEN);
               if (ret == -1) {
                       perror("read");
                       return 1;
               }

               i = 0;
               while (i < ret) {
                       event = (struct inotify_event *)&buffer[i];
                       if (event->mask & IN_CREATE)
                               printf("%s created\n", event->name);
                       if (event->mask & IN_DELETE)
                               printf("%s deleted\n", event->name);
                       i += EVENT_SIZE + event->len;
               }
       }

       return 0;
}