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 2016-12-12 "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\\0\(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).
353 Monitor the filesystem object corresponding to
355 for one event, then remove from
358 .BR IN_ONLYDIR " (since Linux 2.6.15)"
361 only if it is a directory.
362 Using this flag provides an application with a race-free way of
363 ensuring that the monitored object is a directory.
366 The following bits may be set in the
373 Watch was removed explicitly
374 .RB ( inotify_rm_watch (2))
375 or automatically (file was deleted, or filesystem was unmounted).
379 Subject of this event is a directory.
382 Event queue overflowed
384 is \-1 for this event).
387 Filesystem containing watched object was unmounted.
390 event will subsequently be generated for the watch descriptor.
393 Suppose an application is watching the directory
398 The examples below show some events that will be generated
399 for these two objects.
402 fd = open("dir/myfile", O_RDWR);
410 read(fd, buf, count);
418 write(fd, buf, count);
443 Suppose an application is watching the directories
449 The following examples show some events that may be generated.
452 link("dir1/myfile", "dir2/new");
462 rename("dir1/myfile", "dir2/myfile");
479 events will have the same
488 are (the only) links to the same file, and an application is watching
494 Executing the following calls in the order given below will generate
495 the following events:
503 (because its link count changes)
523 Suppose an application is watching the directory
525 and (the empty) directory
527 The following examples show some events that may be generated.
530 mkdir("dir/new", mode);
532 .B "IN_CREATE | IN_ISDIR"
544 .B "IN_DELETE | IN_ISDIR"
549 The following interfaces can be used to limit the amount of
550 kernel memory consumed by inotify:
552 .I /proc/sys/fs/inotify/max_queued_events
553 The value in this file is used when an application calls
555 to set an upper limit on the number of events that can be
556 queued to the corresponding inotify instance.
557 Events in excess of this limit are dropped, but an
559 event is always generated.
561 .I /proc/sys/fs/inotify/max_user_instances
562 This specifies an upper limit on the number of inotify instances
563 that can be created per real user ID.
565 .I /proc/sys/fs/inotify/max_user_watches
566 This specifies an upper limit on the number of watches
567 that can be created per real user ID.
569 Inotify was merged into the 2.6.13 Linux kernel.
570 The required library interfaces were added to glibc in version 2.4.
571 .RB ( IN_DONT_FOLLOW ,
575 were added in glibc version 2.5.)
577 The inotify API is Linux-specific.
579 Inotify file descriptors can be monitored using
584 When an event is available, the file descriptor indicates as readable.
587 signal-driven I/O notification is available for inotify file descriptors;
588 see the discussion of
600 structure (described in
602 that is passed to the signal handler has the following fields set:
604 is set to the inotify file descriptor number;
606 is set to the signal number;
615 If successive output inotify events produced on the
616 inotify file descriptor are identical (same
622 then they are coalesced into a single event if the
623 older event has not yet been read (but see BUGS).
624 This reduces the amount of kernel memory required for the event queue,
625 but also means that an application can't use inotify to reliably count
628 The events returned by reading from an inotify file descriptor
629 form an ordered queue.
630 Thus, for example, it is guaranteed that when renaming from
631 one directory to another, events will be produced in the
632 correct order on the inotify file descriptor.
634 The set of watch descriptors that is being monitored via
635 an inotify file descriptor can be viewed via the entry for
636 the inotify file descriptor in the process's
637 .IR /proc/[pid]/fdinfo
645 returns the number of bytes available to read from an
646 inotify file descriptor.
647 .SS Limitations and caveats
648 The inotify API provides no information about the user or process that
649 triggered the inotify event.
650 In particular, there is no easy
651 way for a process that is monitoring events via inotify
652 to distinguish events that it triggers
653 itself from those that are triggered by other processes.
655 Inotify reports only events that a user-space program triggers through
657 As a result, it does not catch remote events that occur
658 on network filesystems.
659 (Applications must fall back to polling the filesystem
660 to catch such events.)
661 Furthermore, various pseudo-filesystems such as
666 are not monitorable with inotify.
668 The inotify API does not report file accesses and modifications that
675 The inotify API identifies affected files by filename.
676 However, by the time an application processes an inotify event,
677 the filename may already have been deleted or renamed.
679 The inotify API identifies events via watch descriptors.
680 It is the application's responsibility to cache a mapping
681 (if one is needed) between watch descriptors and pathnames.
682 Be aware that directory renamings may affect multiple cached pathnames.
684 Inotify monitoring of directories is not recursive:
685 to monitor subdirectories under a directory,
686 additional watches must be created.
687 This can take a significant amount time for large directory trees.
689 If monitoring an entire directory subtree,
690 and a new subdirectory is created in that tree or an existing directory
691 is renamed into that tree,
692 be aware that by the time you create a watch for the new subdirectory,
693 new files (and subdirectories) may already exist inside the subdirectory.
694 Therefore, you may want to scan the contents of the subdirectory
695 immediately after adding the watch (and, if desired,
696 recursively add watches for any subdirectories that it contains).
698 Note that the event queue can overflow.
699 In this case, events are lost.
700 Robust applications should handle the possibility of
701 lost events gracefully.
702 For example, it may be necessary to rebuild part or all of
703 the application cache.
704 (One simple, but possibly expensive,
705 approach is to close the inotify file descriptor, empty the cache,
706 create a new inotify file descriptor,
707 and then re-create watches and cache entries
708 for the objects to be monitored.)
710 If a filesystem is mounted on top of a monitored directory,
711 no event is generated, and no events are generated
712 for objects immediately under the new mount point.
713 If the filesystem is subsequently unmounted,
714 events will subsequently be generated for the directory and
715 the objects it contains.
717 .SS Dealing with rename() events
722 event pair that is generated by
724 can be matched up via their shared cookie value.
725 However, the task of matching has some challenges.
727 These two events are usually consecutive in the event stream available
728 when reading from the inotify file descriptor.
729 However, this is not guaranteed.
730 If multiple processes are triggering events for monitored objects,
731 then (on rare occasions) an arbitrary number of
732 other events may appear between the
737 Furthermore, it is not guaranteed that the event pair is atomically
738 inserted into the queue: there may be a brief interval where the
740 has appeared, but the
748 event pair generated by
750 is thus inherently racy.
751 (Don't forget that if an object is renamed outside of a monitored directory,
752 there may not even be an
755 Heuristic approaches (e.g., assume the events are always consecutive)
756 can be used to ensure a match in most cases,
757 but will inevitably miss some cases,
758 causing the application to perceive the
762 events as being unrelated.
763 If watch descriptors are destroyed and re-created as a result,
764 then those watch descriptors will be inconsistent with
765 the watch descriptors in any pending events.
766 (Re-creating the inotify file descriptor and rebuilding the cache may
767 be useful to deal with this scenario.)
769 Applications should also allow for the possibility that the
771 event was the last event that could fit in the buffer
772 returned by the current call to
776 event might be fetched only on the next
778 which should be done with a (small) timeout to allow for the fact that
780 .BR IN_MOVED_FROM - IN_MOVED_TO
781 event pair is not atomic,
782 and also the possibility that there may not be any
788 did not create any inotify events.
790 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
797 .\" FIXME . kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
798 .\" implies that unmount events were buggy 2.6.11 to 2.6.36
800 In kernels before 2.6.16, the
805 As originally designed and implemented, the
807 flag did not cause an
809 event to be generated when the watch was dropped after one event.
810 However, as an unintended effect of other changes,
811 since Linux 2.6.36, an
813 event is generated in this case.
815 Before kernel 2.6.25,
816 .\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
817 the kernel code that was intended to coalesce successive identical events
818 (i.e., the two most recent events could potentially be coalesced
819 if the older had not yet been read)
820 instead checked if the most recent event could be coalesced with the
824 When a watch descriptor is removed by calling
825 .BR inotify_rm_watch (2)
826 (or because a watch file is deleted or the filesystem
827 that contains it is unmounted),
828 any pending unread events for that watch descriptor remain available to read.
829 As watch descriptors are subsequently allocated with
830 .BR inotify_add_watch (2),
831 the kernel cycles through the range of possible watch descriptors (0 to
834 When allocating a free watch descriptor, no check is made to see whether that
835 watch descriptor number has any pending unread events in the inotify queue.
836 Thus, it can happen that a watch descriptor is reallocated even
837 when pending unread events exist for a previous incarnation of
838 that watch descriptor number, with the result that the application
839 might then read those events and interpret them as belonging to
840 the file associated with the newly recycled watch descriptor.
841 In practice, the likelihood of hitting this bug may be extremely low,
842 since it requires that an application cycle through
845 release a watch descriptor while leaving unread events for that
846 watch descriptor in the queue,
847 and then recycle that watch descriptor.
848 For this reason, and because there have been no reports
849 of the bug occurring in real-world applications,
851 .\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
852 no kernel changes have yet been made to eliminate this possible bug.
854 The following program demonstrates the usage of the inotify API.
855 It marks the directories passed as a command-line arguments
856 and waits for events of type
862 The following output was recorded while editing the file
863 .I /home/user/temp/foo
864 and listing directory
866 Before the file and the directory were opened,
869 After the file was closed, an
872 After the directory was closed, an
875 Execution of the program ended when the user pressed the ENTER key.
879 $ \fB./a.out /tmp /home/user/temp\fP
880 Press enter key to terminate.
881 Listening for events.
882 IN_OPEN: /home/user/temp/foo [file]
883 IN_CLOSE_WRITE: /home/user/temp/foo [file]
884 IN_OPEN: /tmp/ [directory]
885 IN_CLOSE_NOWRITE: /tmp/ [directory]
887 Listening for events stopped.
896 #include <sys/inotify.h>
899 /* Read all available inotify events from the file descriptor 'fd'.
900 wd is the table of watch descriptors for the directories in argv.
901 argc is the length of wd and argv.
902 argv is the list of watched directories.
903 Entry 0 of wd and argv is unused. */
906 handle_events(int fd, int *wd, int argc, char* argv[])
908 /* Some systems cannot read integer variables if they are not
909 properly aligned. On other systems, incorrect alignment may
910 decrease performance. Hence, the buffer used for reading from
911 the inotify file descriptor should have the same alignment as
912 struct inotify_event. */
915 __attribute__ ((aligned(__alignof__(struct inotify_event))));
916 const struct inotify_event *event;
921 /* Loop while events can be read from inotify file descriptor. */
925 /* Read some events. */
927 len = read(fd, buf, sizeof buf);
928 if (len == \-1 && errno != EAGAIN) {
933 /* If the nonblocking read() found no events to read, then
934 it returns \-1 with errno set to EAGAIN. In that case,
940 /* Loop over all events in the buffer */
942 for (ptr = buf; ptr < buf + len;
943 ptr += sizeof(struct inotify_event) + event\->len) {
945 event = (const struct inotify_event *) ptr;
947 /* Print event type */
949 if (event\->mask & IN_OPEN)
951 if (event\->mask & IN_CLOSE_NOWRITE)
952 printf("IN_CLOSE_NOWRITE: ");
953 if (event\->mask & IN_CLOSE_WRITE)
954 printf("IN_CLOSE_WRITE: ");
956 /* Print the name of the watched directory */
958 for (i = 1; i < argc; ++i) {
959 if (wd[i] == event\->wd) {
960 printf("%s/", argv[i]);
965 /* Print the name of the file */
968 printf("%s", event\->name);
970 /* Print type of filesystem object */
972 if (event\->mask & IN_ISDIR)
973 printf(" [directory]\\n");
975 printf(" [file]\\n");
981 main(int argc, char* argv[])
987 struct pollfd fds[2];
990 printf("Usage: %s PATH [PATH ...]\\n", argv[0]);
994 printf("Press ENTER key to terminate.\\n");
996 /* Create the file descriptor for accessing the inotify API */
998 fd = inotify_init1(IN_NONBLOCK);
1000 perror("inotify_init1");
1004 /* Allocate memory for watch descriptors */
1006 wd = calloc(argc, sizeof(int));
1012 /* Mark directories for events
1014 \- file was closed */
1016 for (i = 1; i < argc; i++) {
1017 wd[i] = inotify_add_watch(fd, argv[i],
1018 IN_OPEN | IN_CLOSE);
1020 fprintf(stderr, "Cannot watch '%s'\\n", argv[i]);
1021 perror("inotify_add_watch");
1026 /* Prepare for polling */
1032 fds[0].fd = STDIN_FILENO;
1033 fds[0].events = POLLIN;
1038 fds[1].events = POLLIN;
1040 /* Wait for events and/or terminal input */
1042 printf("Listening for events.\\n");
1044 poll_num = poll(fds, nfds, \-1);
1045 if (poll_num == \-1) {
1054 if (fds[0].revents & POLLIN) {
1056 /* Console input is available. Empty stdin and quit */
1058 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
1063 if (fds[1].revents & POLLIN) {
1065 /* Inotify events are available */
1067 handle_events(fd, wd, argc, argv);
1072 printf("Listening for events stopped.\\n");
1074 /* Close inotify file descriptor */
1083 .BR inotifywait (1),
1084 .BR inotifywatch (1),
1085 .BR inotify_add_watch (2),
1086 .BR inotify_init (2),
1087 .BR inotify_init1 (2),
1088 .BR inotify_rm_watch (2),
1093 .IR Documentation/filesystems/inotify.txt
1094 in the Linux kernel source tree