]> git.ipfire.org Git - thirdparty/man-pages.git/blame - 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
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.\"
35deeb87 27.TH INOTIFY 7 2016-12-12 "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.
e3a0ac0e 87It is probably wise to do some consistency checking,
6b1cc2c9 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.
34d4e61d 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;
454ab872
MK
148it identifies the filename within to the watched directory.
149This filename 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.,
a4439a50
MK
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.
b0e1ac43
MK
216for the target of
217.BR link (2)
218and for
219.BR unlink (2)),
220and user/group ID (e.g.,
221.BR chown (2)).
3f174f7d 222.TP
858bbaaa 223.BR IN_CLOSE_WRITE " (+)"
f23fc716 224File opened for writing was closed.
3f174f7d 225.TP
f23fc716 226.BR IN_CLOSE_NOWRITE " (*)"
7465ffa6 227File or directory not opened for writing was closed.
3f174f7d 228.TP
e95b1911 229.BR IN_CREATE " (+)"
7a64793b
MK
230File/directory created in watched directory (e.g.,
231.BR open (2)
232.BR O_CREAT ,
233.BR mkdir (2),
234.BR link (2),
1a737afd 235.BR symlink (2),
7a64793b
MK
236.BR bind (2)
237on a UNIX domain socket).
3f174f7d 238.TP
e95b1911 239.BR IN_DELETE " (+)"
f23fc716 240File/directory deleted from watched directory.
3f174f7d
MK
241.TP
242.B IN_DELETE_SELF
243Watched file/directory was itself deleted.
4a1e4cca
MK
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
49b07b8f 248then deletes it from the original filesystem.)
39f43968
MK
249In addition, an
250.B IN_IGNORED
251event will subsequently be generated for the watch descriptor.
3f174f7d 252.TP
e06fc20c 253.BR IN_MODIFY " (+)"
f54a1255
MK
254File was modified (e.g.,
255.BR write (2),
256.BR truncate (2)).
3f174f7d
MK
257.TP
258.B IN_MOVE_SELF
259Watched file/directory was itself moved.
260.TP
e95b1911 261.BR IN_MOVED_FROM " (+)"
107375cf 262Generated for the directory containing the old filename
f23fc716 263when a file is renamed.
3f174f7d 264.TP
e95b1911 265.BR IN_MOVED_TO " (+)"
107375cf 266Generated for the directory containing the new filename
f23fc716 267when a file is renamed.
3f174f7d 268.TP
f23fc716 269.BR IN_OPEN " (*)"
7465ffa6 270File or directory was opened.
64aa9bcb 271.RE
4d2b74dd 272.PP
e95b1911
MK
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
705bb673
MK
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
e95b1911 287When events are generated for objects inside a watched directory, the
4d2b74dd
MK
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
63f6a20a 299.BR inotify_add_watch (2).
4d2b74dd 300
dede00fe 301Two additional convenience macros are defined:
64aa9bcb 302.RS 4
dede00fe
MK
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" .
64aa9bcb 311.RE
4d2b74dd 312.PP
c13182ef 313The following further bits can be specified in
4d2b74dd
MK
314.I mask
315when calling
63f6a20a 316.BR inotify_add_watch (2):
64aa9bcb 317.RS 4
c577b95c 318.TP
31daf529 319.BR IN_DONT_FOLLOW " (since Linux 2.6.15)"
aeb9b6a6
MK
320Don't dereference
321.I pathname
322if it is a symbolic link.
dda869a4 323.TP
0ff2cc88 324.BR IN_EXCL_UNLINK " (since Linux 2.6.36)"
b3ad7609
MK
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
dda869a4 340.B IN_MASK_ADD
7747b84b
MK
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).
dda869a4
MK
346.TP
347.B IN_ONESHOT
dcaff23c 348Monitor the filesystem object corresponding to
aeb9b6a6
MK
349.I pathname
350for one event, then remove from
dda869a4
MK
351watch list.
352.TP
31daf529 353.BR IN_ONLYDIR " (since Linux 2.6.15)"
4e9362fe 354Watch
aeb9b6a6 355.I pathname
4e9362fe 356only if it is a directory.
18d92a14 357Using this flag provides an application with a race-free way of
9dcdfde4 358ensuring that the monitored object is a directory.
64aa9bcb 359.RE
4d2b74dd
MK
360.PP
361The following bits may be set in the
362.I mask
363field returned by
63f6a20a 364.BR read (2):
64aa9bcb 365.RS 4
c577b95c 366.TP
dda869a4 367.B IN_IGNORED
aeb9b6a6
MK
368Watch was removed explicitly
369.RB ( inotify_rm_watch (2))
9ee4a2b6 370or automatically (file was deleted, or filesystem was unmounted).
7b5151b7 371See also BUGS.
dda869a4
MK
372.TP
373.B IN_ISDIR
374Subject of this event is a directory.
375.TP
376.B IN_Q_OVERFLOW
aeb9b6a6
MK
377Event queue overflowed
378.RI ( wd
379is \-1 for this event).
dda869a4
MK
380.TP
381.B IN_UNMOUNT
9ee4a2b6 382Filesystem containing watched object was unmounted.
b01c936e
MK
383In addition, an
384.B IN_IGNORED
385event will subsequently be generated for the watch descriptor.
64aa9bcb 386.RE
415f63be
MK
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
d2c3d8a8 441.IR dir2 ,
415f63be
MK
442and the file
443.IR dir1/myfile .
444The following examples show some events that may be generated.
445.RS 4
446.TP
d2c3d8a8 447link("dir1/myfile", "dir2/new");
415f63be
MK
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");
d2c3d8a8 494Generates an
415f63be
MK
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
d2c3d8a8 514event for
415f63be
MK
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
d2c3d8a8 531rmdir("dir/subdir");
415f63be
MK
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
4d2b74dd 543.SS /proc interfaces
c13182ef 544The following interfaces can be used to limit the amount of
4d2b74dd
MK
545kernel memory consumed by inotify:
546.TP
0daa9e92 547.I /proc/sys/fs/inotify/max_queued_events
4d2b74dd
MK
548The value in this file is used when an application calls
549.BR inotify_init (2)
c13182ef 550to set an upper limit on the number of events that can be
4d2b74dd
MK
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
0daa9e92 556.I /proc/sys/fs/inotify/max_user_instances
c13182ef 557This specifies an upper limit on the number of inotify instances
4d2b74dd
MK
558that can be created per real user ID.
559.TP
0daa9e92 560.I /proc/sys/fs/inotify/max_user_watches
31546b46
VN
561This specifies an upper limit on the number of watches
562that can be created per real user ID.
47297adb 563.SH VERSIONS
2b2581ee
MK
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
64aa9bcb 570were added in glibc version 2.5.)
47297adb 571.SH CONFORMING TO
8382f16d 572The inotify API is Linux-specific.
47297adb 573.SH NOTES
4d2b74dd
MK
574Inotify file descriptors can be monitored using
575.BR select (2),
576.BR poll (2),
c13182ef 577and
2315114c 578.BR epoll (7).
0000daa5
MK
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 .
4d2b74dd 609
c13182ef
MK
610If successive output inotify events produced on the
611inotify file descriptor are identical (same
612.IR wd ,
613.IR mask ,
4d2b74dd
MK
614.IR cookie ,
615and
3f3698d8 616.IR name ),
6f0ab035
MK
617then they are coalesced into a single event if the
618older event has not yet been read (but see BUGS).
8856aab8
MK
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.
4d2b74dd 622
c13182ef
MK
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
4d2b74dd
MK
627correct order on the inotify file descriptor.
628
d742465f
MK
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.
4d2b74dd
MK
637The
638.B FIONREAD
63f6a20a 639.BR ioctl (2)
c13182ef 640returns the number of bytes available to read from an
4d2b74dd 641inotify file descriptor.
613836aa 642.SS Limitations and caveats
67898fdf
MK
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
e226bed7
MK
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.)
fa1d49a6 656Furthermore, various pseudo-filesystems such as
e226bed7
MK
657.IR /proc ,
658.IR /sys ,
659and
660.IR /dev/pts
661are not monitorable with inotify.
662
e449e5f1
MK
663The inotify API does not report file accesses and modifications that
664may occur because of
7a8110f6
HS
665.BR mmap (2),
666.BR msync (2),
e449e5f1 667and
7a8110f6 668.BR munmap (2).
e449e5f1 669
67898fdf
MK
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
da977073 674The inotify API identifies events via watch descriptors.
264276c6
MK
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
4d2b74dd
MK
679Inotify monitoring of directories is not recursive:
680to monitor subdirectories under a directory,
681additional watches must be created.
613836aa
MK
682This can take a significant amount time for large directory trees.
683
a79d28b2
MK
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
613836aa
MK
693Note that the event queue can overflow.
694In this case, events are lost.
09fa72fa 695Robust applications should handle the possibility of
613836aa 696lost events gracefully.
94d52c15
MK
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,
85e179c5 701create a new inotify file descriptor,
94d52c15
MK
702and then re-create watches and cache entries
703for the objects to be monitored.)
85e179c5 704.SS Dealing with rename() events
fa51f4d9 705As noted above, the
85e179c5
MK
706.B IN_MOVED_FROM
707and
708.B IN_MOVED_TO
fa51f4d9 709event pair that is generated by
85e179c5 710.BR rename (2)
fa51f4d9
MK
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.
85e179c5
MK
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.
003798c7
MK
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.
85e179c5
MK
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.
6f1a4954 753(Re-creating the inotify file descriptor and rebuilding the cache may
85e179c5
MK
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
3da91159
MK
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.
47297adb 772.SH BUGS
f9bfa911 773Before Linux 3.19,
360d3116 774.BR fallocate (2)
f9bfa911
MK
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.
e75c6d07 783
bea08fec 784.\" FIXME . kernel commit 611da04f7a31b2208e838be55a42c7a1310ae321
a15ead5e
MK
785.\" implies that unmount events were buggy 2.6.11 to 2.6.36
786.\"
ed7b0235
MK
787In kernels before 2.6.16, the
788.B IN_ONESHOT
c13182ef 789.I mask
ed7b0235 790flag does not work.
6f0ab035 791
7b5151b7
MK
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
6f0ab035 802Before kernel 2.6.25,
22129aa9 803.\" commit 1c17d18e3775485bf1e0ce79575eb637a94494a2
9ed6b517 804the kernel code that was intended to coalesce successive identical events
6f0ab035
MK
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.
ec976a53 810
ec976a53 811When a watch descriptor is removed by calling
e530e367
MK
812.BR inotify_rm_watch (2)
813(or because a watch file is deleted or the filesystem
814that contains it is unmounted),
ec976a53
HS
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
cbe0e644 826might then read those events and interpret them as belonging to
ec976a53 827the file associated with the newly recycled watch descriptor.
2bbf2299
MK
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
08063d8f 833watch descriptor in the queue,
2bbf2299
MK
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,
bea08fec 838.\" FIXME . https://bugzilla.kernel.org/show_bug.cgi?id=77111
2bbf2299 839no kernel changes have yet been made to eliminate this possible bug.
ecd96f7c
HS
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 ,
2ef6778b 845.BR IN_CLOSE_NOWRITE
ecd96f7c
HS
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
2483209a 866$ \fB./a.out /tmp /home/user/temp\fP
ecd96f7c
HS
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{
2483209a
MK
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
ecd96f7c 899 struct inotify_event. */
2483209a 900
ecd96f7c 901 char buf[4096]
2483209a 902 __attribute__ ((aligned(__alignof__(struct inotify_event))));
ecd96f7c
HS
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;
2483209a 930 ptr += sizeof(struct inotify_event) + event\->len) {
ecd96f7c
HS
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");
ecd96f7c
HS
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 }
2483209a 1038
ecd96f7c
HS
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 }
2483209a 1049
ecd96f7c
HS
1050 if (fds[1].revents & POLLIN) {
1051
1052 /* Inotify events are available */
2483209a 1053
ecd96f7c
HS
1054 handle_events(fd, wd, argc, argv);
1055 }
1056 }
1057 }
1058
2483209a
MK
1059 printf("Listening for events stopped.\\n");
1060
ecd96f7c
HS
1061 /* Close inotify file descriptor */
1062
1063 close(fd);
2483209a 1064
ecd96f7c 1065 free(wd);
ecd96f7c
HS
1066 exit(EXIT_SUCCESS);
1067}
1068.fi
47297adb 1069.SH SEE ALSO
f0afb16a
MK
1070.BR inotifywait (1),
1071.BR inotifywatch (1),
4d2b74dd
MK
1072.BR inotify_add_watch (2),
1073.BR inotify_init (2),
43bb5faf 1074.BR inotify_init1 (2),
4d2b74dd
MK
1075.BR inotify_rm_watch (2),
1076.BR read (2),
f75d27e6
HS
1077.BR stat (2),
1078.BR fanotify (7)
173fe7e7
DP
1079
1080.IR Documentation/filesystems/inotify.txt
1081in the Linux kernel source tree