1 .\" Copyright (C) 2006, 2014 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\" Copyright (C) 2014 Heinrich Schuchardt <xypron.glpk@gmx.de>
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .TH inotify 7 (date) "Linux man-pages (unreleased)"
8 inotify \- monitoring filesystem events
12 API provides a mechanism for monitoring filesystem events.
13 Inotify can be used to monitor individual files,
14 or to monitor directories.
15 When a directory is monitored, inotify will return events
16 for the directory itself, and for files inside the directory.
18 The following system calls are used with this API:
21 creates an inotify instance and returns a file descriptor
22 referring to the inotify instance.
29 argument that provides access to some extra functionality.
31 .BR inotify_add_watch (2)
32 manipulates the "watch list" associated with an inotify instance.
33 Each item ("watch") in the watch list specifies the pathname of
35 along with some set of events that the kernel should monitor for the
36 file referred to by that pathname.
37 .BR inotify_add_watch (2)
38 either creates a new watch item, or modifies an existing watch.
39 Each watch has a unique "watch descriptor", an integer
41 .BR inotify_add_watch (2)
42 when the watch is created.
44 When events occur for monitored files and directories,
45 those events are made available to the application as structured data that
46 can be read from the inotify file descriptor using
50 .BR inotify_rm_watch (2)
51 removes an item from an inotify watch list.
53 When all file descriptors referring to an inotify
54 instance have been closed (using
56 the underlying object and its resources are
57 freed for reuse by the kernel;
58 all associated watches are automatically freed.
60 With careful programming,
61 an application can use inotify to efficiently monitor and cache
62 the state of a set of filesystem objects.
63 However, robust applications should allow for the fact that bugs
64 in the monitoring logic or races of the kind described below
65 may leave the cache inconsistent with the filesystem state.
66 It is probably wise to do some consistency checking,
67 and rebuild the cache when inconsistencies are detected.
68 .SS Reading events from an inotify file descriptor
69 To determine what events have occurred, an application
71 from the inotify file descriptor.
72 If no events have so far occurred, then,
73 assuming a blocking file descriptor,
75 will block until at least one event occurs
76 (unless interrupted by a signal,
77 in which case the call fails with the error
84 returns a buffer containing one or more of the following structures:
88 struct inotify_event {
89 int wd; /* Watch descriptor */
90 .\" FIXME . The type of the 'wd' field should probably be "int32_t".
91 .\" I submitted a patch to fix this. See the LKML thread
92 .\" "[patch] Fix type errors in inotify interfaces", 18 Nov 2008
93 .\" glibc bug filed: https://www.sourceware.org/bugzilla/show_bug.cgi?id=7040
94 uint32_t mask; /* Mask describing event */
95 uint32_t cookie; /* Unique cookie associating related
96 events (for rename(2)) */
97 uint32_t len; /* Size of \fIname\fP field */
98 char name[]; /* Optional null\-terminated name */
104 identifies the watch for which this event occurs.
105 It is one of the watch descriptors returned by a previous call to
106 .BR inotify_add_watch (2).
109 contains bits that describe the event that occurred (see below).
112 is a unique integer that connects related events.
113 Currently, this is used only for rename events, and
114 allows the resulting pair of
118 events to be connected by the application.
119 For all other event types,
125 field is present only when an event is returned
126 for a file inside a watched directory;
127 it identifies the filename within the watched directory.
128 This filename is null-terminated,
129 and may include further null bytes (\[aq]\e0\[aq])
130 to align subsequent reads to a suitable address boundary.
134 field counts all of the bytes in
136 including the null bytes;
140 .IR "sizeof(struct inotify_event)+len" .
142 The behavior when the buffer given to
144 is too small to return information about the next event depends
145 on the kernel version: before Linux 2.6.21,
147 returns 0; since Linux 2.6.21,
151 Specifying a buffer of size
155 sizeof(struct inotify_event) + NAME_MAX + 1
159 will be sufficient to read at least one event.
162 .BR inotify_add_watch (2)
168 structure returned when
170 an inotify file descriptor are both bit masks identifying
172 The following bits can be specified in
175 .BR inotify_add_watch (2)
176 and may be returned in the
183 File was accessed (e.g.,
188 Metadata changed\[em]for example, permissions (e.g.,
194 link count (since Linux 2.6.25; e.g.,
196 .\" Events do not occur for link count changes on a file inside a monitored
197 .\" directory. This differs from other metadata changes for files inside
198 .\" a monitored directory.
203 and user/group ID (e.g.,
206 .BR IN_CLOSE_WRITE " (+)"
207 File opened for writing was closed.
209 .BR IN_CLOSE_NOWRITE " (*)"
210 File or directory not opened for writing was closed.
213 File/directory created in watched directory (e.g.,
220 on a UNIX domain socket).
223 File/directory deleted from watched directory.
226 Watched file/directory was itself deleted.
227 (This event also occurs if an object is moved to another filesystem,
230 in effect copies the file to the other filesystem and
231 then deletes it from the original filesystem.)
234 event will subsequently be generated for the watch descriptor.
237 File was modified (e.g.,
242 Watched file/directory was itself moved.
244 .BR IN_MOVED_FROM " (+)"
245 Generated for the directory containing the old filename
246 when a file is renamed.
248 .BR IN_MOVED_TO " (+)"
249 Generated for the directory containing the new filename
250 when a file is renamed.
253 File or directory was opened.
256 Inotify monitoring is inode-based: when monitoring a file
257 (but not when monitoring the directory containing a file),
258 an event can be generated for activity on any link to the file
259 (in the same or a different directory).
261 When monitoring a directory:
263 the events marked above with an asterisk (*) can occur both
264 for the directory itself and for objects inside the directory; and
266 the events marked with a plus sign (+) occur only for objects
267 inside the directory (not for the directory itself).
270 when monitoring a directory,
271 events are not generated for the files inside the directory
272 when the events are performed via a pathname (i.e., a link)
273 that lies outside the monitored directory.
275 When events are generated for objects inside a watched directory, the
277 field in the returned
279 structure identifies the name of the file within the directory.
283 macro is defined as a bit mask of all of the above events.
284 This macro can be used as the
286 argument when calling
287 .BR inotify_add_watch (2).
289 Two additional convenience macros are defined:
294 .BR "IN_MOVED_FROM | IN_MOVED_TO" .
298 .BR "IN_CLOSE_WRITE | IN_CLOSE_NOWRITE" .
301 The following further bits can be specified in
304 .BR inotify_add_watch (2):
307 .BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
310 if it is a symbolic link.
312 .BR IN_EXCL_UNLINK " (since Linux 2.6.36)"
313 .\" commit 8c1934c8d70b22ca8333b216aec6c7d09fdbd6a6
314 By default, when watching events on the children of a directory,
315 events are generated for children even after they have been unlinked
317 This can result in large numbers of uninteresting events for
318 some applications (e.g., if watching
320 in which many applications create temporary files whose
321 names are immediately unlinked).
324 changes the default behavior,
325 so that events are not generated for children after
326 they have been unlinked from the watched directory.
329 If a watch instance already exists for the filesystem object corresponding to
331 add (OR) the events in
333 to the watch mask (instead of replacing the mask);
341 Monitor the filesystem object corresponding to
343 for one event, then remove from
346 .BR IN_ONLYDIR " (since Linux 2.6.15)"
349 only if it is a directory;
355 Using this flag provides an application with a race-free way of
356 ensuring that the monitored object is a directory.
358 .BR IN_MASK_CREATE " (since Linux 4.18)"
361 only if it does not already have a watch associated with it;
366 is already being watched.
368 Using this flag provides an application with a way of ensuring
369 that new watches do not modify existing ones.
370 This is useful because multiple paths may refer to the same inode,
371 and multiple calls to
372 .BR inotify_add_watch (2)
373 without this flag may clobber existing watch masks.
376 The following bits may be set in the
383 Watch was removed explicitly
384 .RB ( inotify_rm_watch (2))
385 or automatically (file was deleted, or filesystem was unmounted).
389 Subject of this event is a directory.
392 Event queue overflowed
394 is \-1 for this event).
397 Filesystem containing watched object was unmounted.
400 event will subsequently be generated for the watch descriptor.
403 Suppose an application is watching the directory
408 The examples below show some events that will be generated
409 for these two objects.
412 fd = open("dir/myfile", O_RDWR);
420 read(fd, buf, count);
428 write(fd, buf, count);
453 Suppose an application is watching the directories
459 The following examples show some events that may be generated.
462 link("dir1/myfile", "dir2/new");
472 rename("dir1/myfile", "dir2/myfile");
489 events will have the same
498 are (the only) links to the same file, and an application is watching
504 Executing the following calls in the order given below will generate
505 the following events:
513 (because its link count changes)
533 Suppose an application is watching the directory
535 and (the empty) directory
537 The following examples show some events that may be generated.
540 mkdir("dir/new", mode);
542 .B "IN_CREATE | IN_ISDIR"
554 .B "IN_DELETE | IN_ISDIR"
559 The following interfaces can be used to limit the amount of
560 kernel memory consumed by inotify:
562 .I /proc/sys/fs/inotify/max_queued_events
563 The value in this file is used when an application calls
565 to set an upper limit on the number of events that can be
566 queued to the corresponding inotify instance.
567 Events in excess of this limit are dropped, but an
569 event is always generated.
571 .I /proc/sys/fs/inotify/max_user_instances
572 This specifies an upper limit on the number of inotify instances
573 that can be created per real user ID.
575 .I /proc/sys/fs/inotify/max_user_watches
576 This specifies an upper limit on the number of watches
577 that can be created per real user ID.
581 Inotify was merged into Linux 2.6.13.
582 The required library interfaces were added in glibc 2.4.
583 .RB ( IN_DONT_FOLLOW ,
587 were added in glibc 2.5.)
589 Inotify file descriptors can be monitored using
594 When an event is available, the file descriptor indicates as readable.
597 signal-driven I/O notification is available for inotify file descriptors;
598 see the discussion of
610 structure (described in
612 that is passed to the signal handler has the following fields set:
614 is set to the inotify file descriptor number;
616 is set to the signal number;
625 If successive output inotify events produced on the
626 inotify file descriptor are identical (same
632 then they are coalesced into a single event if the
633 older event has not yet been read (but see BUGS).
634 This reduces the amount of kernel memory required for the event queue,
635 but also means that an application can't use inotify to reliably count
638 The events returned by reading from an inotify file descriptor
639 form an ordered queue.
640 Thus, for example, it is guaranteed that when renaming from
641 one directory to another, events will be produced in the
642 correct order on the inotify file descriptor.
644 The set of watch descriptors that is being monitored via
645 an inotify file descriptor can be viewed via the entry for
646 the inotify file descriptor in the process's
647 .IR /proc/ pid /fdinfo
655 returns the number of bytes available to read from an
656 inotify file descriptor.
657 .SS Limitations and caveats
658 The inotify API provides no information about the user or process that
659 triggered the inotify event.
660 In particular, there is no easy
661 way for a process that is monitoring events via inotify
662 to distinguish events that it triggers
663 itself from those that are triggered by other processes.
665 Inotify reports only events that a user-space program triggers through
667 As a result, it does not catch remote events that occur
668 on network filesystems.
669 (Applications must fall back to polling the filesystem
670 to catch such events.)
671 Furthermore, various pseudo-filesystems such as
676 are not monitorable with inotify.
678 The inotify API does not report file accesses and modifications that
685 The inotify API identifies affected files by filename.
686 However, by the time an application processes an inotify event,
687 the filename may already have been deleted or renamed.
689 The inotify API identifies events via watch descriptors.
690 It is the application's responsibility to cache a mapping
691 (if one is needed) between watch descriptors and pathnames.
692 Be aware that directory renamings may affect multiple cached pathnames.
694 Inotify monitoring of directories is not recursive:
695 to monitor subdirectories under a directory,
696 additional watches must be created.
697 This can take a significant amount time for large directory trees.
699 If monitoring an entire directory subtree,
700 and a new subdirectory is created in that tree or an existing directory
701 is renamed into that tree,
702 be aware that by the time you create a watch for the new subdirectory,
703 new files (and subdirectories) may already exist inside the subdirectory.
704 Therefore, you may want to scan the contents of the subdirectory
705 immediately after adding the watch (and, if desired,
706 recursively add watches for any subdirectories that it contains).
708 Note that the event queue can overflow.
709 In this case, events are lost.
710 Robust applications should handle the possibility of
711 lost events gracefully.
712 For example, it may be necessary to rebuild part or all of
713 the application cache.
714 (One simple, but possibly expensive,
715 approach is to close the inotify file descriptor, empty the cache,
716 create a new inotify file descriptor,
717 and then re-create watches and cache entries
718 for the objects to be monitored.)
720 If a filesystem is mounted on top of a monitored directory,
721 no event is generated, and no events are generated
722 for objects immediately under the new mount point.
723 If the filesystem is subsequently unmounted,
724 events will subsequently be generated for the directory and
725 the objects it contains.
727 .SS Dealing with rename() events
732 event pair that is generated by
734 can be matched up via their shared cookie value.
735 However, the task of matching has some challenges.
737 These two events are usually consecutive in the event stream available
738 when reading from the inotify file descriptor.
739 However, this is not guaranteed.
740 If multiple processes are triggering events for monitored objects,
741 then (on rare occasions) an arbitrary number of
742 other events may appear between the
747 Furthermore, it is not guaranteed that the event pair is atomically
748 inserted into the queue: there may be a brief interval where the
750 has appeared, but the
758 event pair generated by
760 is thus inherently racy.
761 (Don't forget that if an object is renamed outside of a monitored directory,
762 there may not even be an
765 Heuristic approaches (e.g., assume the events are always consecutive)
766 can be used to ensure a match in most cases,
767 but will inevitably miss some cases,
768 causing the application to perceive the
772 events as being unrelated.
773 If watch descriptors are destroyed and re-created as a result,
774 then those watch descriptors will be inconsistent with
775 the watch descriptors in any pending events.
776 (Re-creating the inotify file descriptor and rebuilding the cache may
777 be useful to deal with this scenario.)
779 Applications should also allow for the possibility that the
781 event was the last event that could fit in the buffer
782 returned by the current call to
786 event might be fetched only on the next
788 which should be done with a (small) timeout to allow for the fact that
790 .BR IN_MOVED_FROM + IN_MOVED_TO
791 event pair is not atomic,
792 and also the possibility that there may not be any
798 did not create any inotify events.
800 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
807 .\" FIXME . kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
808 .\" implies that unmount events were buggy since Linux 2.6.11 to Linux 2.6.36
810 Before Linux 2.6.16, the
815 As originally designed and implemented, the
817 flag did not cause an
819 event to be generated when the watch was dropped after one event.
820 However, as an unintended effect of other changes,
821 since Linux 2.6.36, an
823 event is generated in this case.
826 .\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
827 the kernel code that was intended to coalesce successive identical events
828 (i.e., the two most recent events could potentially be coalesced
829 if the older had not yet been read)
830 instead checked if the most recent event could be coalesced with the
834 When a watch descriptor is removed by calling
835 .BR inotify_rm_watch (2)
836 (or because a watch file is deleted or the filesystem
837 that contains it is unmounted),
838 any pending unread events for that watch descriptor remain available to read.
839 As watch descriptors are subsequently allocated with
840 .BR inotify_add_watch (2),
841 the kernel cycles through the range of possible watch descriptors (1 to
844 When allocating a free watch descriptor, no check is made to see whether that
845 watch descriptor number has any pending unread events in the inotify queue.
846 Thus, it can happen that a watch descriptor is reallocated even
847 when pending unread events exist for a previous incarnation of
848 that watch descriptor number, with the result that the application
849 might then read those events and interpret them as belonging to
850 the file associated with the newly recycled watch descriptor.
851 In practice, the likelihood of hitting this bug may be extremely low,
852 since it requires that an application cycle through
855 release a watch descriptor while leaving unread events for that
856 watch descriptor in the queue,
857 and then recycle that watch descriptor.
858 For this reason, and because there have been no reports
859 of the bug occurring in real-world applications,
861 .\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
862 no kernel changes have yet been made to eliminate this possible bug.
864 The following program demonstrates the usage of the inotify API.
865 It marks the directories passed as a command-line arguments
866 and waits for events of type
868 .BR IN_CLOSE_NOWRITE ,
872 The following output was recorded while editing the file
873 .I /home/user/temp/foo
874 and listing directory
876 Before the file and the directory were opened,
879 After the file was closed, an
882 After the directory was closed, an
885 Execution of the program ended when the user pressed the ENTER key.
889 $ \fB./a.out /tmp /home/user/temp\fP
890 Press enter key to terminate.
891 Listening for events.
892 IN_OPEN: /home/user/temp/foo [file]
893 IN_CLOSE_WRITE: /home/user/temp/foo [file]
894 IN_OPEN: /tmp/ [directory]
895 IN_CLOSE_NOWRITE: /tmp/ [directory]
897 Listening for events stopped.
907 #include <sys/inotify.h>
911 /* Read all available inotify events from the file descriptor \[aq]fd\[aq].
912 wd is the table of watch descriptors for the directories in argv.
913 argc is the length of wd and argv.
914 argv is the list of watched directories.
915 Entry 0 of wd and argv is unused. */
918 handle_events(int fd, int *wd, int argc, char* argv[])
920 /* Some systems cannot read integer variables if they are not
921 properly aligned. On other systems, incorrect alignment may
922 decrease performance. Hence, the buffer used for reading from
923 the inotify file descriptor should have the same alignment as
924 struct inotify_event. */
927 __attribute__ ((aligned(__alignof__(struct inotify_event))));
928 const struct inotify_event *event;
931 /* Loop while events can be read from inotify file descriptor. */
935 /* Read some events. */
937 len = read(fd, buf, sizeof(buf));
938 if (len == \-1 && errno != EAGAIN) {
943 /* If the nonblocking read() found no events to read, then
944 it returns \-1 with errno set to EAGAIN. In that case,
950 /* Loop over all events in the buffer. */
952 for (char *ptr = buf; ptr < buf + len;
953 ptr += sizeof(struct inotify_event) + event\->len) {
955 event = (const struct inotify_event *) ptr;
957 /* Print event type. */
959 if (event\->mask & IN_OPEN)
961 if (event\->mask & IN_CLOSE_NOWRITE)
962 printf("IN_CLOSE_NOWRITE: ");
963 if (event\->mask & IN_CLOSE_WRITE)
964 printf("IN_CLOSE_WRITE: ");
966 /* Print the name of the watched directory. */
968 for (size_t i = 1; i < argc; ++i) {
969 if (wd[i] == event\->wd) {
970 printf("%s/", argv[i]);
975 /* Print the name of the file. */
978 printf("%s", event\->name);
980 /* Print type of filesystem object. */
982 if (event\->mask & IN_ISDIR)
983 printf(" [directory]\en");
985 printf(" [file]\en");
991 main(int argc, char* argv[])
997 struct pollfd fds[2];
1000 printf("Usage: %s PATH [PATH ...]\en", argv[0]);
1004 printf("Press ENTER key to terminate.\en");
1006 /* Create the file descriptor for accessing the inotify API. */
1008 fd = inotify_init1(IN_NONBLOCK);
1010 perror("inotify_init1");
1014 /* Allocate memory for watch descriptors. */
1016 wd = calloc(argc, sizeof(int));
1022 /* Mark directories for events
1024 \- file was closed */
1026 for (i = 1; i < argc; i++) {
1027 wd[i] = inotify_add_watch(fd, argv[i],
1028 IN_OPEN | IN_CLOSE);
1030 fprintf(stderr, "Cannot watch \[aq]%s\[aq]: %s\en",
1031 argv[i], strerror(errno));
1036 /* Prepare for polling. */
1040 fds[0].fd = STDIN_FILENO; /* Console input */
1041 fds[0].events = POLLIN;
1043 fds[1].fd = fd; /* Inotify input */
1044 fds[1].events = POLLIN;
1046 /* Wait for events and/or terminal input. */
1048 printf("Listening for events.\en");
1050 poll_num = poll(fds, nfds, \-1);
1051 if (poll_num == \-1) {
1060 if (fds[0].revents & POLLIN) {
1062 /* Console input is available. Empty stdin and quit. */
1064 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != \[aq]\en\[aq])
1069 if (fds[1].revents & POLLIN) {
1071 /* Inotify events are available. */
1073 handle_events(fd, wd, argc, argv);
1078 printf("Listening for events stopped.\en");
1080 /* Close inotify file descriptor. */
1089 .BR inotifywait (1),
1090 .BR inotifywatch (1),
1091 .BR inotify_add_watch (2),
1092 .BR inotify_init (2),
1093 .BR inotify_init1 (2),
1094 .BR inotify_rm_watch (2),
1099 .I Documentation/filesystems/inotify.txt
1100 in the Linux kernel source tree