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 interact 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 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_process" method should be used to watch for termination of a
306 given child process. A warning will be printed if "SIGCHLD" is passed
307 here, but in future versions of IO::Async this behaviour may be
308 disallowed 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 $f = $loop->later
329
330 Schedules a code reference to be invoked as soon as the current round
331 of IO operations is complete.
332
333 The code reference is never invoked immediately, though the loop will
334 not perform any blocking operations between when it is installed and
335 when it is invoked. It may call "select", "poll" or equivalent with a
336 zero-second timeout, and process any currently-pending IO conditions
337 before the code is invoked, but it will not block for a non-zero amount
338 of time.
339
340 This method is implemented using the "watch_idle" method, with the
341 "when" parameter set to "later". It will return an ID value that can be
342 passed to "unwatch_idle" if required.
343
344 Since version 0.78: If no $code value is passed, a Future will be
345 returned instead. This allows for constructs such as:
346
347 await $loop->later;
348
349 spawn_child
350 $loop->spawn_child( %params )
351
352 This method creates a new child process to run a given code block or
353 command. The %params hash takes the following keys:
354
355 command => ARRAY or STRING
356 Either a reference to an array containing the command and its
357 arguments, or a plain string containing the command. This value
358 is passed into perl's "exec" function.
359
360 code => CODE
361 A block of code to execute in the child process. It will be
362 called in scalar context inside an "eval" block.
363
364 setup => ARRAY
365 A reference to an array which gives file descriptors to set up
366 in the child process before running the code or command. See
367 below.
368
369 on_exit => CODE
370 A continuation to be called when the child processes exits. It
371 will be invoked in the following way:
372
373 $on_exit->( $pid, $exitcode, $dollarbang, $dollarat )
374
375 The second argument is passed the plain perl $? value.
376
377 Exactly one of the "command" or "code" keys must be specified.
378
379 If the "command" key is used, the given array or string is executed
380 using the "exec" function.
381
382 If the "code" key is used, the return value will be used as the exit(2)
383 code from the child if it returns (or 255 if it returned "undef" or
384 thows an exception).
385
386 Case | ($exitcode >> 8) | $dollarbang | $dollarat
387 --------------+------------------------+-------------+----------
388 exec succeeds | exit code from program | 0 | ""
389 exec fails | 255 | $! | ""
390 $code returns | return value | $! | ""
391 $code dies | 255 | $! | $@
392
393 It is usually more convenient to use the "open_process" method in
394 simple cases where an external program is being started in order to
395 interact with it via file IO, or even "run_child" when only the final
396 result is required, rather than interaction while it is running.
397
398 "setup" array
399
400 This array gives a list of file descriptor operations to perform in the
401 child process after it has been fork(2)ed from the parent, before
402 running the code or command. It consists of name/value pairs which are
403 ordered; the operations are performed in the order given.
404
405 fdn => ARRAY
406 Gives an operation on file descriptor n. The first element of
407 the array defines the operation to be performed:
408
409 [ 'close' ]
410 The file descriptor will be closed.
411
412 [ 'dup', $io ]
413 The file descriptor will be dup2(2)ed from the given IO
414 handle.
415
416 [ 'open', $mode, $file ]
417 The file descriptor will be opened from the named file in
418 the given mode. The $mode string should be in the form
419 usually given to the "open" function; such as '<' or '>>'.
420
421 [ 'keep' ]
422 The file descriptor will not be closed; it will be left as-
423 is.
424
425 A non-reference value may be passed as a shortcut, where it
426 would contain the name of the operation with no arguments (i.e.
427 for the "close" and "keep" operations).
428
429 IO => ARRAY
430 Shortcut for passing "fdn", where n is the fileno of the IO
431 reference. In this case, the key must be a reference that
432 implements the "fileno" method. This is mostly useful for
433
434 $handle => 'keep'
435
436 fdn => IO
437 A shortcut for the "dup" case given above.
438
439 stdin => ...
440 stdout => ...
441 stderr => ...
442 Shortcuts for "fd0", "fd1" and "fd2" respectively.
443
444 env => HASH
445 A reference to a hash to set as the child process's
446 environment.
447
448 Note that this will entirely set a new environment, completely
449 replacing the existing one. If you want to simply add new keys
450 or change the values of some keys without removing the other
451 existing ones, you can simply copy %ENV into the hash before
452 setting new keys:
453
454 env => {
455 %ENV,
456 ANOTHER => "key here",
457 }
458
459 nice => INT
460 Change the child process's scheduling priority using
461 "POSIX::nice".
462
463 chdir => STRING
464 Change the child process's working directory using "chdir".
465
466 setuid => INT
467 setgid => INT
468 Change the child process's effective UID or GID.
469
470 setgroups => ARRAY
471 Change the child process's groups list, to those groups whose
472 numbers are given in the ARRAY reference.
473
474 On most systems, only the privileged superuser change user or
475 group IDs. IO::Async will NOT check before detaching the child
476 process whether this is the case.
477
478 If setting both the primary GID and the supplementary groups
479 list, it is suggested to set the primary GID first. Moreover,
480 some operating systems may require that the supplementary
481 groups list contains the primary GID.
482
483 If no directions for what to do with "stdin", "stdout" and "stderr" are
484 given, a default of "keep" is implied. All other file descriptors will
485 be closed, unless a "keep" operation is given for them.
486
487 If "setuid" is used, be sure to place it after any other operations
488 that might require superuser privileges, such as "setgid" or opening
489 special files.
490
491 my ( $pipeRd, $pipeWr ) = IO::Async::OS->pipepair;
492 $loop->spawn_child(
493 command => "/usr/bin/my-command",
494
495 setup => [
496 stdin => [ "open", "<", "/dev/null" ],
497 stdout => $pipeWr,
498 stderr => [ "open", ">>", "/var/log/mycmd.log" ],
499 chdir => "/",
500 ]
501
502 on_exit => sub {
503 my ( $pid, $exitcode ) = @_;
504 my $status = ( $exitcode >> 8 );
505 print "Command exited with status $status\n";
506 },
507 );
508
509 $loop->spawn_child(
510 code => sub {
511 do_something; # executes in a child process
512 return 1;
513 },
514
515 on_exit => sub {
516 my ( $pid, $exitcode, $dollarbang, $dollarat ) = @_;
517 my $status = ( $exitcode >> 8 );
518 print "Child process exited with status $status\n";
519 print " OS error was $dollarbang, exception was $dollarat\n";
520 },
521 );
522
523 open_process
524 $process = $loop->open_process( %params )
525
526 Since version 0.72.
527
528 This creates a new child process to run the given code block or
529 command, and attaches filehandles to it that the parent will watch.
530 This method is a light wrapper around constructing a new
531 IO::Async::Process object, adding it to the loop, and returning it.
532
533 The %params hash is passed directly to the IO::Async::Process
534 constructor.
535
536 open_child
537 $pid = $loop->open_child( %params )
538
539 A back-compatibility wrapper to calling "open_process" and returning
540 the PID of the newly-constructed IO::Async::Process instance. The
541 "on_finish" continuation likewise will be invoked with the PID rather
542 than the process instance.
543
544 $on_finish->( $pid, $exitcode )
545
546 Similarly, a "on_error" continuation is accepted, though note its
547 arguments come in a different order to those of the Process's
548 "on_exception":
549
550 $on_error->( $pid, $exitcode, $errno, $exception )
551
552 This method should not be used in new code; instead use "open_process"
553 directly.
554
555 run_process
556 @results = $loop->run_process( %params )->get
557
558 ( $exitcode, $stdout ) = $loop->run_process( ... )->get # by default
559
560 Since version 0.73.
561
562 Creates a new child process to run the given code block or command,
563 optionally capturing its STDOUT and STDERR streams. By default the
564 returned future will yield the exit code and content of the STDOUT
565 stream, but the "capture" argument can be used to alter what is
566 requested and returned.
567
568 command => ARRAY or STRING
569 code => CODE
570 The command or code to run in the child process (as per the
571 "spawn_child" method)
572
573 stdin => STRING
574 Optional. String to pass in to the child process's STDIN
575 stream.
576
577 setup => ARRAY
578 Optional reference to an array to pass to the underlying
579 "spawn" method.
580
581 capture => ARRAY
582 Optional reference to an array giving a list of names of values
583 which should be returned by resolving future. Values will be
584 returned in the same order as in the list. Valid choices are:
585 "exitcode", "stdout", "stderr".
586
587 cancel_signal => STRING
588 Optional. Name (or number) of the signal to send to the process
589 if the returned future is cancelled. Defaults to "TERM". Use
590 empty string or zero disable sending a signal on cancellation.
591
592 fail_on_nonzero => BOOL
593 Optional. If true, the returned future will fail if the process
594 exits with a nonzero status. The failure will contain a
595 message, the "process" category name, and the capture values
596 that were requested.
597
598 Future->fail( $message, process => @captures )
599
600 This method is intended mainly as an IO::Async-compatible replacement
601 for the perl "readpipe" function (`backticks`), allowing it to replace
602
603 my $output = `command here`;
604
605 with
606
607 my ( $exitcode, $output ) = $loop->run_process(
608 command => "command here",
609 )->get;
610
611 my ( $exitcode, $stdout ) = $loop->run_process(
612 command => "/bin/ps",
613 )->get;
614
615 my $status = ( $exitcode >> 8 );
616 print "ps exited with status $status\n";
617
618 run_child
619 $pid = $loop->run_child( %params )
620
621 A back-compatibility wrapper for "run_process", returning the PID and
622 taking an "on_finish" continuation instead of returning a Future.
623
624 This creates a new child process to run the given code block or
625 command, capturing its STDOUT and STDERR streams. When the process
626 exits, a continuation is invoked being passed the exitcode, and content
627 of the streams.
628
629 Takes the following named arguments in addition to those taken by
630 "run_process":
631
632 on_finish => CODE
633 A continuation to be called when the child process exits and
634 closed its STDOUT and STDERR streams. It will be invoked in the
635 following way:
636
637 $on_finish->( $pid, $exitcode, $stdout, $stderr )
638
639 The second argument is passed the plain perl $? value.
640
641 This method should not be used in new code; instead use "run_process"
642 directly.
643
644 resolver
645 $loop->resolver
646
647 Returns the internally-stored IO::Async::Resolver object, used for name
648 resolution operations by the "resolve", "connect" and "listen" methods.
649
650 set_resolver
651 $loop->set_resolver( $resolver )
652
653 Sets the internally-stored IO::Async::Resolver object. In most cases
654 this method should not be required, but it may be used to provide an
655 alternative resolver for special use-cases.
656
657 resolve
658 @result = $loop->resolve( %params )->get
659
660 This method performs a single name resolution operation. It uses an
661 internally-stored IO::Async::Resolver object. For more detail, see the
662 "resolve" method on the IO::Async::Resolver class.
663
664 connect
665 $handle|$socket = $loop->connect( %params )->get
666
667 This method performs a non-blocking connection to a given address or
668 set of addresses, returning a IO::Async::Future which represents the
669 operation. On completion, the future will yield the connected socket
670 handle, or the given IO::Async::Handle object.
671
672 There are two modes of operation. Firstly, a list of addresses can be
673 provided which will be tried in turn. Alternatively as a convenience,
674 if a host and service name are provided instead of a list of addresses,
675 these will be resolved using the underlying loop's "resolve" method
676 into the list of addresses.
677
678 When attempting to connect to any among a list of addresses, there may
679 be failures among the first attempts, before a valid connection is
680 made. For example, the resolver may have returned some IPv6 addresses,
681 but only IPv4 routes are valid on the system. In this case, the first
682 connect(2) syscall will fail. This isn't yet a fatal error, if there
683 are more addresses to try, perhaps some IPv4 ones.
684
685 For this reason, it is possible that the operation eventually succeeds
686 even though some system calls initially fail. To be aware of individual
687 failures, the optional "on_fail" callback can be used. This will be
688 invoked on each individual socket(2) or connect(2) failure, which may
689 be useful for debugging or logging.
690
691 Because this module simply uses the "getaddrinfo" resolver, it will be
692 fully IPv6-aware if the underlying platform's resolver is. This allows
693 programs to be fully IPv6-capable.
694
695 In plain address mode, the %params hash takes the following keys:
696
697 addrs => ARRAY
698 Reference to an array of (possibly-multiple) address structures
699 to attempt to connect to. Each should be in the layout
700 described for "addr". Such a layout is returned by the
701 "getaddrinfo" named resolver.
702
703 addr => HASH or ARRAY
704 Shortcut for passing a single address to connect to; it may be
705 passed directly with this key, instead of in another array on
706 its own. This should be in a format recognised by
707 IO::Async::OS's "extract_addrinfo" method.
708
709 This example shows how to use the "Socket" functions to
710 construct one for TCP port 8001 on address 10.0.0.1:
711
712 $loop->connect(
713 addr => {
714 family => "inet",
715 socktype => "stream",
716 port => 8001,
717 ip => "10.0.0.1",
718 },
719 ...
720 );
721
722 This example shows another way to connect to a UNIX socket at
723 echo.sock.
724
725 $loop->connect(
726 addr => {
727 family => "unix",
728 socktype => "stream",
729 path => "echo.sock",
730 },
731 ...
732 );
733
734 peer => IO
735 Shortcut for constructing an address to connect to the given IO
736 handle, which must be a IO::Socket or subclass, and is presumed
737 to be a local listening socket (perhaps on "PF_UNIX" or
738 "PF_INET"). This is convenient for connecting to a local
739 filehandle, for example during a unit test or similar.
740
741 local_addrs => ARRAY
742 local_addr => HASH or ARRAY
743 Optional. Similar to the "addrs" or "addr" parameters, these
744 specify a local address or set of addresses to bind(2) the
745 socket to before connect(2)ing it.
746
747 When performing the resolution step too, the "addrs" or "addr" keys are
748 ignored, and instead the following keys are taken:
749
750 host => STRING
751 service => STRING
752 The hostname and service name to connect to.
753
754 local_host => STRING
755 local_service => STRING
756 Optional. The hostname and/or service name to bind(2) the
757 socket to locally before connecting to the peer.
758
759 family => INT
760 socktype => INT
761 protocol => INT
762 flags => INT
763 Optional. Other arguments to pass along with "host" and
764 "service" to the "getaddrinfo" call.
765
766 socktype => STRING
767 Optionally may instead be one of the values 'stream', 'dgram'
768 or 'raw' to stand for "SOCK_STREAM", "SOCK_DGRAM" or
769 "SOCK_RAW". This utility is provided to allow the caller to
770 avoid a separate "use Socket" only for importing these
771 constants.
772
773 It is necessary to pass the "socktype" hint to the resolver when
774 resolving the host/service names into an address, as some OS's
775 "getaddrinfo" functions require this hint. A warning is emitted if
776 neither "socktype" nor "protocol" hint is defined when performing a
777 "getaddrinfo" lookup. To avoid this warning while still specifying no
778 particular "socktype" hint (perhaps to invoke some OS-specific
779 behaviour), pass 0 as the "socktype" value.
780
781 In either case, it also accepts the following arguments:
782
783 handle => IO::Async::Handle
784 Optional. If given a IO::Async::Handle object or a subclass
785 (such as IO::Async::Stream or IO::Async::Socket its handle will
786 be set to the newly-connected socket on success, and that
787 handle used as the result of the future instead.
788
789 on_fail => CODE
790 Optional. After an individual socket(2) or connect(2) syscall
791 has failed, this callback is invoked to inform of the error. It
792 is passed the name of the syscall that failed, the arguments
793 that were passed to it, and the error it generated. I.e.
794
795 $on_fail->( "socket", $family, $socktype, $protocol, $! );
796
797 $on_fail->( "bind", $sock, $address, $! );
798
799 $on_fail->( "connect", $sock, $address, $! );
800
801 Because of the "try all" nature when given a list of multiple
802 addresses, this callback may be invoked multiple times, even
803 before an eventual success.
804
805 This method accepts an "extensions" parameter; see the "EXTENSIONS"
806 section below.
807
808 connect (void)
809 $loop->connect( %params )
810
811 When not returning a future, additional parameters can be given
812 containing the continuations to invoke on success or failure.
813
814 on_connected => CODE
815 A continuation that is invoked on a successful connect(2) call
816 to a valid socket. It will be passed the connected socket
817 handle, as an "IO::Socket" object.
818
819 $on_connected->( $handle )
820
821 on_stream => CODE
822 An alternative to "on_connected", a continuation that is passed
823 an instance of IO::Async::Stream when the socket is connected.
824 This is provided as a convenience for the common case that a
825 Stream object is required as the transport for a Protocol
826 object.
827
828 $on_stream->( $stream )
829
830 on_socket => CODE
831 Similar to "on_stream", but constructs an instance of
832 IO::Async::Socket. This is most useful for "SOCK_DGRAM" or
833 "SOCK_RAW" sockets.
834
835 $on_socket->( $socket )
836
837 on_connect_error => CODE
838 A continuation that is invoked after all of the addresses have
839 been tried, and none of them succeeded. It will be passed the
840 most significant error that occurred, and the name of the
841 operation it occurred in. Errors from the connect(2) syscall
842 are considered most significant, then bind(2), then finally
843 socket(2).
844
845 $on_connect_error->( $syscall, $! )
846
847 on_resolve_error => CODE
848 A continuation that is invoked when the name resolution attempt
849 fails. This is invoked in the same way as the "on_error"
850 continuation for the "resolve" method.
851
852 listen
853 $listener = $loop->listen( %params )->get
854
855 This method sets up a listening socket and arranges for an acceptor
856 callback to be invoked each time a new connection is accepted on the
857 socket. Internally it creates an instance of IO::Async::Listener and
858 adds it to the Loop if not given one in the arguments.
859
860 Addresses may be given directly, or they may be looked up using the
861 system's name resolver, or a socket handle may be given directly.
862
863 If multiple addresses are given, or resolved from the service and
864 hostname, then each will be attempted in turn until one succeeds.
865
866 In named resolver mode, the %params hash takes the following keys:
867
868 service => STRING
869 The service name to listen on.
870
871 host => STRING
872 The hostname to listen on. Optional. Will listen on all
873 addresses if not supplied.
874
875 family => INT
876 socktype => INT
877 protocol => INT
878 flags => INT
879 Optional. Other arguments to pass along with "host" and
880 "service" to the "getaddrinfo" call.
881
882 socktype => STRING
883 Optionally may instead be one of the values 'stream', 'dgram'
884 or 'raw' to stand for "SOCK_STREAM", "SOCK_DGRAM" or
885 "SOCK_RAW". This utility is provided to allow the caller to
886 avoid a separate "use Socket" only for importing these
887 constants.
888
889 It is necessary to pass the "socktype" hint to the resolver when
890 resolving the host/service names into an address, as some OS's
891 "getaddrinfo" functions require this hint. A warning is emitted if
892 neither "socktype" nor "protocol" hint is defined when performing a
893 "getaddrinfo" lookup. To avoid this warning while still specifying no
894 particular "socktype" hint (perhaps to invoke some OS-specific
895 behaviour), pass 0 as the "socktype" value.
896
897 In plain address mode, the %params hash takes the following keys:
898
899 addrs => ARRAY
900 Reference to an array of (possibly-multiple) address structures
901 to attempt to listen on. Each should be in the layout described
902 for "addr". Such a layout is returned by the "getaddrinfo"
903 named resolver.
904
905 addr => ARRAY
906 Shortcut for passing a single address to listen on; it may be
907 passed directly with this key, instead of in another array of
908 its own. This should be in a format recognised by
909 IO::Async::OS's "extract_addrinfo" method. See also the
910 "EXAMPLES" section.
911
912 In direct socket handle mode, the following keys are taken:
913
914 handle => IO
915 The listening socket handle.
916
917 In either case, the following keys are also taken:
918
919 on_fail => CODE
920 Optional. A callback that is invoked if a syscall fails while
921 attempting to create a listening sockets. It is passed the name
922 of the syscall that failed, the arguments that were passed to
923 it, and the error generated. I.e.
924
925 $on_fail->( "socket", $family, $socktype, $protocol, $! );
926
927 $on_fail->( "sockopt", $sock, $optname, $optval, $! );
928
929 $on_fail->( "bind", $sock, $address, $! );
930
931 $on_fail->( "listen", $sock, $queuesize, $! );
932
933 queuesize => INT
934 Optional. The queue size to pass to the listen(2) calls. If not
935 supplied, then 3 will be given instead.
936
937 reuseaddr => BOOL
938 Optional. If true or not supplied then the "SO_REUSEADDR"
939 socket option will be set. To prevent this, pass a false value
940 such as 0.
941
942 v6only => BOOL
943 Optional. If defined, sets or clears the "IPV6_V6ONLY" socket
944 option on "PF_INET6" sockets. This option disables the ability
945 of "PF_INET6" socket to accept connections from "AF_INET"
946 addresses. Not all operating systems allow this option to be
947 disabled.
948
949 An alternative which gives more control over the listener, is to create
950 the IO::Async::Listener object directly and add it explicitly to the
951 Loop.
952
953 This method accepts an "extensions" parameter; see the "EXTENSIONS"
954 section below.
955
956 listen (void)
957 $loop->listen( %params )
958
959 When not returning a future, additional parameters can be given
960 containing the continuations to invoke on success or failure.
961
962 on_notifier => CODE
963 Optional. A callback that is invoked when the Listener object
964 is ready to receive connections. The callback is passed the
965 Listener object itself.
966
967 $on_notifier->( $listener )
968
969 If this callback is required, it may instead be better to
970 construct the Listener object directly.
971
972 on_listen => CODE
973 Optional. A callback that is invoked when the listening socket
974 is ready. Typically this would be used in the name resolver
975 case, in order to inspect the socket's sockname address, or
976 otherwise inspect the filehandle.
977
978 $on_listen->( $socket )
979
980 on_listen_error => CODE
981 A continuation this is invoked after all of the addresses have
982 been tried, and none of them succeeded. It will be passed the
983 most significant error that occurred, and the name of the
984 operation it occurred in. Errors from the listen(2) syscall are
985 considered most significant, then bind(2), then sockopt(2),
986 then finally socket(2).
987
988 on_resolve_error => CODE
989 A continuation that is invoked when the name resolution attempt
990 fails. This is invoked in the same way as the "on_error"
991 continuation for the "resolve" method.
992
994 Because the Magic Constructor searches for OS-specific subclasses of
995 the Loop, several abstractions of OS services are provided, in case
996 specific OSes need to give different implementations on that OS.
997
998 signame2num
999 $signum = $loop->signame2num( $signame )
1000
1001 Legacy wrappers around IO::Async::OS functions.
1002
1003 time
1004 $time = $loop->time
1005
1006 Returns the current UNIX time in fractional seconds. This is currently
1007 equivalent to "Time::HiRes::time" but provided here as a utility for
1008 programs to obtain the time current used by IO::Async for its own
1009 timing purposes.
1010
1011 fork
1012 $pid = $loop->fork( %params )
1013
1014 This method creates a new child process to run a given code block,
1015 returning its process ID.
1016
1017 code => CODE
1018 A block of code to execute in the child process. It will be
1019 called in scalar context inside an "eval" block. The return
1020 value will be used as the exit(2) code from the child if it
1021 returns (or 255 if it returned "undef" or thows an exception).
1022
1023 on_exit => CODE
1024 A optional continuation to be called when the child processes
1025 exits. It will be invoked in the following way:
1026
1027 $on_exit->( $pid, $exitcode )
1028
1029 The second argument is passed the plain perl $? value.
1030
1031 This key is optional; if not supplied, the calling code should
1032 install a handler using the "watch_process" method.
1033
1034 keep_signals => BOOL
1035 Optional boolean. If missing or false, any CODE references in
1036 the %SIG hash will be removed and restored back to "DEFAULT" in
1037 the child process. If true, no adjustment of the %SIG hash will
1038 be performed.
1039
1040 create_thread
1041 $tid = $loop->create_thread( %params )
1042
1043 This method creates a new (non-detached) thread to run the given code
1044 block, returning its thread ID.
1045
1046 code => CODE
1047 A block of code to execute in the thread. It is called in the
1048 context given by the "context" argument, and its return value
1049 will be available to the "on_joined" callback. It is called
1050 inside an "eval" block; if it fails the exception will be
1051 caught.
1052
1053 context => "scalar" | "list" | "void"
1054 Optional. Gives the calling context that "code" is invoked in.
1055 Defaults to "scalar" if not supplied.
1056
1057 on_joined => CODE
1058 Callback to invoke when the thread function returns or throws
1059 an exception. If it returned, this callback will be invoked
1060 with its result
1061
1062 $on_joined->( return => @result )
1063
1064 If it threw an exception the callback is invoked with the value
1065 of $@
1066
1067 $on_joined->( died => $! )
1068
1070 As "IO::Async::Loop" is an abstract base class, specific subclasses of
1071 it are required to implement certain methods that form the base level
1072 of functionality. They are not recommended for applications to use; see
1073 instead the various event objects or higher level methods listed above.
1074
1075 These methods should be considered as part of the interface contract
1076 required to implement a "IO::Async::Loop" subclass.
1077
1078 API_VERSION
1079 IO::Async::Loop->API_VERSION
1080
1081 This method will be called by the magic constructor on the class before
1082 it is constructed, to ensure that the specific implementation will
1083 support the required API. This method should return the API version
1084 that the loop implementation supports. The magic constructor will use
1085 that class, provided it declares a version at least as new as the
1086 version documented here.
1087
1088 The current API version is 0.49.
1089
1090 This method may be implemented using "constant"; e.g
1091
1092 use constant API_VERSION => '0.49';
1093
1094 watch_io
1095 $loop->watch_io( %params )
1096
1097 This method installs callback functions which will be invoked when the
1098 given IO handle becomes read- or write-ready.
1099
1100 The %params hash takes the following keys:
1101
1102 handle => IO
1103 The IO handle to watch.
1104
1105 on_read_ready => CODE
1106 Optional. A CODE reference to call when the handle becomes
1107 read-ready.
1108
1109 on_write_ready => CODE
1110 Optional. A CODE reference to call when the handle becomes
1111 write-ready.
1112
1113 There can only be one filehandle of any given fileno registered at any
1114 one time. For any one filehandle, there can only be one read-readiness
1115 and/or one write-readiness callback at any one time. Registering a new
1116 one will remove an existing one of that type. It is not required that
1117 both are provided.
1118
1119 Applications should use a IO::Async::Handle or IO::Async::Stream
1120 instead of using this method.
1121
1122 If the filehandle does not yet have the "O_NONBLOCK" flag set, it will
1123 be enabled by this method. This will ensure that any subsequent
1124 "sysread", "syswrite", or similar will not block on the filehandle.
1125
1126 unwatch_io
1127 $loop->unwatch_io( %params )
1128
1129 This method removes a watch on an IO handle which was previously
1130 installed by "watch_io".
1131
1132 The %params hash takes the following keys:
1133
1134 handle => IO
1135 The IO handle to remove the watch for.
1136
1137 on_read_ready => BOOL
1138 If true, remove the watch for read-readiness.
1139
1140 on_write_ready => BOOL
1141 If true, remove the watch for write-readiness.
1142
1143 Either or both callbacks may be removed at once. It is not an error to
1144 attempt to remove a callback that is not present. If both callbacks
1145 were provided to the "watch_io" method and only one is removed by this
1146 method, the other shall remain.
1147
1148 watch_signal
1149 $loop->watch_signal( $signal, $code )
1150
1151 This method adds a new signal handler to watch the given signal.
1152
1153 $signal The name of the signal to watch to. This should be a bare name
1154 like "TERM".
1155
1156 $code A CODE reference to the handling callback.
1157
1158 There can only be one callback per signal name. Registering a new one
1159 will remove an existing one.
1160
1161 Applications should use a IO::Async::Signal object, or call
1162 "attach_signal" instead of using this method.
1163
1164 This and "unwatch_signal" are optional; a subclass may implement
1165 neither, or both. If it implements neither then signal handling will be
1166 performed by the base class using a self-connected pipe to interrupt
1167 the main IO blocking.
1168
1169 unwatch_signal
1170 $loop->unwatch_signal( $signal )
1171
1172 This method removes the signal callback for the given signal.
1173
1174 $signal The name of the signal to watch to. This should be a bare name
1175 like "TERM".
1176
1177 watch_time
1178 $id = $loop->watch_time( %args )
1179
1180 This method installs a callback which will be called at the specified
1181 time. The time may either be specified as an absolute value (the "at"
1182 key), or as a delay from the time it is installed (the "after" key).
1183
1184 The returned $id value can be used to identify the timer in case it
1185 needs to be cancelled by the "unwatch_time" method. Note that this
1186 value may be an object reference, so if it is stored, it should be
1187 released after it has been fired or cancelled, so the object itself can
1188 be freed.
1189
1190 The %params hash takes the following keys:
1191
1192 at => NUM
1193 The absolute system timestamp to run the event.
1194
1195 after => NUM
1196 The delay after now at which to run the event, if "at" is not
1197 supplied. A zero or negative delayed timer should be executed
1198 as soon as possible; the next time the "loop_once" method is
1199 invoked.
1200
1201 now => NUM
1202 The time to consider as now if calculating an absolute time
1203 based on "after"; defaults to "time()" if not specified.
1204
1205 code => CODE
1206 CODE reference to the continuation to run at the allotted time.
1207
1208 Either one of "at" or "after" is required.
1209
1210 For more powerful timer functionality as a IO::Async::Notifier (so it
1211 can be used as a child within another Notifier), see instead the
1212 IO::Async::Timer object and its subclasses.
1213
1214 These *_time methods are optional; a subclass may implement neither or
1215 both of them. If it implements neither, then the base class will manage
1216 a queue of timer events. This queue should be handled by the
1217 "loop_once" method implemented by the subclass, using the
1218 "_adjust_timeout" and "_manage_queues" methods.
1219
1220 This is the newer version of the API, replacing "enqueue_timer". It is
1221 unspecified how this method pair interacts with the older
1222 "enqueue/requeue/cancel_timer" triplet.
1223
1224 unwatch_time
1225 $loop->unwatch_time( $id )
1226
1227 Removes a timer callback previously created by "watch_time".
1228
1229 This is the newer version of the API, replacing "cancel_timer". It is
1230 unspecified how this method pair interacts with the older
1231 "enqueue/requeue/cancel_timer" triplet.
1232
1233 enqueue_timer
1234 $id = $loop->enqueue_timer( %params )
1235
1236 An older version of "watch_time". This method should not be used in new
1237 code but is retained for legacy purposes. For simple watch/unwatch
1238 behaviour use instead the new "watch_time" method; though note it has
1239 differently-named arguments. For requeueable timers, consider using an
1240 IO::Async::Timer::Countdown or IO::Async::Timer::Absolute instead.
1241
1242 cancel_timer
1243 $loop->cancel_timer( $id )
1244
1245 An older version of "unwatch_time". This method should not be used in
1246 new code but is retained for legacy purposes.
1247
1248 requeue_timer
1249 $newid = $loop->requeue_timer( $id, %params )
1250
1251 Reschedule an existing timer, moving it to a new time. The old timer is
1252 removed and will not be invoked.
1253
1254 The %params hash takes the same keys as "enqueue_timer", except for the
1255 "code" argument.
1256
1257 The requeue operation may be implemented as a cancel + enqueue, which
1258 may mean the ID changes. Be sure to store the returned $newid value if
1259 it is required.
1260
1261 This method should not be used in new code but is retained for legacy
1262 purposes. For requeueable, consider using an
1263 IO::Async::Timer::Countdown or IO::Async::Timer::Absolute instead.
1264
1265 watch_idle
1266 $id = $loop->watch_idle( %params )
1267
1268 This method installs a callback which will be called at some point in
1269 the near future.
1270
1271 The %params hash takes the following keys:
1272
1273 when => STRING
1274 Specifies the time at which the callback will be invoked. See
1275 below.
1276
1277 code => CODE
1278 CODE reference to the continuation to run at the allotted time.
1279
1280 The "when" parameter defines the time at which the callback will later
1281 be invoked. Must be one of the following values:
1282
1283 later Callback is invoked after the current round of IO events have
1284 been processed by the loop's underlying "loop_once" method.
1285
1286 If a new idle watch is installed from within a "later"
1287 callback, the installed one will not be invoked during this
1288 round. It will be deferred for the next time "loop_once" is
1289 called, after any IO events have been handled.
1290
1291 If there are pending idle handlers, then the "loop_once" method will
1292 use a zero timeout; it will return immediately, having processed any IO
1293 events and idle handlers.
1294
1295 The returned $id value can be used to identify the idle handler in case
1296 it needs to be removed, by calling the "unwatch_idle" method. Note this
1297 value may be a reference, so if it is stored it should be released
1298 after the callback has been invoked or cancled, so the referrant itself
1299 can be freed.
1300
1301 This and "unwatch_idle" are optional; a subclass may implement neither,
1302 or both. If it implements neither then idle handling will be performed
1303 by the base class, using the "_adjust_timeout" and "_manage_queues"
1304 methods.
1305
1306 unwatch_idle
1307 $loop->unwatch_idle( $id )
1308
1309 Cancels a previously-installed idle handler.
1310
1311 watch_process
1312 $loop->watch_process( $pid, $code )
1313
1314 This method adds a new handler for the termination of the given child
1315 process PID, or all child processes.
1316
1317 $pid The PID to watch. Will report on all child processes if this is
1318 0.
1319
1320 $code A CODE reference to the exit handler. It will be invoked as
1321
1322 $code->( $pid, $? )
1323
1324 The second argument is passed the plain perl $? value.
1325
1326 After invocation, the handler for a PID-specific watch is automatically
1327 removed. The all-child watch will remain until it is removed by
1328 "unwatch_process".
1329
1330 This and "unwatch_process" are optional; a subclass may implement
1331 neither, or both. If it implements neither then child watching will be
1332 performed by using "watch_signal" to install a "SIGCHLD" handler, which
1333 will use "waitpid" to look for exited child processes.
1334
1335 If both a PID-specific and an all-process watch are installed, there is
1336 no ordering guarantee as to which will be called first.
1337
1338 NOTE that not all loop classes may be able to support the all-child
1339 watch. The basic Select and Poll-based classes provided by this
1340 distribution do, and those built on top of similar OS-specific
1341 mechanisms such as Linux's Epoll probably will, but typically those
1342 built on top of other event systems such as glib or libuv may not be
1343 able, as the underlying event system may not provide the necessary
1344 hooks to support it.
1345
1346 unwatch_process
1347 $loop->unwatch_process( $pid )
1348
1349 This method removes a watch on an existing child process PID.
1350
1352 The following methods are provided to access internal features which
1353 are required by specific subclasses to implement the loop
1354 functionality. The use cases of each will be documented in the above
1355 section.
1356
1357 _adjust_timeout
1358 $loop->_adjust_timeout( \$timeout )
1359
1360 Shortens the timeout value passed in the scalar reference if it is
1361 longer in seconds than the time until the next queued event on the
1362 timer queue. If there are pending idle handlers, the timeout is reduced
1363 to zero.
1364
1365 _manage_queues
1366 $loop->_manage_queues
1367
1368 Checks the timer queue for callbacks that should have been invoked by
1369 now, and runs them all, removing them from the queue. It also invokes
1370 all of the pending idle handlers. Any new idle handlers installed by
1371 these are not invoked yet; they will wait for the next time this method
1372 is called.
1373
1375 An Extension is a Perl module that provides extra methods in the
1376 "IO::Async::Loop" or other packages. They are intended to provide extra
1377 functionality that easily integrates with the rest of the code.
1378
1379 Certain base methods take an "extensions" parameter; an ARRAY reference
1380 containing a list of extension names. If such a list is passed to a
1381 method, it will immediately call a method whose name is that of the
1382 base method, prefixed by the first extension name in the list,
1383 separated by "_". If the "extensions" list contains more extension
1384 names, it will be passed the remaining ones in another "extensions"
1385 parameter.
1386
1387 For example,
1388
1389 $loop->connect(
1390 extensions => [qw( FOO BAR )],
1391 %args
1392 )
1393
1394 will become
1395
1396 $loop->FOO_connect(
1397 extensions => [qw( BAR )],
1398 %args
1399 )
1400
1401 This is provided so that extension modules, such as IO::Async::SSL can
1402 easily be invoked indirectly, by passing extra arguments to "connect"
1403 methods or similar, without needing every module to be aware of the
1404 "SSL" extension. This functionality is generic and not limited to
1405 "SSL"; other extensions may also use it.
1406
1407 The following methods take an "extensions" parameter:
1408
1409 $loop->connect
1410 $loop->listen
1411
1412 If an extension "listen" method is invoked, it will be passed a
1413 "listener" parameter even if one was not provided to the original
1414 "$loop->listen" call, and it will not receive any of the "on_*" event
1415 callbacks. It should use the "acceptor" parameter on the "listener"
1416 object.
1417
1419 A well-behaved IO::Async program should spend almost all of its time
1420 blocked on input using the underlying "IO::Async::Loop" instance. The
1421 stall watchdog is an optional debugging feature to help detect CPU
1422 spinlocks and other bugs, where control is not returned to the loop
1423 every so often.
1424
1425 If the watchdog is enabled and an event handler consumes more than a
1426 given amount of real time before returning to the event loop, it will
1427 be interrupted by printing a stack trace and terminating the program.
1428 The watchdog is only in effect while the loop itself is not blocking;
1429 it won't fail simply because the loop instance is waiting for input or
1430 timers.
1431
1432 It is implemented using "SIGALRM", so if enabled, this signal will no
1433 longer be available to user code. (Though in any case, most uses of
1434 "alarm()" and "SIGALRM" are better served by one of the
1435 IO::Async::Timer subclasses).
1436
1437 The following environment variables control its behaviour.
1438
1439 IO_ASYNC_WATCHDOG => BOOL
1440 Enables the stall watchdog if set to a non-zero value.
1441
1442 IO_ASYNC_WATCHDOG_INTERVAL => INT
1443 Watchdog interval, in seconds, to pass to the alarm(2) call.
1444 Defaults to 10 seconds.
1445
1446 IO_ASYNC_WATCHDOG_SIGABRT => BOOL
1447 If enabled, the watchdog signal handler will raise a "SIGABRT",
1448 which usually has the effect of breaking out of a running program
1449 in debuggers such as gdb. If not set then the process is terminated
1450 by throwing an exception with "die".
1451
1453 Paul Evans <leonerd@leonerd.org.uk>
1454
1455
1456
1457perl v5.36.0 2022-05-31 IO::Async::Loop(3)