2 .\" Copyright (C) 2006, 2014 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\" Copyright (C) 2014 Heinrich Schuchardt <xypron.glpk@gmx.de>
5 .\" %%%LICENSE_START(VERBATIM)
6 .\" Permission is granted to make and distribute verbatim copies of this
7 .\" manual provided the copyright notice and this permission notice are
8 .\" preserved on all copies.
10 .\" Permission is granted to copy and distribute modified versions of this
11 .\" manual under the conditions for verbatim copying, provided that the
12 .\" entire resulting derived work is distributed under the terms of a
13 .\" permission notice identical to this one.
15 .\" Since the Linux kernel and libraries are constantly changing, this
16 .\" manual page may be incorrect or out-of-date. The author(s) assume no
17 .\" responsibility for errors or omissions, or for damages resulting from
18 .\" the use of the information contained herein. The author(s) may not
19 .\" have taken the same level of care in the production of this manual,
20 .\" which is licensed free of charge, as they might when working
23 .\" Formatted or processed versions of this manual, if unaccompanied by
24 .\" the source, must acknowledge the copyright and authors of this work.
27 .TH INOTIFY 7 2019-03-06 "Linux" "Linux Programmer's Manual"
29 inotify \- monitoring filesystem events
33 API provides a mechanism for monitoring filesystem events.
34 Inotify can be used to monitor individual files,
35 or to monitor directories.
36 When a directory is monitored, inotify will return events
37 for the directory itself, and for files inside the directory.
39 The following system calls are used with this API:
42 creates an inotify instance and returns a file descriptor
43 referring to the inotify instance.
50 argument that provides access to some extra functionality.
52 .BR inotify_add_watch (2)
53 manipulates the "watch list" associated with an inotify instance.
54 Each item ("watch") in the watch list specifies the pathname of
56 along with some set of events that the kernel should monitor for the
57 file referred to by that pathname.
58 .BR inotify_add_watch (2)
59 either creates a new watch item, or modifies an existing watch.
60 Each watch has a unique "watch descriptor", an integer
62 .BR inotify_add_watch (2)
63 when the watch is created.
65 When events occur for monitored files and directories,
66 those events are made available to the application as structured data that
67 can be read from the inotify file descriptor using
71 .BR inotify_rm_watch (2)
72 removes an item from an inotify watch list.
74 When all file descriptors referring to an inotify
75 instance have been closed (using
77 the underlying object and its resources are
78 freed for reuse by the kernel;
79 all associated watches are automatically freed.
81 With careful programming,
82 an application can use inotify to efficiently monitor and cache
83 the state of a set of filesystem objects.
84 However, robust applications should allow for the fact that bugs
85 in the monitoring logic or races of the kind described below
86 may leave the cache inconsistent with the filesystem state.
87 It is probably wise to do some consistency checking,
88 and rebuild the cache when inconsistencies are detected.
89 .SS Reading events from an inotify file descriptor
90 To determine what events have occurred, an application
92 from the inotify file descriptor.
93 If no events have so far occurred, then,
94 assuming a blocking file descriptor,
96 will block until at least one event occurs
97 (unless interrupted by a signal,
98 in which case the call fails with the error
105 returns a buffer containing one or more of the following structures:
109 struct inotify_event {
110 int wd; /* Watch descriptor */
111 .\" FIXME . The type of the 'wd' field should probably be "int32_t".
112 .\" I submitted a patch to fix this. See the LKML thread
113 .\" "[patch] Fix type errors in inotify interfaces", 18 Nov 2008
114 .\" Glibc bug filed: http://sources.redhat.com/bugzilla/show_bug.cgi?id=7040
115 uint32_t mask; /* Mask describing event */
116 uint32_t cookie; /* Unique cookie associating related
117 events (for rename(2)) */
118 uint32_t len; /* Size of \fIname\fP field */
119 char name[]; /* Optional null-terminated name */
125 identifies the watch for which this event occurs.
126 It is one of the watch descriptors returned by a previous call to
127 .BR inotify_add_watch (2).
130 contains bits that describe the event that occurred (see below).
133 is a unique integer that connects related events.
134 Currently, this is used only for rename events, and
135 allows the resulting pair of
139 events to be connected by the application.
140 For all other event types,
146 field is present only when an event is returned
147 for a file inside a watched directory;
148 it identifies the filename within to the watched directory.
149 This filename is null-terminated,
150 and may include further null bytes (\(aq\e0\(aq) to align subsequent reads to a
151 suitable address boundary.
155 field counts all of the bytes in
157 including the null bytes;
161 .IR "sizeof(struct inotify_event)+len" .
163 The behavior when the buffer given to
165 is too small to return information about the next event depends
166 on the kernel version: in kernels before 2.6.21,
168 returns 0; since kernel 2.6.21,
172 Specifying a buffer of size
174 sizeof(struct inotify_event) + NAME_MAX + 1
176 will be sufficient to read at least one event.
179 .BR inotify_add_watch (2)
185 structure returned when
187 an inotify file descriptor are both bit masks identifying
189 The following bits can be specified in
192 .BR inotify_add_watch (2)
193 and may be returned in the
200 File was accessed (e.g.,
205 Metadata changed\(emfor example, permissions (e.g.,
211 link count (since Linux 2.6.25; e.g.,
213 .\" Events do not occur for link count changes on a file inside a monitored
214 .\" directory. This differs from other metadata changes for files inside
215 .\" a monitored directory.
220 and user/group ID (e.g.,
223 .BR IN_CLOSE_WRITE " (+)"
224 File opened for writing was closed.
226 .BR IN_CLOSE_NOWRITE " (*)"
227 File or directory not opened for writing was closed.
230 File/directory created in watched directory (e.g.,
237 on a UNIX domain socket).
240 File/directory deleted from watched directory.
243 Watched file/directory was itself deleted.
244 (This event also occurs if an object is moved to another filesystem,
247 in effect copies the file to the other filesystem and
248 then deletes it from the original filesystem.)
251 event will subsequently be generated for the watch descriptor.
254 File was modified (e.g.,
259 Watched file/directory was itself moved.
261 .BR IN_MOVED_FROM " (+)"
262 Generated for the directory containing the old filename
263 when a file is renamed.
265 .BR IN_MOVED_TO " (+)"
266 Generated for the directory containing the new filename
267 when a file is renamed.
270 File or directory was opened.
273 Inotify monitoring is inode-based: when monitoring a file
274 (but not when monitoring the directory containing a file),
275 an event can be generated for activity on any link to the file
276 (in the same or a different directory).
278 When monitoring a directory:
280 the events marked above with an asterisk (*) can occur both
281 for the directory itself and for objects inside the directory; and
283 the events marked with a plus sign (+) occur only for objects
284 inside the directory (not for the directory itself).
287 when monitoring a directory,
288 events are not generated for the files inside the directory
289 when the events are performed via a pathname (i.e., a link)
290 that lies outside the monitored directory.
292 When events are generated for objects inside a watched directory, the
294 field in the returned
296 structure identifies the name of the file within the directory.
300 macro is defined as a bit mask of all of the above events.
301 This macro can be used as the
303 argument when calling
304 .BR inotify_add_watch (2).
306 Two additional convenience macros are defined:
311 .BR "IN_MOVED_FROM | IN_MOVED_TO" .
315 .BR "IN_CLOSE_WRITE | IN_CLOSE_NOWRITE" .
318 The following further bits can be specified in
321 .BR inotify_add_watch (2):
324 .BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
327 if it is a symbolic link.
329 .BR IN_EXCL_UNLINK " (since Linux 2.6.36)"
330 .\" commit 8c1934c8d70b22ca8333b216aec6c7d09fdbd6a6
331 By default, when watching events on the children of a directory,
332 events are generated for children even after they have been unlinked
334 This can result in large numbers of uninteresting events for
335 some applications (e.g., if watching
337 in which many applications create temporary files whose
338 names are immediately unlinked).
341 changes the default behavior,
342 so that events are not generated for children after
343 they have been unlinked from the watched directory.
346 If a watch instance already exists for the filesystem object corresponding to
348 add (OR) the events in
350 to the watch mask (instead of replacing the mask);
358 Monitor the filesystem object corresponding to
360 for one event, then remove from
363 .BR IN_ONLYDIR " (since Linux 2.6.15)"
366 only if it is a directory;
372 Using this flag provides an application with a race-free way of
373 ensuring that the monitored object is a directory.
375 .BR IN_MASK_CREATE " (since Linux 4.18)"
378 only if it does not already have a watch associated with it;
383 is already being watched.
385 Using this flag provides an application with a way of ensuring
386 that new watches do not modify existing ones.
387 This is useful because multiple paths may refer to the same inode,
388 and multiple calls to
389 .BR inotify_add_watch (2)
390 without this flag may clobber existing watch masks.
393 The following bits may be set in the
400 Watch was removed explicitly
401 .RB ( inotify_rm_watch (2))
402 or automatically (file was deleted, or filesystem was unmounted).
406 Subject of this event is a directory.
409 Event queue overflowed
411 is \-1 for this event).
414 Filesystem containing watched object was unmounted.
417 event will subsequently be generated for the watch descriptor.
420 Suppose an application is watching the directory
425 The examples below show some events that will be generated
426 for these two objects.
429 fd = open("dir/myfile", O_RDWR);
437 read(fd, buf, count);
445 write(fd, buf, count);
470 Suppose an application is watching the directories
476 The following examples show some events that may be generated.
479 link("dir1/myfile", "dir2/new");
489 rename("dir1/myfile", "dir2/myfile");
506 events will have the same
515 are (the only) links to the same file, and an application is watching
521 Executing the following calls in the order given below will generate
522 the following events:
530 (because its link count changes)
550 Suppose an application is watching the directory
552 and (the empty) directory
554 The following examples show some events that may be generated.
557 mkdir("dir/new", mode);
559 .B "IN_CREATE | IN_ISDIR"
571 .B "IN_DELETE | IN_ISDIR"
576 The following interfaces can be used to limit the amount of
577 kernel memory consumed by inotify:
579 .I /proc/sys/fs/inotify/max_queued_events
580 The value in this file is used when an application calls
582 to set an upper limit on the number of events that can be
583 queued to the corresponding inotify instance.
584 Events in excess of this limit are dropped, but an
586 event is always generated.
588 .I /proc/sys/fs/inotify/max_user_instances
589 This specifies an upper limit on the number of inotify instances
590 that can be created per real user ID.
592 .I /proc/sys/fs/inotify/max_user_watches
593 This specifies an upper limit on the number of watches
594 that can be created per real user ID.
596 Inotify was merged into the 2.6.13 Linux kernel.
597 The required library interfaces were added to glibc in version 2.4.
598 .RB ( IN_DONT_FOLLOW ,
602 were added in glibc version 2.5.)
604 The inotify API is Linux-specific.
606 Inotify file descriptors can be monitored using
611 When an event is available, the file descriptor indicates as readable.
614 signal-driven I/O notification is available for inotify file descriptors;
615 see the discussion of
627 structure (described in
629 that is passed to the signal handler has the following fields set:
631 is set to the inotify file descriptor number;
633 is set to the signal number;
642 If successive output inotify events produced on the
643 inotify file descriptor are identical (same
649 then they are coalesced into a single event if the
650 older event has not yet been read (but see BUGS).
651 This reduces the amount of kernel memory required for the event queue,
652 but also means that an application can't use inotify to reliably count
655 The events returned by reading from an inotify file descriptor
656 form an ordered queue.
657 Thus, for example, it is guaranteed that when renaming from
658 one directory to another, events will be produced in the
659 correct order on the inotify file descriptor.
661 The set of watch descriptors that is being monitored via
662 an inotify file descriptor can be viewed via the entry for
663 the inotify file descriptor in the process's
664 .IR /proc/[pid]/fdinfo
672 returns the number of bytes available to read from an
673 inotify file descriptor.
674 .SS Limitations and caveats
675 The inotify API provides no information about the user or process that
676 triggered the inotify event.
677 In particular, there is no easy
678 way for a process that is monitoring events via inotify
679 to distinguish events that it triggers
680 itself from those that are triggered by other processes.
682 Inotify reports only events that a user-space program triggers through
684 As a result, it does not catch remote events that occur
685 on network filesystems.
686 (Applications must fall back to polling the filesystem
687 to catch such events.)
688 Furthermore, various pseudo-filesystems such as
693 are not monitorable with inotify.
695 The inotify API does not report file accesses and modifications that
702 The inotify API identifies affected files by filename.
703 However, by the time an application processes an inotify event,
704 the filename may already have been deleted or renamed.
706 The inotify API identifies events via watch descriptors.
707 It is the application's responsibility to cache a mapping
708 (if one is needed) between watch descriptors and pathnames.
709 Be aware that directory renamings may affect multiple cached pathnames.
711 Inotify monitoring of directories is not recursive:
712 to monitor subdirectories under a directory,
713 additional watches must be created.
714 This can take a significant amount time for large directory trees.
716 If monitoring an entire directory subtree,
717 and a new subdirectory is created in that tree or an existing directory
718 is renamed into that tree,
719 be aware that by the time you create a watch for the new subdirectory,
720 new files (and subdirectories) may already exist inside the subdirectory.
721 Therefore, you may want to scan the contents of the subdirectory
722 immediately after adding the watch (and, if desired,
723 recursively add watches for any subdirectories that it contains).
725 Note that the event queue can overflow.
726 In this case, events are lost.
727 Robust applications should handle the possibility of
728 lost events gracefully.
729 For example, it may be necessary to rebuild part or all of
730 the application cache.
731 (One simple, but possibly expensive,
732 approach is to close the inotify file descriptor, empty the cache,
733 create a new inotify file descriptor,
734 and then re-create watches and cache entries
735 for the objects to be monitored.)
737 If a filesystem is mounted on top of a monitored directory,
738 no event is generated, and no events are generated
739 for objects immediately under the new mount point.
740 If the filesystem is subsequently unmounted,
741 events will subsequently be generated for the directory and
742 the objects it contains.
744 .SS Dealing with rename() events
749 event pair that is generated by
751 can be matched up via their shared cookie value.
752 However, the task of matching has some challenges.
754 These two events are usually consecutive in the event stream available
755 when reading from the inotify file descriptor.
756 However, this is not guaranteed.
757 If multiple processes are triggering events for monitored objects,
758 then (on rare occasions) an arbitrary number of
759 other events may appear between the
764 Furthermore, it is not guaranteed that the event pair is atomically
765 inserted into the queue: there may be a brief interval where the
767 has appeared, but the
775 event pair generated by
777 is thus inherently racy.
778 (Don't forget that if an object is renamed outside of a monitored directory,
779 there may not even be an
782 Heuristic approaches (e.g., assume the events are always consecutive)
783 can be used to ensure a match in most cases,
784 but will inevitably miss some cases,
785 causing the application to perceive the
789 events as being unrelated.
790 If watch descriptors are destroyed and re-created as a result,
791 then those watch descriptors will be inconsistent with
792 the watch descriptors in any pending events.
793 (Re-creating the inotify file descriptor and rebuilding the cache may
794 be useful to deal with this scenario.)
796 Applications should also allow for the possibility that the
798 event was the last event that could fit in the buffer
799 returned by the current call to
803 event might be fetched only on the next
805 which should be done with a (small) timeout to allow for the fact that
807 .BR IN_MOVED_FROM - IN_MOVED_TO
808 event pair is not atomic,
809 and also the possibility that there may not be any
815 did not create any inotify events.
817 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
824 .\" FIXME . kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
825 .\" implies that unmount events were buggy 2.6.11 to 2.6.36
827 In kernels before 2.6.16, the
832 As originally designed and implemented, the
834 flag did not cause an
836 event to be generated when the watch was dropped after one event.
837 However, as an unintended effect of other changes,
838 since Linux 2.6.36, an
840 event is generated in this case.
842 Before kernel 2.6.25,
843 .\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
844 the kernel code that was intended to coalesce successive identical events
845 (i.e., the two most recent events could potentially be coalesced
846 if the older had not yet been read)
847 instead checked if the most recent event could be coalesced with the
851 When a watch descriptor is removed by calling
852 .BR inotify_rm_watch (2)
853 (or because a watch file is deleted or the filesystem
854 that contains it is unmounted),
855 any pending unread events for that watch descriptor remain available to read.
856 As watch descriptors are subsequently allocated with
857 .BR inotify_add_watch (2),
858 the kernel cycles through the range of possible watch descriptors (0 to
861 When allocating a free watch descriptor, no check is made to see whether that
862 watch descriptor number has any pending unread events in the inotify queue.
863 Thus, it can happen that a watch descriptor is reallocated even
864 when pending unread events exist for a previous incarnation of
865 that watch descriptor number, with the result that the application
866 might then read those events and interpret them as belonging to
867 the file associated with the newly recycled watch descriptor.
868 In practice, the likelihood of hitting this bug may be extremely low,
869 since it requires that an application cycle through
872 release a watch descriptor while leaving unread events for that
873 watch descriptor in the queue,
874 and then recycle that watch descriptor.
875 For this reason, and because there have been no reports
876 of the bug occurring in real-world applications,
878 .\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
879 no kernel changes have yet been made to eliminate this possible bug.
881 The following program demonstrates the usage of the inotify API.
882 It marks the directories passed as a command-line arguments
883 and waits for events of type
889 The following output was recorded while editing the file
890 .I /home/user/temp/foo
891 and listing directory
893 Before the file and the directory were opened,
896 After the file was closed, an
899 After the directory was closed, an
902 Execution of the program ended when the user pressed the ENTER key.
906 $ \fB./a.out /tmp /home/user/temp\fP
907 Press enter key to terminate.
908 Listening for events.
909 IN_OPEN: /home/user/temp/foo [file]
910 IN_CLOSE_WRITE: /home/user/temp/foo [file]
911 IN_OPEN: /tmp/ [directory]
912 IN_CLOSE_NOWRITE: /tmp/ [directory]
914 Listening for events stopped.
924 #include <sys/inotify.h>
927 /* Read all available inotify events from the file descriptor 'fd'.
928 wd is the table of watch descriptors for the directories in argv.
929 argc is the length of wd and argv.
930 argv is the list of watched directories.
931 Entry 0 of wd and argv is unused. */
934 handle_events(int fd, int *wd, int argc, char* argv[])
936 /* Some systems cannot read integer variables if they are not
937 properly aligned. On other systems, incorrect alignment may
938 decrease performance. Hence, the buffer used for reading from
939 the inotify file descriptor should have the same alignment as
940 struct inotify_event. */
943 __attribute__ ((aligned(__alignof__(struct inotify_event))));
944 const struct inotify_event *event;
949 /* Loop while events can be read from inotify file descriptor. */
953 /* Read some events. */
955 len = read(fd, buf, sizeof buf);
956 if (len == \-1 && errno != EAGAIN) {
961 /* If the nonblocking read() found no events to read, then
962 it returns \-1 with errno set to EAGAIN. In that case,
968 /* Loop over all events in the buffer */
970 for (ptr = buf; ptr < buf + len;
971 ptr += sizeof(struct inotify_event) + event\->len) {
973 event = (const struct inotify_event *) ptr;
975 /* Print event type */
977 if (event\->mask & IN_OPEN)
979 if (event\->mask & IN_CLOSE_NOWRITE)
980 printf("IN_CLOSE_NOWRITE: ");
981 if (event\->mask & IN_CLOSE_WRITE)
982 printf("IN_CLOSE_WRITE: ");
984 /* Print the name of the watched directory */
986 for (i = 1; i < argc; ++i) {
987 if (wd[i] == event\->wd) {
988 printf("%s/", argv[i]);
993 /* Print the name of the file */
996 printf("%s", event\->name);
998 /* Print type of filesystem object */
1000 if (event\->mask & IN_ISDIR)
1001 printf(" [directory]\en");
1003 printf(" [file]\en");
1009 main(int argc, char* argv[])
1012 int fd, i, poll_num;
1015 struct pollfd fds[2];
1018 printf("Usage: %s PATH [PATH ...]\en", argv[0]);
1022 printf("Press ENTER key to terminate.\en");
1024 /* Create the file descriptor for accessing the inotify API */
1026 fd = inotify_init1(IN_NONBLOCK);
1028 perror("inotify_init1");
1032 /* Allocate memory for watch descriptors */
1034 wd = calloc(argc, sizeof(int));
1040 /* Mark directories for events
1042 \- file was closed */
1044 for (i = 1; i < argc; i++) {
1045 wd[i] = inotify_add_watch(fd, argv[i],
1046 IN_OPEN | IN_CLOSE);
1048 fprintf(stderr, "Cannot watch '%s'\en", argv[i]);
1049 perror("inotify_add_watch");
1054 /* Prepare for polling */
1060 fds[0].fd = STDIN_FILENO;
1061 fds[0].events = POLLIN;
1066 fds[1].events = POLLIN;
1068 /* Wait for events and/or terminal input */
1070 printf("Listening for events.\en");
1072 poll_num = poll(fds, nfds, \-1);
1073 if (poll_num == \-1) {
1082 if (fds[0].revents & POLLIN) {
1084 /* Console input is available. Empty stdin and quit */
1086 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\en')
1091 if (fds[1].revents & POLLIN) {
1093 /* Inotify events are available */
1095 handle_events(fd, wd, argc, argv);
1100 printf("Listening for events stopped.\en");
1102 /* Close inotify file descriptor */
1111 .BR inotifywait (1),
1112 .BR inotifywatch (1),
1113 .BR inotify_add_watch (2),
1114 .BR inotify_init (2),
1115 .BR inotify_init1 (2),
1116 .BR inotify_rm_watch (2),
1121 .IR Documentation/filesystems/inotify.txt
1122 in the Linux kernel source tree