# phpman > man > inotify(7)

[INOTIFY(7)](https://www.chedong.com/phpMan.php/man/INOTIFY/7/markdown)                            Linux Programmer's Manual                           [INOTIFY(7)](https://www.chedong.com/phpMan.php/man/INOTIFY/7/markdown)



## NAME
       inotify - monitoring filesystem events

## DESCRIPTION
       The  _inotify_  API provides a mechanism for monitoring filesystem events.  Inotify can be used
       to monitor individual files, or to monitor directories.  When a directory is monitored,  ino‐
       tify will return events for the directory itself, and for files inside the directory.

       The following system calls are used with this API:

       *  **inotify**___**[init**(2)](https://www.chedong.com/phpMan.php/man/init/2/markdown) creates an inotify instance and returns a file descriptor referring to the
          inotify instance.  The more recent **inotify**___**[init1**(2)](https://www.chedong.com/phpMan.php/man/init1/2/markdown) is like  **inotify**___**[init**(2)](https://www.chedong.com/phpMan.php/man/init/2/markdown),  but  has  a
          _flags_ argument that provides access to some extra functionality.

       *  **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown)  manipulates  the  "watch  list" associated with an inotify instance.
          Each item ("watch") in the watch list specifies the pathname of a file or directory, along
          with  some  set  of events that the kernel should monitor for the file referred to by that
          pathname.  **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown) either creates a new watch item, or modifies  an  existing
          watch.   Each  watch  has  a  unique  "watch  descriptor",  an  integer  returned  by **ino**‐‐
          **tify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown) when the watch is created.

       *  When events occur for monitored files and directories, those events are made available  to
          the application as structured data that can be read from the inotify file descriptor using
          [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) (see below).

       *  **inotify**___**rm**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown) removes an item from an inotify watch list.

       *  When all file descriptors referring  to  an  inotify  instance  have  been  closed  (using
          [**close**(2)](https://www.chedong.com/phpMan.php/man/close/2/markdown)),  the underlying object and its resources are freed for reuse by the kernel; all
          associated watches are automatically freed.

       With careful programming, an application can use inotify to efficiently monitor and cache the
       state of a set of filesystem objects.  However, robust applications should allow for the fact
       that bugs in the monitoring logic or races of the kind described below may  leave  the  cache
       inconsistent with the filesystem state.  It is probably wise to do some consistency checking,
       and rebuild the cache when inconsistencies are detected.

### Reading events from an inotify file descriptor
       To determine what events have occurred, an application [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown)s from  the  inotify  file  de‐
       scriptor.   If  no  events  have  so far occurred, then, assuming a blocking file descriptor,
       [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) will block until at least one event occurs (unless interrupted by a signal, in  which
       case the call fails with the error **EINTR**; see [**signal**(7)](https://www.chedong.com/phpMan.php/man/signal/7/markdown)).

       Each successful [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) returns a buffer containing one or more of the following structures:

           struct inotify_event {
               int      wd;       /* Watch descriptor */
               uint32_t mask;     /* Mask describing event */
               uint32_t cookie;   /* Unique cookie associating related
                                     events (for [rename(2)](https://www.chedong.com/phpMan.php/man/rename/2/markdown)) */
               uint32_t len;      /* Size of _name_ field */
               char     name[];   /* Optional null-terminated name */
           };

       _wd_  identifies the watch for which this event occurs.  It is one of the watch descriptors re‐
       turned by a previous call to **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown).

       _mask_ contains bits that describe the event that occurred (see below).

       _cookie_ is a unique integer that connects related events.  Currently, this is  used  only  for
       rename  events,  and  allows the resulting pair of **IN**___**MOVED**___**FROM** and **IN**___**MOVED**___**TO** events to be
       connected by the application.  For all other event types, _cookie_ is set to 0.

       The _name_ field is present only when an event is returned for a file inside a  watched  direc‐
       tory;  it identifies the filename within the watched directory.  This filename is null-termi‐
       nated, and may include further null bytes ('\0') to align subsequent reads to a suitable  ad‐
       dress boundary.

       The  _len_  field counts all of the bytes in _name_, including the null bytes; the length of each
       _inotify_event_ structure is thus _sizeof(struct_ _inotify_event)+len_.

       The behavior when the buffer given to [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) is too small to return  information  about  the
       next  event depends on the kernel version: in kernels before 2.6.21, [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) returns 0; since
       kernel 2.6.21, [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) fails with the error **EINVAL**.  Specifying a buffer of size

           sizeof(struct inotify_event) + NAME_MAX + 1

       will be sufficient to read at least one event.

### inotify events
       The **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown) _mask_ argument and the _mask_ field of the _inotify_event_ structure  re‐
       turned  when  [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown)ing  an  inotify  file descriptor are both bit masks identifying inotify
       events.  The following bits can be specified in _mask_ when  calling  **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown)  and
       may be returned in the _mask_ field returned by [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown):

           **IN**___**ACCESS** (+)
                  File was accessed (e.g., [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown), [**execve**(2)](https://www.chedong.com/phpMan.php/man/execve/2/markdown)).

           **IN**___**ATTRIB** (*)
                  Metadata changed—for example, permissions (e.g., [**chmod**(2)](https://www.chedong.com/phpMan.php/man/chmod/2/markdown)), timestamps (e.g., **uti**‐‐
                  [**mensat**(2)](https://www.chedong.com/phpMan.php/man/mensat/2/markdown)), extended attributes ([**setxattr**(2)](https://www.chedong.com/phpMan.php/man/setxattr/2/markdown)), link  count  (since  Linux  2.6.25;
                  e.g.,  for  the  target  of  [**link**(2)](https://www.chedong.com/phpMan.php/man/link/2/markdown)  and for [**unlink**(2)](https://www.chedong.com/phpMan.php/man/unlink/2/markdown)), and user/group ID (e.g.,
                  [**chown**(2)](https://www.chedong.com/phpMan.php/man/chown/2/markdown)).

           **IN**___**CLOSE**___**WRITE** (+)
                  File opened for writing was closed.

           **IN**___**CLOSE**___**NOWRITE** (*)
                  File or directory not opened for writing was closed.

           **IN**___**CREATE** (+)
                  File/directory created in watched  directory  (e.g.,  [**open**(2)](https://www.chedong.com/phpMan.php/man/open/2/markdown)  **O**___**CREAT**,  [**mkdir**(2)](https://www.chedong.com/phpMan.php/man/mkdir/2/markdown),
                  [**link**(2)](https://www.chedong.com/phpMan.php/man/link/2/markdown), [**symlink**(2)](https://www.chedong.com/phpMan.php/man/symlink/2/markdown), [**bind**(2)](https://www.chedong.com/phpMan.php/man/bind/2/markdown) on a UNIX domain socket).

           **IN**___**DELETE** (+)
                  File/directory deleted from watched directory.

           **IN**___**DELETE**___**SELF**
                  Watched  file/directory  was itself deleted.  (This event also occurs if an object
                  is moved to another filesystem, since [**mv**(1)](https://www.chedong.com/phpMan.php/man/mv/1/markdown) in effect copies the file to the other
                  filesystem  and  then  deletes  it from the original filesystem.)  In addition, an
                  **IN**___**IGNORED** event will subsequently be generated for the watch descriptor.

           **IN**___**MODIFY** (+)
                  File was modified (e.g., [**write**(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown), [**truncate**(2)](https://www.chedong.com/phpMan.php/man/truncate/2/markdown)).

           **IN**___**MOVE**___**SELF**
                  Watched file/directory was itself moved.

           **IN**___**MOVED**___**FROM** (+)
                  Generated for the directory containing the old filename when a file is renamed.

           **IN**___**MOVED**___**TO** (+)
                  Generated for the directory containing the new filename when a file is renamed.

           **IN**___**OPEN** (*)
                  File or directory was opened.

       Inotify monitoring is inode-based: when monitoring a file (but not when monitoring the direc‐
       tory  containing  a file), an event can be generated for activity on any link to the file (in
       the same or a different directory).

       When monitoring a directory:

       *  the events marked above with an asterisk (*) can occur both for the directory  itself  and
          for objects inside the directory; and

       *  the  events  marked  with a plus sign (+) occur only for objects inside the directory (not
          for the directory itself).

       _Note_: when monitoring a directory, events are not generated for the files inside  the  direc‐
       tory  when the events are performed via a pathname (i.e., a link) that lies outside the moni‐
       tored directory.

       When events are generated for objects inside a watched directory, the _name_ field in  the  re‐
       turned _inotify_event_ structure identifies the name of the file within the directory.

       The  **IN**___**ALL**___**EVENTS** macro is defined as a bit mask of all of the above events.  This macro can
       be used as the _mask_ argument when calling **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown).

       Two additional convenience macros are defined:

           **IN**___**MOVE**
                  Equates to **IN**___**MOVED**___**FROM** **|** **IN**___**MOVED**___**TO**.

           **IN**___**CLOSE**
                  Equates to **IN**___**CLOSE**___**WRITE** **|** **IN**___**CLOSE**___**NOWRITE**.

       The following further bits can be specified in _mask_ when calling **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown):

           **IN**___**DONT**___**FOLLOW** (since Linux 2.6.15)
                  Don't dereference _pathname_ if it is a symbolic link.

           **IN**___**EXCL**___**UNLINK** (since Linux 2.6.36)
                  By default, when watching events on the children of a directory, events are gener‐
                  ated for children even after they have been unlinked from the directory.  This can
                  result in large numbers of uninteresting events for some  applications  (e.g.,  if
                  watching  _/tmp_,  in which many applications create temporary files whose names are
                  immediately unlinked).  Specifying **IN**___**EXCL**___**UNLINK** changes the default behavior, so
                  that  events are not generated for children after they have been unlinked from the
                  watched directory.

           **IN**___**MASK**___**ADD**
                  If a watch instance already exists for  the  filesystem  object  corresponding  to
                  _pathname_,  add (OR) the events in _mask_ to the watch mask (instead of replacing the
                  mask); the error **EINVAL** results if **IN**___**MASK**___**CREATE** is also specified.

           **IN**___**ONESHOT**
                  Monitor the filesystem object corresponding to _pathname_ for one event, then remove
                  from watch list.

           **IN**___**ONLYDIR** (since Linux 2.6.15)
                  Watch _pathname_ only if it is a directory; the error **ENOTDIR** results if _pathname_ is
                  not a directory.  Using this flag provides an application with a race-free way  of
                  ensuring that the monitored object is a directory.

           **IN**___**MASK**___**CREATE** (since Linux 4.18)
                  Watch  _pathname_  only  if it does not already have a watch associated with it; the
                  error **EEXIST** results if _pathname_ is already being watched.

                  Using this flag provides an application with a way of ensuring that new watches do
                  not  modify existing ones.  This is useful because multiple paths may refer to the
                  same inode, and multiple calls to **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown) without this flag may clob‐
                  ber existing watch masks.

       The following bits may be set in the _mask_ field returned by [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown):

           **IN**___**IGNORED**
                  Watch  was  removed  explicitly  (**inotify**___**rm**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown))  or automatically (file was
                  deleted, or filesystem was unmounted).  See also BUGS.

           **IN**___**ISDIR**
                  Subject of this event is a directory.

           **IN**___**Q**___**OVERFLOW**
                  Event queue overflowed (_wd_ is -1 for this event).

           **IN**___**UNMOUNT**
                  Filesystem containing watched object was unmounted.  In  addition,  an  **IN**___**IGNORED**
                  event will subsequently be generated for the watch descriptor.

### Examples
       Suppose  an application is watching the directory _dir_ and the file _dir/myfile_ for all events.
       The examples below show some events that will be generated for these two objects.

           fd = open("dir/myfile", O_RDWR);
                  Generates **IN**___**OPEN** events for both _dir_ and _dir/myfile_.

           read(fd, buf, count);
                  Generates **IN**___**ACCESS** events for both _dir_ and _dir/myfile_.

           write(fd, buf, count);
                  Generates **IN**___**MODIFY** events for both _dir_ and _dir/myfile_.

           fchmod(fd, mode);
                  Generates **IN**___**ATTRIB** events for both _dir_ and _dir/myfile_.

           close(fd);
                  Generates **IN**___**CLOSE**___**WRITE** events for both _dir_ and _dir/myfile_.

       Suppose an application is watching the directories _dir1_ and _dir2_, and the  file  _dir1/myfile_.
       The following examples show some events that may be generated.

           link("dir1/myfile", "dir2/new");
                  Generates an **IN**___**ATTRIB** event for _myfile_ and an **IN**___**CREATE** event for _dir2_.

           rename("dir1/myfile", "dir2/myfile");
                  Generates  an  **IN**___**MOVED**___**FROM** event for _dir1_, an **IN**___**MOVED**___**TO** event for _dir2_, and an
                  **IN**___**MOVE**___**SELF** event for _myfile_.  The **IN**___**MOVED**___**FROM** and **IN**___**MOVED**___**TO** events will have
                  the same _cookie_ value.

       Suppose that _dir1/xx_ and _dir2/yy_ are (the only) links to the same file, and an application is
       watching _dir1_, _dir2_, _dir1/xx_, and _dir2/yy_.  Executing the following calls in the order  given
       below will generate the following events:

           unlink("dir2/yy");
                  Generates  an  **IN**___**ATTRIB**  event  for  _xx_  (because  its link count changes) and an
                  **IN**___**DELETE** event for _dir2_.

           unlink("dir1/xx");
                  Generates  **IN**___**ATTRIB**,  **IN**___**DELETE**___**SELF**,  and  **IN**___**IGNORED**  events  for  _xx_,  and  an
                  **IN**___**DELETE** event for _dir1_.

       Suppose  an  application  is watching the directory _dir_ and (the empty) directory _dir/subdir_.
       The following examples show some events that may be generated.

           mkdir("dir/new", mode);
                  Generates an **IN**___**CREATE** **|** **IN**___**ISDIR** event for _dir_.

           rmdir("dir/subdir");
                  Generates **IN**___**DELETE**___**SELF** and **IN**___**IGNORED** events for  _subdir_,  and  an  **IN**___**DELETE**  **|**
                  **IN**___**ISDIR** event for _dir_.

### /proc interfaces
       The  following  interfaces  can be used to limit the amount of kernel memory consumed by ino‐
       tify:

       _/proc/sys/fs/inotify/max_queued_events_
              The value in this file is used when an application calls **inotify**___**[init**(2)](https://www.chedong.com/phpMan.php/man/init/2/markdown) to set an up‐
              per  limit on the number of events that can be queued to the corresponding inotify in‐
              stance.  Events in excess of this limit are dropped, but an **IN**___**Q**___**OVERFLOW** event is al‐
              ways generated.

       _/proc/sys/fs/inotify/max_user_instances_
              This  specifies  an upper limit on the number of inotify instances that can be created
              per real user ID.

       _/proc/sys/fs/inotify/max_user_watches_
              This specifies an upper limit on the number of watches that can be  created  per  real
              user ID.

## VERSIONS
       Inotify  was merged into the 2.6.13 Linux kernel.  The required library interfaces were added
       to glibc in version 2.4.  (**IN**___**DONT**___**FOLLOW**, **IN**___**MASK**___**ADD**, and **IN**___**ONLYDIR** were  added  in  glibc
       version 2.5.)

## CONFORMING TO
       The inotify API is Linux-specific.

## NOTES
       Inotify  file  descriptors  can be monitored using [**select**(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown), [**poll**(2)](https://www.chedong.com/phpMan.php/man/poll/2/markdown), and [**epoll**(7)](https://www.chedong.com/phpMan.php/man/epoll/7/markdown).  When an
       event is available, the file descriptor indicates as readable.

       Since Linux 2.6.25, signal-driven I/O notification is available for inotify file descriptors;
       see  the  discussion of **F**___**SETFL** (for setting the **O**___**ASYNC** flag), **F**___**SETOWN**, and **F**___**SETSIG** in **fc**‐‐
       [**ntl**(2)](https://www.chedong.com/phpMan.php/man/ntl/2/markdown).  The _siginfo_t_ structure (described in [**sigaction**(2)](https://www.chedong.com/phpMan.php/man/sigaction/2/markdown)) that is  passed  to  the  signal
       handler  has  the  following  fields set: _si_fd_ is set to the inotify file descriptor number;
       _si_signo_ is set to the signal number; _si_code_ is  set  to  **POLL**___**IN**;  and  **POLLIN**  is  set  in
       _si_band_.

       If  successive  output  inotify  events produced on the inotify file descriptor are identical
       (same _wd_, _mask_, _cookie_, and _name_), then they are coalesced into a single event if  the  older
       event  has  not  yet  been read (but see BUGS).  This reduces the amount of kernel memory re‐
       quired for the event queue, but also means that an application can't use inotify to  reliably
       count file events.

       The  events returned by reading from an inotify file descriptor form an ordered queue.  Thus,
       for example, it is guaranteed that when renaming from one directory to another,  events  will
       be produced in the correct order on the inotify file descriptor.

       The  set  of  watch descriptors that is being monitored via an inotify file descriptor can be
       viewed via the entry for the inotify file descriptor in the process's _/proc/[pid]/fdinfo_  di‐
       rectory.  See [**proc**(5)](https://www.chedong.com/phpMan.php/man/proc/5/markdown) for further details.  The **FIONREAD** [**ioctl**(2)](https://www.chedong.com/phpMan.php/man/ioctl/2/markdown) returns the number of bytes
       available to read from an inotify file descriptor.

### Limitations and caveats
       The inotify API provides no information about the user or process that triggered the  inotify
       event.   In particular, there is no easy way for a process that is monitoring events via ino‐
       tify to distinguish events that it triggers itself from those that  are  triggered  by  other
       processes.

       Inotify  reports  only  events that a user-space program triggers through the filesystem API.
       As a result, it does not catch remote events that occur on  network  filesystems.   (Applica‐
       tions  must  fall back to polling the filesystem to catch such events.)  Furthermore, various
       pseudo-filesystems such as _/proc_, _/sys_, and _/dev/pts_ are not monitorable with inotify.

       The inotify API does not report file accesses and modifications that  may  occur  because  of
       [**mmap**(2)](https://www.chedong.com/phpMan.php/man/mmap/2/markdown), [**msync**(2)](https://www.chedong.com/phpMan.php/man/msync/2/markdown), and [**munmap**(2)](https://www.chedong.com/phpMan.php/man/munmap/2/markdown).

       The  inotify  API identifies affected files by filename.  However, by the time an application
       processes an inotify event, the filename may already have been deleted or renamed.

       The inotify API identifies events via watch descriptors.  It is the  application's  responsi‐
       bility  to  cache  a  mapping (if one is needed) between watch descriptors and pathnames.  Be
       aware that directory renamings may affect multiple cached pathnames.

       Inotify monitoring of directories is not recursive: to monitor subdirectories under a  direc‐
       tory,  additional watches must be created.  This can take a significant amount time for large
       directory trees.

       If monitoring an entire directory subtree, and a new subdirectory is created in that tree  or
       an existing directory is renamed into that tree, be aware that by the time you create a watch
       for the new subdirectory, new files (and subdirectories) may already exist inside the  subdi‐
       rectory.   Therefore, you may want to scan the contents of the subdirectory immediately after
       adding the watch (and, if desired, recursively add watches for  any  subdirectories  that  it
       contains).

       Note  that the event queue can overflow.  In this case, events are lost.  Robust applications
       should handle the possibility of lost events gracefully.  For example, it may be necessary to
       rebuild  part or all of the application cache.  (One simple, but possibly expensive, approach
       is to close the inotify file descriptor, empty the cache, create a new inotify file  descrip‐
       tor, and then re-create watches and cache entries for the objects to be monitored.)

       If  a  filesystem  is  mounted on top of a monitored directory, no event is generated, and no
       events are generated for objects immediately under the new mount point.  If the filesystem is
       subsequently  unmounted,  events will subsequently be generated for the directory and the ob‐
       jects it contains.

### Dealing with rename() events
       As noted above, the **IN**___**MOVED**___**FROM** and **IN**___**MOVED**___**TO** event pair that is generated  by  [**rename**(2)](https://www.chedong.com/phpMan.php/man/rename/2/markdown)
       can  be  matched  up  via  their shared cookie value.  However, the task of matching has some
       challenges.

       These two events are usually consecutive in the event stream available when reading from  the
       inotify  file  descriptor.  However, this is not guaranteed.  If multiple processes are trig‐
       gering events for monitored objects, then (on rare occasions) an arbitrary  number  of  other
       events  may  appear between the **IN**___**MOVED**___**FROM** and **IN**___**MOVED**___**TO** events.  Furthermore, it is not
       guaranteed that the event pair is atomically inserted into the queue: there may  be  a  brief
       interval where the **IN**___**MOVED**___**FROM** has appeared, but the **IN**___**MOVED**___**TO** has not.

       Matching  up  the **IN**___**MOVED**___**FROM** and **IN**___**MOVED**___**TO** event pair generated by [**rename**(2)](https://www.chedong.com/phpMan.php/man/rename/2/markdown) is thus in‐
       herently racy.  (Don't forget that if an object is renamed outside of a monitored  directory,
       there  may  not even be an **IN**___**MOVED**___**TO** event.)  Heuristic approaches (e.g., assume the events
       are always consecutive) can be used to ensure a match in most cases, but will inevitably miss
       some  cases,  causing the application to perceive the **IN**___**MOVED**___**FROM** and **IN**___**MOVED**___**TO** events as
       being unrelated.  If watch descriptors are destroyed and re-created as a result,  then  those
       watch  descriptors  will  be  inconsistent  with the watch descriptors in any pending events.
       (Re-creating the inotify file descriptor and rebuilding the cache may be useful to deal  with
       this scenario.)

       Applications  should also allow for the possibility that the **IN**___**MOVED**___**FROM** event was the last
       event that could fit in the buffer returned by the current call to [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown), and the  accompa‐
       nying  **IN**___**MOVED**___**TO** event might be fetched only on the next [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown), which should be done with
       a (small) timeout to allow for the fact that insertion of the **IN**___**MOVED**___**FROM**-**IN**___**MOVED**___**TO** event
       pair is not atomic, and also the possibility that there may not be any **IN**___**MOVED**___**TO** event.

## BUGS
       Before  Linux  3.19, [**fallocate**(2)](https://www.chedong.com/phpMan.php/man/fallocate/2/markdown) did not create any inotify events.  Since Linux 3.19, calls
       to [**fallocate**(2)](https://www.chedong.com/phpMan.php/man/fallocate/2/markdown) generate **IN**___**MODIFY** events.

       In kernels before 2.6.16, the **IN**___**ONESHOT** _mask_ flag does not work.

       As originally designed and implemented, the **IN**___**ONESHOT** flag did not cause an **IN**___**IGNORED** event
       to be generated when the watch was dropped after one event.  However, as an unintended effect
       of other changes, since Linux 2.6.36, an **IN**___**IGNORED** event is generated in this case.

       Before kernel 2.6.25, the kernel code that was  intended  to  coalesce  successive  identical
       events  (i.e., the two most recent events could potentially be coalesced if the older had not
       yet been read) instead checked if the most recent event could be coalesced  with  the  _oldest_
       unread event.

       When a watch descriptor is removed by calling **inotify**___**rm**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown) (or because a watch file is
       deleted or the filesystem that contains it is unmounted), any pending unread events for  that
       watch  descriptor  remain available to read.  As watch descriptors are subsequently allocated
       with **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown), the kernel cycles through the range of possible watch  descriptors
       (0  to  **INT**___**MAX**) incrementally.  When allocating a free watch descriptor, no check is made to
       see whether that watch descriptor number has any pending unread events in the inotify  queue.
       Thus,  it  can  happen that a watch descriptor is reallocated even when pending unread events
       exist for a previous incarnation of that watch descriptor number, with the  result  that  the
       application  might then read those events and interpret them as belonging to the file associ‐
       ated with the newly recycled watch descriptor.  In practice, the likelihood of  hitting  this
       bug  may  be extremely low, since it requires that an application cycle through **INT**___**MAX** watch
       descriptors, release a watch descriptor while leaving unread events for that watch descriptor
       in  the  queue,  and  then recycle that watch descriptor.  For this reason, and because there
       have been no reports of the bug occurring in real-world applications, as of  Linux  3.15,  no
       kernel changes have yet been made to eliminate this possible bug.

## EXAMPLES
       The  following  program  demonstrates the usage of the inotify API.  It marks the directories
       passed as a command-line arguments and waits for events of  type  **IN**___**OPEN**,  **IN**___**CLOSE**___**NOWRITE**,
       and **IN**___**CLOSE**___**WRITE**.

       The  following output was recorded while editing the file _/home/user/temp/foo_ and listing di‐
       rectory _/tmp_.  Before the file and the directory were opened, **IN**___**OPEN** events occurred.  After
       the  file  was  closed, an **IN**___**CLOSE**___**WRITE** event occurred.  After the directory was closed, an
       **IN**___**CLOSE**___**NOWRITE** event occurred.  Execution of the program ended when the  user  pressed  the
       ENTER key.

### Example output
           $ **./a.out** **/tmp** **/home/user/temp**
           Press enter key to terminate.
           Listening for events.
           IN_OPEN: /home/user/temp/foo [file]
           IN_CLOSE_WRITE: /home/user/temp/foo [file]
           IN_OPEN: /tmp/ [directory]
           IN_CLOSE_NOWRITE: /tmp/ [directory]

           Listening for events stopped.

### Program source

       #include <errno.h>
       #include <poll.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <sys/inotify.h>
       #include <unistd.h>
       #include <string.h>

       /* Read all available inotify events from the file descriptor 'fd'.
          wd is the table of watch descriptors for the directories in argv.
          argc is the length of wd and argv.
          argv is the list of watched directories.
          Entry 0 of wd and argv is unused. */

       static void
       handle_events(int fd, int *wd, int argc, char* argv[])
       {
           /* Some systems cannot read integer variables if they are not
              properly aligned. On other systems, incorrect alignment may
              decrease performance. Hence, the buffer used for reading from
              the inotify file descriptor should have the same alignment as
              struct inotify_event. */

           char buf[4096]
               __attribute__ ((aligned(__alignof__(struct inotify_event))));
           const struct inotify_event *event;
           ssize_t len;

           /* Loop while events can be read from inotify file descriptor. */

           for (;;) {

               /* Read some events. */

               len = read(fd, buf, sizeof(buf));
               if (len == -1 && errno != EAGAIN) {
                   perror("read");
                   exit(EXIT_FAILURE);
               }

               /* If the nonblocking read() found no events to read, then
                  it returns -1 with errno set to EAGAIN. In that case,
                  we exit the loop. */

               if (len <= 0)
                   break;

               /* Loop over all events in the buffer */

               for (char *ptr = buf; ptr < buf + len;
                       ptr += sizeof(struct inotify_event) + event->len) {

                   event = (const struct inotify_event *) ptr;

                   /* Print event type */

                   if (event->mask & IN_OPEN)
                       printf("IN_OPEN: ");
                   if (event->mask & IN_CLOSE_NOWRITE)
                       printf("IN_CLOSE_NOWRITE: ");
                   if (event->mask & IN_CLOSE_WRITE)
                       printf("IN_CLOSE_WRITE: ");

                   /* Print the name of the watched directory */

                   for (int i = 1; i < argc; ++i) {
                       if (wd[i] == event->wd) {
                           printf("%s/", argv[i]);
                           break;
                       }
                   }

                   /* Print the name of the file */

                   if (event->len)
                       printf("%s", event->name);

                   /* Print type of filesystem object */

                   if (event->mask & IN_ISDIR)
                       printf(" [directory]\n");
                   else
                       printf(" [file]\n");
               }
           }
       }

       int
       main(int argc, char* argv[])
       {
           char buf;
           int fd, i, poll_num;
           int *wd;
           nfds_t nfds;
           struct pollfd fds[2];

           if (argc < 2) {
               printf("Usage: %s PATH [PATH ...]\n", argv[0]);
               exit(EXIT_FAILURE);
           }

           printf("Press ENTER key to terminate.\n");

           /* Create the file descriptor for accessing the inotify API */

           fd = inotify_init1(IN_NONBLOCK);
           if (fd == -1) {
               perror("inotify_init1");
               exit(EXIT_FAILURE);
           }

           /* Allocate memory for watch descriptors */

           wd = calloc(argc, sizeof(int));
           if (wd == NULL) {
               perror("calloc");
               exit(EXIT_FAILURE);
           }

           /* Mark directories for events
              - file was opened
              - file was closed */

           for (i = 1; i < argc; i++) {
               wd[i] = inotify_add_watch(fd, argv[i],
                                         IN_OPEN | IN_CLOSE);
               if (wd[i] == -1) {
                   fprintf(stderr, "Cannot watch '%s': %s\n",
                           argv[i], strerror(errno));
                   exit(EXIT_FAILURE);
               }
           }

           /* Prepare for polling */

           nfds = 2;

           /* Console input */

           fds[0].fd = STDIN_FILENO;
           fds[0].events = POLLIN;

           /* Inotify input */

           fds[1].fd = fd;
           fds[1].events = POLLIN;

           /* Wait for events and/or terminal input */

           printf("Listening for events.\n");
           while (1) {
               poll_num = poll(fds, nfds, -1);
               if (poll_num == -1) {
                   if (errno == EINTR)
                       continue;
                   perror("poll");
                   exit(EXIT_FAILURE);
               }

               if (poll_num > 0) {

                   if (fds[0].revents & POLLIN) {

                       /* Console input is available. Empty stdin and quit */

                       while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\n')
                           continue;
                       break;
                   }

                   if (fds[1].revents & POLLIN) {

                       /* Inotify events are available */

                       handle_events(fd, wd, argc, argv);
                   }
               }
           }

           printf("Listening for events stopped.\n");

           /* Close inotify file descriptor */

           close(fd);

           free(wd);
           exit(EXIT_SUCCESS);
       }

## SEE ALSO
       [**inotifywait**(1)](https://www.chedong.com/phpMan.php/man/inotifywait/1/markdown), [**inotifywatch**(1)](https://www.chedong.com/phpMan.php/man/inotifywatch/1/markdown), **inotify**___**add**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown), **inotify**___**[init**(2)](https://www.chedong.com/phpMan.php/man/init/2/markdown), **inotify**___**[init1**(2)](https://www.chedong.com/phpMan.php/man/init1/2/markdown), **in**‐‐
       **otify**___**rm**___**[watch**(2)](https://www.chedong.com/phpMan.php/man/watch/2/markdown), [**read**(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown), [**stat**(2)](https://www.chedong.com/phpMan.php/man/stat/2/markdown), [**fanotify**(7)](https://www.chedong.com/phpMan.php/man/fanotify/7/markdown)

       _Documentation/filesystems/inotify.txt_ in the Linux kernel source tree

## COLOPHON
       This page is part of release 5.10 of the Linux  _man-pages_  project.   A  description  of  the
       project,  information about reporting bugs, and the latest version of this page, can be found
       at <https://www.kernel.org/doc/man-pages/>.



Linux                                        2020-11-01                                   [INOTIFY(7)](https://www.chedong.com/phpMan.php/man/INOTIFY/7/markdown)
