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_for_stdin(
22           on_read => sub {
23              my ( $self, $buffref, $eof ) = @_;
24
25              while( $$buffref =~ s/^(.*)\n// ) {
26                 print "You typed a line $1\n";
27              }
28
29              return 0;
30           },
31        ) );
32
33        $loop->run;
34

DESCRIPTION

36       This module provides an abstract class which implements the core loop
37       of the IO::Async framework. Its primary purpose is to store a set of
38       IO::Async::Notifier objects or subclasses of them. It handles all of
39       the lower-level set manipulation actions, and leaves the actual IO
40       readiness testing/notification to the concrete class that implements
41       it. It also provides other functionality such as signal handling, child
42       process managing, and timers.
43
44       See also the two bundled Loop subclasses:
45
46       IO::Async::Loop::Select
47       IO::Async::Loop::Poll
48
49       Or other subclasses that may appear on CPAN which are not part of the
50       core IO::Async distribution.
51
52   Ignoring SIGPIPE
53       Since version 0.66 loading this module automatically ignores "SIGPIPE",
54       as it is highly unlikely that the default-terminate action is the best
55       course of action for an IO::Async-based program to take. If at load
56       time the handler disposition is still set as "DEFAULT", it is set to
57       ignore. If already another handler has been placed there by the program
58       code, it will be left undisturbed.
59

MAGIC CONSTRUCTOR

61   new
62          $loop = IO::Async::Loop->new
63
64       This function attempts to find a good subclass to use, then calls its
65       constructor. It works by making a list of likely candidate classes,
66       then trying each one in turn, "require"ing the module then calling its
67       "new" method. If either of these operations fails, the next subclass is
68       tried. If no class was successful, then an exception is thrown.
69
70       The constructed object is cached, and will be returned again by a
71       subsequent call. The cache will also be set by a constructor on a
72       specific subclass. This behaviour makes it possible to simply use the
73       normal constructor in a module that wishes to interract with the main
74       program's Loop, such as an integration module for another event system.
75
76       For example, the following two $loop variables will refer to the same
77       object:
78
79        use IO::Async::Loop;
80        use IO::Async::Loop::Poll;
81
82        my $loop_poll = IO::Async::Loop::Poll->new;
83
84        my $loop = IO::Async::Loop->new;
85
86       While it is not advised to do so under normal circumstances, if the
87       program really wishes to construct more than one Loop object, it can
88       call the constructor "really_new", or invoke one of the subclass-
89       specific constructors directly.
90
91       The list of candidates is formed from the following choices, in this
92       order:
93
94       ·   $ENV{IO_ASYNC_LOOP}
95
96           If this environment variable is set, it should contain a comma-
97           separated list of subclass names. These names may or may not be
98           fully-qualified; if a name does not contain "::" then it will have
99           "IO::Async::Loop::" prepended to it.  This allows the end-user to
100           specify a particular choice to fit the needs of his use of a
101           program using IO::Async.
102
103       ·   $IO::Async::Loop::LOOP
104
105           If this scalar is set, it should contain a comma-separated list of
106           subclass names. These may or may not be fully-qualified, as with
107           the above case. This allows a program author to suggest a loop
108           module to use.
109
110           In cases where the module subclass is a hard requirement, such as
111           GTK programs using "Glib", it would be better to use the module
112           specifically and invoke its constructor directly.
113
114       ·   IO::Async::OS->LOOP_PREFER_CLASSES
115
116           The IO::Async::OS hints module for the given OS is then consulted
117           to see if it suggests any other module classes specific to the
118           given operating system.
119
120       ·   $^O
121
122           The module called "IO::Async::Loop::$^O" is tried next. This allows
123           specific OSes, such as the ever-tricky "MSWin32", to provide an
124           implementation that might be more efficient than the generic ones,
125           or even work at all.
126
127           This option is now discouraged in favour of the IO::Async::OS hint
128           instead.  At some future point it may be removed entirely, given as
129           currently only "linux" uses it.
130
131       ·   Poll and Select
132
133           Finally, if no other choice has been made by now, the built-in
134           "Poll" module is chosen. This should always work, but in case it
135           doesn't, the "Select" module will be chosen afterwards as a last-
136           case attempt. If this also fails, then the magic constructor itself
137           will throw an exception.
138
139       If any of the explicitly-requested loop types ($ENV{IO_ASYNC_LOOP} or
140       $IO::Async::Loop::LOOP) fails to load then a warning is printed
141       detailing the error.
142
143       Implementors of new "IO::Async::Loop" subclasses should see the notes
144       about "API_VERSION" below.
145

NOTIFIER MANAGEMENT

147       The following methods manage the collection of IO::Async::Notifier
148       objects.
149
150   add
151          $loop->add( $notifier )
152
153       This method adds another notifier object to the stored collection. The
154       object may be a IO::Async::Notifier, or any subclass of it.
155
156       When a notifier is added, any children it has are also added,
157       recursively. In this way, entire sections of a program may be written
158       within a tree of notifier objects, and added or removed on one piece.
159
160   remove
161          $loop->remove( $notifier )
162
163       This method removes a notifier object from the stored collection, and
164       recursively and children notifiers it contains.
165
166   notifiers
167          @notifiers = $loop->notifiers
168
169       Returns a list of all the notifier objects currently stored in the
170       Loop.
171

LOOPING CONTROL

173       The following methods control the actual run cycle of the loop, and
174       hence the program.
175
176   loop_once
177          $count = $loop->loop_once( $timeout )
178
179       This method performs a single wait loop using the specific subclass's
180       underlying mechanism. If $timeout is undef, then no timeout is applied,
181       and it will wait until an event occurs. The intention of the return
182       value is to indicate the number of callbacks that this loop executed,
183       though different subclasses vary in how accurately they can report
184       this. See the documentation for this method in the specific subclass
185       for more information.
186
187   run
188          @result = $loop->run
189
190          $result = $loop->run
191
192       Runs the actual IO event loop. This method blocks until the "stop"
193       method is called, and returns the result that was passed to "stop". In
194       scalar context only the first result is returned; the others will be
195       discarded if more than one value was provided. This method may be
196       called recursively.
197
198       This method is a recent addition and may not be supported by all the
199       "IO::Async::Loop" subclasses currently available on CPAN.
200
201   stop
202          $loop->stop( @result )
203
204       Stops the inner-most "run" method currently in progress, causing it to
205       return the given @result.
206
207       This method is a recent addition and may not be supported by all the
208       "IO::Async::Loop" subclasses currently available on CPAN.
209
210   loop_forever
211          $loop->loop_forever
212
213       A synonym for "run", though this method does not return a result.
214
215   loop_stop
216          $loop->loop_stop
217
218       A synonym for "stop", though this method does not pass any results.
219
220   post_fork
221          $loop->post_fork
222
223       The base implementation of this method does nothing. It is provided in
224       case some Loop subclasses should take special measures after a "fork()"
225       system call if the main body of the program should survive in both
226       running processes.
227
228       This may be required, for example, in a long-running server daemon that
229       forks multiple copies on startup after opening initial listening
230       sockets. A loop implementation that uses some in-kernel resource that
231       becomes shared after forking (for example, a Linux "epoll" or a BSD
232       "kqueue" filehandle) would need recreating in the new child process
233       before the program can continue.
234

FUTURE SUPPORT

236       The following methods relate to IO::Async::Future objects.
237
238   new_future
239          $future = $loop->new_future
240
241       Returns a new IO::Async::Future instance with a reference to the Loop.
242
243   await
244          $loop->await( $future )
245
246       Blocks until the given future is ready, as indicated by its "is_ready"
247       method.  As a convenience it returns the future, to simplify code:
248
249        my @result = $loop->await( $future )->get;
250
251   await_all
252          $loop->await_all( @futures )
253
254       Blocks until all the given futures are ready, as indicated by the
255       "is_ready" method. Equivalent to calling "await" on a
256       "Future->wait_all" except that it doesn't create the surrounding future
257       object.
258
259   delay_future
260          $loop->delay_future( %args )->get
261
262       Returns a new IO::Async::Future instance which will become done at a
263       given point in time. The %args should contain an "at" or "after" key as
264       per the "watch_time" method. The returned future may be cancelled to
265       cancel the timer. At the alloted time the future will succeed with an
266       empty result list.
267
268   timeout_future
269          $loop->timeout_future( %args )->get
270
271       Returns a new IO::Async::Future instance which will fail at a given
272       point in time. The %args should contain an "at" or "after" key as per
273       the "watch_time" method. The returned future may be cancelled to cancel
274       the timer. At the alloted time, the future will fail with the string
275       "Timeout".
276

FEATURES

278       Most of the following methods are higher-level wrappers around base
279       functionality provided by the low-level API documented below. They may
280       be used by IO::Async::Notifier subclasses or called directly by the
281       program.
282
283       The following methods documented with a trailing call to "->get" return
284       Future instances.
285
286   attach_signal
287          $id = $loop->attach_signal( $signal, $code )
288
289       This method adds a new signal handler to watch the given signal. The
290       same signal can be attached to multiple times; its callback functions
291       will all be invoked, in no particular order.
292
293       The returned $id value can be used to identify the signal handler in
294       case it needs to be removed by the "detach_signal" method. Note that
295       this value may be an object reference, so if it is stored, it should be
296       released after it is cancelled, so the object itself can be freed.
297
298       $signal The name of the signal to attach to. This should be a bare name
299               like "TERM".
300
301       $code   A CODE reference to the handling callback.
302
303       Attaching to "SIGCHLD" is not recommended because of the way all child
304       processes use it to report their termination. Instead, the
305       "watch_child" method should be used to watch for termination of a given
306       child process. A warning will be printed if "SIGCHLD" is passed here,
307       but in future versions of IO::Async this behaviour may be disallowed
308       altogether.
309
310       See also POSIX for the "SIGname" constants.
311
312       For a more flexible way to use signals from within Notifiers, see
313       instead the IO::Async::Signal object.
314
315   detach_signal
316          $loop->detach_signal( $signal, $id )
317
318       Removes a previously-attached signal handler.
319
320       $signal The name of the signal to remove from. This should be a bare
321               name like "TERM".
322
323       $id     The value returned by the "attach_signal" method.
324
325   later
326          $loop->later( $code )
327
328       Schedules a code reference to be invoked as soon as the current round
329       of IO operations is complete.
330
331       The code reference is never invoked immediately, though the loop will
332       not perform any blocking operations between when it is installed and
333       when it is invoked. It may call "select", "poll" or equivalent with a
334       zero-second timeout, and process any currently-pending IO conditions
335       before the code is invoked, but it will not block for a non-zero amount
336       of time.
337
338       This method is implemented using the "watch_idle" method, with the
339       "when" parameter set to "later". It will return an ID value that can be
340       passed to "unwatch_idle" if required.
341
342   spawn_child
343          $loop->spawn_child( %params )
344
345       This method creates a new child process to run a given code block or
346       command.  The %params hash takes the following keys:
347
348       command => ARRAY or STRING
349               Either a reference to an array containing the command and its
350               arguments, or a plain string containing the command. This value
351               is passed into perl's "exec" function.
352
353       code => CODE
354               A block of code to execute in the child process. It will be
355               called in scalar context inside an "eval" block.
356
357       setup => ARRAY
358               A reference to an array which gives file descriptors to set up
359               in the child process before running the code or command. See
360               below.
361
362       on_exit => CODE
363               A continuation to be called when the child processes exits. It
364               will be invoked in the following way:
365
366                $on_exit->( $pid, $exitcode, $dollarbang, $dollarat )
367
368               The second argument is passed the plain perl $? value.
369
370       Exactly one of the "command" or "code" keys must be specified.
371
372       If the "command" key is used, the given array or string is executed
373       using the "exec" function.
374
375       If the "code" key is used, the return value will be used as the exit(2)
376       code from the child if it returns (or 255 if it returned "undef" or
377       thows an exception).
378
379        Case          | ($exitcode >> 8)       | $dollarbang | $dollarat
380        --------------+------------------------+-------------+----------
381        exec succeeds | exit code from program |     0       |    ""
382        exec fails    |         255            |     $!      |    ""
383        $code returns |     return value       |     $!      |    ""
384        $code dies    |         255            |     $!      |    $@
385
386       It is usually more convenient to use the "open_process" method in
387       simple cases where an external program is being started in order to
388       interact with it via file IO, or even "run_child" when only the final
389       result is required, rather than interaction while it is running.
390
391       "setup" array
392
393       This array gives a list of file descriptor operations to perform in the
394       child process after it has been fork(2)ed from the parent, before
395       running the code or command. It consists of name/value pairs which are
396       ordered; the operations are performed in the order given.
397
398       fdn => ARRAY
399               Gives an operation on file descriptor n. The first element of
400               the array defines the operation to be performed:
401
402               [ 'close' ]
403                   The file descriptor will be closed.
404
405               [ 'dup', $io ]
406                   The file descriptor will be dup2(2)ed from the given IO
407                   handle.
408
409               [ 'open', $mode, $file ]
410                   The file descriptor will be opened from the named file in
411                   the given mode. The $mode string should be in the form
412                   usually given to the "open" function; such as '<' or '>>'.
413
414               [ 'keep' ]
415                   The file descriptor will not be closed; it will be left as-
416                   is.
417
418               A non-reference value may be passed as a shortcut, where it
419               would contain the name of the operation with no arguments (i.e.
420               for the "close" and "keep" operations).
421
422       IO => ARRAY
423               Shortcut for passing "fdn", where n is the fileno of the IO
424               reference. In this case, the key must be a reference that
425               implements the "fileno" method. This is mostly useful for
426
427                $handle => 'keep'
428
429       fdn => IO
430               A shortcut for the "dup" case given above.
431
432       stdin => ...
433       stdout => ...
434       stderr => ...
435               Shortcuts for "fd0", "fd1" and "fd2" respectively.
436
437       env => HASH
438               A reference to a hash to set as the child process's
439               environment.
440
441               Note that this will entirely set a new environment, completely
442               replacing the existing one. If you want to simply add new keys
443               or change the values of some keys without removing the other
444               existing ones, you can simply copy %ENV into the hash before
445               setting new keys:
446
447                env => {
448                   %ENV,
449                   ANOTHER => "key here",
450                }
451
452       nice => INT
453               Change the child process's scheduling priority using
454               "POSIX::nice".
455
456       chdir => STRING
457               Change the child process's working directory using "chdir".
458
459       setuid => INT
460       setgid => INT
461               Change the child process's effective UID or GID.
462
463       setgroups => ARRAY
464               Change the child process's groups list, to those groups whose
465               numbers are given in the ARRAY reference.
466
467               On most systems, only the privileged superuser change user or
468               group IDs.  IO::Async will NOT check before detaching the child
469               process whether this is the case.
470
471               If setting both the primary GID and the supplementary groups
472               list, it is suggested to set the primary GID first. Moreover,
473               some operating systems may require that the supplementary
474               groups list contains the primary GID.
475
476       If no directions for what to do with "stdin", "stdout" and "stderr" are
477       given, a default of "keep" is implied. All other file descriptors will
478       be closed, unless a "keep" operation is given for them.
479
480       If "setuid" is used, be sure to place it after any other operations
481       that might require superuser privileges, such as "setgid" or opening
482       special files.
483
484          my ( $pipeRd, $pipeWr ) = IO::Async::OS->pipepair;
485          $loop->spawn_child(
486             command => "/usr/bin/my-command",
487
488             setup => [
489                stdin  => [ "open", "<", "/dev/null" ],
490                stdout => $pipeWr,
491                stderr => [ "open", ">>", "/var/log/mycmd.log" ],
492                chdir  => "/",
493             ]
494
495             on_exit => sub {
496                my ( $pid, $exitcode ) = @_;
497                my $status = ( $exitcode >> 8 );
498                print "Command exited with status $status\n";
499             },
500          );
501
502          $loop->spawn_child(
503             code => sub {
504                do_something; # executes in a child process
505                return 1;
506             },
507
508             on_exit => sub {
509                my ( $pid, $exitcode, $dollarbang, $dollarat ) = @_;
510                my $status = ( $exitcode >> 8 );
511                print "Child process exited with status $status\n";
512                print " OS error was $dollarbang, exception was $dollarat\n";
513             },
514          );
515
516   open_process
517          $process = $loop->open_process( %params )
518
519       Since version 0.72.
520
521       This creates a new child process to run the given code block or
522       command, and attaches filehandles to it that the parent will watch.
523       This method is a light wrapper around constructing a new
524       IO::Async::Process object, adding it to the loop, and returning it.
525
526       The %params hash is passed directly to the IO::Async::Process
527       constructor.
528
529   open_child
530          $pid = $loop->open_child( %params )
531
532       A back-compatibility wrapper to calling "open_process" and returning
533       the PID of the newly-constructed IO::Async::Process instance. The
534       "on_finish" continuation likewise will be invoked with the PID rather
535       than the process instance.
536
537          $on_finish->( $pid, $exitcode )
538
539       Similarly, a "on_error" continuation is accepted, though note its
540       arguments come in a different order to those of the Process's
541       "on_exception":
542
543          $on_error->( $pid, $exitcode, $errno, $exception )
544
545       This method should not be used in new code; instead use "open_process"
546       directly.
547
548   run_process
549          @results = $loop->run_process( %params )->get
550
551          ( $exitcode, $stdout ) = $loop->run_process( ... )->get  # by default
552
553       Since version 0.73.
554
555       Creates a new child process to run the given code block or command,
556       optionally capturing its STDOUT and STDERR streams. By default the
557       returned future will yield the exit code and content of the STDOUT
558       stream, but the "capture" argument can be used to alter what is
559       requested and returned.
560
561       command => ARRAY or STRING
562       code => CODE
563               The command or code to run in the child process (as per the
564               "spawn_child" method)
565
566       stdin => STRING
567               Optional. String to pass in to the child process's STDIN
568               stream.
569
570       setup => ARRAY
571               Optional reference to an array to pass to the underlying
572               "spawn" method.
573
574       capture => ARRAY
575               Optional reference to an array giving a list of names of values
576               which should be returned by resolving future. Values will be
577               returned in the same order as in the list. Valid choices are:
578               "exitcode", "stdout", "stderr".
579
580       cancel_signal => STRING
581               Optional. Name (or number) of the signal to send to the process
582               if the returned future is cancelled. Defaults to "TERM". Use
583               empty string or zero disable sending a signal on cancellation.
584
585       fail_on_nonzero => BOOL
586               Optional. If true, the returned future will fail if the process
587               exits with a nonzero status. The failure will contain a
588               message, the "process" category name, and the capture values
589               that were requested.
590
591                  Future->fail( $message, process => @captures )
592
593       This method is intended mainly as an IO::Async-compatible replacement
594       for the perl "readpipe" function (`backticks`), allowing it to replace
595
596          my $output = `command here`;
597
598       with
599
600          my ( $exitcode, $output ) = $loop->run_process(
601             command => "command here",
602          )->get;
603
604          my ( $exitcode, $stdout ) = $loop->run_process(
605             command => "/bin/ps",
606          )->get;
607
608          my $status = ( $exitcode >> 8 );
609          print "ps exited with status $status\n";
610
611   run_child
612          $pid = $loop->run_child( %params )
613
614       A back-compatibility wrapper for "run_process", returning the PID and
615       taking an "on_finish" continuation instead of returning a Future.
616
617       This creates a new child process to run the given code block or
618       command, capturing its STDOUT and STDERR streams. When the process
619       exits, a continuation is invoked being passed the exitcode, and content
620       of the streams.
621
622       Takes the following named arguments in addition to those taken by
623       "run_process":
624
625       on_finish => CODE
626               A continuation to be called when the child process exits and
627               closed its STDOUT and STDERR streams. It will be invoked in the
628               following way:
629
630                $on_finish->( $pid, $exitcode, $stdout, $stderr )
631
632               The second argument is passed the plain perl $? value.
633
634       This method should not be used in new code; intead use "run_process"
635       directly.
636
637   resolver
638          $loop->resolver
639
640       Returns the internally-stored IO::Async::Resolver object, used for name
641       resolution operations by the "resolve", "connect" and "listen" methods.
642
643   set_resolver
644          $loop->set_resolver( $resolver )
645
646       Sets the internally-stored IO::Async::Resolver object. In most cases
647       this method should not be required, but it may be used to provide an
648       alternative resolver for special use-cases.
649
650   resolve
651          @result = $loop->resolve( %params )->get
652
653       This method performs a single name resolution operation. It uses an
654       internally-stored IO::Async::Resolver object. For more detail, see the
655       "resolve" method on the IO::Async::Resolver class.
656
657   connect
658          $handle|$socket = $loop->connect( %params )->get
659
660       This method performs a non-blocking connection to a given address or
661       set of addresses, returning a IO::Async::Future which represents the
662       operation. On completion, the future will yield the connected socket
663       handle, or the given IO::Async::Handle object.
664
665       There are two modes of operation. Firstly, a list of addresses can be
666       provided which will be tried in turn. Alternatively as a convenience,
667       if a host and service name are provided instead of a list of addresses,
668       these will be resolved using the underlying loop's "resolve" method
669       into the list of addresses.
670
671       When attempting to connect to any among a list of addresses, there may
672       be failures among the first attempts, before a valid connection is
673       made. For example, the resolver may have returned some IPv6 addresses,
674       but only IPv4 routes are valid on the system. In this case, the first
675       connect(2) syscall will fail. This isn't yet a fatal error, if there
676       are more addresses to try, perhaps some IPv4 ones.
677
678       For this reason, it is possible that the operation eventually succeeds
679       even though some system calls initially fail. To be aware of individual
680       failures, the optional "on_fail" callback can be used. This will be
681       invoked on each individual socket(2) or connect(2) failure, which may
682       be useful for debugging or logging.
683
684       Because this module simply uses the "getaddrinfo" resolver, it will be
685       fully IPv6-aware if the underlying platform's resolver is. This allows
686       programs to be fully IPv6-capable.
687
688       In plain address mode, the %params hash takes the following keys:
689
690       addrs => ARRAY
691               Reference to an array of (possibly-multiple) address structures
692               to attempt to connect to. Each should be in the layout
693               described for "addr". Such a layout is returned by the
694               "getaddrinfo" named resolver.
695
696       addr => HASH or ARRAY
697               Shortcut for passing a single address to connect to; it may be
698               passed directly with this key, instead of in another array on
699               its own. This should be in a format recognised by
700               IO::Async::OS's "extract_addrinfo" method.
701
702               This example shows how to use the "Socket" functions to
703               construct one for TCP port 8001 on address 10.0.0.1:
704
705                $loop->connect(
706                   addr => {
707                      family   => "inet",
708                      socktype => "stream",
709                      port     => 8001,
710                      ip       => "10.0.0.1",
711                   },
712                   ...
713                );
714
715               This example shows another way to connect to a UNIX socket at
716               echo.sock.
717
718                $loop->connect(
719                   addr => {
720                      family   => "unix",
721                      socktype => "stream",
722                      path     => "echo.sock",
723                   },
724                   ...
725                );
726
727       local_addrs => ARRAY
728       local_addr => HASH or ARRAY
729               Optional. Similar to the "addrs" or "addr" parameters, these
730               specify a local address or set of addresses to bind(2) the
731               socket to before connect(2)ing it.
732
733       When performing the resolution step too, the "addrs" or "addr" keys are
734       ignored, and instead the following keys are taken:
735
736       host => STRING
737       service => STRING
738               The hostname and service name to connect to.
739
740       local_host => STRING
741       local_service => STRING
742               Optional. The hostname and/or service name to bind(2) the
743               socket to locally before connecting to the peer.
744
745       family => INT
746       socktype => INT
747       protocol => INT
748       flags => INT
749               Optional. Other arguments to pass along with "host" and
750               "service" to the "getaddrinfo" call.
751
752       socktype => STRING
753               Optionally may instead be one of the values 'stream', 'dgram'
754               or 'raw' to stand for "SOCK_STREAM", "SOCK_DGRAM" or
755               "SOCK_RAW". This utility is provided to allow the caller to
756               avoid a separate "use Socket" only for importing these
757               constants.
758
759       It is necessary to pass the "socktype" hint to the resolver when
760       resolving the host/service names into an address, as some OS's
761       "getaddrinfo" functions require this hint. A warning is emitted if
762       neither "socktype" nor "protocol" hint is defined when performing a
763       "getaddrinfo" lookup. To avoid this warning while still specifying no
764       particular "socktype" hint (perhaps to invoke some OS-specific
765       behaviour), pass 0 as the "socktype" value.
766
767       In either case, it also accepts the following arguments:
768
769       handle => IO::Async::Handle
770               Optional. If given a IO::Async::Handle object or a subclass
771               (such as IO::Async::Stream or IO::Async::Socket its handle will
772               be set to the newly-connected socket on success, and that
773               handle used as the result of the future instead.
774
775       on_fail => CODE
776               Optional. After an individual socket(2) or connect(2) syscall
777               has failed, this callback is invoked to inform of the error. It
778               is passed the name of the syscall that failed, the arguments
779               that were passed to it, and the error it generated. I.e.
780
781                $on_fail->( "socket", $family, $socktype, $protocol, $! );
782
783                $on_fail->( "bind", $sock, $address, $! );
784
785                $on_fail->( "connect", $sock, $address, $! );
786
787               Because of the "try all" nature when given a list of multiple
788               addresses, this callback may be invoked multiple times, even
789               before an eventual success.
790
791       This method accepts an "extensions" parameter; see the "EXTENSIONS"
792       section below.
793
794   connect (void)
795          $loop->connect( %params )
796
797       When not returning a future, additional parameters can be given
798       containing the continuations to invoke on success or failure.
799
800       on_connected => CODE
801               A continuation that is invoked on a successful connect(2) call
802               to a valid socket. It will be passed the connected socket
803               handle, as an "IO::Socket" object.
804
805                $on_connected->( $handle )
806
807       on_stream => CODE
808               An alternative to "on_connected", a continuation that is passed
809               an instance of IO::Async::Stream when the socket is connected.
810               This is provided as a convenience for the common case that a
811               Stream object is required as the transport for a Protocol
812               object.
813
814                $on_stream->( $stream )
815
816       on_socket => CODE
817               Similar to "on_stream", but constructs an instance of
818               IO::Async::Socket.  This is most useful for "SOCK_DGRAM" or
819               "SOCK_RAW" sockets.
820
821                $on_socket->( $socket )
822
823       on_connect_error => CODE
824               A continuation that is invoked after all of the addresses have
825               been tried, and none of them succeeded. It will be passed the
826               most significant error that occurred, and the name of the
827               operation it occurred in. Errors from the connect(2) syscall
828               are considered most significant, then bind(2), then finally
829               socket(2).
830
831                $on_connect_error->( $syscall, $! )
832
833       on_resolve_error => CODE
834               A continuation that is invoked when the name resolution attempt
835               fails. This is invoked in the same way as the "on_error"
836               continuation for the "resolve" method.
837
838   listen
839          $listener = $loop->listen( %params )->get
840
841       This method sets up a listening socket and arranges for an acceptor
842       callback to be invoked each time a new connection is accepted on the
843       socket. Internally it creates an instance of IO::Async::Listener and
844       adds it to the Loop if not given one in the arguments.
845
846       Addresses may be given directly, or they may be looked up using the
847       system's name resolver, or a socket handle may be given directly.
848
849       If multiple addresses are given, or resolved from the service and
850       hostname, then each will be attempted in turn until one succeeds.
851
852       In named resolver mode, the %params hash takes the following keys:
853
854       service => STRING
855               The service name to listen on.
856
857       host => STRING
858               The hostname to listen on. Optional. Will listen on all
859               addresses if not supplied.
860
861       family => INT
862       socktype => INT
863       protocol => INT
864       flags => INT
865               Optional. Other arguments to pass along with "host" and
866               "service" to the "getaddrinfo" call.
867
868       socktype => STRING
869               Optionally may instead be one of the values 'stream', 'dgram'
870               or 'raw' to stand for "SOCK_STREAM", "SOCK_DGRAM" or
871               "SOCK_RAW". This utility is provided to allow the caller to
872               avoid a separate "use Socket" only for importing these
873               constants.
874
875       It is necessary to pass the "socktype" hint to the resolver when
876       resolving the host/service names into an address, as some OS's
877       "getaddrinfo" functions require this hint. A warning is emitted if
878       neither "socktype" nor "protocol" hint is defined when performing a
879       "getaddrinfo" lookup. To avoid this warning while still specifying no
880       particular "socktype" hint (perhaps to invoke some OS-specific
881       behaviour), pass 0 as the "socktype" value.
882
883       In plain address mode, the %params hash takes the following keys:
884
885       addrs => ARRAY
886               Reference to an array of (possibly-multiple) address structures
887               to attempt to listen on. Each should be in the layout described
888               for "addr". Such a layout is returned by the "getaddrinfo"
889               named resolver.
890
891       addr => ARRAY
892               Shortcut for passing a single address to listen on; it may be
893               passed directly with this key, instead of in another array of
894               its own. This should be in a format recognised by
895               IO::Async::OS's "extract_addrinfo" method. See also the
896               "EXAMPLES" section.
897
898       In direct socket handle mode, the following keys are taken:
899
900       handle => IO
901               The listening socket handle.
902
903       In either case, the following keys are also taken:
904
905       on_fail => CODE
906               Optional. A callback that is invoked if a syscall fails while
907               attempting to create a listening sockets. It is passed the name
908               of the syscall that failed, the arguments that were passed to
909               it, and the error generated. I.e.
910
911                $on_fail->( "socket", $family, $socktype, $protocol, $! );
912
913                $on_fail->( "sockopt", $sock, $optname, $optval, $! );
914
915                $on_fail->( "bind", $sock, $address, $! );
916
917                $on_fail->( "listen", $sock, $queuesize, $! );
918
919       queuesize => INT
920               Optional. The queue size to pass to the listen(2) calls. If not
921               supplied, then 3 will be given instead.
922
923       reuseaddr => BOOL
924               Optional. If true or not supplied then the "SO_REUSEADDR"
925               socket option will be set. To prevent this, pass a false value
926               such as 0.
927
928       v6only => BOOL
929               Optional. If defined, sets or clears the "IPV6_V6ONLY" socket
930               option on "PF_INET6" sockets. This option disables the ability
931               of "PF_INET6" socket to accept connections from "AF_INET"
932               addresses. Not all operating systems allow this option to be
933               disabled.
934
935       An alternative which gives more control over the listener, is to create
936       the IO::Async::Listener object directly and add it explicitly to the
937       Loop.
938
939       This method accepts an "extensions" parameter; see the "EXTENSIONS"
940       section below.
941
942   listen (void)
943          $loop->listen( %params )
944
945       When not returning a future, additional parameters can be given
946       containing the continuations to invoke on success or failure.
947
948       on_notifier => CODE
949               Optional. A callback that is invoked when the Listener object
950               is ready to receive connections. The callback is passed the
951               Listener object itself.
952
953                $on_notifier->( $listener )
954
955               If this callback is required, it may instead be better to
956               construct the Listener object directly.
957
958       on_listen => CODE
959               Optional. A callback that is invoked when the listening socket
960               is ready.  Typically this would be used in the name resolver
961               case, in order to inspect the socket's sockname address, or
962               otherwise inspect the filehandle.
963
964                $on_listen->( $socket )
965
966       on_listen_error => CODE
967               A continuation this is invoked after all of the addresses have
968               been tried, and none of them succeeded. It will be passed the
969               most significant error that occurred, and the name of the
970               operation it occurred in. Errors from the listen(2) syscall are
971               considered most significant, then bind(2), then sockopt(2),
972               then finally socket(2).
973
974       on_resolve_error => CODE
975               A continuation that is invoked when the name resolution attempt
976               fails. This is invoked in the same way as the "on_error"
977               continuation for the "resolve" method.
978

OS ABSTRACTIONS

980       Because the Magic Constructor searches for OS-specific subclasses of
981       the Loop, several abstractions of OS services are provided, in case
982       specific OSes need to give different implementations on that OS.
983
984   signame2num
985          $signum = $loop->signame2num( $signame )
986
987       Legacy wrappers around IO::Async::OS functions.
988
989   time
990          $time = $loop->time
991
992       Returns the current UNIX time in fractional seconds. This is currently
993       equivalent to "Time::HiRes::time" but provided here as a utility for
994       programs to obtain the time current used by IO::Async for its own
995       timing purposes.
996
997   fork
998          $pid = $loop->fork( %params )
999
1000       This method creates a new child process to run a given code block,
1001       returning its process ID.
1002
1003       code => CODE
1004               A block of code to execute in the child process. It will be
1005               called in scalar context inside an "eval" block. The return
1006               value will be used as the exit(2) code from the child if it
1007               returns (or 255 if it returned "undef" or thows an exception).
1008
1009       on_exit => CODE
1010               A optional continuation to be called when the child processes
1011               exits. It will be invoked in the following way:
1012
1013                $on_exit->( $pid, $exitcode )
1014
1015               The second argument is passed the plain perl $? value.
1016
1017               This key is optional; if not supplied, the calling code should
1018               install a handler using the "watch_child" method.
1019
1020       keep_signals => BOOL
1021               Optional boolean. If missing or false, any CODE references in
1022               the %SIG hash will be removed and restored back to "DEFAULT" in
1023               the child process. If true, no adjustment of the %SIG hash will
1024               be performed.
1025
1026   create_thread
1027          $tid = $loop->create_thread( %params )
1028
1029       This method creates a new (non-detached) thread to run the given code
1030       block, returning its thread ID.
1031
1032       code => CODE
1033               A block of code to execute in the thread. It is called in the
1034               context given by the "context" argument, and its return value
1035               will be available to the "on_joined" callback. It is called
1036               inside an "eval" block; if it fails the exception will be
1037               caught.
1038
1039       context => "scalar" | "list" | "void"
1040               Optional. Gives the calling context that "code" is invoked in.
1041               Defaults to "scalar" if not supplied.
1042
1043       on_joined => CODE
1044               Callback to invoke when the thread function returns or throws
1045               an exception.  If it returned, this callback will be invoked
1046               with its result
1047
1048                $on_joined->( return => @result )
1049
1050               If it threw an exception the callback is invoked with the value
1051               of $@
1052
1053                $on_joined->( died => $! )
1054

LOW-LEVEL METHODS

1056       As "IO::Async::Loop" is an abstract base class, specific subclasses of
1057       it are required to implement certain methods that form the base level
1058       of functionality. They are not recommended for applications to use; see
1059       instead the various event objects or higher level methods listed above.
1060
1061       These methods should be considered as part of the interface contract
1062       required to implement a "IO::Async::Loop" subclass.
1063
1064   API_VERSION
1065          IO::Async::Loop->API_VERSION
1066
1067       This method will be called by the magic constructor on the class before
1068       it is constructed, to ensure that the specific implementation will
1069       support the required API. This method should return the API version
1070       that the loop implementation supports. The magic constructor will use
1071       that class, provided it declares a version at least as new as the
1072       version documented here.
1073
1074       The current API version is 0.49.
1075
1076       This method may be implemented using "constant"; e.g
1077
1078        use constant API_VERSION => '0.49';
1079
1080   watch_io
1081          $loop->watch_io( %params )
1082
1083       This method installs callback functions which will be invoked when the
1084       given IO handle becomes read- or write-ready.
1085
1086       The %params hash takes the following keys:
1087
1088       handle => IO
1089               The IO handle to watch.
1090
1091       on_read_ready => CODE
1092               Optional. A CODE reference to call when the handle becomes
1093               read-ready.
1094
1095       on_write_ready => CODE
1096               Optional. A CODE reference to call when the handle becomes
1097               write-ready.
1098
1099       There can only be one filehandle of any given fileno registered at any
1100       one time. For any one filehandle, there can only be one read-readiness
1101       and/or one write-readiness callback at any one time. Registering a new
1102       one will remove an existing one of that type. It is not required that
1103       both are provided.
1104
1105       Applications should use a IO::Async::Handle or IO::Async::Stream
1106       instead of using this method.
1107
1108       If the filehandle does not yet have the "O_NONBLOCK" flag set, it will
1109       be enabled by this method. This will ensure that any subsequent
1110       "sysread", "syswrite", or similar will not block on the filehandle.
1111
1112   unwatch_io
1113          $loop->unwatch_io( %params )
1114
1115       This method removes a watch on an IO handle which was previously
1116       installed by "watch_io".
1117
1118       The %params hash takes the following keys:
1119
1120       handle => IO
1121               The IO handle to remove the watch for.
1122
1123       on_read_ready => BOOL
1124               If true, remove the watch for read-readiness.
1125
1126       on_write_ready => BOOL
1127               If true, remove the watch for write-readiness.
1128
1129       Either or both callbacks may be removed at once. It is not an error to
1130       attempt to remove a callback that is not present. If both callbacks
1131       were provided to the "watch_io" method and only one is removed by this
1132       method, the other shall remain.
1133
1134   watch_signal
1135          $loop->watch_signal( $signal, $code )
1136
1137       This method adds a new signal handler to watch the given signal.
1138
1139       $signal The name of the signal to watch to. This should be a bare name
1140               like "TERM".
1141
1142       $code   A CODE reference to the handling callback.
1143
1144       There can only be one callback per signal name. Registering a new one
1145       will remove an existing one.
1146
1147       Applications should use a IO::Async::Signal object, or call
1148       "attach_signal" instead of using this method.
1149
1150       This and "unwatch_signal" are optional; a subclass may implement
1151       neither, or both. If it implements neither then signal handling will be
1152       performed by the base class using a self-connected pipe to interrupt
1153       the main IO blocking.
1154
1155   unwatch_signal
1156          $loop->unwatch_signal( $signal )
1157
1158       This method removes the signal callback for the given signal.
1159
1160       $signal The name of the signal to watch to. This should be a bare name
1161               like "TERM".
1162
1163   watch_time
1164          $id = $loop->watch_time( %args )
1165
1166       This method installs a callback which will be called at the specified
1167       time.  The time may either be specified as an absolute value (the "at"
1168       key), or as a delay from the time it is installed (the "after" key).
1169
1170       The returned $id value can be used to identify the timer in case it
1171       needs to be cancelled by the "unwatch_time" method. Note that this
1172       value may be an object reference, so if it is stored, it should be
1173       released after it has been fired or cancelled, so the object itself can
1174       be freed.
1175
1176       The %params hash takes the following keys:
1177
1178       at => NUM
1179               The absolute system timestamp to run the event.
1180
1181       after => NUM
1182               The delay after now at which to run the event, if "at" is not
1183               supplied. A zero or negative delayed timer should be executed
1184               as soon as possible; the next time the "loop_once" method is
1185               invoked.
1186
1187       now => NUM
1188               The time to consider as now if calculating an absolute time
1189               based on "after"; defaults to "time()" if not specified.
1190
1191       code => CODE
1192               CODE reference to the continuation to run at the allotted time.
1193
1194       Either one of "at" or "after" is required.
1195
1196       For more powerful timer functionality as a IO::Async::Notifier (so it
1197       can be used as a child within another Notifier), see instead the
1198       IO::Async::Timer object and its subclasses.
1199
1200       These *_time methods are optional; a subclass may implement neither or
1201       both of them. If it implements neither, then the base class will manage
1202       a queue of timer events. This queue should be handled by the
1203       "loop_once" method implemented by the subclass, using the
1204       "_adjust_timeout" and "_manage_queues" methods.
1205
1206       This is the newer version of the API, replacing "enqueue_timer". It is
1207       unspecified how this method pair interacts with the older
1208       "enqueue/requeue/cancel_timer" triplet.
1209
1210   unwatch_time
1211          $loop->unwatch_time( $id )
1212
1213       Removes a timer callback previously created by "watch_time".
1214
1215       This is the newer version of the API, replacing "cancel_timer". It is
1216       unspecified how this method pair interacts with the older
1217       "enqueue/requeue/cancel_timer" triplet.
1218
1219   enqueue_timer
1220          $id = $loop->enqueue_timer( %params )
1221
1222       An older version of "watch_time". This method should not be used in new
1223       code but is retained for legacy purposes. For simple watch/unwatch
1224       behaviour use instead the new "watch_time" method; though note it has
1225       differently-named arguments. For requeueable timers, consider using an
1226       IO::Async::Timer::Countdown or IO::Async::Timer::Absolute instead.
1227
1228   cancel_timer
1229          $loop->cancel_timer( $id )
1230
1231       An older version of "unwatch_time". This method should not be used in
1232       new code but is retained for legacy purposes.
1233
1234   requeue_timer
1235          $newid = $loop->requeue_timer( $id, %params )
1236
1237       Reschedule an existing timer, moving it to a new time. The old timer is
1238       removed and will not be invoked.
1239
1240       The %params hash takes the same keys as "enqueue_timer", except for the
1241       "code" argument.
1242
1243       The requeue operation may be implemented as a cancel + enqueue, which
1244       may mean the ID changes. Be sure to store the returned $newid value if
1245       it is required.
1246
1247       This method should not be used in new code but is retained for legacy
1248       purposes. For requeueable, consider using an
1249       IO::Async::Timer::Countdown or IO::Async::Timer::Absolute instead.
1250
1251   watch_idle
1252          $id = $loop->watch_idle( %params )
1253
1254       This method installs a callback which will be called at some point in
1255       the near future.
1256
1257       The %params hash takes the following keys:
1258
1259       when => STRING
1260               Specifies the time at which the callback will be invoked. See
1261               below.
1262
1263       code => CODE
1264               CODE reference to the continuation to run at the allotted time.
1265
1266       The "when" parameter defines the time at which the callback will later
1267       be invoked. Must be one of the following values:
1268
1269       later   Callback is invoked after the current round of IO events have
1270               been processed by the loop's underlying "loop_once" method.
1271
1272               If a new idle watch is installed from within a "later"
1273               callback, the installed one will not be invoked during this
1274               round. It will be deferred for the next time "loop_once" is
1275               called, after any IO events have been handled.
1276
1277       If there are pending idle handlers, then the "loop_once" method will
1278       use a zero timeout; it will return immediately, having processed any IO
1279       events and idle handlers.
1280
1281       The returned $id value can be used to identify the idle handler in case
1282       it needs to be removed, by calling the "unwatch_idle" method. Note this
1283       value may be a reference, so if it is stored it should be released
1284       after the callback has been invoked or cancled, so the referrant itself
1285       can be freed.
1286
1287       This and "unwatch_idle" are optional; a subclass may implement neither,
1288       or both. If it implements neither then idle handling will be performed
1289       by the base class, using the "_adjust_timeout" and "_manage_queues"
1290       methods.
1291
1292   unwatch_idle
1293          $loop->unwatch_idle( $id )
1294
1295       Cancels a previously-installed idle handler.
1296
1297   watch_child
1298          $loop->watch_child( $pid, $code )
1299
1300       This method adds a new handler for the termination of the given child
1301       process PID, or all child processes.
1302
1303       $pid    The PID to watch. Will report on all child processes if this is
1304               0.
1305
1306       $code   A CODE reference to the exit handler. It will be invoked as
1307
1308                $code->( $pid, $? )
1309
1310               The second argument is passed the plain perl $? value.
1311
1312       After invocation, the handler for a PID-specific watch is automatically
1313       removed. The all-child watch will remain until it is removed by
1314       "unwatch_child".
1315
1316       This and "unwatch_child" are optional; a subclass may implement
1317       neither, or both. If it implements neither then child watching will be
1318       performed by using "watch_signal" to install a "SIGCHLD" handler, which
1319       will use "waitpid" to look for exited child processes.
1320
1321       If both a PID-specific and an all-process watch are installed, there is
1322       no ordering guarantee as to which will be called first.
1323
1324   unwatch_child
1325          $loop->unwatch_child( $pid )
1326
1327       This method removes a watch on an existing child process PID.
1328

METHODS FOR SUBCLASSES

1330       The following methods are provided to access internal features which
1331       are required by specific subclasses to implement the loop
1332       functionality. The use cases of each will be documented in the above
1333       section.
1334
1335   _adjust_timeout
1336          $loop->_adjust_timeout( \$timeout )
1337
1338       Shortens the timeout value passed in the scalar reference if it is
1339       longer in seconds than the time until the next queued event on the
1340       timer queue. If there are pending idle handlers, the timeout is reduced
1341       to zero.
1342
1343   _manage_queues
1344          $loop->_manage_queues
1345
1346       Checks the timer queue for callbacks that should have been invoked by
1347       now, and runs them all, removing them from the queue. It also invokes
1348       all of the pending idle handlers. Any new idle handlers installed by
1349       these are not invoked yet; they will wait for the next time this method
1350       is called.
1351

EXTENSIONS

1353       An Extension is a Perl module that provides extra methods in the
1354       "IO::Async::Loop" or other packages. They are intended to provide extra
1355       functionality that easily integrates with the rest of the code.
1356
1357       Certain base methods take an "extensions" parameter; an ARRAY reference
1358       containing a list of extension names. If such a list is passed to a
1359       method, it will immediately call a method whose name is that of the
1360       base method, prefixed by the first extension name in the list,
1361       separated by "_". If the "extensions" list contains more extension
1362       names, it will be passed the remaining ones in another "extensions"
1363       parameter.
1364
1365       For example,
1366
1367        $loop->connect(
1368           extensions => [qw( FOO BAR )],
1369           %args
1370        )
1371
1372       will become
1373
1374        $loop->FOO_connect(
1375           extensions => [qw( BAR )],
1376           %args
1377        )
1378
1379       This is provided so that extension modules, such as IO::Async::SSL can
1380       easily be invoked indirectly, by passing extra arguments to "connect"
1381       methods or similar, without needing every module to be aware of the
1382       "SSL" extension.  This functionality is generic and not limited to
1383       "SSL"; other extensions may also use it.
1384
1385       The following methods take an "extensions" parameter:
1386
1387        $loop->connect
1388        $loop->listen
1389
1390       If an extension "listen" method is invoked, it will be passed a
1391       "listener" parameter even if one was not provided to the original
1392       "$loop->listen" call, and it will not receive any of the "on_*" event
1393       callbacks. It should use the "acceptor" parameter on the "listener"
1394       object.
1395

STALL WATCHDOG

1397       A well-behaved IO::Async program should spend almost all of its time
1398       blocked on input using the underlying "IO::Async::Loop" instance. The
1399       stall watchdog is an optional debugging feature to help detect CPU
1400       spinlocks and other bugs, where control is not returned to the loop
1401       every so often.
1402
1403       If the watchdog is enabled and an event handler consumes more than a
1404       given amount of real time before returning to the event loop, it will
1405       be interrupted by printing a stack trace and terminating the program.
1406       The watchdog is only in effect while the loop itself is not blocking;
1407       it won't fail simply because the loop instance is waiting for input or
1408       timers.
1409
1410       It is implemented using "SIGALRM", so if enabled, this signal will no
1411       longer be available to user code. (Though in any case, most uses of
1412       "alarm()" and "SIGALRM" are better served by one of the
1413       IO::Async::Timer subclasses).
1414
1415       The following environment variables control its behaviour.
1416
1417       IO_ASYNC_WATCHDOG => BOOL
1418           Enables the stall watchdog if set to a non-zero value.
1419
1420       IO_ASYNC_WATCHDOG_INTERVAL => INT
1421           Watchdog interval, in seconds, to pass to the alarm(2) call.
1422           Defaults to 10 seconds.
1423
1424       IO_ASYNC_WATCHDOG_SIGABRT => BOOL
1425           If enabled, the watchdog signal handler will raise a "SIGABRT",
1426           which usually has the effect of breaking out of a running program
1427           in debuggers such as gdb. If not set then the process is terminated
1428           by throwing an exception with "die".
1429

AUTHOR

1431       Paul Evans <leonerd@leonerd.org.uk>
1432
1433
1434
1435perl v5.30.0                      2019-07-26                IO::Async::Loop(3)
Impressum