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