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