File Coverage

blib/lib/Linux/Inotify2.pm
Criterion Covered Total %
statement 43 68 63.2
branch 13 32 40.6
condition n/a
subroutine 10 23 43.4
pod 9 9 100.0
total 75 132 56.8


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             Linux::Inotify2 - scalable directory/file change notification
4              
5             =head1 SYNOPSIS
6              
7             =head2 Callback Interface
8              
9             use Linux::Inotify2;
10              
11             # create a new object
12             my $inotify = new Linux::Inotify2
13             or die "unable to create new inotify object: $!";
14            
15             # add watchers
16             $inotify->watch ("/etc/passwd", IN_ACCESS, sub {
17             my $e = shift;
18             my $name = $e->fullname;
19             print "$name was accessed\n" if $e->IN_ACCESS;
20             print "$name is no longer mounted\n" if $e->IN_UNMOUNT;
21             print "$name is gone\n" if $e->IN_IGNORED;
22             print "events for $name have been lost\n" if $e->IN_Q_OVERFLOW;
23            
24             # cancel this watcher: remove no further events
25             $e->w->cancel;
26             });
27              
28             # integration into AnyEvent (works with EV, Glib, Tk, POE...)
29             my $inotify_w = AE::io $inotify->fileno, 0, sub { $inotify->poll };
30              
31             # manual event loop
32             $inotify->poll while 1;
33              
34             =head2 Streaming Interface
35              
36             use Linux::Inotify2;
37              
38             # create a new object
39             my $inotify = new Linux::Inotify2
40             or die "Unable to create new inotify object: $!";
41              
42             # create watch
43             $inotify->watch ("/etc/passwd", IN_ACCESS)
44             or die "watch creation failed";
45              
46             while () {
47             my @events = $inotify->read;
48             printf "mask\t%d\n", $_->mask foreach @events;
49             }
50              
51             =head1 DESCRIPTION
52              
53             This module implements an interface to the Linux 2.6.13 and later Inotify
54             file/directory change notification system.
55              
56             It has a number of advantages over the Linux::Inotify module:
57              
58             - it is portable (Linux::Inotify only works on x86)
59             - the equivalent of fullname works correctly
60             - it is better documented
61             - it has callback-style interface, which is better suited for
62             integration.
63              
64             As for the inotify API itself - it is a very tricky, and somewhat
65             unreliable API. For a good overview of the challenges you might run into,
66             see this LWN article: L<https://lwn.net/Articles/605128/>.
67              
68             =head2 The Linux::Inotify2 Class
69              
70             =over 4
71              
72             =cut
73              
74             package Linux::Inotify2;
75              
76 2     2   105663 use Scalar::Util ();
  2         14  
  2         54  
77              
78 2     2   1084 use common::sense;
  2         29  
  2         12  
79              
80 2     2   148 use Exporter qw(import);
  2         5  
  2         274  
81              
82             BEGIN {
83 2     2   8 our $VERSION = '2.3';
84 2         8 our @EXPORT = qw(
85             IN_ACCESS IN_MODIFY IN_ATTRIB IN_CLOSE_WRITE
86             IN_CLOSE_NOWRITE IN_OPEN IN_MOVED_FROM IN_MOVED_TO
87             IN_CREATE IN_DELETE IN_DELETE_SELF IN_MOVE_SELF
88             IN_ALL_EVENTS
89             IN_UNMOUNT IN_Q_OVERFLOW IN_IGNORED
90             IN_CLOSE IN_MOVE
91             IN_ISDIR IN_ONESHOT IN_MASK_ADD
92             IN_DONT_FOLLOW IN_EXCL_UNLINK IN_ONLYDIR
93             );
94              
95 2         11 require XSLoader;
96 2         4513 XSLoader::load Linux::Inotify2, $VERSION;
97             }
98              
99             =item my $inotify = new Linux::Inotify2
100              
101             Create a new notify object and return it. A notify object is kind of a
102             container that stores watches on file system names and is responsible for
103             handling event data.
104              
105             On error, C<undef> is returned and C<$!> will be set accordingly. The
106             following errors are documented:
107              
108             ENFILE The system limit on the total number of file descriptors has been reached.
109             EMFILE The user limit on the total number of inotify instances has been reached.
110             ENOMEM Insufficient kernel memory is available.
111              
112             Example:
113              
114             my $inotify = new Linux::Inotify2
115             or die "Unable to create new inotify object: $!";
116              
117             =cut
118              
119             sub new {
120 1     1 1 135 my ($class) = @_;
121              
122 1         23 my $fd = inotify_init;
123              
124 1 50       7 return unless $fd >= 0;
125              
126 1 50       26 open my $fh, "<&=", $fd
127             or die "cannot open fd $fd as perl handle\n";
128              
129 1         11 bless { fd => $fd, fh => $fh }, $class
130             }
131              
132             =item $watch = $inotify->watch ($name, $mask[, $cb])
133              
134             Add a new watcher to the given notifier. The watcher will create events
135             on the pathname C<$name> as given in C<$mask>, which can be any of the
136             following constants (all exported by default) ORed together. Constants
137             unavailable on your system will evaluate to C<0>.
138              
139             "file" refers to any file system object in the watched object (always a
140             directory), that is files, directories, symlinks, device nodes etc., while
141             "object" refers to the object the watcher has been set on itself:
142              
143             IN_ACCESS object was accessed
144             IN_MODIFY object was modified
145             IN_ATTRIB object metadata changed
146             IN_CLOSE_WRITE writable fd to file / to object was closed
147             IN_CLOSE_NOWRITE readonly fd to file / to object closed
148             IN_OPEN object was opened
149             IN_MOVED_FROM file was moved from this object (directory)
150             IN_MOVED_TO file was moved to this object (directory)
151             IN_CREATE file was created in this object (directory)
152             IN_DELETE file was deleted from this object (directory)
153             IN_DELETE_SELF object itself was deleted
154             IN_MOVE_SELF object itself was moved
155             IN_ALL_EVENTS all of the above events
156              
157             IN_ONESHOT only send event once
158             IN_ONLYDIR only watch the path if it is a directory
159             IN_DONT_FOLLOW don't follow a sym link (Linux 2.6.15+)
160             IN_EXCL_UNLINK don't create events for unlinked objects (Linux 2.6.36+)
161             IN_MASK_ADD not supported with the current version of this module
162              
163             IN_CLOSE same as IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
164             IN_MOVE same as IN_MOVED_FROM | IN_MOVED_TO
165              
166             C<$cb> is a perl code reference that, if given, is called for each
167             event. It receives a C<Linux::Inotify2::Event> object.
168              
169             The returned C<$watch> object is of class C<Linux::Inotify2::Watch>.
170              
171             On error, C<undef> is returned and C<$!> will be set accordingly. The
172             following errors are documented:
173              
174             EBADF The given file descriptor is not valid.
175             EINVAL The given event mask contains no legal events.
176             ENOMEM Insufficient kernel memory was available.
177             ENOSPC The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource.
178             EACCESS Read access to the given file is not permitted.
179              
180             Example, show when C</etc/passwd> gets accessed and/or modified once:
181              
182             $inotify->watch ("/etc/passwd", IN_ACCESS | IN_MODIFY, sub {
183             my $e = shift;
184             print "$e->{w}{name} was accessed\n" if $e->IN_ACCESS;
185             print "$e->{w}{name} was modified\n" if $e->IN_MODIFY;
186             print "$e->{w}{name} is no longer mounted\n" if $e->IN_UNMOUNT;
187             print "events for $e->{w}{name} have been lost\n" if $e->IN_Q_OVERFLOW;
188              
189             $e->w->cancel;
190             });
191              
192             =cut
193              
194             sub watch {
195 1     1 1 753 my ($self, $name, $mask, $cb) = @_;
196              
197 1         28 my $wd = inotify_add_watch $self->{fd}, $name, $mask;
198              
199 1 50       6 return unless $wd >= 0;
200            
201 1         15 my $w = $self->{w}{$wd} = bless {
202             inotify => $self,
203             wd => $wd,
204             name => $name,
205             mask => $mask,
206             cb => $cb,
207             }, "Linux::Inotify2::Watch";
208              
209 1         10 Scalar::Util::weaken $w->{inotify};
210              
211 1         4 $w
212             }
213              
214             =item $inotify->fileno
215              
216             Returns the file descriptor for this notify object. When in non-blocking
217             mode, you are responsible for calling the C<poll> method when this file
218             descriptor becomes ready for reading.
219              
220             =item $inotify->fh
221              
222             Similar to C<fileno>, but returns a perl file handle instead.
223              
224             =cut
225              
226             sub fileno {
227             $_[0]{fd}
228 0     0 1 0 }
229              
230             sub fh {
231             $_[0]{fh}
232 0     0 1 0 }
233              
234             =item $inotify->blocking ($blocking)
235              
236             Clears ($blocking true) or sets ($blocking false) the C<O_NONBLOCK> flag on the file descriptor.
237              
238             =cut
239              
240             sub blocking {
241 1     1 1 333 my ($self, $blocking) = @_;
242              
243 1         13 inotify_blocking $self->{fd}, $blocking;
244             }
245              
246             =item $count = $inotify->poll
247              
248             Reads events from the kernel and handles them. If the notify file
249             descriptor is blocking (the default), then this method waits for at least
250             one event. Otherwise it returns immediately when no pending events could
251             be read.
252              
253             Returns the count of events that have been handled (which can be C<0> in case
254             events have been received but have been ignored or handled internally).
255              
256             Croaks when an error occurs.
257              
258             =cut
259              
260             sub poll {
261 1     1 1 455 scalar &read
262             }
263              
264             =item @events = $inotify->read
265              
266             Reads events from the kernel. Blocks when the file descriptor is in
267             blocking mode (default) until any event arrives. Returns list of
268             C<Linux::Inotify2::Event> objects or empty list if none (non-blocking
269             mode or events got ignored).
270              
271             Croaks on error.
272              
273             Normally you shouldn't use this function, but instead use watcher
274             callbacks and call C<< ->poll >>.
275              
276             =cut
277              
278             sub read {
279 2     2 1 13 my ($self) = @_;
280              
281 2         26 my @ev = inotify_read $self->{fd};
282 2         6 my @res;
283              
284 2         6 for (@ev) {
285             exists $self->{ignore}{$_->{wd}}
286 2 100       11 and next; # watcher has been canceled
287              
288 1         7 push @res, bless $_, "Linux::Inotify2::Event";
289              
290             my $w = $_->{w} = $self->{w}{$_->{wd}}
291 1 50       11 or do {
292             # no such watcher, but maybe we can do overflow handling
293 0 0       0 if ($_->{mask} & IN_Q_OVERFLOW) {
294 0 0       0 if ($self->{on_overflow}) {
295 0         0 $self->{on_overflow}($_);
296             } else {
297 0         0 $self->broadcast ($_);
298             }
299             }
300 0         0 next;
301             };
302              
303 1 50       3 $w->{cb}($_) if $w->{cb};
304 1 50       10 $w->cancel if $_->{mask} & (IN_IGNORED | IN_UNMOUNT | IN_ONESHOT | IN_DELETE_SELF);
305             }
306              
307 2         4 delete $self->{ignore};
308              
309 2 100       17 wantarray ? @res : scalar @res
310             }
311              
312             =item $inotify->on_overflow ($cb->($ev))
313              
314             Sets the callback to be used for overflow handling
315             (default: C<undef>): When C<read> receives an event with C<IN_Q_OVERFLOW>
316             set, it will invoke this callback with the event.
317              
318             When the callback is C<undef>, then it broadcasts the event to all
319             registered watchers, i.e., C<undef> is equivalent to:
320              
321             sub { $inotify->broadcast ($_[0]) }
322              
323             =cut
324              
325             sub on_overflow {
326 0     0 1 0 my $prev = $_[0]{on_overflow};
327              
328 0 0       0 $_[0]{on_overflow} = $_[1]
329             if @_ >= 2;
330              
331 0         0 $prev
332             }
333              
334             =item $inotify->broadcast ($ev)
335              
336             Invokes all registered watcher callbacks and passes the given event to
337             them. Most useful in overflow handlers.
338              
339             =cut
340              
341             sub broadcast {
342 0     0 1 0 my ($self, $ev) = @_;
343              
344 0         0 for my $w (values %{ $self->{w} }) {
  0         0  
345 0         0 local $ev->{w} = $w;
346 0 0       0 $w->{cb}($ev) if $w->{cb};
347             }
348             }
349              
350             =back
351              
352             =head2 The Linux::Inotify2::Event Class
353              
354             Objects of this class are handed as first argument to the watcher
355             callback. It has the following members and methods:
356              
357             =over 4
358              
359             =item $event->w
360              
361             =item $event->{w}
362              
363             The watcher object for this event, if one is available. Generally, you cna
364             only rely on the value of this member inside watcher callbacks.
365              
366             =item $event->name
367              
368             =item $event->{name}
369              
370             The path of the file system object, relative to the watched name.
371              
372             =item $event->fullname
373              
374             Returns the "full" name of the relevant object, i.e. including the C<name>
375             member of the watcher (if the watch object is on a directory and a
376             directory entry is affected), or simply the C<name> member itself when the
377             object is the watch object itself.
378              
379             This call requires C<< $event->{w} >> to be valid, which is generally only
380             the case within watcher callbacks.
381              
382             =item $event->mask
383              
384             =item $event->{mask}
385              
386             The received event mask. In addition to the events described for C<<
387             $inotify->watch >>, the following flags (exported by default) can be set:
388              
389             IN_ISDIR event object is a directory
390             IN_Q_OVERFLOW event queue overflowed
391              
392             # when any of the following flags are set,
393             # then watchers for this event are automatically canceled
394             IN_UNMOUNT filesystem for watched object was unmounted
395             IN_IGNORED file was ignored/is gone (no more events are delivered)
396             IN_ONESHOT only one event was generated
397             IN_Q_OVERFLOW queue overflow - event might not be specific to a watcher
398              
399             =item $event->IN_xxx
400              
401             Returns a boolean that returns true if the event mask contains any events
402             specified by the mask. All of the C<IN_xxx> constants can be used as
403             methods.
404              
405             =item $event->cookie
406              
407             =item $event->{cookie}
408              
409             The event cookie to "synchronize two events". Normally zero, this value is
410             set when two events relating to the same file are generated. As far as I
411             know, this only happens for C<IN_MOVED_FROM> and C<IN_MOVED_TO> events, to
412             identify the old and new name of a file.
413              
414             Note that the inotify API makes it impossible to know whether there will
415             be a C<IN_MOVED_TO> event - you might receive only one of the events,
416             and even if you receive both, there might be any number of events in
417             between. The best approach seems to be to implement a small timeout
418             after C<IN_MOVED_FROM> to see if a matching C<IN_MOVED_TO> event will be
419             received - 2ms seem to work relatively well.
420              
421             =back
422              
423             =cut
424              
425             package Linux::Inotify2::Event;
426              
427 0     0   0 sub w { $_[0]{w} }
428 0     0   0 sub name { $_[0]{name} }
429 0     0   0 sub mask { $_[0]{mask} }
430 0     0   0 sub cookie { $_[0]{cookie} }
431              
432             sub fullname {
433             length $_[0]{name}
434             ? "$_[0]{w}{name}/$_[0]{name}"
435 0 0   0   0 : $_[0]{w}{name};
436             }
437              
438             for my $name (@Linux::Inotify2::EXPORT) {
439             my $mask = &{"Linux::Inotify2::$name"};
440              
441 0     0   0 *$name = sub { $_[0]{mask} & $mask };
442             }
443              
444             =head2 The Linux::Inotify2::Watch Class
445              
446             Watcher objects are created by calling the C<watch> method of a notifier.
447              
448             It has the following members and methods:
449              
450             =over 4
451              
452             =item $watch->name
453              
454             =item $watch->{name}
455              
456             The name as specified in the C<watch> call. For the object itself, this is
457             the empty string. For directory watches, this is the name of the entry
458             without leading path elements.
459              
460             =item $watch->mask
461              
462             =item $watch->{mask}
463              
464             The mask as specified in the C<watch> call.
465              
466             =item $watch->cb ([new callback])
467              
468             =item $watch->{cb}
469              
470             The callback as specified in the C<watch> call. Can optionally be changed.
471              
472             =item $watch->cancel
473              
474             Cancels/removes this watcher. Future events, even if already queued queued,
475             will not be handled and resources will be freed.
476              
477             =back
478              
479             =cut
480              
481             package Linux::Inotify2::Watch;
482              
483 0     0   0 sub name { $_[0]{name} }
484 0     0   0 sub mask { $_[0]{mask} }
485              
486             sub cb {
487 0 0   0   0 $_[0]{cb} = $_[1] if @_ > 1;
488             $_[0]{cb}
489 0         0 }
490              
491             sub cancel {
492 2     2   356 my ($self) = @_;
493              
494             my $inotify = delete $self->{inotify}
495 2 100       9 or return 1; # already canceled
496              
497 1         5 delete $inotify->{w}{$self->{wd}}; # we are no longer there
498 1         3 $inotify->{ignore}{$self->{wd}} = 1; # ignore further events for one poll
499              
500             (Linux::Inotify2::inotify_rm_watch $inotify->{fd}, $self->{wd})
501 1 50       13 ? 1 : undef
502             }
503              
504             =head1 SEE ALSO
505              
506             L<AnyEvent>, L<Linux::Inotify>.
507              
508             =head1 AUTHOR
509              
510             Marc Lehmann <schmorp@schmorp.de>
511             http://home.schmorp.de/
512              
513             =cut
514              
515             1