ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/Linux-Inotify2/Inotify2.pm
Revision: 1.33
Committed: Mon Dec 9 03:09:43 2019 UTC (6 years, 9 months ago) by root
Branch: MAIN
CVS Tags: rel-2_2
Changes since 1.32: +3 -2 lines
Log Message:
2.2

File Contents

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