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 2014-05-23 "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 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 of events */
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 file pathname relative to the watched directory.
149 This pathname 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.,
216 and user/group ID (e.g.,
219 .BR IN_CLOSE_WRITE " (*)"
220 File opened for writing was closed.
222 .BR IN_CLOSE_NOWRITE " (*)"
223 File not opened for writing was closed.
226 File/directory created in watched directory (e.g.,
233 on a UNIX domain socket).
236 File/directory deleted from watched directory.
239 Watched file/directory was itself deleted.
240 (This event also occurs if an object is moved to another filesystem,
243 in effect copies the file to the other filesystem and
244 then deletes it from the original filesystem.)
247 event will subsequently be generated for the watch descriptor.
250 File was modified (e.g.,
255 Watched file/directory was itself moved.
257 .BR IN_MOVED_FROM " (*)"
258 Generated for the directory containing the old filename
259 when a file is renamed.
261 .BR IN_MOVED_TO " (*)"
262 Generated for the directory containing the new filename
263 when a file is renamed.
269 When monitoring a directory,
270 the events marked with an asterisk (*) above can occur for
271 files in the directory, in which case the
273 field in the returned
275 structure identifies the name of the file within the directory.
279 macro is defined as a bit mask of all of the above events.
280 This macro can be used as the
282 argument when calling
283 .BR inotify_add_watch (2).
285 Two additional convenience macros are defined:
290 .BR "IN_MOVED_FROM | IN_MOVED_TO" .
294 .BR "IN_CLOSE_WRITE | IN_CLOSE_NOWRITE" .
297 The following further bits can be specified in
300 .BR inotify_add_watch (2):
303 .BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
306 if it is a symbolic link.
308 .BR IN_EXCL_UNLINK " (since Linux 2.6.36)"
309 .\" commit 8c1934c8d70b22ca8333b216aec6c7d09fdbd6a6
310 By default, when watching events on the children of a directory,
311 events are generated for children even after they have been unlinked
313 This can result in large numbers of uninteresting events for
314 some applications (e.g., if watching
316 in which many applications create temporary files whose
317 names are immediately unlinked).
320 changes the default behavior,
321 so that events are not generated for children after
322 they have been unlinked from the watched directory.
325 Add (OR) events to watch mask for this pathname if
326 it already exists (instead of replacing mask).
331 for one event, then remove from
334 .BR IN_ONLYDIR " (since Linux 2.6.15)"
337 if it is a directory.
340 The following bits may be set in the
347 Watch was removed explicitly
348 .RB ( inotify_rm_watch (2))
349 or automatically (file was deleted, or filesystem was unmounted).
353 Subject of this event is a directory.
356 Event queue overflowed
358 is \-1 for this event).
361 Filesystem containing watched object was unmounted.
364 event will subsequently be generated for the watch descriptor.
367 Suppose an application is watching the directory
372 The examples below show some events that will be generated
373 for these two objects.
376 fd = open("dir/myfile", O_RDWR);
384 read(fd, buf, count);
392 write(fd, buf, count);
417 Suppose an application is watching the directories
423 The following examples show some events that may be generated.
426 link("dir1/myfile", "dir2/new");
436 rename("dir1/myfile", "dir2/myfile");
453 events will have the same
462 are (the only) links to the same file, and an application is watching
468 Executing the following calls in the order given below will generate
469 the following events:
477 (because its link count changes)
497 Suppose an application is watching the directory
499 and (the empty) directory
501 The following examples show some events that may be generated.
504 mkdir("dir/new", mode);
506 .B "IN_CREATE | IN_ISDIR"
518 .B "IN_DELETE | IN_ISDIR"
523 The following interfaces can be used to limit the amount of
524 kernel memory consumed by inotify:
526 .I /proc/sys/fs/inotify/max_queued_events
527 The value in this file is used when an application calls
529 to set an upper limit on the number of events that can be
530 queued to the corresponding inotify instance.
531 Events in excess of this limit are dropped, but an
533 event is always generated.
535 .I /proc/sys/fs/inotify/max_user_instances
536 This specifies an upper limit on the number of inotify instances
537 that can be created per real user ID.
539 .I /proc/sys/fs/inotify/max_user_watches
540 This specifies an upper limit on the number of watches
541 that can be created per real user ID.
543 Inotify was merged into the 2.6.13 Linux kernel.
544 The required library interfaces were added to glibc in version 2.4.
545 .RB ( IN_DONT_FOLLOW ,
549 were added in glibc version 2.5.)
551 The inotify API is Linux-specific.
553 Inotify file descriptors can be monitored using
558 When an event is available, the file descriptor indicates as readable.
561 signal-driven I/O notification is available for inotify file descriptors;
562 see the discussion of
574 structure (described in
576 that is passed to the signal handler has the following fields set:
578 is set to the inotify file descriptor number;
580 is set to the signal number;
589 If successive output inotify events produced on the
590 inotify file descriptor are identical (same
596 then they are coalesced into a single event if the
597 older event has not yet been read (but see BUGS).
598 This reduces the amount of kernel memory required for the event queue,
599 but also means that an application can't use inotify to reliably count
602 The events returned by reading from an inotify file descriptor
603 form an ordered queue.
604 Thus, for example, it is guaranteed that when renaming from
605 one directory to another, events will be produced in the
606 correct order on the inotify file descriptor.
611 returns the number of bytes available to read from an
612 inotify file descriptor.
613 .SS Limitations and caveats
614 The inotify API provides no information about the user or process that
615 triggered the inotify event.
616 In particular, there is no easy
617 way for a process that is monitoring events via inotify
618 to distinguish events that it triggers
619 itself from those that are triggered by other processes.
621 Inotify reports only events that a user-space program triggers through
623 As a result, it does not catch remote events that occur
624 on network filesystems.
625 (Applications must fall back to polling the filesystem
626 to catch such events.)
627 Furthermore, various pseudo-filesystems such as
632 are not monitorable with inotify.
634 The inotify API does not report file accesses and modifications that
641 The inotify API identifies affected files by filename.
642 However, by the time an application processes an inotify event,
643 the filename may already have been deleted or renamed.
645 The inotify API identifies events via watch descriptors.
646 It is the application's responsibility to cache a mapping
647 (if one is needed) between watch descriptors and pathnames.
648 Be aware that directory renamings may affect multiple cached pathnames.
650 Inotify monitoring of directories is not recursive:
651 to monitor subdirectories under a directory,
652 additional watches must be created.
653 This can take a significant amount time for large directory trees.
655 If monitoring an entire directory subtree,
656 and a new subdirectory is created in that tree or an existing directory
657 is renamed into that tree,
658 be aware that by the time you create a watch for the new subdirectory,
659 new files (and subdirectories) may already exist inside the subdirectory.
660 Therefore, you may want to scan the contents of the subdirectory
661 immediately after adding the watch (and, if desired,
662 recursively add watches for any subdirectories that it contains).
664 Note that the event queue can overflow.
665 In this case, events are lost.
666 Robust applications should handle the possibility of
667 lost events gracefully.
668 For example, it may be necessary to rebuild part or all of
669 the application cache.
670 (One simple, but possibly expensive,
671 approach is to close the inotify file descriptor, empty the cache,
672 create a new inotify file descriptor,
673 and then re-create watches and cache entries
674 for the objects to be monitored.)
675 .SS Dealing with rename() events
680 event pair that is generated by
682 can be matched up via their shared cookie value.
683 However, the task of matching has some challenges.
685 These two events are usually consecutive in the event stream available
686 when reading from the inotify file descriptor.
687 However, this is not guaranteed.
688 If multiple processes are triggering events for monitored objects,
689 then (on rare occasions) an arbitrary number of
690 other events may appear between the
700 event pair generated by
702 is thus inherently racy.
703 (Don't forget that if an object is renamed outside of a monitored directory,
704 there may not even be an
707 Heuristic approaches (e.g., assume the events are always consecutive)
708 can be used to ensure a match in most cases,
709 but will inevitably miss some cases,
710 causing the application to perceive the
714 events as being unrelated.
715 If watch descriptors are destroyed and re-created as a result,
716 then those watch descriptors will be inconsistent with
717 the watch descriptors in any pending events.
718 (Re-creating the inotify file descriptor and rebuilding the cache may
719 be useful to deal with this scenario.)
721 Applications should also allow for the possibility that the
723 event was the last event that could fit in the buffer
724 returned by the current call to
728 event might be fetched only on the next
731 .\" FIXME kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
732 .\" implies that unmount events were buggy 2.6.11 to 2.6.36
734 In kernels before 2.6.16, the
739 As originally designed and implemented, the
741 flag did not cause an
743 event to be generated when the watch was dropped after one event.
744 However, as an unintended effect of other changes,
745 since Linux 2.6.36, an
747 event is generated in this case.
749 Before kernel 2.6.25,
750 .\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
751 the kernel code that was intended to coalesce successive identical events
752 (i.e., the two most recent events could potentially be coalesced
753 if the older had not yet been read)
754 instead checked if the most recent event could be coalesced with the
758 As of Linux 3.15, the following bug exists:
759 .\" FIXME https://bugzilla.kernel.org/show_bug.cgi?id=77111
760 When a watch descriptor is removed by calling
761 .BR inotify_rm_watch (2),
762 any pending unread events for that watch descriptor remain available to read.
763 As watch descriptors are subsequently allocated with
764 .BR inotify_add_watch (2),
765 the kernel cycles through the range of possible watch descriptors (0 to
768 When allocating a free watch descriptor, no check is made to see whether that
769 watch descriptor number has any pending unread events in the inotify queue.
770 Thus, it can happen that a watch descriptor is reallocated even
771 when pending unread events exist for a previous incarnation of
772 that watch descriptor number, with the result that the application
773 might then read those events and interpret them as belonging to
774 the file associated with the newly recycled watch descriptor.
776 The following program demonstrates the usage of the inotify API.
777 It marks the directories passed as a command-line arguments
778 and waits for events of type
784 The following output was recorded while editing the file
785 .I /home/user/temp/foo
786 and listing directory
788 Before the file and the directory were opened,
791 After the file was closed, an
794 After the directory was closed, an
797 Execution of the program ended when the user pressed the ENTER key.
801 $ \fB./a.out /tmp /home/user/temp\fP
802 Press enter key to terminate.
803 Listening for events.
804 IN_OPEN: /home/user/temp/foo [file]
805 IN_CLOSE_WRITE: /home/user/temp/foo [file]
806 IN_OPEN: /tmp/ [directory]
807 IN_CLOSE_NOWRITE: /tmp/ [directory]
809 Listening for events stopped.
818 #include <sys/inotify.h>
821 /* Read all available inotify events from the file descriptor 'fd'.
822 wd is the table of watch descriptors for the directories in argv.
823 argc is the length of wd and argv.
824 argv is the list of watched directories.
825 Entry 0 of wd and argv is unused. */
828 handle_events(int fd, int *wd, int argc, char* argv[])
830 /* Some systems cannot read integer variables if they are not
831 properly aligned. On other systems, incorrect alignment may
832 decrease performance. Hence, the buffer used for reading from
833 the inotify file descriptor should have the same alignment as
834 struct inotify_event. */
837 __attribute__ ((aligned(__alignof__(struct inotify_event))));
838 const struct inotify_event *event;
843 /* Loop while events can be read from inotify file descriptor. */
847 /* Read some events. */
849 len = read(fd, buf, sizeof buf);
850 if (len == \-1 && errno != EAGAIN) {
855 /* If the nonblocking read() found no events to read, then
856 it returns \-1 with errno set to EAGAIN. In that case,
862 /* Loop over all events in the buffer */
864 for (ptr = buf; ptr < buf + len;
865 ptr += sizeof(struct inotify_event) + event\->len) {
867 event = (const struct inotify_event *) ptr;
869 /* Print event type */
871 if (event\->mask & IN_OPEN)
873 if (event\->mask & IN_CLOSE_NOWRITE)
874 printf("IN_CLOSE_NOWRITE: ");
875 if (event\->mask & IN_CLOSE_WRITE)
876 printf("IN_CLOSE_WRITE: ");
878 /* Print the name of the watched directory */
880 for (i = 1; i < argc; ++i) {
881 if (wd[i] == event\->wd) {
882 printf("%s/", argv[i]);
887 /* Print the name of the file */
890 printf("%s", event\->name);
892 /* Print type of filesystem object */
894 if (event\->mask & IN_ISDIR)
895 printf(" [directory]\\n");
897 printf(" [file]\\n");
903 main(int argc, char* argv[])
909 struct pollfd fds[2];
912 printf("Usage: %s PATH [PATH ...]\\n", argv[0]);
916 printf("Press ENTER key to terminate.\\n");
918 /* Create the file descriptor for accessing the inotify API */
920 fd = inotify_init1(IN_NONBLOCK);
922 perror("inotify_init1");
926 /* Allocate memory for watch descriptors */
928 wd = calloc(argc, sizeof(int));
934 /* Mark directories for events
936 \- file was closed */
938 for (i = 1; i < argc; i++) {
939 wd[i] = inotify_add_watch(fd, argv[i],
942 fprintf(stderr, "Cannot watch '%s'\\n", argv[i]);
943 perror("inotify_add_watch");
948 /* Prepare for polling */
954 fds[0].fd = STDIN_FILENO;
955 fds[0].events = POLLIN;
960 fds[1].events = POLLIN;
962 /* Wait for events and/or terminal input */
964 printf("Listening for events.\\n");
966 poll_num = poll(fds, nfds, \-1);
967 if (poll_num == \-1) {
976 if (fds[0].revents & POLLIN) {
978 /* Console input is available. Empty stdin and quit */
980 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
985 if (fds[1].revents & POLLIN) {
987 /* Inotify events are available */
989 handle_events(fd, wd, argc, argv);
994 printf("Listening for events stopped.\\n");
996 /* Close inotify file descriptor */
1005 .BR inotifywait (1),
1006 .BR inotifywatch (1),
1007 .BR inotify_add_watch (2),
1008 .BR inotify_init (2),
1009 .BR inotify_init1 (2),
1010 .BR inotify_rm_watch (2),
1015 .IR Documentation/filesystems/inotify.txt
1016 in the Linux kernel source tree