While reading the The linux programming interface book I finally dived deep in Inotify and how it works.

Basically inotify is a notification system for events happening on files/directory like access, changes, edit and so on. It was meant to replace dnotify, an older notification system, that used signals to notify about changes. Inotify is based on file descriptor opened when you watch a file and a read syscall to check the status of the file.

The flow of calls is the following:

  • Our program uses inotify_init() to create an inotify instance
  • Then we use inotify_add_watch() to add an item to the watchlist and we decided on which event we want to listen to. The function returns a file descriptor that we use to distinguish between data arriving.
  • We do a read() on the file descriptor returned from the previous step. The read can return several data, not just one datum.
  • After our application exit we close the file descriptor associated with the inotify instance.

Following there’s the inotify event structure and the explaination I took from the book.

struct inotify_event {
int wd; /* Watch descriptor on which event occurred */
  uint32_t mask; /* Bits describing event that occurred */
uint32_t cookie; /* Cookie for related events (for rename()) */
uint32_t len; /* Size of 'name' field */
char name[]; /* Optional null-terminated filename */

This structure contains all the data relevant to understand where the event comes from. wd is the file descriptor we added the watch on, the mask is an integer mask to understand the event that occurred by doing the bitwise & of the integer with the event value, the cookie is a field used for rename related event (IN_MOVED_FROM and IN_MOVED_TO), len is the length of the name field, name is the filename where the event happened.

Following I attach a simple program I wrote to check when a user invoke an ls command the current directory or in the parent directory.