1IO::Async::Loop(3) User Contributed Perl Documentation IO::Async::Loop(3)
2
3
4
6 "IO::Async::Loop" - core loop of the "IO::Async" framework
7
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
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
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
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
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
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
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 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_child
549 $pid = $loop->run_child( %params )
550
551 This creates a new child process to run the given code block or
552 command, capturing its STDOUT and STDERR streams. When the process
553 exits, a continuation is invoked being passed the exitcode, and content
554 of the streams.
555
556 command => ARRAY or STRING
557 code => CODE
558 The command or code to run in the child process (as per the
559 "spawn_child" method)
560
561 on_finish => CODE
562 A continuation to be called when the child process exits and
563 closed its STDOUT and STDERR streams. It will be invoked in the
564 following way:
565
566 $on_finish->( $pid, $exitcode, $stdout, $stderr )
567
568 The second argument is passed the plain perl $? value.
569
570 stdin => STRING
571 Optional. String to pass in to the child process's STDIN
572 stream.
573
574 setup => ARRAY
575 Optional reference to an array to pass to the underlying
576 "spawn" method.
577
578 This method is intended mainly as an IO::Async-compatible replacement
579 for the perl "readpipe" function (`backticks`), allowing it to replace
580
581 my $output = `command here`;
582
583 with
584
585 $loop->run_child(
586 command => "command here",
587 on_finish => sub {
588 my ( undef, $exitcode, $output ) = @_;
589 ...
590 }
591 );
592
593 $loop->run_child(
594 command => "/bin/ps",
595
596 on_finish => sub {
597 my ( $pid, $exitcode, $stdout, $stderr ) = @_;
598 my $status = ( $exitcode >> 8 );
599 print "ps [PID $pid] exited with status $status\n";
600 },
601 );
602
603 resolver
604 $loop->resolver
605
606 Returns the internally-stored IO::Async::Resolver object, used for name
607 resolution operations by the "resolve", "connect" and "listen" methods.
608
609 set_resolver
610 $loop->set_resolver( $resolver )
611
612 Sets the internally-stored IO::Async::Resolver object. In most cases
613 this method should not be required, but it may be used to provide an
614 alternative resolver for special use-cases.
615
616 resolve
617 @result = $loop->resolve( %params )->get
618
619 This method performs a single name resolution operation. It uses an
620 internally-stored IO::Async::Resolver object. For more detail, see the
621 "resolve" method on the IO::Async::Resolver class.
622
623 connect
624 $handle|$socket = $loop->connect( %params )->get
625
626 This method performs a non-blocking connection to a given address or
627 set of addresses, returning a IO::Async::Future which represents the
628 operation. On completion, the future will yield the connected socket
629 handle, or the given IO::Async::Handle object.
630
631 There are two modes of operation. Firstly, a list of addresses can be
632 provided which will be tried in turn. Alternatively as a convenience,
633 if a host and service name are provided instead of a list of addresses,
634 these will be resolved using the underlying loop's "resolve" method
635 into the list of addresses.
636
637 When attempting to connect to any among a list of addresses, there may
638 be failures among the first attempts, before a valid connection is
639 made. For example, the resolver may have returned some IPv6 addresses,
640 but only IPv4 routes are valid on the system. In this case, the first
641 connect(2) syscall will fail. This isn't yet a fatal error, if there
642 are more addresses to try, perhaps some IPv4 ones.
643
644 For this reason, it is possible that the operation eventually succeeds
645 even though some system calls initially fail. To be aware of individual
646 failures, the optional "on_fail" callback can be used. This will be
647 invoked on each individual socket(2) or connect(2) failure, which may
648 be useful for debugging or logging.
649
650 Because this module simply uses the "getaddrinfo" resolver, it will be
651 fully IPv6-aware if the underlying platform's resolver is. This allows
652 programs to be fully IPv6-capable.
653
654 In plain address mode, the %params hash takes the following keys:
655
656 addrs => ARRAY
657 Reference to an array of (possibly-multiple) address structures
658 to attempt to connect to. Each should be in the layout
659 described for "addr". Such a layout is returned by the
660 "getaddrinfo" named resolver.
661
662 addr => HASH or ARRAY
663 Shortcut for passing a single address to connect to; it may be
664 passed directly with this key, instead of in another array on
665 its own. This should be in a format recognised by
666 IO::Async::OS's "extract_addrinfo" method.
667
668 This example shows how to use the "Socket" functions to
669 construct one for TCP port 8001 on address 10.0.0.1:
670
671 $loop->connect(
672 addr => {
673 family => "inet",
674 socktype => "stream",
675 port => 8001,
676 ip => "10.0.0.1",
677 },
678 ...
679 );
680
681 This example shows another way to connect to a UNIX socket at
682 echo.sock.
683
684 $loop->connect(
685 addr => {
686 family => "unix",
687 socktype => "stream",
688 path => "echo.sock",
689 },
690 ...
691 );
692
693 local_addrs => ARRAY
694 local_addr => HASH or ARRAY
695 Optional. Similar to the "addrs" or "addr" parameters, these
696 specify a local address or set of addresses to bind(2) the
697 socket to before connect(2)ing it.
698
699 When performing the resolution step too, the "addrs" or "addr" keys are
700 ignored, and instead the following keys are taken:
701
702 host => STRING
703 service => STRING
704 The hostname and service name to connect to.
705
706 local_host => STRING
707 local_service => STRING
708 Optional. The hostname and/or service name to bind(2) the
709 socket to locally before connecting to the peer.
710
711 family => INT
712 socktype => INT
713 protocol => INT
714 flags => INT
715 Optional. Other arguments to pass along with "host" and
716 "service" to the "getaddrinfo" call.
717
718 socktype => STRING
719 Optionally may instead be one of the values 'stream', 'dgram'
720 or 'raw' to stand for "SOCK_STREAM", "SOCK_DGRAM" or
721 "SOCK_RAW". This utility is provided to allow the caller to
722 avoid a separate "use Socket" only for importing these
723 constants.
724
725 It is necessary to pass the "socktype" hint to the resolver when
726 resolving the host/service names into an address, as some OS's
727 "getaddrinfo" functions require this hint. A warning is emitted if
728 neither "socktype" nor "protocol" hint is defined when performing a
729 "getaddrinfo" lookup. To avoid this warning while still specifying no
730 particular "socktype" hint (perhaps to invoke some OS-specific
731 behaviour), pass 0 as the "socktype" value.
732
733 In either case, it also accepts the following arguments:
734
735 handle => IO::Async::Handle
736 Optional. If given a IO::Async::Handle object or a subclass
737 (such as IO::Async::Stream or IO::Async::Socket its handle will
738 be set to the newly-connected socket on success, and that
739 handle used as the result of the future instead.
740
741 on_fail => CODE
742 Optional. After an individual socket(2) or connect(2) syscall
743 has failed, this callback is invoked to inform of the error. It
744 is passed the name of the syscall that failed, the arguments
745 that were passed to it, and the error it generated. I.e.
746
747 $on_fail->( "socket", $family, $socktype, $protocol, $! );
748
749 $on_fail->( "bind", $sock, $address, $! );
750
751 $on_fail->( "connect", $sock, $address, $! );
752
753 Because of the "try all" nature when given a list of multiple
754 addresses, this callback may be invoked multiple times, even
755 before an eventual success.
756
757 This method accepts an "extensions" parameter; see the "EXTENSIONS"
758 section below.
759
760 connect (void)
761 $loop->connect( %params )
762
763 When not returning a future, additional parameters can be given
764 containing the continuations to invoke on success or failure.
765
766 on_connected => CODE
767 A continuation that is invoked on a successful connect(2) call
768 to a valid socket. It will be passed the connected socket
769 handle, as an "IO::Socket" object.
770
771 $on_connected->( $handle )
772
773 on_stream => CODE
774 An alternative to "on_connected", a continuation that is passed
775 an instance of IO::Async::Stream when the socket is connected.
776 This is provided as a convenience for the common case that a
777 Stream object is required as the transport for a Protocol
778 object.
779
780 $on_stream->( $stream )
781
782 on_socket => CODE
783 Similar to "on_stream", but constructs an instance of
784 IO::Async::Socket. This is most useful for "SOCK_DGRAM" or
785 "SOCK_RAW" sockets.
786
787 $on_socket->( $socket )
788
789 on_connect_error => CODE
790 A continuation that is invoked after all of the addresses have
791 been tried, and none of them succeeded. It will be passed the
792 most significant error that occurred, and the name of the
793 operation it occurred in. Errors from the connect(2) syscall
794 are considered most significant, then bind(2), then finally
795 socket(2).
796
797 $on_connect_error->( $syscall, $! )
798
799 on_resolve_error => CODE
800 A continuation that is invoked when the name resolution attempt
801 fails. This is invoked in the same way as the "on_error"
802 continuation for the "resolve" method.
803
804 listen
805 $listener = $loop->listen( %params )->get
806
807 This method sets up a listening socket and arranges for an acceptor
808 callback to be invoked each time a new connection is accepted on the
809 socket. Internally it creates an instance of IO::Async::Listener and
810 adds it to the Loop if not given one in the arguments.
811
812 Addresses may be given directly, or they may be looked up using the
813 system's name resolver, or a socket handle may be given directly.
814
815 If multiple addresses are given, or resolved from the service and
816 hostname, then each will be attempted in turn until one succeeds.
817
818 In named resolver mode, the %params hash takes the following keys:
819
820 service => STRING
821 The service name to listen on.
822
823 host => STRING
824 The hostname to listen on. Optional. Will listen on all
825 addresses if not supplied.
826
827 family => INT
828 socktype => INT
829 protocol => INT
830 flags => INT
831 Optional. Other arguments to pass along with "host" and
832 "service" to the "getaddrinfo" call.
833
834 socktype => STRING
835 Optionally may instead be one of the values 'stream', 'dgram'
836 or 'raw' to stand for "SOCK_STREAM", "SOCK_DGRAM" or
837 "SOCK_RAW". This utility is provided to allow the caller to
838 avoid a separate "use Socket" only for importing these
839 constants.
840
841 It is necessary to pass the "socktype" hint to the resolver when
842 resolving the host/service names into an address, as some OS's
843 "getaddrinfo" functions require this hint. A warning is emitted if
844 neither "socktype" nor "protocol" hint is defined when performing a
845 "getaddrinfo" lookup. To avoid this warning while still specifying no
846 particular "socktype" hint (perhaps to invoke some OS-specific
847 behaviour), pass 0 as the "socktype" value.
848
849 In plain address mode, the %params hash takes the following keys:
850
851 addrs => ARRAY
852 Reference to an array of (possibly-multiple) address structures
853 to attempt to listen on. Each should be in the layout described
854 for "addr". Such a layout is returned by the "getaddrinfo"
855 named resolver.
856
857 addr => ARRAY
858 Shortcut for passing a single address to listen on; it may be
859 passed directly with this key, instead of in another array of
860 its own. This should be in a format recognised by
861 IO::Async::OS's "extract_addrinfo" method. See also the
862 "EXAMPLES" section.
863
864 In direct socket handle mode, the following keys are taken:
865
866 handle => IO
867 The listening socket handle.
868
869 In either case, the following keys are also taken:
870
871 on_fail => CODE
872 Optional. A callback that is invoked if a syscall fails while
873 attempting to create a listening sockets. It is passed the name
874 of the syscall that failed, the arguments that were passed to
875 it, and the error generated. I.e.
876
877 $on_fail->( "socket", $family, $socktype, $protocol, $! );
878
879 $on_fail->( "sockopt", $sock, $optname, $optval, $! );
880
881 $on_fail->( "bind", $sock, $address, $! );
882
883 $on_fail->( "listen", $sock, $queuesize, $! );
884
885 queuesize => INT
886 Optional. The queue size to pass to the listen(2) calls. If not
887 supplied, then 3 will be given instead.
888
889 reuseaddr => BOOL
890 Optional. If true or not supplied then the "SO_REUSEADDR"
891 socket option will be set. To prevent this, pass a false value
892 such as 0.
893
894 v6only => BOOL
895 Optional. If defined, sets or clears the "IPV6_V6ONLY" socket
896 option on "PF_INET6" sockets. This option disables the ability
897 of "PF_INET6" socket to accept connections from "AF_INET"
898 addresses. Not all operating systems allow this option to be
899 disabled.
900
901 An alternative which gives more control over the listener, is to create
902 the IO::Async::Listener object directly and add it explicitly to the
903 Loop.
904
905 This method accepts an "extensions" parameter; see the "EXTENSIONS"
906 section below.
907
908 listen (void)
909 $loop->listen( %params )
910
911 When not returning a future, additional parameters can be given
912 containing the continuations to invoke on success or failure.
913
914 on_notifier => CODE
915 Optional. A callback that is invoked when the Listener object
916 is ready to receive connections. The callback is passed the
917 Listener object itself.
918
919 $on_notifier->( $listener )
920
921 If this callback is required, it may instead be better to
922 construct the Listener object directly.
923
924 on_listen => CODE
925 Optional. A callback that is invoked when the listening socket
926 is ready. Typically this would be used in the name resolver
927 case, in order to inspect the socket's sockname address, or
928 otherwise inspect the filehandle.
929
930 $on_listen->( $socket )
931
932 on_listen_error => CODE
933 A continuation this is invoked after all of the addresses have
934 been tried, and none of them succeeded. It will be passed the
935 most significant error that occurred, and the name of the
936 operation it occurred in. Errors from the listen(2) syscall are
937 considered most significant, then bind(2), then sockopt(2),
938 then finally socket(2).
939
940 on_resolve_error => CODE
941 A continuation that is invoked when the name resolution attempt
942 fails. This is invoked in the same way as the "on_error"
943 continuation for the "resolve" method.
944
946 Because the Magic Constructor searches for OS-specific subclasses of
947 the Loop, several abstractions of OS services are provided, in case
948 specific OSes need to give different implementations on that OS.
949
950 signame2num
951 $signum = $loop->signame2num( $signame )
952
953 Legacy wrappers around IO::Async::OS functions.
954
955 time
956 $time = $loop->time
957
958 Returns the current UNIX time in fractional seconds. This is currently
959 equivalent to "Time::HiRes::time" but provided here as a utility for
960 programs to obtain the time current used by IO::Async for its own
961 timing purposes.
962
963 fork
964 $pid = $loop->fork( %params )
965
966 This method creates a new child process to run a given code block,
967 returning its process ID.
968
969 code => CODE
970 A block of code to execute in the child process. It will be
971 called in scalar context inside an "eval" block. The return
972 value will be used as the exit(2) code from the child if it
973 returns (or 255 if it returned "undef" or thows an exception).
974
975 on_exit => CODE
976 A optional continuation to be called when the child processes
977 exits. It will be invoked in the following way:
978
979 $on_exit->( $pid, $exitcode )
980
981 The second argument is passed the plain perl $? value.
982
983 This key is optional; if not supplied, the calling code should
984 install a handler using the "watch_child" method.
985
986 keep_signals => BOOL
987 Optional boolean. If missing or false, any CODE references in
988 the %SIG hash will be removed and restored back to "DEFAULT" in
989 the child process. If true, no adjustment of the %SIG hash will
990 be performed.
991
992 create_thread
993 $tid = $loop->create_thread( %params )
994
995 This method creates a new (non-detached) thread to run the given code
996 block, returning its thread ID.
997
998 code => CODE
999 A block of code to execute in the thread. It is called in the
1000 context given by the "context" argument, and its return value
1001 will be available to the "on_joined" callback. It is called
1002 inside an "eval" block; if it fails the exception will be
1003 caught.
1004
1005 context => "scalar" | "list" | "void"
1006 Optional. Gives the calling context that "code" is invoked in.
1007 Defaults to "scalar" if not supplied.
1008
1009 on_joined => CODE
1010 Callback to invoke when the thread function returns or throws
1011 an exception. If it returned, this callback will be invoked
1012 with its result
1013
1014 $on_joined->( return => @result )
1015
1016 If it threw an exception the callback is invoked with the value
1017 of $@
1018
1019 $on_joined->( died => $! )
1020
1022 As "IO::Async::Loop" is an abstract base class, specific subclasses of
1023 it are required to implement certain methods that form the base level
1024 of functionality. They are not recommended for applications to use; see
1025 instead the various event objects or higher level methods listed above.
1026
1027 These methods should be considered as part of the interface contract
1028 required to implement a "IO::Async::Loop" subclass.
1029
1030 API_VERSION
1031 IO::Async::Loop->API_VERSION
1032
1033 This method will be called by the magic constructor on the class before
1034 it is constructed, to ensure that the specific implementation will
1035 support the required API. This method should return the API version
1036 that the loop implementation supports. The magic constructor will use
1037 that class, provided it declares a version at least as new as the
1038 version documented here.
1039
1040 The current API version is 0.49.
1041
1042 This method may be implemented using "constant"; e.g
1043
1044 use constant API_VERSION => '0.49';
1045
1046 watch_io
1047 $loop->watch_io( %params )
1048
1049 This method installs callback functions which will be invoked when the
1050 given IO handle becomes read- or write-ready.
1051
1052 The %params hash takes the following keys:
1053
1054 handle => IO
1055 The IO handle to watch.
1056
1057 on_read_ready => CODE
1058 Optional. A CODE reference to call when the handle becomes
1059 read-ready.
1060
1061 on_write_ready => CODE
1062 Optional. A CODE reference to call when the handle becomes
1063 write-ready.
1064
1065 There can only be one filehandle of any given fileno registered at any
1066 one time. For any one filehandle, there can only be one read-readiness
1067 and/or one write-readiness callback at any one time. Registering a new
1068 one will remove an existing one of that type. It is not required that
1069 both are provided.
1070
1071 Applications should use a IO::Async::Handle or IO::Async::Stream
1072 instead of using this method.
1073
1074 If the filehandle does not yet have the "O_NONBLOCK" flag set, it will
1075 be enabled by this method. This will ensure that any subsequent
1076 "sysread", "syswrite", or similar will not block on the filehandle.
1077
1078 unwatch_io
1079 $loop->unwatch_io( %params )
1080
1081 This method removes a watch on an IO handle which was previously
1082 installed by "watch_io".
1083
1084 The %params hash takes the following keys:
1085
1086 handle => IO
1087 The IO handle to remove the watch for.
1088
1089 on_read_ready => BOOL
1090 If true, remove the watch for read-readiness.
1091
1092 on_write_ready => BOOL
1093 If true, remove the watch for write-readiness.
1094
1095 Either or both callbacks may be removed at once. It is not an error to
1096 attempt to remove a callback that is not present. If both callbacks
1097 were provided to the "watch_io" method and only one is removed by this
1098 method, the other shall remain.
1099
1100 watch_signal
1101 $loop->watch_signal( $signal, $code )
1102
1103 This method adds a new signal handler to watch the given signal.
1104
1105 $signal The name of the signal to watch to. This should be a bare name
1106 like "TERM".
1107
1108 $code A CODE reference to the handling callback.
1109
1110 There can only be one callback per signal name. Registering a new one
1111 will remove an existing one.
1112
1113 Applications should use a IO::Async::Signal object, or call
1114 "attach_signal" instead of using this method.
1115
1116 This and "unwatch_signal" are optional; a subclass may implement
1117 neither, or both. If it implements neither then signal handling will be
1118 performed by the base class using a self-connected pipe to interrupt
1119 the main IO blocking.
1120
1121 unwatch_signal
1122 $loop->unwatch_signal( $signal )
1123
1124 This method removes the signal callback for the given signal.
1125
1126 $signal The name of the signal to watch to. This should be a bare name
1127 like "TERM".
1128
1129 watch_time
1130 $id = $loop->watch_time( %args )
1131
1132 This method installs a callback which will be called at the specified
1133 time. The time may either be specified as an absolute value (the "at"
1134 key), or as a delay from the time it is installed (the "after" key).
1135
1136 The returned $id value can be used to identify the timer in case it
1137 needs to be cancelled by the "unwatch_time" method. Note that this
1138 value may be an object reference, so if it is stored, it should be
1139 released after it has been fired or cancelled, so the object itself can
1140 be freed.
1141
1142 The %params hash takes the following keys:
1143
1144 at => NUM
1145 The absolute system timestamp to run the event.
1146
1147 after => NUM
1148 The delay after now at which to run the event, if "at" is not
1149 supplied. A zero or negative delayed timer should be executed
1150 as soon as possible; the next time the "loop_once" method is
1151 invoked.
1152
1153 now => NUM
1154 The time to consider as now if calculating an absolute time
1155 based on "after"; defaults to "time()" if not specified.
1156
1157 code => CODE
1158 CODE reference to the continuation to run at the allotted time.
1159
1160 Either one of "at" or "after" is required.
1161
1162 For more powerful timer functionality as a IO::Async::Notifier (so it
1163 can be used as a child within another Notifier), see instead the
1164 IO::Async::Timer object and its subclasses.
1165
1166 These *_time methods are optional; a subclass may implement neither or
1167 both of them. If it implements neither, then the base class will manage
1168 a queue of timer events. This queue should be handled by the
1169 "loop_once" method implemented by the subclass, using the
1170 "_adjust_timeout" and "_manage_queues" methods.
1171
1172 This is the newer version of the API, replacing "enqueue_timer". It is
1173 unspecified how this method pair interacts with the older
1174 "enqueue/requeue/cancel_timer" triplet.
1175
1176 unwatch_time
1177 $loop->unwatch_time( $id )
1178
1179 Removes a timer callback previously created by "watch_time".
1180
1181 This is the newer version of the API, replacing "cancel_timer". It is
1182 unspecified how this method pair interacts with the older
1183 "enqueue/requeue/cancel_timer" triplet.
1184
1185 enqueue_timer
1186 $id = $loop->enqueue_timer( %params )
1187
1188 An older version of "watch_time". This method should not be used in new
1189 code but is retained for legacy purposes. For simple watch/unwatch
1190 behaviour use instead the new "watch_time" method; though note it has
1191 differently-named arguments. For requeueable timers, consider using an
1192 IO::Async::Timer::Countdown or IO::Async::Timer::Absolute instead.
1193
1194 cancel_timer
1195 $loop->cancel_timer( $id )
1196
1197 An older version of "unwatch_time". This method should not be used in
1198 new code but is retained for legacy purposes.
1199
1200 requeue_timer
1201 $newid = $loop->requeue_timer( $id, %params )
1202
1203 Reschedule an existing timer, moving it to a new time. The old timer is
1204 removed and will not be invoked.
1205
1206 The %params hash takes the same keys as "enqueue_timer", except for the
1207 "code" argument.
1208
1209 The requeue operation may be implemented as a cancel + enqueue, which
1210 may mean the ID changes. Be sure to store the returned $newid value if
1211 it is required.
1212
1213 This method should not be used in new code but is retained for legacy
1214 purposes. For requeueable, consider using an
1215 IO::Async::Timer::Countdown or IO::Async::Timer::Absolute instead.
1216
1217 watch_idle
1218 $id = $loop->watch_idle( %params )
1219
1220 This method installs a callback which will be called at some point in
1221 the near future.
1222
1223 The %params hash takes the following keys:
1224
1225 when => STRING
1226 Specifies the time at which the callback will be invoked. See
1227 below.
1228
1229 code => CODE
1230 CODE reference to the continuation to run at the allotted time.
1231
1232 The "when" parameter defines the time at which the callback will later
1233 be invoked. Must be one of the following values:
1234
1235 later Callback is invoked after the current round of IO events have
1236 been processed by the loop's underlying "loop_once" method.
1237
1238 If a new idle watch is installed from within a "later"
1239 callback, the installed one will not be invoked during this
1240 round. It will be deferred for the next time "loop_once" is
1241 called, after any IO events have been handled.
1242
1243 If there are pending idle handlers, then the "loop_once" method will
1244 use a zero timeout; it will return immediately, having processed any IO
1245 events and idle handlers.
1246
1247 The returned $id value can be used to identify the idle handler in case
1248 it needs to be removed, by calling the "unwatch_idle" method. Note this
1249 value may be a reference, so if it is stored it should be released
1250 after the callback has been invoked or cancled, so the referrant itself
1251 can be freed.
1252
1253 This and "unwatch_idle" are optional; a subclass may implement neither,
1254 or both. If it implements neither then idle handling will be performed
1255 by the base class, using the "_adjust_timeout" and "_manage_queues"
1256 methods.
1257
1258 unwatch_idle
1259 $loop->unwatch_idle( $id )
1260
1261 Cancels a previously-installed idle handler.
1262
1263 watch_child
1264 $loop->watch_child( $pid, $code )
1265
1266 This method adds a new handler for the termination of the given child
1267 process PID, or all child processes.
1268
1269 $pid The PID to watch. Will report on all child processes if this is
1270 0.
1271
1272 $code A CODE reference to the exit handler. It will be invoked as
1273
1274 $code->( $pid, $? )
1275
1276 The second argument is passed the plain perl $? value.
1277
1278 After invocation, the handler for a PID-specific watch is automatically
1279 removed. The all-child watch will remain until it is removed by
1280 "unwatch_child".
1281
1282 This and "unwatch_child" are optional; a subclass may implement
1283 neither, or both. If it implements neither then child watching will be
1284 performed by using "watch_signal" to install a "SIGCHLD" handler, which
1285 will use "waitpid" to look for exited child processes.
1286
1287 If both a PID-specific and an all-process watch are installed, there is
1288 no ordering guarantee as to which will be called first.
1289
1290 unwatch_child
1291 $loop->unwatch_child( $pid )
1292
1293 This method removes a watch on an existing child process PID.
1294
1296 The following methods are provided to access internal features which
1297 are required by specific subclasses to implement the loop
1298 functionality. The use cases of each will be documented in the above
1299 section.
1300
1301 _adjust_timeout
1302 $loop->_adjust_timeout( \$timeout )
1303
1304 Shortens the timeout value passed in the scalar reference if it is
1305 longer in seconds than the time until the next queued event on the
1306 timer queue. If there are pending idle handlers, the timeout is reduced
1307 to zero.
1308
1309 _manage_queues
1310 $loop->_manage_queues
1311
1312 Checks the timer queue for callbacks that should have been invoked by
1313 now, and runs them all, removing them from the queue. It also invokes
1314 all of the pending idle handlers. Any new idle handlers installed by
1315 these are not invoked yet; they will wait for the next time this method
1316 is called.
1317
1319 An Extension is a Perl module that provides extra methods in the
1320 "IO::Async::Loop" or other packages. They are intended to provide extra
1321 functionality that easily integrates with the rest of the code.
1322
1323 Certain base methods take an "extensions" parameter; an ARRAY reference
1324 containing a list of extension names. If such a list is passed to a
1325 method, it will immediately call a method whose name is that of the
1326 base method, prefixed by the first extension name in the list,
1327 separated by "_". If the "extensions" list contains more extension
1328 names, it will be passed the remaining ones in another "extensions"
1329 parameter.
1330
1331 For example,
1332
1333 $loop->connect(
1334 extensions => [qw( FOO BAR )],
1335 %args
1336 )
1337
1338 will become
1339
1340 $loop->FOO_connect(
1341 extensions => [qw( BAR )],
1342 %args
1343 )
1344
1345 This is provided so that extension modules, such as IO::Async::SSL can
1346 easily be invoked indirectly, by passing extra arguments to "connect"
1347 methods or similar, without needing every module to be aware of the
1348 "SSL" extension. This functionality is generic and not limited to
1349 "SSL"; other extensions may also use it.
1350
1351 The following methods take an "extensions" parameter:
1352
1353 $loop->connect
1354 $loop->listen
1355
1356 If an extension "listen" method is invoked, it will be passed a
1357 "listener" parameter even if one was not provided to the original
1358 "$loop->listen" call, and it will not receive any of the "on_*" event
1359 callbacks. It should use the "acceptor" parameter on the "listener"
1360 object.
1361
1363 A well-behaved IO::Async program should spend almost all of its time
1364 blocked on input using the underlying "IO::Async::Loop" instance. The
1365 stall watchdog is an optional debugging feature to help detect CPU
1366 spinlocks and other bugs, where control is not returned to the loop
1367 every so often.
1368
1369 If the watchdog is enabled and an event handler consumes more than a
1370 given amount of real time before returning to the event loop, it will
1371 be interrupted by printing a stack trace and terminating the program.
1372 The watchdog is only in effect while the loop itself is not blocking;
1373 it won't fail simply because the loop instance is waiting for input or
1374 timers.
1375
1376 It is implemented using "SIGALRM", so if enabled, this signal will no
1377 longer be available to user code. (Though in any case, most uses of
1378 "alarm()" and "SIGALRM" are better served by one of the
1379 IO::Async::Timer subclasses).
1380
1381 The following environment variables control its behaviour.
1382
1383 IO_ASYNC_WATCHDOG => BOOL
1384 Enables the stall watchdog if set to a non-zero value.
1385
1386 IO_ASYNC_WATCHDOG_INTERVAL => INT
1387 Watchdog interval, in seconds, to pass to the alarm(2) call.
1388 Defaults to 10 seconds.
1389
1390 IO_ASYNC_WATCHDOG_SIGABRT => BOOL
1391 If enabled, the watchdog signal handler will raise a "SIGABRT",
1392 which usually has the effect of breaking out of a running program
1393 in debuggers such as gdb. If not set then the process is terminated
1394 by throwing an exception with "die".
1395
1397 Paul Evans <leonerd@leonerd.org.uk>
1398
1399
1400
1401perl v5.28.0 2018-07-14 IO::Async::Loop(3)