1IO::Async::Loop(3)    User Contributed Perl Documentation   IO::Async::Loop(3)
2
3
4

NAME

6       "IO::Async::Loop" - core loop of the "IO::Async" framework
7

SYNOPSIS

9        use IO::Async::Stream;
10        use IO::Async::Timer::Countdown;
11
12        use IO::Async::Loop;
13
14        my $loop = IO::Async::Loop->new();
15
16        $loop->add( IO::Async::Timer::Countdown->new(
17           delay => 10,
18           on_expire => sub { print "10 seconds have passed\n" },
19        )->start );
20
21        $loop->add( IO::Async::Stream->new(
22           read_handle => \*STDIN,
23
24           on_read => sub {
25              my ( $self, $buffref, $closed ) = @_;
26
27              if( $$buffref =~ s/^(.*)\n// ) {
28                 print "You typed a line $1\n";
29                 return 1;
30              }
31
32              return 0;
33           },
34        ) );
35
36        $loop->loop_forever();
37

DESCRIPTION

39       This module provides an abstract class which implements the core loop
40       of the "IO::Async" framework. Its primary purpose is to store a set of
41       IO::Async::Notifier objects or subclasses of them. It handles all of
42       the lower-level set manipulation actions, and leaves the actual IO
43       readiness testing/notification to the concrete class that implements
44       it. It also provides other functionallity such as signal handling,
45       child process managing, and timers.
46
47       See also the two bundled Loop subclasses:
48
49       IO::Async::Loop::Select
50       IO::Async::Loop::Poll
51
52       Or other subclasses that may appear on CPAN which are not part of the
53       core "IO::Async" distribution.
54

MAGIC CONSTRUCTOR

56   $loop = IO::Async::Loop->new()
57       This function attempts to find a good subclass to use, then calls its
58       constructor. It works by making a list of likely candidate classes,
59       then trying each one in turn, "require"ing the module then calling its
60       "new" method. If either of these operations fails, the next subclass is
61       tried. If no class was successful, then an exception is thrown.
62
63       The list of candidates is formed from the following choices, in this
64       order:
65
66       ·   $ENV{IO_ASYNC_LOOP}
67
68           If this environment variable is set, it should contain a comma-
69           separated list of subclass names. These names may or may not be
70           fully-qualified; if a name does not contain "::" then it will have
71           "IO::Async::Loop::" prepended to it.  This allows the end-user to
72           specify a particular choice to fit the needs of his use of a
73           program using "IO::Async".
74
75       ·   $IO::Async::Loop::LOOP
76
77           If this scalar is set, it should contain a comma-separated list of
78           subclass names. These may or may not be fully-qualified, as with
79           the above case. This allows a program author to suggest a loop
80           module to use.
81
82           In cases where the module subclass is a hard requirement, such as
83           GTK programs using "Glib", it would be better to use the module
84           specifically and invoke its constructor directly.
85
86       ·   $^O
87
88           The module called "IO::Async::Loop::$^O" is tried next. This allows
89           specific OSes, such as the ever-tricky "MSWin32", to provide an
90           implementation that might be more efficient than the generic ones,
91           or even work at all.
92
93       ·   Poll and Select
94
95           Finally, if no other choice has been made by now, the built-in
96           "Poll" module is chosen. This should always work, but in case it
97           doesn't, the "Select" module will be chosen afterwards as a last-
98           case attempt. If this also fails, then the magic constructor itself
99           will throw an exception.
100
101       If any of the explicitly-requested loop types ($ENV{IO_ASYNC_LOOP} or
102       $IO::Async::Loop::LOOP) fails to load then a warning is printed
103       detailing the error.
104
105       Implementors of new "IO::Async::Loop" subclasses should see the notes
106       about "API_VERSION" below.
107

NOTIFIER MANAGEMENT

109       The following methods manage the collection of "IO::Async::Notifier"
110       objects.
111
112   $loop->add( $notifier )
113       This method adds another notifier object to the stored collection. The
114       object may be a "IO::Async::Notifier", or any subclass of it.
115
116       When a notifier is added, any children it has are also added,
117       recursively. In this way, entire sections of a program may be written
118       within a tree of notifier objects, and added or removed on one piece.
119
120   $loop->remove( $notifier )
121       This method removes a notifier object from the stored collection, and
122       recursively and children notifiers it contains.
123

LOOPING CONTROL

125       The following methods control the actual run cycle of the loop, and
126       hence the program.
127
128   $count = $loop->loop_once( $timeout )
129       This method performs a single wait loop using the specific subclass's
130       underlying mechanism. If $timeout is undef, then no timeout is applied,
131       and it will wait until an event occurs. The intention of the return
132       value is to indicate the number of callbacks that this loop executed,
133       though different subclasses vary in how accurately they can report
134       this. See the documentation for this method in the specific subclass
135       for more information.
136
137   $loop->loop_forever()
138       This method repeatedly calls the "loop_once" method with no timeout
139       (i.e.  allowing the underlying mechanism to block indefinitely), until
140       the "loop_stop" method is called from an event callback.
141
142   $loop->loop_stop()
143       This method cancels a running "loop_forever", and makes that method
144       return.  It would be called from an event callback triggered by an
145       event that occured within the loop.
146

FEATURES

148       Most of the following methods are higher-level wrappers around base
149       functionallity provided by the low-level API documented below. They may
150       be used by "IO::Async::Notifier" subclasses or called directly by the
151       program.
152
153   $id = $loop->attach_signal( $signal, $code )
154       This method adds a new signal handler to watch the given signal. The
155       same signal can be attached to multiple times; its callback functions
156       will all be invoked, in no particular order.
157
158       The returned $id value can be used to identify the signal handler in
159       case it needs to be removed by the "detach_signal()" method. Note that
160       this value may be an object reference, so if it is stored, it should be
161       released after it cancelled, so the object itself can be freed.
162
163       $signal The name of the signal to attach to. This should be a bare name
164               like "TERM".
165
166       $code   A CODE reference to the handling callback.
167
168       Attaching to "SIGCHLD" is not recommended because of the way all child
169       processes use it to report their termination. Instead, the
170       "watch_child" method should be used to watch for termination of a given
171       child process. A warning will be printed if "SIGCHLD" is passed here,
172       but in future versions of "IO::Async" this behaviour may be disallowed
173       altogether.
174
175       See also POSIX for the "SIGname" constants.
176
177       For a more flexible way to use signals from within Notifiers, see
178       instead the IO::Async::Signal object.
179
180   $loop->detach_signal( $signal, $id )
181       Removes a previously-attached signal handler.
182
183       $signal The name of the signal to remove from. This should be a bare
184               name like "TERM".
185
186       $id     The value returned by the "attach_signal" method.
187
188   $loop->later( $code )
189       Installs a new idle handler which invokes its callback when the IO loop
190       is idle.
191
192       This method is implemented using the "watch_idle" method, with the
193       "when" parameter set to "later". It will return an ID value that can be
194       passed to "unwatch_idle" if required.
195
196   $pid = $loop->detach_child( %params )
197       This method creates a new child process to run a given code block. For
198       more detail, see the "detach_child()" method on the
199       IO::Async::ChildManager class.
200
201   $code = $loop->detach_code( %params )
202       This method creates a new detached code object. It is equivalent to
203       calling the "IO::Async::DetachedCode" constructor, passing in the given
204       loop. See the documentation on this class for more information.
205
206   $loop->spawn_child( %params )
207       This method creates a new child process to run a given code block or
208       command.  For more detail, see the "detach_child()" method on the
209       IO::Async::ChildManager class.
210
211   $loop->open_child( %params )
212       This method creates a new child process to run the given code block or
213       command, and attaches filehandles to it that the parent will watch. For
214       more detail, see the "open_child()" method on the
215       IO::Async::ChildManager class.
216
217   $loop->run_child( %params )
218       This method creates a new child process to run the given code block or
219       command, captures its STDOUT and STDERR streams, and passes them to the
220       given continuation. For more detail see the "run_child()" method on the
221       IO::Async::ChildManager class.
222
223   $loop->resolve( %params )
224       This method performs a single name resolution operation. It uses an
225       internally-stored "IO::Async::Resolver" object. For more detail, see
226       the "resolve()" method on the IO::Async::Resolver class.
227
228   $loop->connect( %params )
229       This method performs a non-blocking connect operation. It uses an
230       internally-stored "IO::Async::Connector" object. For more detail, see
231       the "connect()" method on the IO::Async::Connector class.
232
233   $loop->listen( %params )
234       This method sets up a listening socket. It creates an instance of
235       IO::Async::Listener and adds it to the Loop.
236
237       Most parameters given to this method are passed into the constructed
238       Listener object's "listen" method. In addition, the following arguments
239       are also recognised directly:
240
241       on_listen => CODE
242               Optional. A callback that is invoked when the listening socket
243               is ready.  Typically this would be used in the name resolver
244               case, in order to inspect the socket's sockname address, or
245               otherwise inspect the filehandle.
246
247                $on_listen->( $socket )
248
249       on_notifier => CODE
250               Optional. A callback that is invoked when the Listener object
251               is ready to receive connections. The callback is passed the
252               Listener object itself.
253
254                $on_notifier->( $listener )
255
256               If this callback is required, it may instead be better to
257               construct the Listener object directly.
258
259       An alternative which gives more control over the listener, is to create
260       the "IO::Async::Listener" object directly and add it explicitly to the
261       Loop.
262

OS ABSTRACTIONS

264       Because the Magic Constructor searches for OS-specific subclasses of
265       the Loop, several abstractions of OS services are provided, in case
266       specific OSes need to give different implementations on that OS.
267
268   ( $S1, $S2 ) = $loop->socketpair( $family, $socktype, $proto )
269       An abstraction of the "socketpair()" syscall, where any argument may be
270       missing (or given as "undef").
271
272       If $family is not provided, a suitable value will be provided by the OS
273       (likely "AF_UNIX" on POSIX-based platforms). If $socktype is not
274       provided, then "SOCK_STREAM" will be used.
275
276   ( $rd, $wr ) = $loop->pipepair()
277       An abstraction of the "pipe()" syscall, which returns the two new
278       handles.
279
280   ( $rdA, $wrA, $rdB, $wrB ) = $loop->pipequad()
281       This method is intended for creating two pairs of filehandles that are
282       linked together, suitable for passing as the STDIN/STDOUT pair to a
283       child process.  After this function returns, $rdA and $wrA will be a
284       linked pair, as will $rdB and $wrB.
285
286       On platforms that support "socketpair()", this implementation will be
287       preferred, in which case $rdA and $wrB will actually be the same
288       filehandle, as will $rdB and $wrA. This saves a file descriptor in the
289       parent process.
290
291       When creating a "IO::Async::Stream" or subclass of it, the
292       "read_handle" and "write_handle" parameters should always be used.
293
294        my ( $childRd, $myWr, $myRd, $childWr ) = $loop->pipequad();
295
296        $loop->open_child(
297           stdin  => $childRd,
298           stdout => $childWr,
299           ...
300        );
301
302        my $str = IO::Async::Stream->new(
303           read_handle  => $myRd,
304           write_handle => $myWr,
305           ...
306        );
307        $loop->add( $str );
308
309   $signum = $loop->signame2num( $signame )
310       This utility method converts a signal name (such as "TERM") into its
311       system- specific signal number. This may be useful to pass to
312       "POSIX::SigSet" or use in other places which use numbers instead of
313       symbolic names.
314

LOW-LEVEL METHODS

316       As "IO::Async::Loop" is an abstract base class, specific subclasses of
317       it are required to implement certain methods that form the base level
318       of functionallity. They are not recommended for applications to use;
319       see instead the various event objects or higher level methods listed
320       above.
321
322       These methods should be considered as part of the interface contract
323       required to implement a "IO::Async::Loop" subclass.
324
325   IO::Async::Loop->API_VERSION
326       This method will be called by the magic constructor on the class before
327       it is constructed, to ensure that the specific implementation will
328       support the required API. This method should return the API version
329       that the loop implementation supports. The magic constructor will use
330       that class, provided it declares a version at least as new as the
331       version documented here.
332
333       The current API version is 0.24.
334
335       This method may be implemented using "constant"; e.g
336
337        use constant API_VERSION => '0.24';
338
339   $loop->watch_io( %params )
340       This method installs callback functions which will be invoked when the
341       given IO handle becomes read- or write-ready.
342
343       The %params hash takes the following keys:
344
345       handle => IO
346               The IO handle to watch.
347
348       on_read_ready => CODE
349               Optional. A CODE reference to call when the handle becomes
350               read-ready.
351
352       on_write_ready => CODE
353               Optional. A CODE reference to call when the handle becomes
354               write-ready.
355
356       There can only be one filehandle of any given fileno registered at any
357       one time. For any one filehandle, there can only be one read-readiness
358       and/or one write-readiness callback at any one time. Registering a new
359       one will remove an existing one of that type. It is not required that
360       both are provided.
361
362       Applications should use a "IO::Async::Handle" or "IO::Async::Stream"
363       instead of using this method.
364
365   $loop->unwatch_io( %params )
366       This method removes a watch on an IO handle which was previously
367       installed by "watch_io".
368
369       The %params hash takes the following keys:
370
371       handle => IO
372               The IO handle to remove the watch for.
373
374       on_read_ready => BOOL
375               If true, remove the watch for read-readiness.
376
377       on_write_ready => BOOL
378               If true, remove the watch for write-readiness.
379
380       Either or both callbacks may be removed at once. It is not an error to
381       attempt to remove a callback that is not present. If both callbacks
382       were provided to the "watch_io" method and only one is removed by this
383       method, the other shall remain.
384
385   $loop->watch_signal( $signal, $code )
386       This method adds a new signal handler to watch the given signal.
387
388       $signal The name of the signal to watch to. This should be a bare name
389               like "TERM".
390
391       $code   A CODE reference to the handling callback.
392
393       There can only be one callback per signal name. Registering a new one
394       will remove an existing one.
395
396       Applications should use a "IO::Async::Signal" object, or call
397       "attach_signal" instead of using this method.
398
399       This and "unwatch_signal" are optional; a subclass may implement
400       neither, or both. If it implements neither then signal handling will be
401       performed by the base class using a self-connected pipe to interrupt
402       the main IO blocking.
403
404   $loop->unwatch_signal( $signal )
405       This method removes the signal callback for the given signal.
406
407       $signal The name of the signal to watch to. This should be a bare name
408               like "TERM".
409
410   $id = $loop->enqueue_timer( %params )
411       This method installs a callback which will be called at the specified
412       time.  The time may either be specified as an absolute value (the
413       "time" key), or as a delay from the time it is installed (the "delay"
414       key).
415
416       The returned $id value can be used to identify the timer in case it
417       needs to be cancelled by the "cancel_timer()" method. Note that this
418       value may be an object reference, so if it is stored, it should be
419       released after it has been fired or cancelled, so the object itself can
420       be freed.
421
422       The %params hash takes the following keys:
423
424       time => NUM
425               The absolute system timestamp to run the event.
426
427       delay => NUM
428               The delay after now at which to run the event, if "time" is not
429               supplied. A zero or negative delayed timer should be executed
430               as soon as possible; the next time the "loop_once()" method is
431               invoked.
432
433       now => NUM
434               The time to consider as now if calculating an absolute time
435               based on "delay"; defaults to "time()" if not specified.
436
437       code => CODE
438               CODE reference to the continuation to run at the allotted time.
439
440       Either one of "time" or "delay" is required.
441
442       For more powerful timer functionallity as a "IO::Async::Notifier" (so
443       it can be used as a child within another Notifier), see instead the
444       IO::Async::Timer object and its subclasses.
445
446       These *_timer methods are optional; a subclass may implement none or
447       all of them. If it implements none, then the base class will manage a
448       queue of timer events. This queue should be handled by the "loop_once"
449       method implemented by the subclass, using the "_adjust_timeout" and
450       "_manage_queues" methods.
451
452   $loop->cancel_timer( $id )
453       Cancels a previously-enqueued timer event by removing it from the
454       queue.
455
456   $newid = $loop->requeue_timer( $id, %params )
457       Reschedule an existing timer, moving it to a new time. The old timer is
458       removed and will not be invoked.
459
460       The %params hash takes the same keys as "enqueue_timer()", except for
461       the "code" argument.
462
463       The requeue operation may be implemented as a cancel + enqueue, which
464       may mean the ID changes. Be sure to store the returned $newid value if
465       it is required.
466
467   $id = $loop->watch_idle( %params )
468       This method installs a callback which will be called at some point in
469       the near future.
470
471       The %params hash takes the following keys:
472
473       when => STRING
474               Specifies the time at which the callback will be invoked. See
475               below.
476
477       code => CODE
478               CODE reference to the continuation to run at the allotted time.
479
480       The "when" parameter defines the time at which the callback will later
481       be invoked. Must be one of the following values:
482
483       later   Callback is invoked after the current round of IO events have
484               been processed by the loop's underlying "loop_once" method.
485
486               If a new idle watch is installed from within a "later"
487               callback, the installed one will not be invoked during this
488               round. It will be deferred for the next time "loop_once" is
489               called, after any IO events have been handled.
490
491       If there are pending idle handlers, then the "loop_once" method will
492       use a zero timeout; it will return immediately, having processed any IO
493       events and idle handlers.
494
495       The returned $id value can be used to identify the idle handler in case
496       it needs to be removed, by calling the "unwatch_idle" method. Note this
497       value may be a reference, so if it is stored it should be released
498       after the callback has been invoked or cancled, so the referrant itself
499       can be freed.
500
501       This and "unwatch_idle" are optional; a subclass may implement neither,
502       or both. If it implements neither then idle handling will be performed
503       by the base class, using the "_adjust_timeout" and "_manage_queues"
504       methods.
505
506   $loop->unwatch_idle( $id )
507       Cancels a previously-installed idle handler.
508
509   $loop->watch_child( $pid, $code )
510       This method adds a new handler for the termination of the given child
511       process PID.
512
513       $pid    The PID to watch.
514
515       $code   A CODE reference to the exit handler. It will be invoked as
516
517                $code->( $pid, $? )
518
519               The second argument is passed the plain perl $? value. To use
520               that usefully, see "WEXITSTATUS()" and others from "POSIX".
521
522       After invocation, the handler is automatically removed.
523
524       This and "unwatch_child" are optional; a subclass may implement
525       neither, or both. If it implements neither then child watching will be
526       performed by using "watch_signal" to install a "SIGCHLD" handler, which
527       will use "waitpid" to look for exited child processes.
528
529   $loop->unwatch_child( $pid )
530       This method removes a watch on an existing child process PID.
531

METHODS FOR SUBCLASSES

533       The following methods are provided to access internal features which
534       are required by specific subclasses to implement the loop
535       functionallity. The use cases of each will be documented in the above
536       section.
537
538   $loop->_adjust_timeout( \$timeout )
539       Shortens the timeout value passed in the scalar reference if it is
540       longer in seconds than the time until the next queued event on the
541       timer queue. If there are pending idle handlers, the timeout is reduced
542       to zero.
543
544   $loop->_manage_queues
545       Checks the timer queue for callbacks that should have been invoked by
546       now, and runs them all, removing them from the queue. It also invokes
547       all of the pending idle handlers. Any new idle handlers installed by
548       these are not invoked yet; they will wait for the next time this method
549       is called.
550

AUTHOR

552       Paul Evans <leonerd@leonerd.org.uk>
553
554
555
556perl v5.12.1                      2010-06-09                IO::Async::Loop(3)
Impressum