inotify

On this page 7

inotify is a Linux kernel subsystem and API that notifies user-space programs about filesystem events, such as files being created, modified, moved or deleted, so applications can react immediately instead of repeatedly scanning directories. It has been part of the mainline kernel since version 2.6.13 in 2005, where it replaced the older and clumsier dnotify mechanism.

In the Linux filesystem stack, inotify sits above the virtual filesystem layer, which means it works with ext4, XFS, Btrfs, tmpfs and most other local filesystems. Tools such as file synchronizers, build systems, desktop file managers, log shippers and systemd path units all depend on it.

How inotify delivers filesystem events

inotify works through a file descriptor-based interface built on three system calls. A program calls inotify_init1() to obtain an inotify instance, adds one watch per file or directory with inotify_add_watch(), and then reads a stream of event records from the descriptor with read(), typically inside a poll(), select() or epoll loop.

Each record is a struct inotify_event containing a watch descriptor, an event mask, a cookie that links the two halves of a rename, and, for events inside a watched directory, the name of the affected entry. The kernel queues events per instance and merges identical consecutive events to limit queue growth.

CallPurposeReturns
inotify_init1()Creates a new inotify instanceFile descriptor for reading events
inotify_add_watch()Watches a path for selected eventsWatch descriptor, an integer
inotify_rm_watch()Removes a watchZero on success
read()Retrieves queued event recordsOne or more event structures
close()Destroys the instance and all watchesZero on success
inotify system calls and their roles

Watches are tied to inodes, not path names. If a watched file is renamed, the watch follows the inode; if it is deleted and replaced, the old watch ends with IN_IGNORED and the program must add a new one.

Event types an inotify watch can report

An inotify watch reports only the events selected in its bit mask, so a program can subscribe narrowly and reduce noise. The most widely used flags are listed below; several can be combined, and IN_ALL_EVENTS selects them all.

FlagTriggered whenTypical use
IN_CREATEAn entry is created in a watched directoryDetecting new uploads
IN_CLOSE_WRITEA file opened for writing is closedProcessing a file once fully written
IN_MODIFYFile content is writtenLive preview or tailing
IN_MOVED_FROM / IN_MOVED_TOAn entry is renamed or movedTracking renames with the cookie
IN_DELETEAn entry is removed from a watched directoryCleaning up indexes or caches
IN_ATTRIBMetadata such as permissions or timestamps changeReacting to chmod or touch
IN_Q_OVERFLOWThe event queue overflowedTriggering a full rescan
Common inotify event flags

A common best practice is to act on `IN_CLOSE_WRITE` rather than `IN_MODIFY` when processing incoming files, because a single large write produces many modify events while the file is still incomplete.

inotify compared with other change-detection methods

inotify is the standard per-object notification API on Linux, but it is not the only option. Polling remains universal, dnotify is its obsolete predecessor, and fanotify offers mount-wide or filesystem-wide monitoring aimed at security and auditing software.

MethodScopeStrengthsWeaknesses
PollingAny pathWorks everywhere, including network sharesSlow reaction and wasted CPU and I/O
dnotifyDirectories onlyHistorical compatibilityUses signals and holds directories open
inotifyIndividual files and directoriesPrecise, efficient, widely supportedNo recursion; one watch per directory
fanotifyMounts or whole filesystemsScales to large trees; can allow or deny accessNeeds elevated privileges for many features
Ways to detect filesystem changes on Linux

On other platforms the equivalent roles are filled by kqueue on BSD and macOS, FSEvents on macOS, and ReadDirectoryChangesW on Windows. Cross-platform libraries wrap these differences behind a single interface.

Practical use and kernel limits

Administrators usually meet inotify through the inotify-tools package, which provides inotifywait for blocking until an event occurs and inotifywatch for gathering event statistics. A command such as inotifywait -m -e close_write /srv/incoming prints each completed file, which makes simple shell automation easy.

Because inotify watches are not recursive, a program that monitors a tree must add a watch to every subdirectory and add new ones as directories appear. Large trees therefore hit the per-user kernel limits, which are tunable under /proc/sys/fs/inotify/.

SettingControlsEffect of raising it
max_user_watchesTotal watches per userAllows monitoring larger directory trees
max_user_instancesinotify instances per userAllows more concurrent watching programs
max_queued_eventsQueue length per instanceReduces the risk of overflow during bursts
inotify kernel tunables

Defaults vary by kernel version and available memory; recent kernels size max_user_watches automatically, often in the tens of thousands to over a million. Each watch consumes a small amount of unswappable kernel memory, so the value should match real need, and it is set persistently with a file under /etc/sysctl.d/.

Limitations and common mistakes with inotify

The most frequent misunderstanding is expecting inotify to see every change on every filesystem. It reports only changes made through the local kernel, so edits made by another client on NFS, SMB or other network filesystems are usually invisible, and many FUSE and pseudo filesystems such as /proc and sysfs report little or nothing.

  • Queue overflow loses events: when IN_Q_OVERFLOW arrives, the program must rescan instead of trusting its state.
  • Race conditions on new directories: files created before a watch is added to a fresh subdirectory are missed unless the program scans it.
  • No user or process information: events do not say who made the change; fanotify or the audit subsystem is needed for that.
  • Exhausted watch limits produce the error message “no space left on device”, which misleadingly suggests a full disk.
  • Renames need pairing: matching IN_MOVED_FROM and IN_MOVED_TO by cookie is required to tell a rename from a delete plus create.

Robust applications therefore treat inotify as a fast hint, not a complete journal, combining event handling with periodic reconciliation scans.

In simple terms

Imagine waiting for a letter by walking to the mailbox every five minutes. That is how a program behaves without inotify: it keeps checking folders to see whether anything changed. inotify is like a doorbell that rings the moment a file arrives, changes or disappears.

Programs ask the Linux kernel to watch certain files or folders, and the kernel tells them as soon as something happens. This saves time and computing power, and it is why tools that sync files or rebuild software can react almost instantly.

A practical example

A printing company receives customer artwork through an SFTP server running Linux. Files land in /srv/upload, and each one must be converted to a print-ready PDF. Previously, a cron job scanned the folder every minute, so customers waited up to 60 seconds and partially uploaded files were sometimes processed by mistake.

The administrator replaces the cron job with a small service that runs inotifywait -m -e close_write on the upload directory and passes each finished file to the conversion script. Conversion now starts within a fraction of a second after an upload completes, and because the service reacts only to closed files, broken half-uploaded jobs disappear. A nightly scan remains as a safety net for any missed event.