ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/Linux-Inotify2/Inotify2.pm
Revision: 1.32
Committed: Fri Oct 26 01:16:22 2018 UTC (5 years, 8 months ago) by root
Branch: MAIN
CVS Tags: rel-2_1
Changes since 1.31: +1 -3 lines
Log Message:
2.1

File Contents

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