Inotify - Filesystem Change Notification

A filesystem change notification mechanism introduced starting with Linux kernel 2.6.13. It monitors the filesystem and promptly alerts dedicated applications of related events, such as delete, read, write, and unmount operations. [1]

inotify C API

Inotify provides 3 system calls [2]

inotify_init()

Creates an instance of the inotify subsystem in the kernel. Returns -1 on failure; on success it returns a file descriptor, and you call read() to wait for alerts. read() returns a struct inotify_event event structure:

struct inotify_event
{
 int      wd;       /* Watch descriptor */
 uint32_t mask;     /* Mask of events */
 uint32_t cookie;   /* Unique cookie associating related events (for rename(2)) */
 uint32_t len;      /* Size of name field */
 char     name[];   /* Optional null-terminated name */
};

inotify_add_watch()

Used to add a watch. Each watch must be given a pathname and a list of related events; to watch multiple events, simply combine them with the logical OR operator — the pipe (|) operator in C

inotify_add_watch( fd, "/home/strike", IN_MODIFY | IN_CREATE | IN_DELETE );

This call returns a unique identifier, which is used to modify or remove the associated watch. If the call fails it returns -1.

Event list:

  • IN_ACCESS: the file was accessed;

  • IN_MODIFY: the file was modified;

  • IN_ATTRIB: the file’s attributes were changed, e.g. via chmod, chown, touch, etc.;

  • IN_CLOSE_WRITE: a writable file was closed;

  • IN_CLOSE_NOWRITE: a non-writable file was closed;

  • IN_CLOSE: the file was closed, equivalent to (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE);

  • IN_OPEN: the file was opened;

  • IN_MOVED_FROM: the file was moved away, e.g. via mv;

  • IN_MOVED_TO: the file was moved in, e.g. via mv or cp;

  • IN_MOVE: the file was moved, equivalent to (IN_MOVED_FROM | IN_MOVED_TO);

  • IN_CREATE: a new file was created;

  • IN_DELETE: the file was deleted, e.g. via rm;

  • IN_DELETE_SELF: self-deletion, i.e. an executable file deletes itself while running;

  • IN_MOVE_SELF: self-move, i.e. an executable file moves itself while running;

  • IN_ONESHOT: watch for only a single event;

  • IN_ONLYDIR: watch directories only;

  • IN_UNMOUNT: the host filesystem was unmounted;

  • IN_ALL_EVENTS: all of the events above;

inotify_rm_watch()

Removes a watch.

inotify-tools

The Inotify tools library provides command-line tools for monitoring filesystem activity [3]

apt-get install inotify-tools

This tool provides two commands

  • inotifywait simply blocks and waits for inotify events.

You can monitor any set of files and directories, or watch an entire directory tree (directories, subdirectories, sub-subdirectories, and so on).

inotifywait -rme modify,attrib,move,close_write,create,delete,delete_self path

  • inotifywatch collects statistics about the watched filesystem, including how many times each inotify event occurred.

inotifywatch [OPTION] FILE

References