TOC   Previous   Next

inotify

Example code

Monitor the pathnames named as command-line arguments

We begin by creating an inotify instance:

int
main(int argc, char *argv[])
{
    int inotify_fd, wd, j;

    if (argc < 2 || strcmp(argv[1], "--help") == 0)
        usageErr("%s path...\n", argv[0]);

    inotify_fd = inotify_init();

We then establish one watch for each pathname specified on command line:

    for (j = 1; j < argc; j++) {
        wd = inotify_add_watch(inotify_fd, argv[j], IN_ALL_EVENTS);
        printf("Watching %s using watch descriptor %d\n", argv[j], wd);
    } 
	

Now we can read events from the inotify file descriptor:

#define BUF_LEN 10000

    char buf[BUF_LEN];     /* For input inotify_event structures */
    ssize_t nread;
    char *p;

    for (;;) {

        /* Read some events from inotify fd */

        nread = read(inotify_fd, buf, BUF_LEN);
        if (nread == 0)             /* End-of-file */
            break;
        if (nread == -1) {          /* Error */
            if (errno == EINTR)     /* Interrupted by signal */
                continue;           /* Restart read() */
            else
                errExit("read");    /* Other error */
        } 

        printf("Read %ld bytes from inotify fd\n", (long) nread);

        /* Each buffer may contain multiple events; 
           process all of them */

        for (p = buf; p < buf + nread;
                p += sizeof(struct inotify_event) +
                        ((struct inotify_event *) p)->len) {

            display_inotify_event((struct inotify_event *) p);
        }
    }

Our display_inotify_event() is trivial:

static void
display_inotify_event(struct inotify_event *i)
{
    printf("        wd =%2d; ", i->wd);
    if (i->cookie > 0)
        printf("cookie =%4d; ", i->cookie);

    printf("mask = ");
    if (i->mask & IN_ACCESS)        printf("IN_ACCESS ");
    if (i->mask & IN_ATTRIB)        printf("IN_ATTRIB ");
    if (i->mask & IN_CLOSE_NOWRITE) printf("IN_CLOSE_NOWRITE ");
    if (i->mask & IN_CLOSE_WRITE)   printf("IN_CLOSE_WRITE ");
    if (i->mask & IN_CREATE)        printf("IN_CREATE ");
    if (i->mask & IN_DELETE)        printf("IN_DELETE ");
    if (i->mask & IN_DELETE_SELF)   printf("IN_DELETE_SELF ");
    if (i->mask & IN_IGNORED)       printf("IN_IGNORED ");
    if (i->mask & IN_ISDIR)         printf("IN_ISDIR ");
    if (i->mask & IN_MODIFY)        printf("IN_MODIFY ");
    if (i->mask & IN_MOVE_SELF)     printf("IN_MOVE_SELF ");
    if (i->mask & IN_MOVED_FROM)    printf("IN_MOVED_FROM ");
    if (i->mask & IN_MOVED_TO)      printf("IN_MOVED_TO ");
    if (i->mask & IN_OPEN)          printf("IN_OPEN ");
    if (i->mask & IN_Q_OVERFLOW)    printf("IN_Q_OVERFLOW ");
    if (i->mask & IN_UNMOUNT)       printf("IN_UNMOUNT ");
    printf("\n");

    if (i->len > 0)
        printf("                name = %s\n", i->name);
} /* display_inotify_event */

(C) 2006, Michael Kerrisk