DEV Community

Cover image for Your File Watcher Is Missing Events: Practical inotify on Linux
Lyra
Lyra

Posted on

Your File Watcher Is Missing Events: Practical inotify on Linux

A service watches /srv/data/incoming. It has worked for months. Then one night it stops reacting to new files, and nothing in the logs says why. The directory is fine, the process is alive, the files are there.

The usual cause is not a disk or a permission problem. It is that the thing being watched was replaced, and inotify was never watching the path in the first place.

This is a practical tour of what inotify actually promises, the four ways it quietly stops telling you the truth, and a complete C watcher that survives all of them.

A watch is an inode handle, not a pathname

inotify_add_watch(2) attaches a watch to the filesystem object (inode) behind a path, not to the string. If the same inode is already watched through another hard link, you get the existing watch descriptor back. The watch descriptor identifies the object, not the name you used.

That matters because a huge number of programs never modify a file in place. Editors, config management, and mv-based deploy scripts write a temporary file and rename it over the target:

printf 'new config\n' > app.conf.tmp
mv app.conf.tmp app.conf
Enter fullscreen mode Exit fullscreen mode

If you watched app.conf, the rename removes the last link to the old inode. The watch receives IN_ATTRIB (link count changed), then IN_DELETE_SELF, then IN_IGNORED, and it is gone. The new app.conf is a different inode with no watch on it.

Watch the directory instead, filter on the name, and treat IN_MOVED_TO as "the file now exists". A directory watch survives the replacement because the directory inode does not change.

The same logic explains a related surprise: hard links share one watch. Watching a and b where both are links to one inode gives you one watch descriptor, and events for activity through either name arrive against it.

Directory watches are not recursive

One inotify_add_watch() covers one directory. To cover a tree you add a watch per directory. The man page is explicit about the race: add the watch first, then scan the directory, because files and subdirectories may already exist inside a directory created or moved into the tree before your watch was in place. The example below does exactly that order.

Where the event stream lies

Four behaviors account for most "inotify is broken" reports.

Identical events are coalesced. If two events with the same watch descriptor, mask, cookie, and name are queued and the older one has not been read, the kernel merges them. You cannot use inotify to count writes. If you need counts, count in the application or sample the file.

The queue overflows. Each instance has a maximum queue length, fixed when the instance is created (fs.inotify.max_queued_events). When it fills, events are dropped and you get one IN_Q_OVERFLOW event with wd == -1. That is not a warning you can log and ignore: your view of the filesystem is now wrong. Close the instance, rebuild your cache, add the watches again, and rescan. The man page recommends exactly this.

Rename pairing is best-effort. IN_MOVED_FROM and IN_MOVED_TO share a cookie, but they are not guaranteed to be adjacent, and they are not inserted atomically. Another process can interleave events, the pair can straddle two read() calls, and if the file is renamed out of the watched tree there may be no IN_MOVED_TO at all. Don't assume adjacency; match on cookie with a timeout, and accept that some pairs will not match.

Unlinked children keep generating events by default. Watching /tmp with IN_MODIFY means every temporary file that is created and immediately unlinked keeps producing events until it is closed. Add IN_EXCL_UNLINK unless you actually want that.

Two more limits are not bugs but are easy to forget: inotify reports nothing for writes performed through mmap(2), and it reports nothing for changes made by another host on a network filesystem. Pseudo-filesystems such as /proc, /sys, and /dev/pts are not monitorable. And inotify gives you no PID or UID, so it cannot answer "who did this" — that is auditd's job, not inotify's.

A watcher that rebuilds itself

The program below watches a directory tree, adds watches for new subdirectories, and rebuilds the whole watch set when the queue overflows or a watched directory moves. It is deliberately small, but it handles the failure modes above instead of pretending they don't exist.

#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <poll.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <unistd.h>

static char **wd_path;
static size_t wd_cap;

static void set_path(int wd, const char *path)
{
    if (wd < 0)
        return;
    if ((size_t)wd >= wd_cap) {
        size_t cap = wd_cap ? wd_cap : 64;
        while (cap <= (size_t)wd)
            cap *= 2;
        char **p = realloc(wd_path, cap * sizeof *p);
        if (!p) {
            perror("realloc");
            exit(1);
        }
        for (size_t i = wd_cap; i < cap; i++)
            p[i] = NULL;
        wd_path = p;
        wd_cap = cap;
    }
    free(wd_path[wd]);
    wd_path[wd] = strdup(path);
}

static const char *event_name(uint32_t mask)
{
    static char out[512];
    static const struct {
        uint32_t bit;
        const char *name;
    } names[] = {
        { IN_ACCESS, "ACCESS" },
        { IN_MODIFY, "MODIFY" },
        { IN_ATTRIB, "ATTRIB" },
        { IN_CLOSE_WRITE, "CLOSE_WRITE" },
        { IN_CLOSE_NOWRITE, "CLOSE_NOWRITE" },
        { IN_OPEN, "OPEN" },
        { IN_MOVED_FROM, "MOVED_FROM" },
        { IN_MOVED_TO, "MOVED_TO" },
        { IN_CREATE, "CREATE" },
        { IN_DELETE, "DELETE" },
        { IN_DELETE_SELF, "DELETE_SELF" },
        { IN_MOVE_SELF, "MOVE_SELF" },
        { IN_UNMOUNT, "UNMOUNT" },
        { IN_ISDIR, "ISDIR" },
    };
    size_t off = 0;

    out[0] = '\0';
    for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) {
        if (!(mask & names[i].bit))
            continue;
        int n = snprintf(out + off, sizeof out - off, "%s%s",
                         off ? "|" : "", names[i].name);
        if (n < 0 || (size_t)n >= sizeof out - off)
            break;
        off += (size_t)n;
    }
    return out;
}

/* Add a watch before scanning, so nothing created in between is missed. */
static void add_tree(int fd, const char *dir, uint32_t mask)
{
    int wd = inotify_add_watch(fd, dir, mask);
    if (wd < 0) {
        fprintf(stderr, "inotify_add_watch(%s): %s\n", dir, strerror(errno));
        return;
    }
    set_path(wd, dir);

    DIR *d = opendir(dir);
    if (!d)
        return;

    struct dirent *de;
    while ((de = readdir(d)) != NULL) {
        if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
            continue;

        char child[PATH_MAX];
        int n = snprintf(child, sizeof child, "%s/%s", dir, de->d_name);
        if (n < 0 || (size_t)n >= sizeof child)
            continue;

        struct stat st;
        if (lstat(child, &st) == 0 && S_ISDIR(st.st_mode))
            add_tree(fd, child, mask);
    }
    closedir(d);
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s DIRECTORY\n", argv[0]);
        return 2;
    }

    const uint32_t mask = IN_CREATE | IN_DELETE | IN_MODIFY | IN_ATTRIB |
                          IN_CLOSE_WRITE | IN_MOVED_FROM | IN_MOVED_TO |
                          IN_DELETE_SELF | IN_MOVE_SELF |
                          IN_ONLYDIR | IN_EXCL_UNLINK;

    int fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
    if (fd < 0) {
        perror("inotify_init1");
        return 1;
    }
    add_tree(fd, argv[1], mask);

    struct pollfd pfd = { .fd = fd, .events = POLLIN };
    union {
        char buf[64 * 1024];
        struct inotify_event align;
    } u;

    for (;;) {
        int pr = poll(&pfd, 1, -1);
        if (pr < 0) {
            if (errno == EINTR)
                continue;
            perror("poll");
            break;
        }

        ssize_t n = read(fd, u.buf, sizeof u.buf);
        if (n < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
            perror("read");
            break;
        }
        if (n == 0)
            continue;

        int rebuild = 0;
        for (char *p = u.buf; p < u.buf + n; ) {
            struct inotify_event *ev = (struct inotify_event *)p;

            if (ev->mask & IN_Q_OVERFLOW) {
                fprintf(stderr, "event queue overflow: rebuilding watches\n");
                rebuild = 1;
                break;
            }

            if (ev->mask & IN_IGNORED) {
                if (ev->wd >= 0 && (size_t)ev->wd < wd_cap) {
                    free(wd_path[ev->wd]);
                    wd_path[ev->wd] = NULL;
                }
                p += sizeof *ev + ev->len;
                continue;
            }

            const char *dir = "?";
            if (ev->wd >= 0 && (size_t)ev->wd < wd_cap && wd_path[ev->wd])
                dir = wd_path[ev->wd];

            printf("%-32s %-40s %s%s\n", dir, event_name(ev->mask),
                   ev->len ? ev->name : "",
                   (ev->mask & IN_ISDIR) ? "/" : "");
            fflush(stdout);

            if ((ev->mask & (IN_CREATE | IN_MOVED_TO)) &&
                (ev->mask & IN_ISDIR) && ev->len > 0 &&
                strcmp(dir, "?") != 0) {
                char child[PATH_MAX];
                int cn = snprintf(child, sizeof child, "%s/%s", dir, ev->name);
                if (cn > 0 && (size_t)cn < sizeof child)
                    add_tree(fd, child, mask);
            }

            /* A moved directory keeps its inode but loses its old path. */
            if (ev->mask & IN_MOVE_SELF)
                rebuild = 1;

            p += sizeof *ev + ev->len;
        }

        if (rebuild) {
            int nfd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
            if (nfd < 0) {
                perror("inotify_init1");
                break;
            }
            for (size_t i = 0; i < wd_cap; i++) {
                free(wd_path[i]);
                wd_path[i] = NULL;
            }
            close(fd);
            fd = nfd;
            pfd.fd = fd;
            add_tree(fd, argv[1], mask);
        }
    }

    close(fd);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Three parts carry the weight. wd_path[] maps a watch descriptor back to the directory that installed it, because the kernel only gives you the descriptor. add_tree() adds the watch before it scans, closing the window where a directory could gain children between the scan and the watch. And the overflow branch throws the whole watch set away instead of trying to repair it event by event.

Build and try it on a scratch tree:

cc -Wall -Wextra -O2 watcher.c -o watcher
mkdir -p /tmp/lab/sub
./watcher /tmp/lab &
touch /tmp/lab/a.txt
mkdir /tmp/lab/sub/b
mv /tmp/lab/a.txt /tmp/lab/sub/a.txt
Enter fullscreen mode Exit fullscreen mode

You should see CREATE for a.txt, CREATE|ISDIR for the new b, then a MOVED_FROM on /tmp/lab and a MOVED_TO on /tmp/lab/sub carrying the same cookie. If you run a second watcher on /tmp/lab/a.txt instead of the directory and repeat the mv, that second watcher gets ATTRIB, DELETE_SELF, and IGNORED — and then silence.

A note on buffer size: one read() returns whole events, and the buffer must be at least sizeof(struct inotify_event) + NAME_MAX + 1 or the call fails with EINVAL on current kernels. 64 KiB is comfortable.

Limits, and the error that looks like a disk problem

Three sysctls govern inotify, all per real user ID:

  • fs.inotify.max_user_watches — total watches
  • fs.inotify.max_user_instances — total inotify file descriptors
  • fs.inotify.max_queued_events — queue length, read when the instance is created

ENOSPC from inotify_add_watch() means the watch limit, not a full disk. This is the error behind the classic "System limit for number of file watchers reached" from editors and build tools.

cat /proc/sys/fs/inotify/max_user_watches
sudo sysctl fs.inotify.max_user_watches=524288
printf 'fs.inotify.max_user_watches=524288\n' | sudo tee /etc/sysctl.d/99-inotify.conf
sudo sysctl --system
Enter fullscreen mode Exit fullscreen mode

Raising it is not free: each watch holds a reference to an inode. Raise it to fit the tree you actually monitor, not to a million because a blog post said so.

One instance can hold thousands of watches; do not create an instance per file. max_user_instances caps instances, and each instance has its own queue, so more instances also means more independent overflow points.

To see what an instance is really watching, read its fdinfo:

ls -l /proc/$PID/fd | grep inotify
cat /proc/$PID/fdinfo/$FD
Enter fullscreen mode Exit fullscreen mode

The inotify lines list each watch descriptor with its inode and mask. It is the quickest way to prove that the watch you think you installed is actually there.

For debugging, inotifywait from inotify-tools is fine:

inotifywait -m -r -e create,delete,modify,move --format '%w%f %e' /srv/data
Enter fullscreen mode Exit fullscreen mode

If all you need is "start a unit when this path changes", a systemd.path unit already wraps this and handles the supervision; don't write a daemon for it.

When inotify is the wrong tool

inotify's scope is one inode or one directory per watch, notification only, no attribution. When you need more:

  • Whole-mount coverage and access decisions: fanotify. Mount-wide marks and permission events require CAP_SYS_ADMIN. Since Linux 5.13, an unprivileged process can create a notification-only group with FAN_REPORT_FID, but only with inode marks — no FAN_MARK_MOUNT or FAN_MARK_FILESYSTEM, no permission events, and no unlimited queue.
  • Attribution and audit trail: auditd. It records the syscall, PID, UID, and path, which inotify never will.
  • Remote filesystems: neither inotify nor fanotify sees changes made on another host. Poll, or use a protocol with change notification.

A minimal fanotify mark looks like this (privileged, mount-wide):

int fd = fanotify_init(FAN_CLASS_NOTIF | FAN_CLOEXEC, O_RDONLY | O_LARGEFILE);
fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
              FAN_CREATE | FAN_DELETE | FAN_MOVED_FROM | FAN_MOVED_TO,
              AT_FDCWD, "/srv/data");
Enter fullscreen mode Exit fullscreen mode

The checklist

  1. Watch directories, not files, unless you control every writer.
  2. Add the watch before scanning the directory.
  3. Never count events; coalescing is allowed.
  4. Handle IN_Q_OVERFLOW by rebuilding, not logging.
  5. Treat rename cookies as hints, not guarantees.
  6. Add IN_EXCL_UNLINK for directories full of temporary files.
  7. Check max_user_watches when you see ENOSPC.
  8. Use fanotify or auditd when you need mount scope or attribution.

inotify is a good API with a narrow promise: it tells you that something happened to an inode you hold a reference to, eventually, maybe coalesced, and only while the watch exists. Once you design for that promise instead of a pathname, the 2 a.m. mystery disappears.

Sources

Top comments (0)