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