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-03-15 "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 When monitoring a directory:
275 the events marked above with an asterisk (*) can occur both
276 for the directory itself and for objects inside the directory; and
278 the events marked with a plus sign (+) occur only for objects
279 inside the directory (not for the directory itself).
282 when monitoring a directory,
283 events are not generated for the files inside the directory
284 when the events are performed via a pathname (i.e., a link)
285 that lies outside the monitored directory.
287 When events are generated for objects inside a watched directory, the
289 field in the returned
291 structure identifies the name of the file within the directory.
295 macro is defined as a bit mask of all of the above events.
296 This macro can be used as the
298 argument when calling
299 .BR inotify_add_watch (2).
301 Two additional convenience macros are defined:
306 .BR "IN_MOVED_FROM | IN_MOVED_TO" .
310 .BR "IN_CLOSE_WRITE | IN_CLOSE_NOWRITE" .
313 The following further bits can be specified in
316 .BR inotify_add_watch (2):
319 .BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
322 if it is a symbolic link.
324 .BR IN_EXCL_UNLINK " (since Linux 2.6.36)"
325 .\" commit 8c1934c8d70b22ca8333b216aec6c7d09fdbd6a6
326 By default, when watching events on the children of a directory,
327 events are generated for children even after they have been unlinked
329 This can result in large numbers of uninteresting events for
330 some applications (e.g., if watching
332 in which many applications create temporary files whose
333 names are immediately unlinked).
336 changes the default behavior,
337 so that events are not generated for children after
338 they have been unlinked from the watched directory.
341 If a watch instance already exists for the filesystem object corresponding to
343 add (OR) the events in
345 to the watch mask (instead of replacing the mask).
348 Monitor the filesystem object corresponding to
350 for one event, then remove from
353 .BR IN_ONLYDIR " (since Linux 2.6.15)"
356 only if it is a directory.
357 Using this flag provides an application with a race-free way of
358 ensuring that the monitored object is a directory.
361 The following bits may be set in the
368 Watch was removed explicitly
369 .RB ( inotify_rm_watch (2))
370 or automatically (file was deleted, or filesystem was unmounted).
374 Subject of this event is a directory.
377 Event queue overflowed
379 is \-1 for this event).
382 Filesystem containing watched object was unmounted.
385 event will subsequently be generated for the watch descriptor.
388 Suppose an application is watching the directory
393 The examples below show some events that will be generated
394 for these two objects.
397 fd = open("dir/myfile", O_RDWR);
405 read(fd, buf, count);
413 write(fd, buf, count);
438 Suppose an application is watching the directories
444 The following examples show some events that may be generated.
447 link("dir1/myfile", "dir2/new");
457 rename("dir1/myfile", "dir2/myfile");
474 events will have the same
483 are (the only) links to the same file, and an application is watching
489 Executing the following calls in the order given below will generate
490 the following events:
498 (because its link count changes)
518 Suppose an application is watching the directory
520 and (the empty) directory
522 The following examples show some events that may be generated.
525 mkdir("dir/new", mode);
527 .B "IN_CREATE | IN_ISDIR"
539 .B "IN_DELETE | IN_ISDIR"
544 The following interfaces can be used to limit the amount of
545 kernel memory consumed by inotify:
547 .I /proc/sys/fs/inotify/max_queued_events
548 The value in this file is used when an application calls
550 to set an upper limit on the number of events that can be
551 queued to the corresponding inotify instance.
552 Events in excess of this limit are dropped, but an
554 event is always generated.
556 .I /proc/sys/fs/inotify/max_user_instances
557 This specifies an upper limit on the number of inotify instances
558 that can be created per real user ID.
560 .I /proc/sys/fs/inotify/max_user_watches
561 This specifies an upper limit on the number of watches
562 that can be created per real user ID.
564 Inotify was merged into the 2.6.13 Linux kernel.
565 The required library interfaces were added to glibc in version 2.4.
566 .RB ( IN_DONT_FOLLOW ,
570 were added in glibc version 2.5.)
572 The inotify API is Linux-specific.
574 Inotify file descriptors can be monitored using
579 When an event is available, the file descriptor indicates as readable.
582 signal-driven I/O notification is available for inotify file descriptors;
583 see the discussion of
595 structure (described in
597 that is passed to the signal handler has the following fields set:
599 is set to the inotify file descriptor number;
601 is set to the signal number;
610 If successive output inotify events produced on the
611 inotify file descriptor are identical (same
617 then they are coalesced into a single event if the
618 older event has not yet been read (but see BUGS).
619 This reduces the amount of kernel memory required for the event queue,
620 but also means that an application can't use inotify to reliably count
623 The events returned by reading from an inotify file descriptor
624 form an ordered queue.
625 Thus, for example, it is guaranteed that when renaming from
626 one directory to another, events will be produced in the
627 correct order on the inotify file descriptor.
629 The set of watch descriptors that is being monitored via
630 an inotify file descriptor can be viewed via the entry for
631 the inotify file descriptor in the process's
632 .IR /proc/[pid]/fdinfo
640 returns the number of bytes available to read from an
641 inotify file descriptor.
642 .SS Limitations and caveats
643 The inotify API provides no information about the user or process that
644 triggered the inotify event.
645 In particular, there is no easy
646 way for a process that is monitoring events via inotify
647 to distinguish events that it triggers
648 itself from those that are triggered by other processes.
650 Inotify reports only events that a user-space program triggers through
652 As a result, it does not catch remote events that occur
653 on network filesystems.
654 (Applications must fall back to polling the filesystem
655 to catch such events.)
656 Furthermore, various pseudo-filesystems such as
661 are not monitorable with inotify.
663 The inotify API does not report file accesses and modifications that
670 The inotify API identifies affected files by filename.
671 However, by the time an application processes an inotify event,
672 the filename may already have been deleted or renamed.
674 The inotify API identifies events via watch descriptors.
675 It is the application's responsibility to cache a mapping
676 (if one is needed) between watch descriptors and pathnames.
677 Be aware that directory renamings may affect multiple cached pathnames.
679 Inotify monitoring of directories is not recursive:
680 to monitor subdirectories under a directory,
681 additional watches must be created.
682 This can take a significant amount time for large directory trees.
684 If monitoring an entire directory subtree,
685 and a new subdirectory is created in that tree or an existing directory
686 is renamed into that tree,
687 be aware that by the time you create a watch for the new subdirectory,
688 new files (and subdirectories) may already exist inside the subdirectory.
689 Therefore, you may want to scan the contents of the subdirectory
690 immediately after adding the watch (and, if desired,
691 recursively add watches for any subdirectories that it contains).
693 Note that the event queue can overflow.
694 In this case, events are lost.
695 Robust applications should handle the possibility of
696 lost events gracefully.
697 For example, it may be necessary to rebuild part or all of
698 the application cache.
699 (One simple, but possibly expensive,
700 approach is to close the inotify file descriptor, empty the cache,
701 create a new inotify file descriptor,
702 and then re-create watches and cache entries
703 for the objects to be monitored.)
704 .SS Dealing with rename() events
709 event pair that is generated by
711 can be matched up via their shared cookie value.
712 However, the task of matching has some challenges.
714 These two events are usually consecutive in the event stream available
715 when reading from the inotify file descriptor.
716 However, this is not guaranteed.
717 If multiple processes are triggering events for monitored objects,
718 then (on rare occasions) an arbitrary number of
719 other events may appear between the
724 Furthermore, it is not guaranteed that the event pair is atomically
725 inserted into the queue: there may be a brief interval where the
727 has appeared, but the
735 event pair generated by
737 is thus inherently racy.
738 (Don't forget that if an object is renamed outside of a monitored directory,
739 there may not even be an
742 Heuristic approaches (e.g., assume the events are always consecutive)
743 can be used to ensure a match in most cases,
744 but will inevitably miss some cases,
745 causing the application to perceive the
749 events as being unrelated.
750 If watch descriptors are destroyed and re-created as a result,
751 then those watch descriptors will be inconsistent with
752 the watch descriptors in any pending events.
753 (Re-creating the inotify file descriptor and rebuilding the cache may
754 be useful to deal with this scenario.)
756 Applications should also allow for the possibility that the
758 event was the last event that could fit in the buffer
759 returned by the current call to
763 event might be fetched only on the next
765 which should be done with a (small) timeout to allow for the fact that
767 .BR IN_MOVED_FROM - IN_MOVED_TO
768 event pair is not atomic,
769 and also the possibility that there may not be any
775 did not create any inotify events.
777 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
784 .\" FIXME . kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
785 .\" implies that unmount events were buggy 2.6.11 to 2.6.36
787 In kernels before 2.6.16, the
792 As originally designed and implemented, the
794 flag did not cause an
796 event to be generated when the watch was dropped after one event.
797 However, as an unintended effect of other changes,
798 since Linux 2.6.36, an
800 event is generated in this case.
802 Before kernel 2.6.25,
803 .\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
804 the kernel code that was intended to coalesce successive identical events
805 (i.e., the two most recent events could potentially be coalesced
806 if the older had not yet been read)
807 instead checked if the most recent event could be coalesced with the
811 When a watch descriptor is removed by calling
812 .BR inotify_rm_watch (2)
813 (or because a watch file is deleted or the filesystem
814 that contains it is unmounted),
815 any pending unread events for that watch descriptor remain available to read.
816 As watch descriptors are subsequently allocated with
817 .BR inotify_add_watch (2),
818 the kernel cycles through the range of possible watch descriptors (0 to
821 When allocating a free watch descriptor, no check is made to see whether that
822 watch descriptor number has any pending unread events in the inotify queue.
823 Thus, it can happen that a watch descriptor is reallocated even
824 when pending unread events exist for a previous incarnation of
825 that watch descriptor number, with the result that the application
826 might then read those events and interpret them as belonging to
827 the file associated with the newly recycled watch descriptor.
828 In practice, the likelihood of hitting this bug may be extremely low,
829 since it requires that an application cycle through
832 release a watch descriptor while leaving unread events for that
833 watch descriptor in the queue,
834 and then recycle that watch descriptor.
835 For this reason, and because there have been no reports
836 of the bug occurring in real-world applications,
838 .\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
839 no kernel changes have yet been made to eliminate this possible bug.
841 The following program demonstrates the usage of the inotify API.
842 It marks the directories passed as a command-line arguments
843 and waits for events of type
849 The following output was recorded while editing the file
850 .I /home/user/temp/foo
851 and listing directory
853 Before the file and the directory were opened,
856 After the file was closed, an
859 After the directory was closed, an
862 Execution of the program ended when the user pressed the ENTER key.
866 $ \fB./a.out /tmp /home/user/temp\fP
867 Press enter key to terminate.
868 Listening for events.
869 IN_OPEN: /home/user/temp/foo [file]
870 IN_CLOSE_WRITE: /home/user/temp/foo [file]
871 IN_OPEN: /tmp/ [directory]
872 IN_CLOSE_NOWRITE: /tmp/ [directory]
874 Listening for events stopped.
883 #include <sys/inotify.h>
886 /* Read all available inotify events from the file descriptor 'fd'.
887 wd is the table of watch descriptors for the directories in argv.
888 argc is the length of wd and argv.
889 argv is the list of watched directories.
890 Entry 0 of wd and argv is unused. */
893 handle_events(int fd, int *wd, int argc, char* argv[])
895 /* Some systems cannot read integer variables if they are not
896 properly aligned. On other systems, incorrect alignment may
897 decrease performance. Hence, the buffer used for reading from
898 the inotify file descriptor should have the same alignment as
899 struct inotify_event. */
902 __attribute__ ((aligned(__alignof__(struct inotify_event))));
903 const struct inotify_event *event;
908 /* Loop while events can be read from inotify file descriptor. */
912 /* Read some events. */
914 len = read(fd, buf, sizeof buf);
915 if (len == \-1 && errno != EAGAIN) {
920 /* If the nonblocking read() found no events to read, then
921 it returns \-1 with errno set to EAGAIN. In that case,
927 /* Loop over all events in the buffer */
929 for (ptr = buf; ptr < buf + len;
930 ptr += sizeof(struct inotify_event) + event\->len) {
932 event = (const struct inotify_event *) ptr;
934 /* Print event type */
936 if (event\->mask & IN_OPEN)
938 if (event\->mask & IN_CLOSE_NOWRITE)
939 printf("IN_CLOSE_NOWRITE: ");
940 if (event\->mask & IN_CLOSE_WRITE)
941 printf("IN_CLOSE_WRITE: ");
943 /* Print the name of the watched directory */
945 for (i = 1; i < argc; ++i) {
946 if (wd[i] == event\->wd) {
947 printf("%s/", argv[i]);
952 /* Print the name of the file */
955 printf("%s", event\->name);
957 /* Print type of filesystem object */
959 if (event\->mask & IN_ISDIR)
960 printf(" [directory]\\n");
962 printf(" [file]\\n");
968 main(int argc, char* argv[])
974 struct pollfd fds[2];
977 printf("Usage: %s PATH [PATH ...]\\n", argv[0]);
981 printf("Press ENTER key to terminate.\\n");
983 /* Create the file descriptor for accessing the inotify API */
985 fd = inotify_init1(IN_NONBLOCK);
987 perror("inotify_init1");
991 /* Allocate memory for watch descriptors */
993 wd = calloc(argc, sizeof(int));
999 /* Mark directories for events
1001 \- file was closed */
1003 for (i = 1; i < argc; i++) {
1004 wd[i] = inotify_add_watch(fd, argv[i],
1005 IN_OPEN | IN_CLOSE);
1007 fprintf(stderr, "Cannot watch '%s'\\n", argv[i]);
1008 perror("inotify_add_watch");
1013 /* Prepare for polling */
1019 fds[0].fd = STDIN_FILENO;
1020 fds[0].events = POLLIN;
1025 fds[1].events = POLLIN;
1027 /* Wait for events and/or terminal input */
1029 printf("Listening for events.\\n");
1031 poll_num = poll(fds, nfds, \-1);
1032 if (poll_num == \-1) {
1041 if (fds[0].revents & POLLIN) {
1043 /* Console input is available. Empty stdin and quit */
1045 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
1050 if (fds[1].revents & POLLIN) {
1052 /* Inotify events are available */
1054 handle_events(fd, wd, argc, argv);
1059 printf("Listening for events stopped.\\n");
1061 /* Close inotify file descriptor */
1070 .BR inotifywait (1),
1071 .BR inotifywatch (1),
1072 .BR inotify_add_watch (2),
1073 .BR inotify_init (2),
1074 .BR inotify_init1 (2),
1075 .BR inotify_rm_watch (2),
1080 .IR Documentation/filesystems/inotify.txt
1081 in the Linux kernel source tree