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