]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man7/inotify.7
inotify.7: Mounting a filesystem on top of a monitored directory causes no event
[thirdparty/man-pages.git] / man7 / inotify.7
1 '\" t
2 .\" Copyright (C) 2006, 2014 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\" Copyright (C) 2014 Heinrich Schuchardt <xypron.glpk@gmx.de>
4 .\"
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.
9 .\"
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.
14 .\"
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
21 .\" professionally.
22 .\"
23 .\" Formatted or processed versions of this manual, if unaccompanied by
24 .\" the source, must acknowledge the copyright and authors of this work.
25 .\" %%%LICENSE_END
26 .\"
27 .TH INOTIFY 7 2016-12-12 "Linux" "Linux Programmer's Manual"
28 .SH NAME
29 inotify \- monitoring filesystem events
30 .SH DESCRIPTION
31 The
32 .I inotify
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.
38
39 The following system calls are used with this API:
40 .IP * 3
41 .BR inotify_init (2)
42 creates an inotify instance and returns a file descriptor
43 referring to the inotify instance.
44 The more recent
45 .BR inotify_init1 (2)
46 is like
47 .BR inotify_init (2),
48 but has a
49 .IR flags
50 argument that provides access to some extra functionality.
51 .IP *
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
55 a file or directory,
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
61 returned by
62 .BR inotify_add_watch (2)
63 when the watch is created.
64 .IP *
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
68 .BR read (2)
69 (see below).
70 .IP *
71 .BR inotify_rm_watch (2)
72 removes an item from an inotify watch list.
73 .IP *
74 When all file descriptors referring to an inotify
75 instance have been closed (using
76 .BR close (2)),
77 the underlying object and its resources are
78 freed for reuse by the kernel;
79 all associated watches are automatically freed.
80 .PP
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
91 .BR read (2)s
92 from the inotify file descriptor.
93 If no events have so far occurred, then,
94 assuming a blocking file descriptor,
95 .BR read (2)
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
99 .BR EINTR ;
100 see
101 .BR signal (7)).
102
103 Each successful
104 .BR read (2)
105 returns a buffer containing one or more of the following structures:
106 .in +4n
107 .nf
108
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 */
120 };
121 .fi
122 .in
123
124 .I wd
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).
128
129 .I mask
130 contains bits that describe the event that occurred (see below).
131
132 .I cookie
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
136 .B IN_MOVED_FROM
137 and
138 .B IN_MOVED_TO
139 events to be connected by the application.
140 For all other event types,
141 .I cookie
142 is set to 0.
143
144 The
145 .I name
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.
152
153 The
154 .I len
155 field counts all of the bytes in
156 .IR name ,
157 including the null bytes;
158 the length of each
159 .I inotify_event
160 structure is thus
161 .IR "sizeof(struct inotify_event)+len" .
162
163 The behavior when the buffer given to
164 .BR read (2)
165 is too small to return information about the next event depends
166 on the kernel version: in kernels before 2.6.21,
167 .BR read (2)
168 returns 0; since kernel 2.6.21,
169 .BR read (2)
170 fails with the error
171 .BR EINVAL .
172 Specifying a buffer of size
173
174 sizeof(struct inotify_event) + NAME_MAX + 1
175
176 will be sufficient to read at least one event.
177 .SS inotify events
178 The
179 .BR inotify_add_watch (2)
180 .I mask
181 argument and the
182 .I mask
183 field of the
184 .I inotify_event
185 structure returned when
186 .BR read (2)ing
187 an inotify file descriptor are both bit masks identifying
188 inotify events.
189 The following bits can be specified in
190 .I mask
191 when calling
192 .BR inotify_add_watch (2)
193 and may be returned in the
194 .I mask
195 field returned by
196 .BR read (2):
197 .RS 4
198 .TP
199 .BR IN_ACCESS " (+)"
200 File was accessed (e.g.,
201 .BR read (2),
202 .BR execve (2)).
203 .TP
204 .BR IN_ATTRIB " (*)"
205 Metadata changed\(emfor example, permissions (e.g.,
206 .BR chmod (2)),
207 timestamps (e.g.,
208 .BR utimensat (2)),
209 extended attributes
210 .RB ( setxattr (2)),
211 link count (since Linux 2.6.25; e.g.,
212 .\" FIXME .
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.
216 for the target of
217 .BR link (2)
218 and for
219 .BR unlink (2)),
220 and user/group ID (e.g.,
221 .BR chown (2)).
222 .TP
223 .BR IN_CLOSE_WRITE " (+)"
224 File opened for writing was closed.
225 .TP
226 .BR IN_CLOSE_NOWRITE " (*)"
227 File or directory not opened for writing was closed.
228 .TP
229 .BR IN_CREATE " (+)"
230 File/directory created in watched directory (e.g.,
231 .BR open (2)
232 .BR O_CREAT ,
233 .BR mkdir (2),
234 .BR link (2),
235 .BR symlink (2),
236 .BR bind (2)
237 on a UNIX domain socket).
238 .TP
239 .BR IN_DELETE " (+)"
240 File/directory deleted from watched directory.
241 .TP
242 .B IN_DELETE_SELF
243 Watched file/directory was itself deleted.
244 (This event also occurs if an object is moved to another filesystem,
245 since
246 .BR mv (1)
247 in effect copies the file to the other filesystem and
248 then deletes it from the original filesystem.)
249 In addition, an
250 .B IN_IGNORED
251 event will subsequently be generated for the watch descriptor.
252 .TP
253 .BR IN_MODIFY " (+)"
254 File was modified (e.g.,
255 .BR write (2),
256 .BR truncate (2)).
257 .TP
258 .B IN_MOVE_SELF
259 Watched file/directory was itself moved.
260 .TP
261 .BR IN_MOVED_FROM " (+)"
262 Generated for the directory containing the old filename
263 when a file is renamed.
264 .TP
265 .BR IN_MOVED_TO " (+)"
266 Generated for the directory containing the new filename
267 when a file is renamed.
268 .TP
269 .BR IN_OPEN " (*)"
270 File or directory was opened.
271 .RE
272 .PP
273 Inotify monitoring is inode-based: when monitoring a file
274 (but not when monitoring the directory containing a file),
275 an event can be generated for activity on any link to the file
276 (in the same or a different directory).
277
278 When monitoring a directory:
279 .IP * 3
280 the events marked above with an asterisk (*) can occur both
281 for the directory itself and for objects inside the directory; and
282 .IP *
283 the events marked with a plus sign (+) occur only for objects
284 inside the directory (not for the directory itself).
285 .PP
286 .IR Note :
287 when monitoring a directory,
288 events are not generated for the files inside the directory
289 when the events are performed via a pathname (i.e., a link)
290 that lies outside the monitored directory.
291
292 When events are generated for objects inside a watched directory, the
293 .I name
294 field in the returned
295 .I inotify_event
296 structure identifies the name of the file within the directory.
297 .PP
298 The
299 .B IN_ALL_EVENTS
300 macro is defined as a bit mask of all of the above events.
301 This macro can be used as the
302 .I mask
303 argument when calling
304 .BR inotify_add_watch (2).
305
306 Two additional convenience macros are defined:
307 .RS 4
308 .TP
309 .BR IN_MOVE
310 Equates to
311 .BR "IN_MOVED_FROM | IN_MOVED_TO" .
312 .TP
313 .BR IN_CLOSE
314 Equates to
315 .BR "IN_CLOSE_WRITE | IN_CLOSE_NOWRITE" .
316 .RE
317 .PP
318 The following further bits can be specified in
319 .I mask
320 when calling
321 .BR inotify_add_watch (2):
322 .RS 4
323 .TP
324 .BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
325 Don't dereference
326 .I pathname
327 if it is a symbolic link.
328 .TP
329 .BR IN_EXCL_UNLINK " (since Linux 2.6.36)"
330 .\" commit 8c1934c8d70b22ca8333b216aec6c7d09fdbd6a6
331 By default, when watching events on the children of a directory,
332 events are generated for children even after they have been unlinked
333 from the directory.
334 This can result in large numbers of uninteresting events for
335 some applications (e.g., if watching
336 .IR /tmp ,
337 in which many applications create temporary files whose
338 names are immediately unlinked).
339 Specifying
340 .B IN_EXCL_UNLINK
341 changes the default behavior,
342 so that events are not generated for children after
343 they have been unlinked from the watched directory.
344 .TP
345 .B IN_MASK_ADD
346 If a watch instance already exists for the filesystem object corresponding to
347 .IR pathname ,
348 add (OR) the events in
349 .I mask
350 to the watch mask (instead of replacing the mask).
351 .TP
352 .B IN_ONESHOT
353 Monitor the filesystem object corresponding to
354 .I pathname
355 for one event, then remove from
356 watch list.
357 .TP
358 .BR IN_ONLYDIR " (since Linux 2.6.15)"
359 Watch
360 .I pathname
361 only if it is a directory.
362 Using this flag provides an application with a race-free way of
363 ensuring that the monitored object is a directory.
364 .RE
365 .PP
366 The following bits may be set in the
367 .I mask
368 field returned by
369 .BR read (2):
370 .RS 4
371 .TP
372 .B IN_IGNORED
373 Watch was removed explicitly
374 .RB ( inotify_rm_watch (2))
375 or automatically (file was deleted, or filesystem was unmounted).
376 See also BUGS.
377 .TP
378 .B IN_ISDIR
379 Subject of this event is a directory.
380 .TP
381 .B IN_Q_OVERFLOW
382 Event queue overflowed
383 .RI ( wd
384 is \-1 for this event).
385 .TP
386 .B IN_UNMOUNT
387 Filesystem containing watched object was unmounted.
388 In addition, an
389 .B IN_IGNORED
390 event will subsequently be generated for the watch descriptor.
391 .RE
392 .SS Examples
393 Suppose an application is watching the directory
394 .I dir
395 and the file
396 .IR dir/myfile
397 for all events.
398 The examples below show some events that will be generated
399 for these two objects.
400 .RS 4
401 .TP
402 fd = open("dir/myfile", O_RDWR);
403 Generates
404 .B IN_OPEN
405 events for both
406 .I dir
407 and
408 .IR dir/myfile .
409 .TP
410 read(fd, buf, count);
411 Generates
412 .B IN_ACCESS
413 events for both
414 .I dir
415 and
416 .IR dir/myfile .
417 .TP
418 write(fd, buf, count);
419 Generates
420 .B IN_MODIFY
421 events for both
422 .I dir
423 and
424 .IR dir/myfile .
425 .TP
426 fchmod(fd, mode);
427 Generates
428 .B IN_ATTRIB
429 events for both
430 .I dir
431 and
432 .IR dir/myfile .
433 .TP
434 close(fd);
435 Generates
436 .B IN_CLOSE_WRITE
437 events for both
438 .I dir
439 and
440 .IR dir/myfile .
441 .RE
442 .PP
443 Suppose an application is watching the directories
444 .I dir1
445 and
446 .IR dir2 ,
447 and the file
448 .IR dir1/myfile .
449 The following examples show some events that may be generated.
450 .RS 4
451 .TP
452 link("dir1/myfile", "dir2/new");
453 Generates an
454 .B IN_ATTRIB
455 event for
456 .IR myfile
457 and an
458 .B IN_CREATE
459 event for
460 .IR dir2 .
461 .TP
462 rename("dir1/myfile", "dir2/myfile");
463 Generates an
464 .B IN_MOVED_FROM
465 event for
466 .IR dir1 ,
467 an
468 .B IN_MOVED_TO
469 event for
470 .IR dir2 ,
471 and an
472 .B IN_MOVE_SELF
473 event for
474 .IR myfile .
475 The
476 .B IN_MOVED_FROM
477 and
478 .B IN_MOVED_TO
479 events will have the same
480 .I cookie
481 value.
482 .RE
483 .PP
484 Suppose that
485 .IR dir1/xx
486 and
487 .IR dir2/yy
488 are (the only) links to the same file, and an application is watching
489 .IR dir1 ,
490 .IR dir2 ,
491 .IR dir1/xx ,
492 and
493 .IR dir2/yy .
494 Executing the following calls in the order given below will generate
495 the following events:
496 .RS 4
497 .TP
498 unlink("dir2/yy");
499 Generates an
500 .BR IN_ATTRIB
501 event for
502 .IR xx
503 (because its link count changes)
504 and an
505 .B IN_DELETE
506 event for
507 .IR dir2 .
508 .TP
509 unlink("dir1/xx");
510 Generates
511 .BR IN_ATTRIB ,
512 .BR IN_DELETE_SELF ,
513 and
514 .BR IN_IGNORED
515 events for
516 .IR xx ,
517 and an
518 .BR IN_DELETE
519 event for
520 .IR dir1 .
521 .RE
522 .PP
523 Suppose an application is watching the directory
524 .IR dir
525 and (the empty) directory
526 .IR dir/subdir .
527 The following examples show some events that may be generated.
528 .RS 4
529 .TP
530 mkdir("dir/new", mode);
531 Generates an
532 .B "IN_CREATE | IN_ISDIR"
533 event for
534 .IR dir .
535 .TP
536 rmdir("dir/subdir");
537 Generates
538 .B IN_DELETE_SELF
539 and
540 .B IN_IGNORED
541 events for
542 .IR subdir ,
543 and an
544 .B "IN_DELETE | IN_ISDIR"
545 event for
546 .IR dir .
547 .RE
548 .SS /proc interfaces
549 The following interfaces can be used to limit the amount of
550 kernel memory consumed by inotify:
551 .TP
552 .I /proc/sys/fs/inotify/max_queued_events
553 The value in this file is used when an application calls
554 .BR inotify_init (2)
555 to set an upper limit on the number of events that can be
556 queued to the corresponding inotify instance.
557 Events in excess of this limit are dropped, but an
558 .B IN_Q_OVERFLOW
559 event is always generated.
560 .TP
561 .I /proc/sys/fs/inotify/max_user_instances
562 This specifies an upper limit on the number of inotify instances
563 that can be created per real user ID.
564 .TP
565 .I /proc/sys/fs/inotify/max_user_watches
566 This specifies an upper limit on the number of watches
567 that can be created per real user ID.
568 .SH VERSIONS
569 Inotify was merged into the 2.6.13 Linux kernel.
570 The required library interfaces were added to glibc in version 2.4.
571 .RB ( IN_DONT_FOLLOW ,
572 .BR IN_MASK_ADD ,
573 and
574 .B IN_ONLYDIR
575 were added in glibc version 2.5.)
576 .SH CONFORMING TO
577 The inotify API is Linux-specific.
578 .SH NOTES
579 Inotify file descriptors can be monitored using
580 .BR select (2),
581 .BR poll (2),
582 and
583 .BR epoll (7).
584 When an event is available, the file descriptor indicates as readable.
585
586 Since Linux 2.6.25,
587 signal-driven I/O notification is available for inotify file descriptors;
588 see the discussion of
589 .B F_SETFL
590 (for setting the
591 .B O_ASYNC
592 flag),
593 .BR F_SETOWN ,
594 and
595 .B F_SETSIG
596 in
597 .BR fcntl (2).
598 The
599 .I siginfo_t
600 structure (described in
601 .BR sigaction (2))
602 that is passed to the signal handler has the following fields set:
603 .IR si_fd
604 is set to the inotify file descriptor number;
605 .IR si_signo
606 is set to the signal number;
607 .IR si_code
608 is set to
609 .BR POLL_IN ;
610 and
611 .B POLLIN
612 is set in
613 .IR si_band .
614
615 If successive output inotify events produced on the
616 inotify file descriptor are identical (same
617 .IR wd ,
618 .IR mask ,
619 .IR cookie ,
620 and
621 .IR name ),
622 then they are coalesced into a single event if the
623 older event has not yet been read (but see BUGS).
624 This reduces the amount of kernel memory required for the event queue,
625 but also means that an application can't use inotify to reliably count
626 file events.
627
628 The events returned by reading from an inotify file descriptor
629 form an ordered queue.
630 Thus, for example, it is guaranteed that when renaming from
631 one directory to another, events will be produced in the
632 correct order on the inotify file descriptor.
633
634 The set of watch descriptors that is being monitored via
635 an inotify file descriptor can be viewed via the entry for
636 the inotify file descriptor in the process's
637 .IR /proc/[pid]/fdinfo
638 directory.
639 See
640 .BR proc (5)
641 for further details.
642 The
643 .B FIONREAD
644 .BR ioctl (2)
645 returns the number of bytes available to read from an
646 inotify file descriptor.
647 .SS Limitations and caveats
648 The inotify API provides no information about the user or process that
649 triggered the inotify event.
650 In particular, there is no easy
651 way for a process that is monitoring events via inotify
652 to distinguish events that it triggers
653 itself from those that are triggered by other processes.
654
655 Inotify reports only events that a user-space program triggers through
656 the filesystem API.
657 As a result, it does not catch remote events that occur
658 on network filesystems.
659 (Applications must fall back to polling the filesystem
660 to catch such events.)
661 Furthermore, various pseudo-filesystems such as
662 .IR /proc ,
663 .IR /sys ,
664 and
665 .IR /dev/pts
666 are not monitorable with inotify.
667
668 The inotify API does not report file accesses and modifications that
669 may occur because of
670 .BR mmap (2),
671 .BR msync (2),
672 and
673 .BR munmap (2).
674
675 The inotify API identifies affected files by filename.
676 However, by the time an application processes an inotify event,
677 the filename may already have been deleted or renamed.
678
679 The inotify API identifies events via watch descriptors.
680 It is the application's responsibility to cache a mapping
681 (if one is needed) between watch descriptors and pathnames.
682 Be aware that directory renamings may affect multiple cached pathnames.
683
684 Inotify monitoring of directories is not recursive:
685 to monitor subdirectories under a directory,
686 additional watches must be created.
687 This can take a significant amount time for large directory trees.
688
689 If monitoring an entire directory subtree,
690 and a new subdirectory is created in that tree or an existing directory
691 is renamed into that tree,
692 be aware that by the time you create a watch for the new subdirectory,
693 new files (and subdirectories) may already exist inside the subdirectory.
694 Therefore, you may want to scan the contents of the subdirectory
695 immediately after adding the watch (and, if desired,
696 recursively add watches for any subdirectories that it contains).
697
698 Note that the event queue can overflow.
699 In this case, events are lost.
700 Robust applications should handle the possibility of
701 lost events gracefully.
702 For example, it may be necessary to rebuild part or all of
703 the application cache.
704 (One simple, but possibly expensive,
705 approach is to close the inotify file descriptor, empty the cache,
706 create a new inotify file descriptor,
707 and then re-create watches and cache entries
708 for the objects to be monitored.)
709
710 If a filesystem is mounted on top of a monitored directory,
711 no event is generated, and no events are generated
712 for objects immediately under the new mount point.
713 If the filesystem is subsequently unmounted,
714 events will subsequently be generated for the directory and
715 the objects it contains.
716 .\"
717 .SS Dealing with rename() events
718 As noted above, the
719 .B IN_MOVED_FROM
720 and
721 .B IN_MOVED_TO
722 event pair that is generated by
723 .BR rename (2)
724 can be matched up via their shared cookie value.
725 However, the task of matching has some challenges.
726
727 These two events are usually consecutive in the event stream available
728 when reading from the inotify file descriptor.
729 However, this is not guaranteed.
730 If multiple processes are triggering events for monitored objects,
731 then (on rare occasions) an arbitrary number of
732 other events may appear between the
733 .B IN_MOVED_FROM
734 and
735 .B IN_MOVED_TO
736 events.
737 Furthermore, it is not guaranteed that the event pair is atomically
738 inserted into the queue: there may be a brief interval where the
739 .B IN_MOVED_FROM
740 has appeared, but the
741 .B IN_MOVED_TO
742 has not.
743
744 Matching up the
745 .B IN_MOVED_FROM
746 and
747 .B IN_MOVED_TO
748 event pair generated by
749 .BR rename (2)
750 is thus inherently racy.
751 (Don't forget that if an object is renamed outside of a monitored directory,
752 there may not even be an
753 .BR IN_MOVED_TO
754 event.)
755 Heuristic approaches (e.g., assume the events are always consecutive)
756 can be used to ensure a match in most cases,
757 but will inevitably miss some cases,
758 causing the application to perceive the
759 .B IN_MOVED_FROM
760 and
761 .B IN_MOVED_TO
762 events as being unrelated.
763 If watch descriptors are destroyed and re-created as a result,
764 then those watch descriptors will be inconsistent with
765 the watch descriptors in any pending events.
766 (Re-creating the inotify file descriptor and rebuilding the cache may
767 be useful to deal with this scenario.)
768
769 Applications should also allow for the possibility that the
770 .B IN_MOVED_FROM
771 event was the last event that could fit in the buffer
772 returned by the current call to
773 .BR read (2),
774 and the accompanying
775 .B IN_MOVED_TO
776 event might be fetched only on the next
777 .BR read (2),
778 which should be done with a (small) timeout to allow for the fact that
779 insertion of the
780 .BR IN_MOVED_FROM - IN_MOVED_TO
781 event pair is not atomic,
782 and also the possibility that there may not be any
783 .B IN_MOVED_TO
784 event.
785 .SH BUGS
786 Before Linux 3.19,
787 .BR fallocate (2)
788 did not create any inotify events.
789 Since Linux 3.19,
790 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
791 calls to
792 .BR fallocate (2)
793 generate
794 .B IN_MODIFY
795 events.
796
797 .\" FIXME . kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
798 .\" implies that unmount events were buggy 2.6.11 to 2.6.36
799 .\"
800 In kernels before 2.6.16, the
801 .B IN_ONESHOT
802 .I mask
803 flag does not work.
804
805 As originally designed and implemented, the
806 .B IN_ONESHOT
807 flag did not cause an
808 .B IN_IGNORED
809 event to be generated when the watch was dropped after one event.
810 However, as an unintended effect of other changes,
811 since Linux 2.6.36, an
812 .B IN_IGNORED
813 event is generated in this case.
814
815 Before kernel 2.6.25,
816 .\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
817 the kernel code that was intended to coalesce successive identical events
818 (i.e., the two most recent events could potentially be coalesced
819 if the older had not yet been read)
820 instead checked if the most recent event could be coalesced with the
821 .I oldest
822 unread event.
823
824 When a watch descriptor is removed by calling
825 .BR inotify_rm_watch (2)
826 (or because a watch file is deleted or the filesystem
827 that contains it is unmounted),
828 any pending unread events for that watch descriptor remain available to read.
829 As watch descriptors are subsequently allocated with
830 .BR inotify_add_watch (2),
831 the kernel cycles through the range of possible watch descriptors (0 to
832 .BR INT_MAX )
833 incrementally.
834 When allocating a free watch descriptor, no check is made to see whether that
835 watch descriptor number has any pending unread events in the inotify queue.
836 Thus, it can happen that a watch descriptor is reallocated even
837 when pending unread events exist for a previous incarnation of
838 that watch descriptor number, with the result that the application
839 might then read those events and interpret them as belonging to
840 the file associated with the newly recycled watch descriptor.
841 In practice, the likelihood of hitting this bug may be extremely low,
842 since it requires that an application cycle through
843 .B INT_MAX
844 watch descriptors,
845 release a watch descriptor while leaving unread events for that
846 watch descriptor in the queue,
847 and then recycle that watch descriptor.
848 For this reason, and because there have been no reports
849 of the bug occurring in real-world applications,
850 as of Linux 3.15,
851 .\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
852 no kernel changes have yet been made to eliminate this possible bug.
853 .SH EXAMPLE
854 The following program demonstrates the usage of the inotify API.
855 It marks the directories passed as a command-line arguments
856 and waits for events of type
857 .BR IN_OPEN ,
858 .BR IN_CLOSE_NOWRITE
859 and
860 .BR IN_CLOSE_WRITE .
861 .PP
862 The following output was recorded while editing the file
863 .I /home/user/temp/foo
864 and listing directory
865 .IR /tmp .
866 Before the file and the directory were opened,
867 .B IN_OPEN
868 events occurred.
869 After the file was closed, an
870 .B IN_CLOSE_WRITE
871 event occurred.
872 After the directory was closed, an
873 .B IN_CLOSE_NOWRITE
874 event occurred.
875 Execution of the program ended when the user pressed the ENTER key.
876 .SS Example output
877 .in +4n
878 .nf
879 $ \fB./a.out /tmp /home/user/temp\fP
880 Press enter key to terminate.
881 Listening for events.
882 IN_OPEN: /home/user/temp/foo [file]
883 IN_CLOSE_WRITE: /home/user/temp/foo [file]
884 IN_OPEN: /tmp/ [directory]
885 IN_CLOSE_NOWRITE: /tmp/ [directory]
886
887 Listening for events stopped.
888 .fi
889 .in
890 .SS Program source
891 .nf
892 #include <errno.h>
893 #include <poll.h>
894 #include <stdio.h>
895 #include <stdlib.h>
896 #include <sys/inotify.h>
897 #include <unistd.h>
898
899 /* Read all available inotify events from the file descriptor 'fd'.
900 wd is the table of watch descriptors for the directories in argv.
901 argc is the length of wd and argv.
902 argv is the list of watched directories.
903 Entry 0 of wd and argv is unused. */
904
905 static void
906 handle_events(int fd, int *wd, int argc, char* argv[])
907 {
908 /* Some systems cannot read integer variables if they are not
909 properly aligned. On other systems, incorrect alignment may
910 decrease performance. Hence, the buffer used for reading from
911 the inotify file descriptor should have the same alignment as
912 struct inotify_event. */
913
914 char buf[4096]
915 __attribute__ ((aligned(__alignof__(struct inotify_event))));
916 const struct inotify_event *event;
917 int i;
918 ssize_t len;
919 char *ptr;
920
921 /* Loop while events can be read from inotify file descriptor. */
922
923 for (;;) {
924
925 /* Read some events. */
926
927 len = read(fd, buf, sizeof buf);
928 if (len == \-1 && errno != EAGAIN) {
929 perror("read");
930 exit(EXIT_FAILURE);
931 }
932
933 /* If the nonblocking read() found no events to read, then
934 it returns \-1 with errno set to EAGAIN. In that case,
935 we exit the loop. */
936
937 if (len <= 0)
938 break;
939
940 /* Loop over all events in the buffer */
941
942 for (ptr = buf; ptr < buf + len;
943 ptr += sizeof(struct inotify_event) + event\->len) {
944
945 event = (const struct inotify_event *) ptr;
946
947 /* Print event type */
948
949 if (event\->mask & IN_OPEN)
950 printf("IN_OPEN: ");
951 if (event\->mask & IN_CLOSE_NOWRITE)
952 printf("IN_CLOSE_NOWRITE: ");
953 if (event\->mask & IN_CLOSE_WRITE)
954 printf("IN_CLOSE_WRITE: ");
955
956 /* Print the name of the watched directory */
957
958 for (i = 1; i < argc; ++i) {
959 if (wd[i] == event\->wd) {
960 printf("%s/", argv[i]);
961 break;
962 }
963 }
964
965 /* Print the name of the file */
966
967 if (event\->len)
968 printf("%s", event\->name);
969
970 /* Print type of filesystem object */
971
972 if (event\->mask & IN_ISDIR)
973 printf(" [directory]\\n");
974 else
975 printf(" [file]\\n");
976 }
977 }
978 }
979
980 int
981 main(int argc, char* argv[])
982 {
983 char buf;
984 int fd, i, poll_num;
985 int *wd;
986 nfds_t nfds;
987 struct pollfd fds[2];
988
989 if (argc < 2) {
990 printf("Usage: %s PATH [PATH ...]\\n", argv[0]);
991 exit(EXIT_FAILURE);
992 }
993
994 printf("Press ENTER key to terminate.\\n");
995
996 /* Create the file descriptor for accessing the inotify API */
997
998 fd = inotify_init1(IN_NONBLOCK);
999 if (fd == \-1) {
1000 perror("inotify_init1");
1001 exit(EXIT_FAILURE);
1002 }
1003
1004 /* Allocate memory for watch descriptors */
1005
1006 wd = calloc(argc, sizeof(int));
1007 if (wd == NULL) {
1008 perror("calloc");
1009 exit(EXIT_FAILURE);
1010 }
1011
1012 /* Mark directories for events
1013 \- file was opened
1014 \- file was closed */
1015
1016 for (i = 1; i < argc; i++) {
1017 wd[i] = inotify_add_watch(fd, argv[i],
1018 IN_OPEN | IN_CLOSE);
1019 if (wd[i] == \-1) {
1020 fprintf(stderr, "Cannot watch '%s'\\n", argv[i]);
1021 perror("inotify_add_watch");
1022 exit(EXIT_FAILURE);
1023 }
1024 }
1025
1026 /* Prepare for polling */
1027
1028 nfds = 2;
1029
1030 /* Console input */
1031
1032 fds[0].fd = STDIN_FILENO;
1033 fds[0].events = POLLIN;
1034
1035 /* Inotify input */
1036
1037 fds[1].fd = fd;
1038 fds[1].events = POLLIN;
1039
1040 /* Wait for events and/or terminal input */
1041
1042 printf("Listening for events.\\n");
1043 while (1) {
1044 poll_num = poll(fds, nfds, \-1);
1045 if (poll_num == \-1) {
1046 if (errno == EINTR)
1047 continue;
1048 perror("poll");
1049 exit(EXIT_FAILURE);
1050 }
1051
1052 if (poll_num > 0) {
1053
1054 if (fds[0].revents & POLLIN) {
1055
1056 /* Console input is available. Empty stdin and quit */
1057
1058 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
1059 continue;
1060 break;
1061 }
1062
1063 if (fds[1].revents & POLLIN) {
1064
1065 /* Inotify events are available */
1066
1067 handle_events(fd, wd, argc, argv);
1068 }
1069 }
1070 }
1071
1072 printf("Listening for events stopped.\\n");
1073
1074 /* Close inotify file descriptor */
1075
1076 close(fd);
1077
1078 free(wd);
1079 exit(EXIT_SUCCESS);
1080 }
1081 .fi
1082 .SH SEE ALSO
1083 .BR inotifywait (1),
1084 .BR inotifywatch (1),
1085 .BR inotify_add_watch (2),
1086 .BR inotify_init (2),
1087 .BR inotify_init1 (2),
1088 .BR inotify_rm_watch (2),
1089 .BR read (2),
1090 .BR stat (2),
1091 .BR fanotify (7)
1092
1093 .IR Documentation/filesystems/inotify.txt
1094 in the Linux kernel source tree