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