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