1 .\" Copyright (C) 2006, 2014 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\" Copyright (C) 2014 Heinrich Schuchardt <xypron.glpk@gmx.de>
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein. The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
26 .TH INOTIFY 7 2021-03-22 "Linux" "Linux Programmer's Manual"
28 inotify \- monitoring filesystem events
32 API provides a mechanism for monitoring filesystem events.
33 Inotify can be used to monitor individual files,
34 or to monitor directories.
35 When a directory is monitored, inotify will return events
36 for the directory itself, and for files inside the directory.
38 The following system calls are used with this API:
41 creates an inotify instance and returns a file descriptor
42 referring to the inotify instance.
49 argument that provides access to some extra functionality.
51 .BR inotify_add_watch (2)
52 manipulates the "watch list" associated with an inotify instance.
53 Each item ("watch") in the watch list specifies the pathname of
55 along with some set of events that the kernel should monitor for the
56 file referred to by that pathname.
57 .BR inotify_add_watch (2)
58 either creates a new watch item, or modifies an existing watch.
59 Each watch has a unique "watch descriptor", an integer
61 .BR inotify_add_watch (2)
62 when the watch is created.
64 When events occur for monitored files and directories,
65 those events are made available to the application as structured data that
66 can be read from the inotify file descriptor using
70 .BR inotify_rm_watch (2)
71 removes an item from an inotify watch list.
73 When all file descriptors referring to an inotify
74 instance have been closed (using
76 the underlying object and its resources are
77 freed for reuse by the kernel;
78 all associated watches are automatically freed.
80 With careful programming,
81 an application can use inotify to efficiently monitor and cache
82 the state of a set of filesystem objects.
83 However, robust applications should allow for the fact that bugs
84 in the monitoring logic or races of the kind described below
85 may leave the cache inconsistent with the filesystem state.
86 It is probably wise to do some consistency checking,
87 and rebuild the cache when inconsistencies are detected.
88 .SS Reading events from an inotify file descriptor
89 To determine what events have occurred, an application
91 from the inotify file descriptor.
92 If no events have so far occurred, then,
93 assuming a blocking file descriptor,
95 will block until at least one event occurs
96 (unless interrupted by a signal,
97 in which case the call fails with the error
104 returns a buffer containing one or more of the following structures:
108 struct inotify_event {
109 int wd; /* Watch descriptor */
110 .\" FIXME . The type of the 'wd' field should probably be "int32_t".
111 .\" I submitted a patch to fix this. See the LKML thread
112 .\" "[patch] Fix type errors in inotify interfaces", 18 Nov 2008
113 .\" Glibc bug filed: http://sources.redhat.com/bugzilla/show_bug.cgi?id=7040
114 uint32_t mask; /* Mask describing event */
115 uint32_t cookie; /* Unique cookie associating related
116 events (for rename(2)) */
117 uint32_t len; /* Size of \fIname\fP field */
118 char name[]; /* Optional null\-terminated name */
124 identifies the watch for which this event occurs.
125 It is one of the watch descriptors returned by a previous call to
126 .BR inotify_add_watch (2).
129 contains bits that describe the event that occurred (see below).
132 is a unique integer that connects related events.
133 Currently, this is used only for rename events, and
134 allows the resulting pair of
138 events to be connected by the application.
139 For all other event types,
145 field is present only when an event is returned
146 for a file inside a watched directory;
147 it identifies the filename within the watched directory.
148 This filename is null-terminated,
149 and may include further null bytes (\(aq\e0\(aq) to align subsequent reads to a
150 suitable address boundary.
154 field counts all of the bytes in
156 including the null bytes;
160 .IR "sizeof(struct inotify_event)+len" .
162 The behavior when the buffer given to
164 is too small to return information about the next event depends
165 on the kernel version: in kernels before 2.6.21,
167 returns 0; since kernel 2.6.21,
171 Specifying a buffer of size
173 sizeof(struct inotify_event) + NAME_MAX + 1
175 will be sufficient to read at least one event.
178 .BR inotify_add_watch (2)
184 structure returned when
186 an inotify file descriptor are both bit masks identifying
188 The following bits can be specified in
191 .BR inotify_add_watch (2)
192 and may be returned in the
199 File was accessed (e.g.,
204 Metadata changed\(emfor example, permissions (e.g.,
210 link count (since Linux 2.6.25; e.g.,
212 .\" Events do not occur for link count changes on a file inside a monitored
213 .\" directory. This differs from other metadata changes for files inside
214 .\" a monitored directory.
219 and user/group ID (e.g.,
222 .BR IN_CLOSE_WRITE " (+)"
223 File opened for writing was closed.
225 .BR IN_CLOSE_NOWRITE " (*)"
226 File or directory not opened for writing was closed.
229 File/directory created in watched directory (e.g.,
236 on a UNIX domain socket).
239 File/directory deleted from watched directory.
242 Watched file/directory was itself deleted.
243 (This event also occurs if an object is moved to another filesystem,
246 in effect copies the file to the other filesystem and
247 then deletes it from the original filesystem.)
250 event will subsequently be generated for the watch descriptor.
253 File was modified (e.g.,
258 Watched file/directory was itself moved.
260 .BR IN_MOVED_FROM " (+)"
261 Generated for the directory containing the old filename
262 when a file is renamed.
264 .BR IN_MOVED_TO " (+)"
265 Generated for the directory containing the new filename
266 when a file is renamed.
269 File or directory was opened.
272 Inotify monitoring is inode-based: when monitoring a file
273 (but not when monitoring the directory containing a file),
274 an event can be generated for activity on any link to the file
275 (in the same or a different directory).
277 When monitoring a directory:
279 the events marked above with an asterisk (*) can occur both
280 for the directory itself and for objects inside the directory; and
282 the events marked with a plus sign (+) occur only for objects
283 inside the directory (not for the directory itself).
286 when monitoring a directory,
287 events are not generated for the files inside the directory
288 when the events are performed via a pathname (i.e., a link)
289 that lies outside the monitored directory.
291 When events are generated for objects inside a watched directory, the
293 field in the returned
295 structure identifies the name of the file within the directory.
299 macro is defined as a bit mask of all of the above events.
300 This macro can be used as the
302 argument when calling
303 .BR inotify_add_watch (2).
305 Two additional convenience macros are defined:
310 .BR "IN_MOVED_FROM | IN_MOVED_TO" .
314 .BR "IN_CLOSE_WRITE | IN_CLOSE_NOWRITE" .
317 The following further bits can be specified in
320 .BR inotify_add_watch (2):
323 .BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
326 if it is a symbolic link.
328 .BR IN_EXCL_UNLINK " (since Linux 2.6.36)"
329 .\" commit 8c1934c8d70b22ca8333b216aec6c7d09fdbd6a6
330 By default, when watching events on the children of a directory,
331 events are generated for children even after they have been unlinked
333 This can result in large numbers of uninteresting events for
334 some applications (e.g., if watching
336 in which many applications create temporary files whose
337 names are immediately unlinked).
340 changes the default behavior,
341 so that events are not generated for children after
342 they have been unlinked from the watched directory.
345 If a watch instance already exists for the filesystem object corresponding to
347 add (OR) the events in
349 to the watch mask (instead of replacing the mask);
357 Monitor the filesystem object corresponding to
359 for one event, then remove from
362 .BR IN_ONLYDIR " (since Linux 2.6.15)"
365 only if it is a directory;
371 Using this flag provides an application with a race-free way of
372 ensuring that the monitored object is a directory.
374 .BR IN_MASK_CREATE " (since Linux 4.18)"
377 only if it does not already have a watch associated with it;
382 is already being watched.
384 Using this flag provides an application with a way of ensuring
385 that new watches do not modify existing ones.
386 This is useful because multiple paths may refer to the same inode,
387 and multiple calls to
388 .BR inotify_add_watch (2)
389 without this flag may clobber existing watch masks.
392 The following bits may be set in the
399 Watch was removed explicitly
400 .RB ( inotify_rm_watch (2))
401 or automatically (file was deleted, or filesystem was unmounted).
405 Subject of this event is a directory.
408 Event queue overflowed
410 is \-1 for this event).
413 Filesystem containing watched object was unmounted.
416 event will subsequently be generated for the watch descriptor.
419 Suppose an application is watching the directory
424 The examples below show some events that will be generated
425 for these two objects.
428 fd = open("dir/myfile", O_RDWR);
436 read(fd, buf, count);
444 write(fd, buf, count);
469 Suppose an application is watching the directories
475 The following examples show some events that may be generated.
478 link("dir1/myfile", "dir2/new");
488 rename("dir1/myfile", "dir2/myfile");
505 events will have the same
514 are (the only) links to the same file, and an application is watching
520 Executing the following calls in the order given below will generate
521 the following events:
529 (because its link count changes)
549 Suppose an application is watching the directory
551 and (the empty) directory
553 The following examples show some events that may be generated.
556 mkdir("dir/new", mode);
558 .B "IN_CREATE | IN_ISDIR"
570 .B "IN_DELETE | IN_ISDIR"
575 The following interfaces can be used to limit the amount of
576 kernel memory consumed by inotify:
578 .I /proc/sys/fs/inotify/max_queued_events
579 The value in this file is used when an application calls
581 to set an upper limit on the number of events that can be
582 queued to the corresponding inotify instance.
583 Events in excess of this limit are dropped, but an
585 event is always generated.
587 .I /proc/sys/fs/inotify/max_user_instances
588 This specifies an upper limit on the number of inotify instances
589 that can be created per real user ID.
591 .I /proc/sys/fs/inotify/max_user_watches
592 This specifies an upper limit on the number of watches
593 that can be created per real user ID.
595 Inotify was merged into the 2.6.13 Linux kernel.
596 The required library interfaces were added to glibc in version 2.4.
597 .RB ( IN_DONT_FOLLOW ,
601 were added in glibc version 2.5.)
603 The inotify API is Linux-specific.
605 Inotify file descriptors can be monitored using
610 When an event is available, the file descriptor indicates as readable.
613 signal-driven I/O notification is available for inotify file descriptors;
614 see the discussion of
626 structure (described in
628 that is passed to the signal handler has the following fields set:
630 is set to the inotify file descriptor number;
632 is set to the signal number;
641 If successive output inotify events produced on the
642 inotify file descriptor are identical (same
648 then they are coalesced into a single event if the
649 older event has not yet been read (but see BUGS).
650 This reduces the amount of kernel memory required for the event queue,
651 but also means that an application can't use inotify to reliably count
654 The events returned by reading from an inotify file descriptor
655 form an ordered queue.
656 Thus, for example, it is guaranteed that when renaming from
657 one directory to another, events will be produced in the
658 correct order on the inotify file descriptor.
660 The set of watch descriptors that is being monitored via
661 an inotify file descriptor can be viewed via the entry for
662 the inotify file descriptor in the process's
663 .IR /proc/[pid]/fdinfo
671 returns the number of bytes available to read from an
672 inotify file descriptor.
673 .SS Limitations and caveats
674 The inotify API provides no information about the user or process that
675 triggered the inotify event.
676 In particular, there is no easy
677 way for a process that is monitoring events via inotify
678 to distinguish events that it triggers
679 itself from those that are triggered by other processes.
681 Inotify reports only events that a user-space program triggers through
683 As a result, it does not catch remote events that occur
684 on network filesystems.
685 (Applications must fall back to polling the filesystem
686 to catch such events.)
687 Furthermore, various pseudo-filesystems such as
692 are not monitorable with inotify.
694 The inotify API does not report file accesses and modifications that
701 The inotify API identifies affected files by filename.
702 However, by the time an application processes an inotify event,
703 the filename may already have been deleted or renamed.
705 The inotify API identifies events via watch descriptors.
706 It is the application's responsibility to cache a mapping
707 (if one is needed) between watch descriptors and pathnames.
708 Be aware that directory renamings may affect multiple cached pathnames.
710 Inotify monitoring of directories is not recursive:
711 to monitor subdirectories under a directory,
712 additional watches must be created.
713 This can take a significant amount time for large directory trees.
715 If monitoring an entire directory subtree,
716 and a new subdirectory is created in that tree or an existing directory
717 is renamed into that tree,
718 be aware that by the time you create a watch for the new subdirectory,
719 new files (and subdirectories) may already exist inside the subdirectory.
720 Therefore, you may want to scan the contents of the subdirectory
721 immediately after adding the watch (and, if desired,
722 recursively add watches for any subdirectories that it contains).
724 Note that the event queue can overflow.
725 In this case, events are lost.
726 Robust applications should handle the possibility of
727 lost events gracefully.
728 For example, it may be necessary to rebuild part or all of
729 the application cache.
730 (One simple, but possibly expensive,
731 approach is to close the inotify file descriptor, empty the cache,
732 create a new inotify file descriptor,
733 and then re-create watches and cache entries
734 for the objects to be monitored.)
736 If a filesystem is mounted on top of a monitored directory,
737 no event is generated, and no events are generated
738 for objects immediately under the new mount point.
739 If the filesystem is subsequently unmounted,
740 events will subsequently be generated for the directory and
741 the objects it contains.
743 .SS Dealing with rename() events
748 event pair that is generated by
750 can be matched up via their shared cookie value.
751 However, the task of matching has some challenges.
753 These two events are usually consecutive in the event stream available
754 when reading from the inotify file descriptor.
755 However, this is not guaranteed.
756 If multiple processes are triggering events for monitored objects,
757 then (on rare occasions) an arbitrary number of
758 other events may appear between the
763 Furthermore, it is not guaranteed that the event pair is atomically
764 inserted into the queue: there may be a brief interval where the
766 has appeared, but the
774 event pair generated by
776 is thus inherently racy.
777 (Don't forget that if an object is renamed outside of a monitored directory,
778 there may not even be an
781 Heuristic approaches (e.g., assume the events are always consecutive)
782 can be used to ensure a match in most cases,
783 but will inevitably miss some cases,
784 causing the application to perceive the
788 events as being unrelated.
789 If watch descriptors are destroyed and re-created as a result,
790 then those watch descriptors will be inconsistent with
791 the watch descriptors in any pending events.
792 (Re-creating the inotify file descriptor and rebuilding the cache may
793 be useful to deal with this scenario.)
795 Applications should also allow for the possibility that the
797 event was the last event that could fit in the buffer
798 returned by the current call to
802 event might be fetched only on the next
804 which should be done with a (small) timeout to allow for the fact that
806 .BR IN_MOVED_FROM + IN_MOVED_TO
807 event pair is not atomic,
808 and also the possibility that there may not be any
814 did not create any inotify events.
816 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
823 .\" FIXME . kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
824 .\" implies that unmount events were buggy 2.6.11 to 2.6.36
826 In kernels before 2.6.16, the
831 As originally designed and implemented, the
833 flag did not cause an
835 event to be generated when the watch was dropped after one event.
836 However, as an unintended effect of other changes,
837 since Linux 2.6.36, an
839 event is generated in this case.
841 Before kernel 2.6.25,
842 .\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
843 the kernel code that was intended to coalesce successive identical events
844 (i.e., the two most recent events could potentially be coalesced
845 if the older had not yet been read)
846 instead checked if the most recent event could be coalesced with the
850 When a watch descriptor is removed by calling
851 .BR inotify_rm_watch (2)
852 (or because a watch file is deleted or the filesystem
853 that contains it is unmounted),
854 any pending unread events for that watch descriptor remain available to read.
855 As watch descriptors are subsequently allocated with
856 .BR inotify_add_watch (2),
857 the kernel cycles through the range of possible watch descriptors (0 to
860 When allocating a free watch descriptor, no check is made to see whether that
861 watch descriptor number has any pending unread events in the inotify queue.
862 Thus, it can happen that a watch descriptor is reallocated even
863 when pending unread events exist for a previous incarnation of
864 that watch descriptor number, with the result that the application
865 might then read those events and interpret them as belonging to
866 the file associated with the newly recycled watch descriptor.
867 In practice, the likelihood of hitting this bug may be extremely low,
868 since it requires that an application cycle through
871 release a watch descriptor while leaving unread events for that
872 watch descriptor in the queue,
873 and then recycle that watch descriptor.
874 For this reason, and because there have been no reports
875 of the bug occurring in real-world applications,
877 .\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
878 no kernel changes have yet been made to eliminate this possible bug.
880 The following program demonstrates the usage of the inotify API.
881 It marks the directories passed as a command-line arguments
882 and waits for events of type
884 .BR IN_CLOSE_NOWRITE ,
888 The following output was recorded while editing the file
889 .I /home/user/temp/foo
890 and listing directory
892 Before the file and the directory were opened,
895 After the file was closed, an
898 After the directory was closed, an
901 Execution of the program ended when the user pressed the ENTER key.
905 $ \fB./a.out /tmp /home/user/temp\fP
906 Press enter key to terminate.
907 Listening for events.
908 IN_OPEN: /home/user/temp/foo [file]
909 IN_CLOSE_WRITE: /home/user/temp/foo [file]
910 IN_OPEN: /tmp/ [directory]
911 IN_CLOSE_NOWRITE: /tmp/ [directory]
913 Listening for events stopped.
923 #include <sys/inotify.h>
927 /* Read all available inotify events from the file descriptor \(aqfd\(aq.
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;
947 /* Loop while events can be read from inotify file descriptor. */
951 /* Read some events. */
953 len = read(fd, buf, sizeof(buf));
954 if (len == \-1 && errno != EAGAIN) {
959 /* If the nonblocking read() found no events to read, then
960 it returns \-1 with errno set to EAGAIN. In that case,
966 /* Loop over all events in the buffer. */
968 for (char *ptr = buf; ptr < buf + len;
969 ptr += sizeof(struct inotify_event) + event\->len) {
971 event = (const struct inotify_event *) ptr;
973 /* Print event type. */
975 if (event\->mask & IN_OPEN)
977 if (event\->mask & IN_CLOSE_NOWRITE)
978 printf("IN_CLOSE_NOWRITE: ");
979 if (event\->mask & IN_CLOSE_WRITE)
980 printf("IN_CLOSE_WRITE: ");
982 /* Print the name of the watched directory. */
984 for (int i = 1; i < argc; ++i) {
985 if (wd[i] == event\->wd) {
986 printf("%s/", argv[i]);
991 /* Print the name of the file. */
994 printf("%s", event\->name);
996 /* Print type of filesystem object. */
998 if (event\->mask & IN_ISDIR)
999 printf(" [directory]\en");
1001 printf(" [file]\en");
1007 main(int argc, char* argv[])
1010 int fd, i, poll_num;
1013 struct pollfd fds[2];
1016 printf("Usage: %s PATH [PATH ...]\en", argv[0]);
1020 printf("Press ENTER key to terminate.\en");
1022 /* Create the file descriptor for accessing the inotify API. */
1024 fd = inotify_init1(IN_NONBLOCK);
1026 perror("inotify_init1");
1030 /* Allocate memory for watch descriptors. */
1032 wd = calloc(argc, sizeof(int));
1038 /* Mark directories for events
1040 \- file was closed */
1042 for (i = 1; i < argc; i++) {
1043 wd[i] = inotify_add_watch(fd, argv[i],
1044 IN_OPEN | IN_CLOSE);
1046 fprintf(stderr, "Cannot watch \(aq%s\(aq: %s\en",
1047 argv[i], strerror(errno));
1052 /* Prepare for polling. */
1056 fds[0].fd = STDIN_FILENO; /* Console input */
1057 fds[0].events = POLLIN;
1059 fds[1].fd = fd; /* Inotify input */
1060 fds[1].events = POLLIN;
1062 /* Wait for events and/or terminal input. */
1064 printf("Listening for events.\en");
1066 poll_num = poll(fds, nfds, \-1);
1067 if (poll_num == \-1) {
1076 if (fds[0].revents & POLLIN) {
1078 /* Console input is available. Empty stdin and quit. */
1080 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != \(aq\en\(aq)
1085 if (fds[1].revents & POLLIN) {
1087 /* Inotify events are available. */
1089 handle_events(fd, wd, argc, argv);
1094 printf("Listening for events stopped.\en");
1096 /* Close inotify file descriptor. */
1105 .BR inotifywait (1),
1106 .BR inotifywatch (1),
1107 .BR inotify_add_watch (2),
1108 .BR inotify_init (2),
1109 .BR inotify_init1 (2),
1110 .BR inotify_rm_watch (2),
1115 .IR Documentation/filesystems/inotify.txt
1116 in the Linux kernel source tree