malloc.3: Clarify that realloc() may move the memory block
[man-pages.git] / man7 / inotify.7
blob547ceed5d368b7e2751fb71fec04e96bb953a2aa
1 .\" Copyright (C) 2006, 2014 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\" Copyright (C) 2014 Heinrich Schuchardt <xypron.glpk@gmx.de>
3 .\"
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.
8 .\"
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.
13 .\"
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
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .TH INOTIFY 7 2021-03-22 "Linux" "Linux Programmer's Manual"
27 .SH NAME
28 inotify \- monitoring filesystem events
29 .SH DESCRIPTION
30 The
31 .I inotify
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.
37 .PP
38 The following system calls are used with this API:
39 .IP * 3
40 .BR inotify_init (2)
41 creates an inotify instance and returns a file descriptor
42 referring to the inotify instance.
43 The more recent
44 .BR inotify_init1 (2)
45 is like
46 .BR inotify_init (2),
47 but has a
48 .IR flags
49 argument that provides access to some extra functionality.
50 .IP *
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
54 a file or directory,
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
60 returned by
61 .BR inotify_add_watch (2)
62 when the watch is created.
63 .IP *
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
67 .BR read (2)
68 (see below).
69 .IP *
70 .BR inotify_rm_watch (2)
71 removes an item from an inotify watch list.
72 .IP *
73 When all file descriptors referring to an inotify
74 instance have been closed (using
75 .BR close (2)),
76 the underlying object and its resources are
77 freed for reuse by the kernel;
78 all associated watches are automatically freed.
79 .PP
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
90 .BR read (2)s
91 from the inotify file descriptor.
92 If no events have so far occurred, then,
93 assuming a blocking file descriptor,
94 .BR read (2)
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
98 .BR EINTR ;
99 see
100 .BR signal (7)).
102 Each successful
103 .BR read (2)
104 returns a buffer containing one or more of the following structures:
106 .in +4n
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 */
123 .I wd
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).
128 .I mask
129 contains bits that describe the event that occurred (see below).
131 .I cookie
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
135 .B IN_MOVED_FROM
137 .B IN_MOVED_TO
138 events to be connected by the application.
139 For all other event types,
140 .I cookie
141 is set to 0.
144 .I name
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.
153 .I len
154 field counts all of the bytes in
155 .IR name ,
156 including the null bytes;
157 the length of each
158 .I inotify_event
159 structure is thus
160 .IR "sizeof(struct inotify_event)+len" .
162 The behavior when the buffer given to
163 .BR read (2)
164 is too small to return information about the next event depends
165 on the kernel version: in kernels before 2.6.21,
166 .BR read (2)
167 returns 0; since kernel 2.6.21,
168 .BR read (2)
169 fails with the error
170 .BR EINVAL .
171 Specifying a buffer of size
173     sizeof(struct inotify_event) + NAME_MAX + 1
175 will be sufficient to read at least one event.
176 .SS inotify events
178 .BR inotify_add_watch (2)
179 .I mask
180 argument and the
181 .I mask
182 field of the
183 .I inotify_event
184 structure returned when
185 .BR read (2)ing
186 an inotify file descriptor are both bit masks identifying
187 inotify events.
188 The following bits can be specified in
189 .I mask
190 when calling
191 .BR inotify_add_watch (2)
192 and may be returned in the
193 .I mask
194 field returned by
195 .BR read (2):
196 .RS 4
198 .BR IN_ACCESS " (+)"
199 File was accessed (e.g.,
200 .BR read (2),
201 .BR execve (2)).
203 .BR IN_ATTRIB " (*)"
204 Metadata changed\(emfor example, permissions (e.g.,
205 .BR chmod (2)),
206 timestamps (e.g.,
207 .BR utimensat (2)),
208 extended attributes
209 .RB ( setxattr (2)),
210 link count (since Linux 2.6.25; e.g.,
211 .\" FIXME .
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.
215 for the target of
216 .BR link (2)
217 and for
218 .BR unlink (2)),
219 and user/group ID (e.g.,
220 .BR chown (2)).
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.
228 .BR IN_CREATE " (+)"
229 File/directory created in watched directory (e.g.,
230 .BR open (2)
231 .BR O_CREAT ,
232 .BR mkdir (2),
233 .BR link (2),
234 .BR symlink (2),
235 .BR bind (2)
236 on a UNIX domain socket).
238 .BR IN_DELETE " (+)"
239 File/directory deleted from watched directory.
241 .B IN_DELETE_SELF
242 Watched file/directory was itself deleted.
243 (This event also occurs if an object is moved to another filesystem,
244 since
245 .BR mv (1)
246 in effect copies the file to the other filesystem and
247 then deletes it from the original filesystem.)
248 In addition, an
249 .B IN_IGNORED
250 event will subsequently be generated for the watch descriptor.
252 .BR IN_MODIFY " (+)"
253 File was modified (e.g.,
254 .BR write (2),
255 .BR truncate (2)).
257 .B IN_MOVE_SELF
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.
268 .BR IN_OPEN " (*)"
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:
278 .IP * 3
279 the events marked above with an asterisk (*) can occur both
280 for the directory itself and for objects inside the directory; and
281 .IP *
282 the events marked with a plus sign (+) occur only for objects
283 inside the directory (not for the directory itself).
285 .IR Note :
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
292 .I name
293 field in the returned
294 .I inotify_event
295 structure identifies the name of the file within the directory.
298 .B IN_ALL_EVENTS
299 macro is defined as a bit mask of all of the above events.
300 This macro can be used as the
301 .I mask
302 argument when calling
303 .BR inotify_add_watch (2).
305 Two additional convenience macros are defined:
306 .RS 4
308 .BR IN_MOVE
309 Equates to
310 .BR "IN_MOVED_FROM | IN_MOVED_TO" .
312 .BR IN_CLOSE
313 Equates to
314 .BR "IN_CLOSE_WRITE | IN_CLOSE_NOWRITE" .
317 The following further bits can be specified in
318 .I mask
319 when calling
320 .BR inotify_add_watch (2):
321 .RS 4
323 .BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
324 Don't dereference
325 .I pathname
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
332 from the directory.
333 This can result in large numbers of uninteresting events for
334 some applications (e.g., if watching
335 .IR /tmp ,
336 in which many applications create temporary files whose
337 names are immediately unlinked).
338 Specifying
339 .B IN_EXCL_UNLINK
340 changes the default behavior,
341 so that events are not generated for children after
342 they have been unlinked from the watched directory.
344 .B IN_MASK_ADD
345 If a watch instance already exists for the filesystem object corresponding to
346 .IR pathname ,
347 add (OR) the events in
348 .I mask
349 to the watch mask (instead of replacing the mask);
350 the error
351 .B EINVAL
352 results if
353 .B IN_MASK_CREATE
354 is also specified.
356 .B IN_ONESHOT
357 Monitor the filesystem object corresponding to
358 .I pathname
359 for one event, then remove from
360 watch list.
362 .BR IN_ONLYDIR " (since Linux 2.6.15)"
363 Watch
364 .I pathname
365 only if it is a directory;
366 the error
367 .B ENOTDIR
368 results if
369 .I pathname
370 is not 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)"
375 Watch
376 .I pathname
377 only if it does not already have a watch associated with it;
378 the error
379 .B EEXIST
380 results if
381 .I pathname
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
393 .I mask
394 field returned by
395 .BR read (2):
396 .RS 4
398 .B IN_IGNORED
399 Watch was removed explicitly
400 .RB ( inotify_rm_watch (2))
401 or automatically (file was deleted, or filesystem was unmounted).
402 See also BUGS.
404 .B IN_ISDIR
405 Subject of this event is a directory.
407 .B IN_Q_OVERFLOW
408 Event queue overflowed
409 .RI ( wd
410 is \-1 for this event).
412 .B IN_UNMOUNT
413 Filesystem containing watched object was unmounted.
414 In addition, an
415 .B IN_IGNORED
416 event will subsequently be generated for the watch descriptor.
418 .SS Examples
419 Suppose an application is watching the directory
420 .I dir
421 and the file
422 .IR dir/myfile
423 for all events.
424 The examples below show some events that will be generated
425 for these two objects.
426 .RS 4
428 fd = open("dir/myfile", O_RDWR);
429 Generates
430 .B IN_OPEN
431 events for both
432 .I dir
434 .IR dir/myfile .
436 read(fd, buf, count);
437 Generates
438 .B IN_ACCESS
439 events for both
440 .I dir
442 .IR dir/myfile .
444 write(fd, buf, count);
445 Generates
446 .B IN_MODIFY
447 events for both
448 .I dir
450 .IR dir/myfile .
452 fchmod(fd, mode);
453 Generates
454 .B IN_ATTRIB
455 events for both
456 .I dir
458 .IR dir/myfile .
460 close(fd);
461 Generates
462 .B IN_CLOSE_WRITE
463 events for both
464 .I dir
466 .IR dir/myfile .
469 Suppose an application is watching the directories
470 .I dir1
472 .IR dir2 ,
473 and the file
474 .IR dir1/myfile .
475 The following examples show some events that may be generated.
476 .RS 4
478 link("dir1/myfile", "dir2/new");
479 Generates an
480 .B IN_ATTRIB
481 event for
482 .IR myfile
483 and an
484 .B IN_CREATE
485 event for
486 .IR dir2 .
488 rename("dir1/myfile", "dir2/myfile");
489 Generates an
490 .B IN_MOVED_FROM
491 event for
492 .IR dir1 ,
494 .B IN_MOVED_TO
495 event for
496 .IR dir2 ,
497 and an
498 .B IN_MOVE_SELF
499 event for
500 .IR myfile .
502 .B IN_MOVED_FROM
504 .B IN_MOVED_TO
505 events will have the same
506 .I cookie
507 value.
510 Suppose that
511 .IR dir1/xx
513 .IR dir2/yy
514 are (the only) links to the same file, and an application is watching
515 .IR dir1 ,
516 .IR dir2 ,
517 .IR dir1/xx ,
519 .IR dir2/yy .
520 Executing the following calls in the order given below will generate
521 the following events:
522 .RS 4
524 unlink("dir2/yy");
525 Generates an
526 .BR IN_ATTRIB
527 event for
528 .IR xx
529 (because its link count changes)
530 and an
531 .B IN_DELETE
532 event for
533 .IR dir2 .
535 unlink("dir1/xx");
536 Generates
537 .BR IN_ATTRIB ,
538 .BR IN_DELETE_SELF ,
540 .BR IN_IGNORED
541 events for
542 .IR xx ,
543 and an
544 .BR IN_DELETE
545 event for
546 .IR dir1 .
549 Suppose an application is watching the directory
550 .IR dir
551 and (the empty) directory
552 .IR dir/subdir .
553 The following examples show some events that may be generated.
554 .RS 4
556 mkdir("dir/new", mode);
557 Generates an
558 .B "IN_CREATE | IN_ISDIR"
559 event for
560 .IR dir .
562 rmdir("dir/subdir");
563 Generates
564 .B IN_DELETE_SELF
566 .B IN_IGNORED
567 events for
568 .IR subdir ,
569 and an
570 .B "IN_DELETE | IN_ISDIR"
571 event for
572 .IR dir .
574 .SS /proc interfaces
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
580 .BR inotify_init (2)
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
584 .B IN_Q_OVERFLOW
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.
594 .SH VERSIONS
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 ,
598 .BR IN_MASK_ADD ,
600 .B IN_ONLYDIR
601 were added in glibc version 2.5.)
602 .SH CONFORMING TO
603 The inotify API is Linux-specific.
604 .SH NOTES
605 Inotify file descriptors can be monitored using
606 .BR select (2),
607 .BR poll (2),
609 .BR epoll (7).
610 When an event is available, the file descriptor indicates as readable.
612 Since Linux 2.6.25,
613 signal-driven I/O notification is available for inotify file descriptors;
614 see the discussion of
615 .B F_SETFL
616 (for setting the
617 .B O_ASYNC
618 flag),
619 .BR F_SETOWN ,
621 .B F_SETSIG
623 .BR fcntl (2).
625 .I siginfo_t
626 structure (described in
627 .BR sigaction (2))
628 that is passed to the signal handler has the following fields set:
629 .IR si_fd
630 is set to the inotify file descriptor number;
631 .IR si_signo
632 is set to the signal number;
633 .IR si_code
634 is set to
635 .BR POLL_IN ;
637 .B POLLIN
638 is set in
639 .IR si_band .
641 If successive output inotify events produced on the
642 inotify file descriptor are identical (same
643 .IR wd ,
644 .IR mask ,
645 .IR cookie ,
647 .IR name ),
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
652 file events.
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
664 directory.
666 .BR proc (5)
667 for further details.
669 .B FIONREAD
670 .BR ioctl (2)
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
682 the filesystem API.
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
688 .IR /proc ,
689 .IR /sys ,
691 .IR /dev/pts
692 are not monitorable with inotify.
694 The inotify API does not report file accesses and modifications that
695 may occur because of
696 .BR mmap (2),
697 .BR msync (2),
699 .BR munmap (2).
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
744 As noted above, the
745 .B IN_MOVED_FROM
747 .B IN_MOVED_TO
748 event pair that is generated by
749 .BR rename (2)
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
759 .B IN_MOVED_FROM
761 .B IN_MOVED_TO
762 events.
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
765 .B IN_MOVED_FROM
766 has appeared, but the
767 .B IN_MOVED_TO
768 has not.
770 Matching up the
771 .B IN_MOVED_FROM
773 .B IN_MOVED_TO
774 event pair generated by
775 .BR rename (2)
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
779 .BR IN_MOVED_TO
780 event.)
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
785 .B IN_MOVED_FROM
787 .B IN_MOVED_TO
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
796 .B IN_MOVED_FROM
797 event was the last event that could fit in the buffer
798 returned by the current call to
799 .BR read (2),
800 and the accompanying
801 .B IN_MOVED_TO
802 event might be fetched only on the next
803 .BR read (2),
804 which should be done with a (small) timeout to allow for the fact that
805 insertion of the
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
809 .B IN_MOVED_TO
810 event.
811 .SH BUGS
812 Before Linux 3.19,
813 .BR fallocate (2)
814 did not create any inotify events.
815 Since Linux 3.19,
816 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
817 calls to
818 .BR fallocate (2)
819 generate
820 .B IN_MODIFY
821 events.
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
827 .B IN_ONESHOT
828 .I mask
829 flag does not work.
831 As originally designed and implemented, the
832 .B IN_ONESHOT
833 flag did not cause an
834 .B IN_IGNORED
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
838 .B IN_IGNORED
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
847 .I oldest
848 unread event.
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
858 .BR INT_MAX )
859 incrementally.
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
869 .B INT_MAX
870 watch descriptors,
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,
876 as of Linux 3.15,
877 .\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
878 no kernel changes have yet been made to eliminate this possible bug.
879 .SH EXAMPLES
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
883 .BR IN_OPEN ,
884 .BR IN_CLOSE_NOWRITE ,
886 .BR IN_CLOSE_WRITE .
888 The following output was recorded while editing the file
889 .I /home/user/temp/foo
890 and listing directory
891 .IR /tmp .
892 Before the file and the directory were opened,
893 .B IN_OPEN
894 events occurred.
895 After the file was closed, an
896 .B IN_CLOSE_WRITE
897 event occurred.
898 After the directory was closed, an
899 .B IN_CLOSE_NOWRITE
900 event occurred.
901 Execution of the program ended when the user pressed the ENTER key.
902 .SS Example output
903 .in +4n
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.
916 .SS Program source
919 #include <errno.h>
920 #include <poll.h>
921 #include <stdio.h>
922 #include <stdlib.h>
923 #include <sys/inotify.h>
924 #include <unistd.h>
925 #include <string.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. */
933 static void
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. */
942     char buf[4096]
943         __attribute__ ((aligned(__alignof__(struct inotify_event))));
944     const struct inotify_event *event;
945     ssize_t len;
947     /* Loop while events can be read from inotify file descriptor. */
949     for (;;) {
951         /* Read some events. */
953         len = read(fd, buf, sizeof(buf));
954         if (len == \-1 && errno != EAGAIN) {
955             perror("read");
956             exit(EXIT_FAILURE);
957         }
959         /* If the nonblocking read() found no events to read, then
960            it returns \-1 with errno set to EAGAIN. In that case,
961            we exit the loop. */
963         if (len <= 0)
964             break;
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)
976                 printf("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]);
987                     break;
988                 }
989             }
991             /* Print the name of the file. */
993             if (event\->len)
994                 printf("%s", event\->name);
996             /* Print type of filesystem object. */
998             if (event\->mask & IN_ISDIR)
999                 printf(" [directory]\en");
1000             else
1001                 printf(" [file]\en");
1002         }
1003     }
1007 main(int argc, char* argv[])
1009     char buf;
1010     int fd, i, poll_num;
1011     int *wd;
1012     nfds_t nfds;
1013     struct pollfd fds[2];
1015     if (argc < 2) {
1016         printf("Usage: %s PATH [PATH ...]\en", argv[0]);
1017         exit(EXIT_FAILURE);
1018     }
1020     printf("Press ENTER key to terminate.\en");
1022     /* Create the file descriptor for accessing the inotify API. */
1024     fd = inotify_init1(IN_NONBLOCK);
1025     if (fd == \-1) {
1026         perror("inotify_init1");
1027         exit(EXIT_FAILURE);
1028     }
1030     /* Allocate memory for watch descriptors. */
1032     wd = calloc(argc, sizeof(int));
1033     if (wd == NULL) {
1034         perror("calloc");
1035         exit(EXIT_FAILURE);
1036     }
1038     /* Mark directories for events
1039        \- file was opened
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);
1045         if (wd[i] == \-1) {
1046             fprintf(stderr, "Cannot watch \(aq%s\(aq: %s\en",
1047                     argv[i], strerror(errno));
1048             exit(EXIT_FAILURE);
1049         }
1050     }
1052     /* Prepare for polling. */
1054     nfds = 2;
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");
1065     while (1) {
1066         poll_num = poll(fds, nfds, \-1);
1067         if (poll_num == \-1) {
1068             if (errno == EINTR)
1069                 continue;
1070             perror("poll");
1071             exit(EXIT_FAILURE);
1072         }
1074         if (poll_num > 0) {
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)
1081                     continue;
1082                 break;
1083             }
1085             if (fds[1].revents & POLLIN) {
1087                 /* Inotify events are available. */
1089                 handle_events(fd, wd, argc, argv);
1090             }
1091         }
1092     }
1094     printf("Listening for events stopped.\en");
1096     /* Close inotify file descriptor. */
1098     close(fd);
1100     free(wd);
1101     exit(EXIT_SUCCESS);
1104 .SH SEE ALSO
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),
1111 .BR read (2),
1112 .BR stat (2),
1113 .BR fanotify (7)
1115 .IR Documentation/filesystems/inotify.txt
1116 in the Linux kernel source tree