1inotify(7)             Miscellaneous Information Manual             inotify(7)
2
3
4

NAME

6       inotify - monitoring filesystem events
7

DESCRIPTION

9       The  inotify API provides a mechanism for monitoring filesystem events.
10       Inotify can be used to monitor individual files, or to monitor directo‐
11       ries.   When  a  directory is monitored, inotify will return events for
12       the directory itself, and for files inside the directory.
13
14       The following system calls are used with this API:
15
16inotify_init(2) creates an inotify instance and returns a  file  de‐
17          scriptor  referring  to  the inotify instance.  The more recent ino‐
18          tify_init1(2) is like inotify_init(2), but has a flags argument that
19          provides access to some extra functionality.
20
21inotify_add_watch(2) manipulates the "watch list" associated with an
22          inotify instance.  Each item ("watch") in the watch  list  specifies
23          the  pathname  of a file or directory, along with some set of events
24          that the kernel should monitor for the  file  referred  to  by  that
25          pathname.   inotify_add_watch(2) either creates a new watch item, or
26          modifies an existing watch.  Each watch has a unique "watch descrip‐
27          tor",  an integer returned by inotify_add_watch(2) when the watch is
28          created.
29
30       •  When events occur for monitored files and directories, those  events
31          are made available to the application as structured data that can be
32          read from the inotify file descriptor using read(2) (see below).
33
34inotify_rm_watch(2) removes an item from an inotify watch list.
35
36       •  When all file descriptors referring to an inotify instance have been
37          closed (using close(2)), the underlying object and its resources are
38          freed for reuse by the kernel; all associated watches are  automati‐
39          cally freed.
40
41       With careful programming, an application can use inotify to efficiently
42       monitor and cache the state of a set of filesystem  objects.   However,
43       robust applications should allow for the fact that bugs in the monitor‐
44       ing logic or races of the kind described below may leave the cache  in‐
45       consistent  with  the filesystem state.  It is probably wise to do some
46       consistency checking, and rebuild the cache  when  inconsistencies  are
47       detected.
48
49   Reading events from an inotify file descriptor
50       To  determine  what  events have occurred, an application read(2)s from
51       the inotify file descriptor.  If no events have so far occurred,  then,
52       assuming  a blocking file descriptor, read(2) will block until at least
53       one event occurs (unless interrupted by a signal,  in  which  case  the
54       call fails with the error EINTR; see signal(7)).
55
56       Each  successful read(2) returns a buffer containing one or more of the
57       following structures:
58
59           struct inotify_event {
60               int      wd;       /* Watch descriptor */
61               uint32_t mask;     /* Mask describing event */
62               uint32_t cookie;   /* Unique cookie associating related
63                                     events (for rename(2)) */
64               uint32_t len;      /* Size of name field */
65               char     name[];   /* Optional null-terminated name */
66           };
67
68       wd identifies the watch for which this event occurs.  It is one of  the
69       watch descriptors returned by a previous call to inotify_add_watch(2).
70
71       mask contains bits that describe the event that occurred (see below).
72
73       cookie  is  a  unique integer that connects related events.  Currently,
74       this is used only for rename events, and allows the resulting  pair  of
75       IN_MOVED_FROM  and  IN_MOVED_TO  events to be connected by the applica‐
76       tion.  For all other event types, cookie is set to 0.
77
78       The name field is present only when an event is returned for a file in‐
79       side a watched directory; it identifies the filename within the watched
80       directory.  This filename is null-terminated, and may  include  further
81       null  bytes  ('\0')  to  align  subsequent  reads to a suitable address
82       boundary.
83
84       The len field counts all of the  bytes  in  name,  including  the  null
85       bytes; the length of each inotify_event structure is thus sizeof(struct
86       inotify_event)+len.
87
88       The behavior when the buffer given to read(2) is too  small  to  return
89       information  about the next event depends on the kernel version: before
90       Linux 2.6.21, read(2) returns 0; since Linux 2.6.21, read(2) fails with
91       the error EINVAL.  Specifying a buffer of size
92
93           sizeof(struct inotify_event) + NAME_MAX + 1
94
95       will be sufficient to read at least one event.
96
97   inotify events
98       The  inotify_add_watch(2)  mask argument and the mask field of the ino‐
99       tify_event structure returned when read(2)ing an inotify file  descrip‐
100       tor  are both bit masks identifying inotify events.  The following bits
101       can be specified in mask when calling inotify_add_watch(2) and  may  be
102       returned in the mask field returned by read(2):
103
104           IN_ACCESS (+)
105                  File was accessed (e.g., read(2), execve(2)).
106
107           IN_ATTRIB (*)
108                  Metadata  changed—for example, permissions (e.g., chmod(2)),
109                  timestamps (e.g., utimensat(2)), extended attributes  (setx‐
110                  attr(2)), link count (since Linux 2.6.25; e.g., for the tar‐
111                  get of link(2) and for unlink(2)), and user/group ID  (e.g.,
112                  chown(2)).
113
114           IN_CLOSE_WRITE (+)
115                  File opened for writing was closed.
116
117           IN_CLOSE_NOWRITE (*)
118                  File or directory not opened for writing was closed.
119
120           IN_CREATE (+)
121                  File/directory  created  in watched directory (e.g., open(2)
122                  O_CREAT, mkdir(2), link(2), symlink(2), bind(2)  on  a  UNIX
123                  domain socket).
124
125           IN_DELETE (+)
126                  File/directory deleted from watched directory.
127
128           IN_DELETE_SELF
129                  Watched file/directory was itself deleted.  (This event also
130                  occurs if an object is moved to  another  filesystem,  since
131                  mv(1)  in effect copies the file to the other filesystem and
132                  then deletes it from the original filesystem.)  In addition,
133                  an  IN_IGNORED  event will subsequently be generated for the
134                  watch descriptor.
135
136           IN_MODIFY (+)
137                  File was modified (e.g., write(2), truncate(2)).
138
139           IN_MOVE_SELF
140                  Watched file/directory was itself moved.
141
142           IN_MOVED_FROM (+)
143                  Generated for the directory containing the old filename when
144                  a file is renamed.
145
146           IN_MOVED_TO (+)
147                  Generated for the directory containing the new filename when
148                  a file is renamed.
149
150           IN_OPEN (*)
151                  File or directory was opened.
152
153       Inotify monitoring is inode-based: when monitoring a file (but not when
154       monitoring  the directory containing a file), an event can be generated
155       for activity on any link to the file (in the same or a different direc‐
156       tory).
157
158       When monitoring a directory:
159
160       •  the  events marked above with an asterisk (*) can occur both for the
161          directory itself and for objects inside the directory; and
162
163       •  the events marked with a plus sign (+) occur only for objects inside
164          the directory (not for the directory itself).
165
166       Note:  when  monitoring  a  directory, events are not generated for the
167       files inside the directory when the events are performed via a pathname
168       (i.e., a link) that lies outside the monitored directory.
169
170       When  events  are generated for objects inside a watched directory, the
171       name field in the returned inotify_event structure identifies the  name
172       of the file within the directory.
173
174       The  IN_ALL_EVENTS  macro  is defined as a bit mask of all of the above
175       events.  This macro can be used as the mask argument when calling  ino‐
176       tify_add_watch(2).
177
178       Two additional convenience macros are defined:
179
180           IN_MOVE
181                  Equates to IN_MOVED_FROM | IN_MOVED_TO.
182
183           IN_CLOSE
184                  Equates to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE.
185
186       The  following  further bits can be specified in mask when calling ino‐
187       tify_add_watch(2):
188
189           IN_DONT_FOLLOW (since Linux 2.6.15)
190                  Don't dereference pathname if it is a symbolic link.
191
192           IN_EXCL_UNLINK (since Linux 2.6.36)
193                  By default, when watching events on the children of a direc‐
194                  tory, events are generated for children even after they have
195                  been unlinked from the directory.  This can result in  large
196                  numbers of uninteresting events for some applications (e.g.,
197                  if watching /tmp, in which many applications  create  tempo‐
198                  rary  files whose names are immediately unlinked).  Specify‐
199                  ing IN_EXCL_UNLINK changes the  default  behavior,  so  that
200                  events  are  not generated for children after they have been
201                  unlinked from the watched directory.
202
203           IN_MASK_ADD
204                  If a watch instance already exists for the filesystem object
205                  corresponding  to  pathname,  add (OR) the events in mask to
206                  the watch mask (instead of replacing the  mask);  the  error
207                  EINVAL results if IN_MASK_CREATE is also specified.
208
209           IN_ONESHOT
210                  Monitor  the filesystem object corresponding to pathname for
211                  one event, then remove from watch list.
212
213           IN_ONLYDIR (since Linux 2.6.15)
214                  Watch pathname only if it is a directory; the error  ENOTDIR
215                  results  if  pathname  is  not a directory.  Using this flag
216                  provides an application with a  race-free  way  of  ensuring
217                  that the monitored object is a directory.
218
219           IN_MASK_CREATE (since Linux 4.18)
220                  Watch  pathname only if it does not already have a watch as‐
221                  sociated with it; the error EEXIST results  if  pathname  is
222                  already being watched.
223
224                  Using this flag provides an application with a way of ensur‐
225                  ing that new watches do not modify existing ones.   This  is
226                  useful  because  multiple paths may refer to the same inode,
227                  and multiple calls to inotify_add_watch(2) without this flag
228                  may clobber existing watch masks.
229
230       The following bits may be set in the mask field returned by read(2):
231
232           IN_IGNORED
233                  Watch  was removed explicitly (inotify_rm_watch(2)) or auto‐
234                  matically (file was deleted, or filesystem  was  unmounted).
235                  See also BUGS.
236
237           IN_ISDIR
238                  Subject of this event is a directory.
239
240           IN_Q_OVERFLOW
241                  Event queue overflowed (wd is -1 for this event).
242
243           IN_UNMOUNT
244                  Filesystem  containing watched object was unmounted.  In ad‐
245                  dition, an IN_IGNORED event will subsequently  be  generated
246                  for the watch descriptor.
247
248   Examples
249       Suppose  an  application  is  watching  the  directory dir and the file
250       dir/myfile for all events.  The examples below show  some  events  that
251       will be generated for these two objects.
252
253           fd = open("dir/myfile", O_RDWR);
254                  Generates IN_OPEN events for both dir and dir/myfile.
255
256           read(fd, buf, count);
257                  Generates IN_ACCESS events for both dir and dir/myfile.
258
259           write(fd, buf, count);
260                  Generates IN_MODIFY events for both dir and dir/myfile.
261
262           fchmod(fd, mode);
263                  Generates IN_ATTRIB events for both dir and dir/myfile.
264
265           close(fd);
266                  Generates IN_CLOSE_WRITE events for both dir and dir/myfile.
267
268       Suppose  an  application is watching the directories dir1 and dir2, and
269       the file dir1/myfile.  The following examples show some events that may
270       be generated.
271
272           link("dir1/myfile", "dir2/new");
273                  Generates  an  IN_ATTRIB  event  for myfile and an IN_CREATE
274                  event for dir2.
275
276           rename("dir1/myfile", "dir2/myfile");
277                  Generates an IN_MOVED_FROM event for  dir1,  an  IN_MOVED_TO
278                  event  for  dir2, and an IN_MOVE_SELF event for myfile.  The
279                  IN_MOVED_FROM and IN_MOVED_TO  events  will  have  the  same
280                  cookie value.
281
282       Suppose that dir1/xx and dir2/yy are (the only) links to the same file,
283       and an application is watching dir1, dir2, dir1/xx, and dir2/yy.   Exe‐
284       cuting  the  following calls in the order given below will generate the
285       following events:
286
287           unlink("dir2/yy");
288                  Generates an IN_ATTRIB event for xx (because its link  count
289                  changes) and an IN_DELETE event for dir2.
290
291           unlink("dir1/xx");
292                  Generates  IN_ATTRIB,  IN_DELETE_SELF, and IN_IGNORED events
293                  for xx, and an IN_DELETE event for dir1.
294
295       Suppose an application is watching the directory dir  and  (the  empty)
296       directory dir/subdir.  The following examples show some events that may
297       be generated.
298
299           mkdir("dir/new", mode);
300                  Generates an IN_CREATE | IN_ISDIR event for dir.
301
302           rmdir("dir/subdir");
303                  Generates IN_DELETE_SELF and IN_IGNORED events  for  subdir,
304                  and an IN_DELETE | IN_ISDIR event for dir.
305
306   /proc interfaces
307       The following interfaces can be used to limit the amount of kernel mem‐
308       ory consumed by inotify:
309
310       /proc/sys/fs/inotify/max_queued_events
311              The value in this file is used when an  application  calls  ino‐
312              tify_init(2)  to set an upper limit on the number of events that
313              can be queued to the corresponding inotify instance.  Events  in
314              excess  of this limit are dropped, but an IN_Q_OVERFLOW event is
315              always generated.
316
317       /proc/sys/fs/inotify/max_user_instances
318              This specifies an upper limit on the number of inotify instances
319              that can be created per real user ID.
320
321       /proc/sys/fs/inotify/max_user_watches
322              This  specifies an upper limit on the number of watches that can
323              be created per real user ID.
324

STANDARDS

326       Linux.
327

HISTORY

329       Inotify was merged into Linux 2.6.13.  The required library  interfaces
330       were  added in glibc 2.4.  (IN_DONT_FOLLOW, IN_MASK_ADD, and IN_ONLYDIR
331       were added in glibc 2.5.)
332

NOTES

334       Inotify file descriptors can be monitored using select(2), poll(2), and
335       epoll(7).  When an event is available, the file descriptor indicates as
336       readable.
337
338       Since Linux 2.6.25, signal-driven I/O notification is available for in‐
339       otify  file descriptors; see the discussion of F_SETFL (for setting the
340       O_ASYNC flag), F_SETOWN,  and  F_SETSIG  in  fcntl(2).   The  siginfo_t
341       structure (described in sigaction(2)) that is passed to the signal han‐
342       dler has the following fields set: si_fd is set to the inotify file de‐
343       scriptor  number;  si_signo is set to the signal number; si_code is set
344       to POLL_IN; and POLLIN is set in si_band.
345
346       If successive output inotify events produced on the  inotify  file  de‐
347       scriptor are identical (same wd, mask, cookie, and name), then they are
348       coalesced into a single event if the older event has not yet been  read
349       (but  see BUGS).  This reduces the amount of kernel memory required for
350       the event queue, but also means that an application can't  use  inotify
351       to reliably count file events.
352
353       The  events returned by reading from an inotify file descriptor form an
354       ordered queue.  Thus, for example, it is guaranteed that when  renaming
355       from  one  directory to another, events will be produced in the correct
356       order on the inotify file descriptor.
357
358       The set of watch descriptors that is being  monitored  via  an  inotify
359       file  descriptor  can  be viewed via the entry for the inotify file de‐
360       scriptor in the process's /proc/pid/fdinfo directory.  See proc(5)  for
361       further  details.   The  FIONREAD  ioctl(2) returns the number of bytes
362       available to read from an inotify file descriptor.
363
364   Limitations and caveats
365       The inotify API provides no information about the user or process  that
366       triggered the inotify event.  In particular, there is no easy way for a
367       process that is monitoring events via  inotify  to  distinguish  events
368       that  it  triggers  itself  from those that are triggered by other pro‐
369       cesses.
370
371       Inotify reports only events that a user-space program triggers  through
372       the  filesystem API.  As a result, it does not catch remote events that
373       occur on network filesystems.  (Applications must fall back to  polling
374       the  filesystem  to  catch  such events.)  Furthermore, various pseudo-
375       filesystems such as /proc, /sys, and /dev/pts are not monitorable  with
376       inotify.
377
378       The  inotify  API  does not report file accesses and modifications that
379       may occur because of mmap(2), msync(2), and munmap(2).
380
381       The inotify API identifies affected files by filename.  However, by the
382       time  an  application  processes an inotify event, the filename may al‐
383       ready have been deleted or renamed.
384
385       The inotify API identifies events via watch descriptors.  It is the ap‐
386       plication's  responsibility  to  cache a mapping (if one is needed) be‐
387       tween watch descriptors and pathnames.  Be aware that directory  renam‐
388       ings may affect multiple cached pathnames.
389
390       Inotify  monitoring  of directories is not recursive: to monitor subdi‐
391       rectories under a directory, additional watches must be created.   This
392       can take a significant amount time for large directory trees.
393
394       If  monitoring  an  entire directory subtree, and a new subdirectory is
395       created in that tree or an existing  directory  is  renamed  into  that
396       tree,  be  aware that by the time you create a watch for the new subdi‐
397       rectory, new files (and subdirectories) may already  exist  inside  the
398       subdirectory.  Therefore, you may want to scan the contents of the sub‐
399       directory immediately after adding the watch (and, if  desired,  recur‐
400       sively add watches for any subdirectories that it contains).
401
402       Note that the event queue can overflow.  In this case, events are lost.
403       Robust applications should handle the possibility of lost events grace‐
404       fully.   For example, it may be necessary to rebuild part or all of the
405       application cache.  (One simple, but possibly expensive, approach is to
406       close  the  inotify file descriptor, empty the cache, create a new ino‐
407       tify file descriptor, and then re-create watches and cache entries  for
408       the objects to be monitored.)
409
410       If a filesystem is mounted on top of a monitored directory, no event is
411       generated, and no events are generated for  objects  immediately  under
412       the  new  mount  point.   If  the filesystem is subsequently unmounted,
413       events will subsequently be generated for the directory and the objects
414       it contains.
415
416   Dealing with rename() events
417       As  noted  above,  the IN_MOVED_FROM and IN_MOVED_TO event pair that is
418       generated by rename(2) can be matched up via their shared cookie value.
419       However, the task of matching has some challenges.
420
421       These  two events are usually consecutive in the event stream available
422       when reading from the inotify file descriptor.  However,  this  is  not
423       guaranteed.   If multiple processes are triggering events for monitored
424       objects, then (on rare occasions) an arbitrary number of  other  events
425       may  appear between the IN_MOVED_FROM and IN_MOVED_TO events.  Further‐
426       more, it is not guaranteed that the event pair is  atomically  inserted
427       into  the  queue: there may be a brief interval where the IN_MOVED_FROM
428       has appeared, but the IN_MOVED_TO has not.
429
430       Matching up the IN_MOVED_FROM and IN_MOVED_TO event pair  generated  by
431       rename(2)  is thus inherently racy.  (Don't forget that if an object is
432       renamed outside of a monitored directory, there  may  not  even  be  an
433       IN_MOVED_TO  event.)  Heuristic approaches (e.g., assume the events are
434       always consecutive) can be used to ensure a match in  most  cases,  but
435       will  inevitably  miss  some cases, causing the application to perceive
436       the IN_MOVED_FROM and IN_MOVED_TO events as being unrelated.  If  watch
437       descriptors  are destroyed and re-created as a result, then those watch
438       descriptors will be inconsistent with  the  watch  descriptors  in  any
439       pending  events.  (Re-creating the inotify file descriptor and rebuild‐
440       ing the cache may be useful to deal with this scenario.)
441
442       Applications  should  also  allow  for   the   possibility   that   the
443       IN_MOVED_FROM event was the last event that could fit in the buffer re‐
444       turned by the current call to read(2), and the accompanying IN_MOVED_TO
445       event  might  be fetched only on the next read(2), which should be done
446       with a (small) timeout to allow for the  fact  that  insertion  of  the
447       IN_MOVED_FROM+IN_MOVED_TO event pair is not atomic, and also the possi‐
448       bility that there may not be any IN_MOVED_TO event.
449

BUGS

451       Before Linux 3.19, fallocate(2) did  not  create  any  inotify  events.
452       Since Linux 3.19, calls to fallocate(2) generate IN_MODIFY events.
453
454       Before Linux 2.6.16, the IN_ONESHOT mask flag does not work.
455
456       As  originally  designed  and  implemented, the IN_ONESHOT flag did not
457       cause an IN_IGNORED event to be generated when the  watch  was  dropped
458       after  one  event.   However, as an unintended effect of other changes,
459       since Linux 2.6.36, an IN_IGNORED event is generated in this case.
460
461       Before Linux 2.6.25, the kernel code that was intended to coalesce suc‐
462       cessive identical events (i.e., the two most recent events could poten‐
463       tially be coalesced if the older had not yet been read) instead checked
464       if  the  most  recent  event  could be coalesced with the oldest unread
465       event.
466
467       When a watch descriptor is removed by calling  inotify_rm_watch(2)  (or
468       because  a  watch file is deleted or the filesystem that contains it is
469       unmounted), any pending unread events for that watch descriptor  remain
470       available  to  read.   As  watch descriptors are subsequently allocated
471       with inotify_add_watch(2), the kernel cycles through the range of  pos‐
472       sible  watch descriptors (1 to INT_MAX) incrementally.  When allocating
473       a free watch descriptor, no check is made to see whether that watch de‐
474       scriptor  number  has  any  pending unread events in the inotify queue.
475       Thus, it can happen that a watch descriptor is  reallocated  even  when
476       pending  unread  events  exist for a previous incarnation of that watch
477       descriptor number, with the result that the application might then read
478       those  events  and  interpret  them as belonging to the file associated
479       with the newly recycled watch descriptor.  In practice, the  likelihood
480       of hitting this bug may be extremely low, since it requires that an ap‐
481       plication cycle through INT_MAX watch descriptors, release a watch  de‐
482       scriptor  while  leaving unread events for that watch descriptor in the
483       queue, and then recycle that watch descriptor.  For  this  reason,  and
484       because  there  have been no reports of the bug occurring in real-world
485       applications, as of Linux 3.15, no kernel changes have yet been made to
486       eliminate this possible bug.
487

EXAMPLES

489       The  following  program  demonstrates the usage of the inotify API.  It
490       marks the directories passed as a command-line arguments and waits  for
491       events of type IN_OPEN, IN_CLOSE_NOWRITE, and IN_CLOSE_WRITE.
492
493       The   following   output   was   recorded   while   editing   the  file
494       /home/user/temp/foo and listing directory /tmp.  Before  the  file  and
495       the directory were opened, IN_OPEN events occurred.  After the file was
496       closed, an IN_CLOSE_WRITE event  occurred.   After  the  directory  was
497       closed,  an  IN_CLOSE_NOWRITE event occurred.  Execution of the program
498       ended when the user pressed the ENTER key.
499
500   Example output
501           $ ./a.out /tmp /home/user/temp
502           Press enter key to terminate.
503           Listening for events.
504           IN_OPEN: /home/user/temp/foo [file]
505           IN_CLOSE_WRITE: /home/user/temp/foo [file]
506           IN_OPEN: /tmp/ [directory]
507           IN_CLOSE_NOWRITE: /tmp/ [directory]
508
509           Listening for events stopped.
510
511   Program source
512
513       #include <errno.h>
514       #include <poll.h>
515       #include <stdio.h>
516       #include <stdlib.h>
517       #include <sys/inotify.h>
518       #include <unistd.h>
519       #include <string.h>
520
521       /* Read all available inotify events from the file descriptor 'fd'.
522          wd is the table of watch descriptors for the directories in argv.
523          argc is the length of wd and argv.
524          argv is the list of watched directories.
525          Entry 0 of wd and argv is unused. */
526
527       static void
528       handle_events(int fd, int *wd, int argc, char* argv[])
529       {
530           /* Some systems cannot read integer variables if they are not
531              properly aligned. On other systems, incorrect alignment may
532              decrease performance. Hence, the buffer used for reading from
533              the inotify file descriptor should have the same alignment as
534              struct inotify_event. */
535
536           char buf[4096]
537               __attribute__ ((aligned(__alignof__(struct inotify_event))));
538           const struct inotify_event *event;
539           ssize_t len;
540
541           /* Loop while events can be read from inotify file descriptor. */
542
543           for (;;) {
544
545               /* Read some events. */
546
547               len = read(fd, buf, sizeof(buf));
548               if (len == -1 && errno != EAGAIN) {
549                   perror("read");
550                   exit(EXIT_FAILURE);
551               }
552
553               /* If the nonblocking read() found no events to read, then
554                  it returns -1 with errno set to EAGAIN. In that case,
555                  we exit the loop. */
556
557               if (len <= 0)
558                   break;
559
560               /* Loop over all events in the buffer. */
561
562               for (char *ptr = buf; ptr < buf + len;
563                       ptr += sizeof(struct inotify_event) + event->len) {
564
565                   event = (const struct inotify_event *) ptr;
566
567                   /* Print event type. */
568
569                   if (event->mask & IN_OPEN)
570                       printf("IN_OPEN: ");
571                   if (event->mask & IN_CLOSE_NOWRITE)
572                       printf("IN_CLOSE_NOWRITE: ");
573                   if (event->mask & IN_CLOSE_WRITE)
574                       printf("IN_CLOSE_WRITE: ");
575
576                   /* Print the name of the watched directory. */
577
578                   for (size_t i = 1; i < argc; ++i) {
579                       if (wd[i] == event->wd) {
580                           printf("%s/", argv[i]);
581                           break;
582                       }
583                   }
584
585                   /* Print the name of the file. */
586
587                   if (event->len)
588                       printf("%s", event->name);
589
590                   /* Print type of filesystem object. */
591
592                   if (event->mask & IN_ISDIR)
593                       printf(" [directory]\n");
594                   else
595                       printf(" [file]\n");
596               }
597           }
598       }
599
600       int
601       main(int argc, char* argv[])
602       {
603           char buf;
604           int fd, i, poll_num;
605           int *wd;
606           nfds_t nfds;
607           struct pollfd fds[2];
608
609           if (argc < 2) {
610               printf("Usage: %s PATH [PATH ...]\n", argv[0]);
611               exit(EXIT_FAILURE);
612           }
613
614           printf("Press ENTER key to terminate.\n");
615
616           /* Create the file descriptor for accessing the inotify API. */
617
618           fd = inotify_init1(IN_NONBLOCK);
619           if (fd == -1) {
620               perror("inotify_init1");
621               exit(EXIT_FAILURE);
622           }
623
624           /* Allocate memory for watch descriptors. */
625
626           wd = calloc(argc, sizeof(int));
627           if (wd == NULL) {
628               perror("calloc");
629               exit(EXIT_FAILURE);
630           }
631
632           /* Mark directories for events
633              - file was opened
634              - file was closed */
635
636           for (i = 1; i < argc; i++) {
637               wd[i] = inotify_add_watch(fd, argv[i],
638                                         IN_OPEN | IN_CLOSE);
639               if (wd[i] == -1) {
640                   fprintf(stderr, "Cannot watch '%s': %s\n",
641                           argv[i], strerror(errno));
642                   exit(EXIT_FAILURE);
643               }
644           }
645
646           /* Prepare for polling. */
647
648           nfds = 2;
649
650           fds[0].fd = STDIN_FILENO;       /* Console input */
651           fds[0].events = POLLIN;
652
653           fds[1].fd = fd;                 /* Inotify input */
654           fds[1].events = POLLIN;
655
656           /* Wait for events and/or terminal input. */
657
658           printf("Listening for events.\n");
659           while (1) {
660               poll_num = poll(fds, nfds, -1);
661               if (poll_num == -1) {
662                   if (errno == EINTR)
663                       continue;
664                   perror("poll");
665                   exit(EXIT_FAILURE);
666               }
667
668               if (poll_num > 0) {
669
670                   if (fds[0].revents & POLLIN) {
671
672                       /* Console input is available. Empty stdin and quit. */
673
674                       while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\n')
675                           continue;
676                       break;
677                   }
678
679                   if (fds[1].revents & POLLIN) {
680
681                       /* Inotify events are available. */
682
683                       handle_events(fd, wd, argc, argv);
684                   }
685               }
686           }
687
688           printf("Listening for events stopped.\n");
689
690           /* Close inotify file descriptor. */
691
692           close(fd);
693
694           free(wd);
695           exit(EXIT_SUCCESS);
696       }
697

SEE ALSO

699       inotifywait(1), inotifywatch(1), inotify_add_watch(2), inotify_init(2),
700       inotify_init1(2), inotify_rm_watch(2), read(2), stat(2), fanotify(7)
701
702       Documentation/filesystems/inotify.txt in the Linux kernel source tree
703
704
705
706Linux man-pages 6.05              2023-07-08                        inotify(7)
Impressum