1# You may distribute under the terms of either the GNU General Public License 2# or the Artistic License (the same terms as Perl itself) 3# 4# (C) Paul Evans, 2007-2021 -- leonerd@leonerd.org.uk 5 6package IO::Async::Loop; 7 8use strict; 9use warnings; 10 11our $VERSION = '0.800'; 12 13# When editing this value don't forget to update the docs below 14use constant NEED_API_VERSION => '0.33'; 15 16# Base value but some classes might override 17use constant _CAN_ON_HANGUP => 0; 18 19# Most Loop implementations do not accurately handle sub-second timers. 20# This only matters for unit tests 21use constant _CAN_SUBSECOND_ACCURATELY => 0; 22 23# Does the loop implementation support IO_ASYNC_WATCHDOG? 24use constant _CAN_WATCHDOG => 0; 25 26# Does the loop support ->watch_process on PID 0 to observe all exits? 27use constant _CAN_WATCH_ALL_PIDS => 1; 28 29# Watchdog configuration constants 30use constant WATCHDOG_ENABLE => $ENV{IO_ASYNC_WATCHDOG}; 31use constant WATCHDOG_INTERVAL => $ENV{IO_ASYNC_WATCHDOG_INTERVAL} || 10; 32use constant WATCHDOG_SIGABRT => $ENV{IO_ASYNC_WATCHDOG_SIGABRT}; 33 34use Carp; 35 36use Time::HiRes qw(); # empty import 37use POSIX qw( WNOHANG ); 38use Scalar::Util qw( refaddr weaken ); 39use Socket qw( SO_REUSEADDR AF_INET6 IPPROTO_IPV6 IPV6_V6ONLY ); 40 41use IO::Async::OS; 42use IO::Async::Metrics '$METRICS'; 43 44use constant HAVE_SIGNALS => IO::Async::OS->HAVE_SIGNALS; 45use constant HAVE_POSIX_FORK => IO::Async::OS->HAVE_POSIX_FORK; 46use constant HAVE_THREADS => IO::Async::OS->HAVE_THREADS; 47 48# Never sleep for more than 1 second if a signal proxy is registered, to avoid 49# a borderline race condition. 50# There is a race condition in perl involving signals interacting with XS code 51# that implements blocking syscalls. There is a slight chance a signal will 52# arrive in the XS function, before the blocking itself. Perl will not run our 53# (safe) deferred signal handler in this case. To mitigate this, if we have a 54# signal proxy, we'll adjust the maximal timeout. The signal handler will be 55# run when the XS function returns. 56our $MAX_SIGWAIT_TIME = 1; 57 58# Also, never sleep for more than 1 second if the OS does not support signals 59# and we have child watches registered (so we must use waitpid() polling) 60our $MAX_CHILDWAIT_TIME = 1; 61 62# Maybe our calling program will have a suggested hint of a specific Loop 63# class or list of classes to use 64our $LOOP; 65 66# Undocumented; used only by the test scripts. 67# Setting this value true will avoid the IO::Async::Loop::$^O candidate in the 68# magic constructor 69our $LOOP_NO_OS; 70 71# SIGALRM handler for watchdog 72$SIG{ALRM} = sub { 73 # There are two extra frames here; this one and the signal handler itself 74 local $Carp::CarpLevel = $Carp::CarpLevel + 2; 75 if( WATCHDOG_SIGABRT ) { 76 print STDERR Carp::longmess( "Watchdog timeout" ); 77 kill ABRT => $$; 78 } 79 else { 80 Carp::confess( "Watchdog timeout" ); 81 } 82} if WATCHDOG_ENABLE; 83 84# There are two default values that might apply; undef or "DEFAULT" 85$SIG{PIPE} = "IGNORE" if ( $SIG{PIPE} || "DEFAULT" ) eq "DEFAULT"; 86 87=head1 NAME 88 89C<IO::Async::Loop> - core loop of the C<IO::Async> framework 90 91=head1 SYNOPSIS 92 93 use IO::Async::Stream; 94 use IO::Async::Timer::Countdown; 95 96 use IO::Async::Loop; 97 98 my $loop = IO::Async::Loop->new; 99 100 $loop->add( IO::Async::Timer::Countdown->new( 101 delay => 10, 102 on_expire => sub { print "10 seconds have passed\n" }, 103 )->start ); 104 105 $loop->add( IO::Async::Stream->new_for_stdin( 106 on_read => sub { 107 my ( $self, $buffref, $eof ) = @_; 108 109 while( $$buffref =~ s/^(.*)\n// ) { 110 print "You typed a line $1\n"; 111 } 112 113 return 0; 114 }, 115 ) ); 116 117 $loop->run; 118 119=head1 DESCRIPTION 120 121This module provides an abstract class which implements the core loop of the 122L<IO::Async> framework. Its primary purpose is to store a set of 123L<IO::Async::Notifier> objects or subclasses of them. It handles all of the 124lower-level set manipulation actions, and leaves the actual IO readiness 125testing/notification to the concrete class that implements it. It also 126provides other functionality such as signal handling, child process managing, 127and timers. 128 129See also the two bundled Loop subclasses: 130 131=over 4 132 133=item L<IO::Async::Loop::Select> 134 135=item L<IO::Async::Loop::Poll> 136 137=back 138 139Or other subclasses that may appear on CPAN which are not part of the core 140L<IO::Async> distribution. 141 142=head2 Ignoring SIGPIPE 143 144Since version I<0.66> loading this module automatically ignores C<SIGPIPE>, as 145it is highly unlikely that the default-terminate action is the best course of 146action for an L<IO::Async>-based program to take. If at load time the handler 147disposition is still set as C<DEFAULT>, it is set to ignore. If already 148another handler has been placed there by the program code, it will be left 149undisturbed. 150 151=cut 152 153# Internal constructor used by subclasses 154sub __new 155{ 156 my $class = shift; 157 158 # Detect if the API version provided by the subclass is sufficient 159 $class->can( "API_VERSION" ) or 160 die "$class is too old for IO::Async $VERSION; it does not provide \->API_VERSION\n"; 161 162 $class->API_VERSION >= NEED_API_VERSION or 163 die "$class is too old for IO::Async $VERSION; we need API version >= ".NEED_API_VERSION.", it provides ".$class->API_VERSION."\n"; 164 165 WATCHDOG_ENABLE and !$class->_CAN_WATCHDOG and 166 warn "$class cannot implement IO_ASYNC_WATCHDOG\n"; 167 168 my $self = bless { 169 notifiers => {}, # {nkey} = notifier 170 iowatches => {}, # {fd} = [ $on_read_ready, $on_write_ready, $on_hangup ] 171 sigattaches => {}, # {sig} => \@callbacks 172 childmanager => undef, 173 childwatches => {}, # {pid} => $code 174 threadwatches => {}, # {tid} => $code 175 timequeue => undef, 176 deferrals => [], 177 os => {}, # A generic scratchpad for IO::Async::OS to store whatever it wants 178 }, $class; 179 180 $METRICS and $METRICS->inc_gauge( loops => [ class => ref $self ] ); 181 182 # It's possible this is a specific subclass constructor. We still want the 183 # magic IO::Async::Loop->new constructor to yield this if it's the first 184 # one 185 our $ONE_TRUE_LOOP ||= $self; 186 187 # Legacy support - temporary until all CPAN classes are updated; bump NEEDAPI version at that point 188 my $old_timer = $self->can( "enqueue_timer" ) != \&enqueue_timer; 189 if( $old_timer != ( $self->can( "cancel_timer" ) != \&cancel_timer ) ) { 190 die "$class should overload both ->enqueue_timer and ->cancel_timer, or neither"; 191 } 192 193 if( $old_timer ) { 194 warnings::warnif( deprecated => "Enabling old_timer workaround for old loop class " . $class ); 195 } 196 197 $self->{old_timer} = $old_timer; 198 199 return $self; 200} 201 202sub DESTROY 203{ 204 my $self = shift; 205 206 $METRICS and $METRICS->dec_gauge( loops => [ class => ref $self ] ); 207} 208 209=head1 MAGIC CONSTRUCTOR 210 211=head2 new 212 213 $loop = IO::Async::Loop->new 214 215This function attempts to find a good subclass to use, then calls its 216constructor. It works by making a list of likely candidate classes, then 217trying each one in turn, C<require>ing the module then calling its C<new> 218method. If either of these operations fails, the next subclass is tried. If 219no class was successful, then an exception is thrown. 220 221The constructed object is cached, and will be returned again by a subsequent 222call. The cache will also be set by a constructor on a specific subclass. This 223behaviour makes it possible to simply use the normal constructor in a module 224that wishes to interact with the main program's Loop, such as an integration 225module for another event system. 226 227For example, the following two C<$loop> variables will refer to the same 228object: 229 230 use IO::Async::Loop; 231 use IO::Async::Loop::Poll; 232 233 my $loop_poll = IO::Async::Loop::Poll->new; 234 235 my $loop = IO::Async::Loop->new; 236 237While it is not advised to do so under normal circumstances, if the program 238really wishes to construct more than one Loop object, it can call the 239constructor C<really_new>, or invoke one of the subclass-specific constructors 240directly. 241 242The list of candidates is formed from the following choices, in this order: 243 244=over 4 245 246=item * $ENV{IO_ASYNC_LOOP} 247 248If this environment variable is set, it should contain a comma-separated list 249of subclass names. These names may or may not be fully-qualified; if a name 250does not contain C<::> then it will have C<IO::Async::Loop::> prepended to it. 251This allows the end-user to specify a particular choice to fit the needs of 252his use of a program using L<IO::Async>. 253 254=item * $IO::Async::Loop::LOOP 255 256If this scalar is set, it should contain a comma-separated list of subclass 257names. These may or may not be fully-qualified, as with the above case. This 258allows a program author to suggest a loop module to use. 259 260In cases where the module subclass is a hard requirement, such as GTK programs 261using C<Glib>, it would be better to use the module specifically and invoke 262its constructor directly. 263 264=item * IO::Async::OS->LOOP_PREFER_CLASSES 265 266The L<IO::Async::OS> hints module for the given OS is then consulted to see if 267it suggests any other module classes specific to the given operating system. 268 269=item * $^O 270 271The module called C<IO::Async::Loop::$^O> is tried next. This allows specific 272OSes, such as the ever-tricky C<MSWin32>, to provide an implementation that 273might be more efficient than the generic ones, or even work at all. 274 275This option is now discouraged in favour of the L<IO::Async::OS> hint instead. 276At some future point it may be removed entirely, given as currently only 277C<linux> uses it. 278 279=item * Poll and Select 280 281Finally, if no other choice has been made by now, the built-in C<Poll> module 282is chosen. This should always work, but in case it doesn't, the C<Select> 283module will be chosen afterwards as a last-case attempt. If this also fails, 284then the magic constructor itself will throw an exception. 285 286=back 287 288If any of the explicitly-requested loop types (C<$ENV{IO_ASYNC_LOOP}> or 289C<$IO::Async::Loop::LOOP>) fails to load then a warning is printed detailing 290the error. 291 292Implementors of new C<IO::Async::Loop> subclasses should see the notes about 293C<API_VERSION> below. 294 295=cut 296 297sub __try_new 298{ 299 my ( $class ) = @_; 300 301 ( my $file = "$class.pm" ) =~ s{::}{/}g; 302 303 eval { 304 local $SIG{__WARN__} = sub {}; 305 require $file; 306 } or return; 307 308 my $self; 309 $self = eval { $class->new } and return $self; 310 311 # Oh dear. We've loaded the code OK but for some reason the constructor 312 # wasn't happy. Being polite we ought really to unload the file again, 313 # but perl doesn't actually provide us a way to do this. 314 315 return undef; 316} 317 318sub new 319{ 320 return our $ONE_TRUE_LOOP ||= shift->really_new; 321} 322 323# Ensure that the loop is DESTROYed recursively at exit time, before GD happens 324END { 325 undef our $ONE_TRUE_LOOP; 326} 327 328sub really_new 329{ 330 shift; # We're going to ignore the class name actually given 331 my $self; 332 333 my @candidates; 334 335 push @candidates, split( m/,/, $ENV{IO_ASYNC_LOOP} ) if defined $ENV{IO_ASYNC_LOOP}; 336 337 push @candidates, split( m/,/, $LOOP ) if defined $LOOP; 338 339 foreach my $class ( @candidates ) { 340 $class =~ m/::/ or $class = "IO::Async::Loop::$class"; 341 $self = __try_new( $class ) and return $self; 342 343 my ( $topline ) = split m/\n/, $@; # Ignore all the other lines; they'll be require's verbose output 344 warn "Unable to use $class - $topline\n"; 345 } 346 347 unless( $LOOP_NO_OS ) { 348 foreach my $class ( IO::Async::OS->LOOP_PREFER_CLASSES, "IO::Async::Loop::$^O" ) { 349 $class =~ m/::/ or $class = "IO::Async::Loop::$class"; 350 $self = __try_new( $class ) and return $self; 351 352 # Don't complain about these ones 353 } 354 } 355 356 return IO::Async::Loop->new_builtin; 357} 358 359sub new_builtin 360{ 361 shift; 362 my $self; 363 364 foreach my $class ( IO::Async::OS->LOOP_BUILTIN_CLASSES ) { 365 $self = __try_new( "IO::Async::Loop::$class" ) and return $self; 366 } 367 368 croak "Cannot find a suitable candidate class"; 369} 370 371####################### 372# Notifier management # 373####################### 374 375=head1 NOTIFIER MANAGEMENT 376 377The following methods manage the collection of L<IO::Async::Notifier> objects. 378 379=cut 380 381=head2 add 382 383 $loop->add( $notifier ) 384 385This method adds another notifier object to the stored collection. The object 386may be a L<IO::Async::Notifier>, or any subclass of it. 387 388When a notifier is added, any children it has are also added, recursively. In 389this way, entire sections of a program may be written within a tree of 390notifier objects, and added or removed on one piece. 391 392=cut 393 394sub add 395{ 396 my $self = shift; 397 my ( $notifier ) = @_; 398 399 if( defined $notifier->parent ) { 400 croak "Cannot add a child notifier directly - add its parent"; 401 } 402 403 if( defined $notifier->loop ) { 404 croak "Cannot add a notifier that is already a member of a loop"; 405 } 406 407 $self->_add_noparentcheck( $notifier ); 408} 409 410sub _add_noparentcheck 411{ 412 my $self = shift; 413 my ( $notifier ) = @_; 414 415 my $nkey = refaddr $notifier; 416 417 $self->{notifiers}->{$nkey} = $notifier; 418 $METRICS and $METRICS->inc_gauge( notifiers => ); 419 420 $notifier->__set_loop( $self ); 421 422 $self->_add_noparentcheck( $_ ) for $notifier->children; 423 424 return; 425} 426 427=head2 remove 428 429 $loop->remove( $notifier ) 430 431This method removes a notifier object from the stored collection, and 432recursively and children notifiers it contains. 433 434=cut 435 436sub remove 437{ 438 my $self = shift; 439 my ( $notifier ) = @_; 440 441 if( defined $notifier->parent ) { 442 croak "Cannot remove a child notifier directly - remove its parent"; 443 } 444 445 $self->_remove_noparentcheck( $notifier ); 446} 447 448sub _remove_noparentcheck 449{ 450 my $self = shift; 451 my ( $notifier ) = @_; 452 453 my $nkey = refaddr $notifier; 454 455 exists $self->{notifiers}->{$nkey} or croak "Notifier does not exist in collection"; 456 457 delete $self->{notifiers}->{$nkey}; 458 $METRICS and $METRICS->dec_gauge( notifiers => ); 459 460 $notifier->__set_loop( undef ); 461 462 $self->_remove_noparentcheck( $_ ) for $notifier->children; 463 464 return; 465} 466 467=head2 notifiers 468 469 @notifiers = $loop->notifiers 470 471Returns a list of all the notifier objects currently stored in the Loop. 472 473=cut 474 475sub notifiers 476{ 477 my $self = shift; 478 # Sort so the order remains stable under additions/removals 479 return map { $self->{notifiers}->{$_} } sort keys %{ $self->{notifiers} }; 480} 481 482################### 483# Looping support # 484################### 485 486=head1 LOOPING CONTROL 487 488The following methods control the actual run cycle of the loop, and hence the 489program. 490 491=cut 492 493=head2 loop_once 494 495 $count = $loop->loop_once( $timeout ) 496 497This method performs a single wait loop using the specific subclass's 498underlying mechanism. If C<$timeout> is undef, then no timeout is applied, and 499it will wait until an event occurs. The intention of the return value is to 500indicate the number of callbacks that this loop executed, though different 501subclasses vary in how accurately they can report this. See the documentation 502for this method in the specific subclass for more information. 503 504=cut 505 506sub loop_once 507{ 508 my $self = shift; 509 my ( $timeout ) = @_; 510 511 croak "Expected that $self overrides ->loop_once"; 512} 513 514=head2 run 515 516 @result = $loop->run 517 518 $result = $loop->run 519 520Runs the actual IO event loop. This method blocks until the C<stop> method is 521called, and returns the result that was passed to C<stop>. In scalar context 522only the first result is returned; the others will be discarded if more than 523one value was provided. This method may be called recursively. 524 525This method is a recent addition and may not be supported by all the 526C<IO::Async::Loop> subclasses currently available on CPAN. 527 528=cut 529 530sub run 531{ 532 my $self = shift; 533 534 local $self->{running} = 1; 535 local $self->{result} = []; 536 537 while( $self->{running} ) { 538 $self->loop_once( undef ); 539 } 540 541 return wantarray ? @{ $self->{result} } : $self->{result}[0]; 542} 543 544=head2 stop 545 546 $loop->stop( @result ) 547 548Stops the inner-most C<run> method currently in progress, causing it to return 549the given C<@result>. 550 551This method is a recent addition and may not be supported by all the 552C<IO::Async::Loop> subclasses currently available on CPAN. 553 554=cut 555 556sub stop 557{ 558 my $self = shift; 559 560 @{ $self->{result} } = @_; 561 undef $self->{running}; 562} 563 564=head2 loop_forever 565 566 $loop->loop_forever 567 568A synonym for C<run>, though this method does not return a result. 569 570=cut 571 572sub loop_forever 573{ 574 my $self = shift; 575 $self->run; 576 return; 577} 578 579=head2 loop_stop 580 581 $loop->loop_stop 582 583A synonym for C<stop>, though this method does not pass any results. 584 585=cut 586 587sub loop_stop 588{ 589 my $self = shift; 590 $self->stop; 591} 592 593=head2 post_fork 594 595 $loop->post_fork 596 597The base implementation of this method does nothing. It is provided in case 598some Loop subclasses should take special measures after a C<fork()> system 599call if the main body of the program should survive in both running processes. 600 601This may be required, for example, in a long-running server daemon that forks 602multiple copies on startup after opening initial listening sockets. A loop 603implementation that uses some in-kernel resource that becomes shared after 604forking (for example, a Linux C<epoll> or a BSD C<kqueue> filehandle) would 605need recreating in the new child process before the program can continue. 606 607=cut 608 609sub post_fork 610{ 611 my $self = shift; 612 613 IO::Async::OS->post_fork( $self ); 614} 615 616########### 617# Futures # 618########### 619 620=head1 FUTURE SUPPORT 621 622The following methods relate to L<IO::Async::Future> objects. 623 624=cut 625 626=head2 new_future 627 628 $future = $loop->new_future 629 630Returns a new L<IO::Async::Future> instance with a reference to the Loop. 631 632=cut 633 634sub new_future 635{ 636 my $self = shift; 637 require IO::Async::Future; 638 return IO::Async::Future->new( $self ); 639} 640 641=head2 await 642 643 $loop->await( $future ) 644 645Blocks until the given future is ready, as indicated by its C<is_ready> method. 646As a convenience it returns the future, to simplify code: 647 648 my @result = $loop->await( $future )->get; 649 650=cut 651 652sub await 653{ 654 my $self = shift; 655 my ( $future ) = @_; 656 657 $self->loop_once until $future->is_ready; 658 659 return $future; 660} 661 662=head2 await_all 663 664 $loop->await_all( @futures ) 665 666Blocks until all the given futures are ready, as indicated by the C<is_ready> 667method. Equivalent to calling C<await> on a C<< Future->wait_all >> except 668that it doesn't create the surrounding future object. 669 670=cut 671 672sub _all_ready { $_->is_ready or return 0 for @_; return 1 } 673 674sub await_all 675{ 676 my $self = shift; 677 my @futures = @_; 678 679 $self->loop_once until _all_ready @futures; 680} 681 682=head2 delay_future 683 684 $loop->delay_future( %args )->get 685 686Returns a new L<IO::Async::Future> instance which will become done at a given 687point in time. The C<%args> should contain an C<at> or C<after> key as per the 688C<watch_time> method. The returned future may be cancelled to cancel the 689timer. At the alloted time the future will succeed with an empty result list. 690 691=cut 692 693sub delay_future 694{ 695 my $self = shift; 696 my %args = @_; 697 698 my $future = $self->new_future; 699 my $id = $self->watch_time( %args, 700 code => sub { $future->done }, 701 ); 702 703 $future->on_cancel( sub { shift->loop->unwatch_time( $id ) } ); 704 705 return $future; 706} 707 708=head2 timeout_future 709 710 $loop->timeout_future( %args )->get 711 712Returns a new L<IO::Async::Future> instance which will fail at a given point 713in time. The C<%args> should contain an C<at> or C<after> key as per the 714C<watch_time> method. The returned future may be cancelled to cancel the 715timer. At the alloted time, the future will fail with the string C<"Timeout">. 716 717=cut 718 719sub timeout_future 720{ 721 my $self = shift; 722 my %args = @_; 723 724 my $future = $self->new_future; 725 my $id = $self->watch_time( %args, 726 code => sub { $future->fail( "Timeout" ) }, 727 ); 728 729 $future->on_cancel( sub { shift->loop->unwatch_time( $id ) } ); 730 731 return $future; 732} 733 734############ 735# Features # 736############ 737 738=head1 FEATURES 739 740Most of the following methods are higher-level wrappers around base 741functionality provided by the low-level API documented below. They may be 742used by L<IO::Async::Notifier> subclasses or called directly by the program. 743 744The following methods documented with a trailing call to C<< ->get >> return 745L<Future> instances. 746 747=cut 748 749sub __new_feature 750{ 751 my $self = shift; 752 my ( $classname ) = @_; 753 754 ( my $filename = "$classname.pm" ) =~ s{::}{/}g; 755 require $filename; 756 757 # These features aren't supposed to be "user visible", so if methods called 758 # on it carp or croak, the shortmess line ought to skip IO::Async::Loop and 759 # go on report its caller. To make this work, add the feature class to our 760 # @CARP_NOT list. 761 push our(@CARP_NOT), $classname; 762 763 return $classname->new( loop => $self ); 764} 765 766=head2 attach_signal 767 768 $id = $loop->attach_signal( $signal, $code ) 769 770This method adds a new signal handler to watch the given signal. The same 771signal can be attached to multiple times; its callback functions will all be 772invoked, in no particular order. 773 774The returned C<$id> value can be used to identify the signal handler in case 775it needs to be removed by the C<detach_signal> method. Note that this value 776may be an object reference, so if it is stored, it should be released after it 777is cancelled, so the object itself can be freed. 778 779=over 8 780 781=item $signal 782 783The name of the signal to attach to. This should be a bare name like C<TERM>. 784 785=item $code 786 787A CODE reference to the handling callback. 788 789=back 790 791Attaching to C<SIGCHLD> is not recommended because of the way all child 792processes use it to report their termination. Instead, the C<watch_process> 793method should be used to watch for termination of a given child process. A 794warning will be printed if C<SIGCHLD> is passed here, but in future versions 795of L<IO::Async> this behaviour may be disallowed altogether. 796 797See also L<POSIX> for the C<SIGI<name>> constants. 798 799For a more flexible way to use signals from within Notifiers, see instead the 800L<IO::Async::Signal> object. 801 802=cut 803 804sub attach_signal 805{ 806 my $self = shift; 807 my ( $signal, $code ) = @_; 808 809 HAVE_SIGNALS or croak "This OS cannot ->attach_signal"; 810 811 if( $signal eq "CHLD" ) { 812 # We make special exception to allow $self->watch_process to do this 813 caller eq "IO::Async::Loop" or 814 carp "Attaching to SIGCHLD is not advised - use ->watch_process instead"; 815 } 816 817 if( not $self->{sigattaches}->{$signal} ) { 818 my @attaches; 819 $self->watch_signal( $signal, sub { 820 foreach my $attachment ( @attaches ) { 821 $attachment->(); 822 } 823 } ); 824 $self->{sigattaches}->{$signal} = \@attaches; 825 } 826 827 push @{ $self->{sigattaches}->{$signal} }, $code; 828 829 return \$self->{sigattaches}->{$signal}->[-1]; 830} 831 832=head2 detach_signal 833 834 $loop->detach_signal( $signal, $id ) 835 836Removes a previously-attached signal handler. 837 838=over 8 839 840=item $signal 841 842The name of the signal to remove from. This should be a bare name like 843C<TERM>. 844 845=item $id 846 847The value returned by the C<attach_signal> method. 848 849=back 850 851=cut 852 853sub detach_signal 854{ 855 my $self = shift; 856 my ( $signal, $id ) = @_; 857 858 HAVE_SIGNALS or croak "This OS cannot ->detach_signal"; 859 860 # Can't use grep because we have to preserve the addresses 861 my $attaches = $self->{sigattaches}->{$signal} or return; 862 863 for (my $i = 0; $i < @$attaches; ) { 864 $i++, next unless \$attaches->[$i] == $id; 865 866 splice @$attaches, $i, 1, (); 867 } 868 869 if( !@$attaches ) { 870 $self->unwatch_signal( $signal ); 871 delete $self->{sigattaches}->{$signal}; 872 } 873} 874 875=head2 later 876 877 $loop->later( $code ) 878 879 $f = $loop->later 880 881Schedules a code reference to be invoked as soon as the current round of IO 882operations is complete. 883 884The code reference is never invoked immediately, though the loop will not 885perform any blocking operations between when it is installed and when it is 886invoked. It may call C<select>, C<poll> or equivalent with a zero-second 887timeout, and process any currently-pending IO conditions before the code is 888invoked, but it will not block for a non-zero amount of time. 889 890This method is implemented using the C<watch_idle> method, with the C<when> 891parameter set to C<later>. It will return an ID value that can be passed to 892C<unwatch_idle> if required. 893 894I<Since version 0.78>: If no C<$code> value is passed, a L<Future> will be 895returned instead. This allows for constructs such as: 896 897 await $loop->later; 898 899=cut 900 901sub later 902{ 903 my $self = shift; 904 my ( $code ) = @_; 905 906 return $self->watch_idle( when => 'later', code => $code ) 907 if $code; 908 909 my $f = $self->new_future; 910 my $id = $self->watch_idle( when => 'later', code => sub { 911 $f->done unless $f->is_ready; 912 } ); 913 $f->on_cancel( sub { 914 $self->unwatch_idle( $id ); 915 } ); 916 return $f; 917} 918 919=head2 spawn_child 920 921 $loop->spawn_child( %params ) 922 923This method creates a new child process to run a given code block or command. 924The C<%params> hash takes the following keys: 925 926=over 8 927 928=item command => ARRAY or STRING 929 930Either a reference to an array containing the command and its arguments, or a 931plain string containing the command. This value is passed into perl's 932C<exec> function. 933 934=item code => CODE 935 936A block of code to execute in the child process. It will be called in scalar 937context inside an C<eval> block. 938 939=item setup => ARRAY 940 941A reference to an array which gives file descriptors to set up in the child 942process before running the code or command. See below. 943 944=item on_exit => CODE 945 946A continuation to be called when the child processes exits. It will be invoked 947in the following way: 948 949 $on_exit->( $pid, $exitcode, $dollarbang, $dollarat ) 950 951The second argument is passed the plain perl C<$?> value. 952 953=back 954 955Exactly one of the C<command> or C<code> keys must be specified. 956 957If the C<command> key is used, the given array or string is executed using the 958C<exec> function. 959 960If the C<code> key is used, the return value will be used as the C<exit(2)> 961code from the child if it returns (or 255 if it returned C<undef> or thows an 962exception). 963 964 Case | ($exitcode >> 8) | $dollarbang | $dollarat 965 --------------+------------------------+-------------+---------- 966 exec succeeds | exit code from program | 0 | "" 967 exec fails | 255 | $! | "" 968 $code returns | return value | $! | "" 969 $code dies | 255 | $! | $@ 970 971It is usually more convenient to use the C<open_process> method in simple 972cases where an external program is being started in order to interact with it 973via file IO, or even C<run_child> when only the final result is required, 974rather than interaction while it is running. 975 976=head3 C<setup> array 977 978This array gives a list of file descriptor operations to perform in the child 979process after it has been C<fork(2)>ed from the parent, before running the code 980or command. It consists of name/value pairs which are ordered; the operations 981are performed in the order given. 982 983=over 8 984 985=item fdI<n> => ARRAY 986 987Gives an operation on file descriptor I<n>. The first element of the array 988defines the operation to be performed: 989 990=over 4 991 992=item [ 'close' ] 993 994The file descriptor will be closed. 995 996=item [ 'dup', $io ] 997 998The file descriptor will be C<dup2(2)>ed from the given IO handle. 999 1000=item [ 'open', $mode, $file ] 1001 1002The file descriptor will be opened from the named file in the given mode. The 1003C<$mode> string should be in the form usually given to the C<open> function; 1004such as '<' or '>>'. 1005 1006=item [ 'keep' ] 1007 1008The file descriptor will not be closed; it will be left as-is. 1009 1010=back 1011 1012A non-reference value may be passed as a shortcut, where it would contain the 1013name of the operation with no arguments (i.e. for the C<close> and C<keep> 1014operations). 1015 1016=item IO => ARRAY 1017 1018Shortcut for passing C<fdI<n>>, where I<n> is the fileno of the IO 1019reference. In this case, the key must be a reference that implements the 1020C<fileno> method. This is mostly useful for 1021 1022 $handle => 'keep' 1023 1024=item fdI<n> => IO 1025 1026A shortcut for the C<dup> case given above. 1027 1028=item stdin => ... 1029 1030=item stdout => ... 1031 1032=item stderr => ... 1033 1034Shortcuts for C<fd0>, C<fd1> and C<fd2> respectively. 1035 1036=item env => HASH 1037 1038A reference to a hash to set as the child process's environment. 1039 1040Note that this will entirely set a new environment, completely replacing the 1041existing one. If you want to simply add new keys or change the values of some 1042keys without removing the other existing ones, you can simply copy C<%ENV> 1043into the hash before setting new keys: 1044 1045 env => { 1046 %ENV, 1047 ANOTHER => "key here", 1048 } 1049 1050=item nice => INT 1051 1052Change the child process's scheduling priority using C<POSIX::nice>. 1053 1054=item chdir => STRING 1055 1056Change the child process's working directory using C<chdir>. 1057 1058=item setuid => INT 1059 1060=item setgid => INT 1061 1062Change the child process's effective UID or GID. 1063 1064=item setgroups => ARRAY 1065 1066Change the child process's groups list, to those groups whose numbers are 1067given in the ARRAY reference. 1068 1069On most systems, only the privileged superuser change user or group IDs. 1070L<IO::Async> will B<NOT> check before detaching the child process whether 1071this is the case. 1072 1073If setting both the primary GID and the supplementary groups list, it is 1074suggested to set the primary GID first. Moreover, some operating systems may 1075require that the supplementary groups list contains the primary GID. 1076 1077=back 1078 1079If no directions for what to do with C<stdin>, C<stdout> and C<stderr> are 1080given, a default of C<keep> is implied. All other file descriptors will be 1081closed, unless a C<keep> operation is given for them. 1082 1083If C<setuid> is used, be sure to place it after any other operations that 1084might require superuser privileges, such as C<setgid> or opening special 1085files. 1086 1087Z<> 1088 1089 my ( $pipeRd, $pipeWr ) = IO::Async::OS->pipepair; 1090 $loop->spawn_child( 1091 command => "/usr/bin/my-command", 1092 1093 setup => [ 1094 stdin => [ "open", "<", "/dev/null" ], 1095 stdout => $pipeWr, 1096 stderr => [ "open", ">>", "/var/log/mycmd.log" ], 1097 chdir => "/", 1098 ] 1099 1100 on_exit => sub { 1101 my ( $pid, $exitcode ) = @_; 1102 my $status = ( $exitcode >> 8 ); 1103 print "Command exited with status $status\n"; 1104 }, 1105 ); 1106 1107 $loop->spawn_child( 1108 code => sub { 1109 do_something; # executes in a child process 1110 return 1; 1111 }, 1112 1113 on_exit => sub { 1114 my ( $pid, $exitcode, $dollarbang, $dollarat ) = @_; 1115 my $status = ( $exitcode >> 8 ); 1116 print "Child process exited with status $status\n"; 1117 print " OS error was $dollarbang, exception was $dollarat\n"; 1118 }, 1119 ); 1120 1121=cut 1122 1123sub spawn_child 1124{ 1125 my $self = shift; 1126 my %params = @_; 1127 1128 my $childmanager = $self->{childmanager} ||= 1129 $self->__new_feature( "IO::Async::Internals::ChildManager" ); 1130 1131 $childmanager->spawn_child( %params ); 1132} 1133 1134=head2 open_process 1135 1136 $process = $loop->open_process( %params ) 1137 1138I<Since version 0.72.> 1139 1140This creates a new child process to run the given code block or command, and 1141attaches filehandles to it that the parent will watch. This method is a light 1142wrapper around constructing a new L<IO::Async::Process> object, adding it to 1143the loop, and returning it. 1144 1145The C<%params> hash is passed directly to the L<IO::Async::Process> 1146constructor. 1147 1148=cut 1149 1150sub open_process 1151{ 1152 my $self = shift; 1153 my %params = @_; 1154 1155 $params{on_exit} and croak "Cannot pass 'on_exit' parameter through ->open_process"; 1156 1157 require IO::Async::Process; 1158 my $process = IO::Async::Process->new( %params ); 1159 1160 $self->add( $process ); 1161 1162 return $process; 1163} 1164 1165=head2 open_child 1166 1167 $pid = $loop->open_child( %params ) 1168 1169A back-compatibility wrapper to calling L</open_process> and returning the PID 1170of the newly-constructed L<IO::Async::Process> instance. The C<on_finish> 1171continuation likewise will be invoked with the PID rather than the process 1172instance. 1173 1174 $on_finish->( $pid, $exitcode ) 1175 1176Similarly, a C<on_error> continuation is accepted, though note its arguments 1177come in a different order to those of the Process's C<on_exception>: 1178 1179 $on_error->( $pid, $exitcode, $errno, $exception ) 1180 1181This method should not be used in new code; instead use L</open_process> 1182directly. 1183 1184=cut 1185 1186sub open_child 1187{ 1188 my $self = shift; 1189 my %params = @_; 1190 1191 my $on_finish = delete $params{on_finish}; 1192 ref $on_finish or croak "Expected 'on_finish' to be a reference"; 1193 $params{on_finish} = sub { 1194 my ( $process, $exitcode ) = @_; 1195 $on_finish->( $process->pid, $exitcode ); 1196 }; 1197 1198 if( my $on_error = delete $params{on_error} ) { 1199 ref $on_error or croak "Expected 'on_error' to be a reference"; 1200 1201 $params{on_exception} = sub { 1202 my ( $process, $exception, $errno, $exitcode ) = @_; 1203 # Swap order 1204 $on_error->( $process->pid, $exitcode, $errno, $exception ); 1205 }; 1206 } 1207 1208 return $self->open_process( %params )->pid; 1209} 1210 1211=head2 run_process 1212 1213 @results = $loop->run_process( %params )->get 1214 1215 ( $exitcode, $stdout ) = $loop->run_process( ... )->get # by default 1216 1217I<Since version 0.73.> 1218 1219Creates a new child process to run the given code block or command, optionally 1220capturing its STDOUT and STDERR streams. By default the returned future will 1221yield the exit code and content of the STDOUT stream, but the C<capture> 1222argument can be used to alter what is requested and returned. 1223 1224=over 8 1225 1226=item command => ARRAY or STRING 1227 1228=item code => CODE 1229 1230The command or code to run in the child process (as per the C<spawn_child> 1231method) 1232 1233=item stdin => STRING 1234 1235Optional. String to pass in to the child process's STDIN stream. 1236 1237=item setup => ARRAY 1238 1239Optional reference to an array to pass to the underlying C<spawn> method. 1240 1241=item capture => ARRAY 1242 1243Optional reference to an array giving a list of names of values which should 1244be returned by resolving future. Values will be returned in the same order as 1245in the list. Valid choices are: C<exitcode>, C<stdout>, C<stderr>. 1246 1247=item cancel_signal => STRING 1248 1249Optional. Name (or number) of the signal to send to the process if the 1250returned future is cancelled. Defaults to C<TERM>. Use empty string or zero 1251disable sending a signal on cancellation. 1252 1253=item fail_on_nonzero => BOOL 1254 1255Optional. If true, the returned future will fail if the process exits with a 1256nonzero status. The failure will contain a message, the C<process> category 1257name, and the capture values that were requested. 1258 1259 Future->fail( $message, process => @captures ) 1260 1261=back 1262 1263This method is intended mainly as an IO::Async-compatible replacement for the 1264perl C<readpipe> function (`backticks`), allowing it to replace 1265 1266 my $output = `command here`; 1267 1268with 1269 1270 my ( $exitcode, $output ) = $loop->run_process( 1271 command => "command here", 1272 )->get; 1273 1274Z<> 1275 1276 my ( $exitcode, $stdout ) = $loop->run_process( 1277 command => "/bin/ps", 1278 )->get; 1279 1280 my $status = ( $exitcode >> 8 ); 1281 print "ps exited with status $status\n"; 1282 1283=cut 1284 1285sub _run_process 1286{ 1287 my $self = shift; 1288 my %params = @_; 1289 1290 $params{on_finish} and croak "Unrecognised parameter on_finish"; 1291 1292 my $capture = delete $params{capture} // [qw(exitcode stdout)]; 1293 ref $capture eq "ARRAY" or croak "Expected 'capture' to be an array reference"; 1294 1295 my %subparams; 1296 my %results; 1297 1298 if( my $child_stdin = delete $params{stdin} ) { 1299 ref $child_stdin and croak "Expected 'stdin' not to be a reference"; 1300 $subparams{stdin} = { from => $child_stdin }; 1301 } 1302 1303 foreach (qw( code command setup notifier_name )) { 1304 $subparams{$_} = delete $params{$_}; 1305 } 1306 1307 foreach my $name ( @$capture ) { 1308 grep { $_ eq $name } qw( exitcode stdout stderr ) or croak "Unexpected capture $name"; 1309 1310 $subparams{stdout} = { into => \$results{stdout} } if $name eq "stdout"; 1311 $subparams{stderr} = { into => \$results{stderr} } if $name eq "stderr"; 1312 } 1313 1314 my $cancel_signal = delete $params{cancel_signal} // "TERM"; 1315 1316 my $fail_on_nonzero = delete $params{fail_on_nonzero}; 1317 1318 croak "Unrecognised parameters " . join( ", ", keys %params ) if keys %params; 1319 1320 my $future = $self->new_future; 1321 1322 require IO::Async::Process; 1323 my $process = IO::Async::Process->new( 1324 %subparams, 1325 on_finish => sub { 1326 ( undef, $results{exitcode} ) = @_; 1327 1328 if( $fail_on_nonzero and $results{exitcode} > 0 ) { 1329 $future->fail( "Process failed with exit code $results{exitcode}\n", 1330 process => @results{ @$capture } 1331 ); 1332 } 1333 else { 1334 $future->done( @results{ @$capture } ); 1335 } 1336 }, 1337 ); 1338 1339 $future->on_cancel(sub { 1340 $process->kill( $cancel_signal ); 1341 }) if $cancel_signal; 1342 1343 $self->add( $process ); 1344 1345 return ( $future, $process ); 1346} 1347 1348sub run_process 1349{ 1350 my $self = shift; 1351 return ( $self->_run_process( @_ ) )[0]; 1352} 1353 1354=head2 run_child 1355 1356 $pid = $loop->run_child( %params ) 1357 1358A back-compatibility wrapper for L</run_process>, returning the PID and taking 1359an C<on_finish> continuation instead of returning a Future. 1360 1361This creates a new child process to run the given code block or command, 1362capturing its STDOUT and STDERR streams. When the process exits, a 1363continuation is invoked being passed the exitcode, and content of the streams. 1364 1365Takes the following named arguments in addition to those taken by 1366C<run_process>: 1367 1368=over 8 1369 1370=item on_finish => CODE 1371 1372A continuation to be called when the child process exits and closed its STDOUT 1373and STDERR streams. It will be invoked in the following way: 1374 1375 $on_finish->( $pid, $exitcode, $stdout, $stderr ) 1376 1377The second argument is passed the plain perl C<$?> value. 1378 1379=back 1380 1381This method should not be used in new code; instead use L</run_process> 1382directly. 1383 1384=cut 1385 1386sub run_child 1387{ 1388 my $self = shift; 1389 my %params = @_; 1390 1391 my $on_finish = delete $params{on_finish}; 1392 ref $on_finish or croak "Expected 'on_finish' to be a reference"; 1393 1394 my ( $f, $process ) = $self->_run_process( 1395 %params, 1396 capture => [qw( exitcode stdout stderr )], 1397 ); 1398 my $pid = $process->pid; 1399 1400 $f->on_done( sub { 1401 undef $f; # capture cycle 1402 $on_finish->( $pid, @_ ); 1403 }); 1404 1405 return $pid; 1406} 1407 1408=head2 resolver 1409 1410 $loop->resolver 1411 1412Returns the internally-stored L<IO::Async::Resolver> object, used for name 1413resolution operations by the C<resolve>, C<connect> and C<listen> methods. 1414 1415=cut 1416 1417sub resolver 1418{ 1419 my $self = shift; 1420 1421 return $self->{resolver} ||= do { 1422 require IO::Async::Resolver; 1423 my $resolver = IO::Async::Resolver->new; 1424 $self->add( $resolver ); 1425 $resolver; 1426 } 1427} 1428 1429=head2 set_resolver 1430 1431 $loop->set_resolver( $resolver ) 1432 1433Sets the internally-stored L<IO::Async::Resolver> object. In most cases this 1434method should not be required, but it may be used to provide an alternative 1435resolver for special use-cases. 1436 1437=cut 1438 1439sub set_resolver 1440{ 1441 my $self = shift; 1442 my ( $resolver ) = @_; 1443 1444 $resolver->can( $_ ) or croak "Resolver is unsuitable as it does not implement $_" 1445 for qw( resolve getaddrinfo getnameinfo ); 1446 1447 $self->{resolver} = $resolver; 1448 1449 $self->add( $resolver ); 1450} 1451 1452=head2 resolve 1453 1454 @result = $loop->resolve( %params )->get 1455 1456This method performs a single name resolution operation. It uses an 1457internally-stored L<IO::Async::Resolver> object. For more detail, see the 1458C<resolve> method on the L<IO::Async::Resolver> class. 1459 1460=cut 1461 1462sub resolve 1463{ 1464 my $self = shift; 1465 my ( %params ) = @_; 1466 1467 $self->resolver->resolve( %params ); 1468} 1469 1470=head2 connect 1471 1472 $handle|$socket = $loop->connect( %params )->get 1473 1474This method performs a non-blocking connection to a given address or set of 1475addresses, returning a L<IO::Async::Future> which represents the operation. On 1476completion, the future will yield the connected socket handle, or the given 1477L<IO::Async::Handle> object. 1478 1479There are two modes of operation. Firstly, a list of addresses can be provided 1480which will be tried in turn. Alternatively as a convenience, if a host and 1481service name are provided instead of a list of addresses, these will be 1482resolved using the underlying loop's C<resolve> method into the list of 1483addresses. 1484 1485When attempting to connect to any among a list of addresses, there may be 1486failures among the first attempts, before a valid connection is made. For 1487example, the resolver may have returned some IPv6 addresses, but only IPv4 1488routes are valid on the system. In this case, the first C<connect(2)> syscall 1489will fail. This isn't yet a fatal error, if there are more addresses to try, 1490perhaps some IPv4 ones. 1491 1492For this reason, it is possible that the operation eventually succeeds even 1493though some system calls initially fail. To be aware of individual failures, 1494the optional C<on_fail> callback can be used. This will be invoked on each 1495individual C<socket(2)> or C<connect(2)> failure, which may be useful for 1496debugging or logging. 1497 1498Because this module simply uses the C<getaddrinfo> resolver, it will be fully 1499IPv6-aware if the underlying platform's resolver is. This allows programs to 1500be fully IPv6-capable. 1501 1502In plain address mode, the C<%params> hash takes the following keys: 1503 1504=over 8 1505 1506=item addrs => ARRAY 1507 1508Reference to an array of (possibly-multiple) address structures to attempt to 1509connect to. Each should be in the layout described for C<addr>. Such a layout 1510is returned by the C<getaddrinfo> named resolver. 1511 1512=item addr => HASH or ARRAY 1513 1514Shortcut for passing a single address to connect to; it may be passed directly 1515with this key, instead of in another array on its own. This should be in a 1516format recognised by L<IO::Async::OS>'s C<extract_addrinfo> method. 1517 1518This example shows how to use the C<Socket> functions to construct one for TCP 1519port 8001 on address 10.0.0.1: 1520 1521 $loop->connect( 1522 addr => { 1523 family => "inet", 1524 socktype => "stream", 1525 port => 8001, 1526 ip => "10.0.0.1", 1527 }, 1528 ... 1529 ); 1530 1531This example shows another way to connect to a UNIX socket at F<echo.sock>. 1532 1533 $loop->connect( 1534 addr => { 1535 family => "unix", 1536 socktype => "stream", 1537 path => "echo.sock", 1538 }, 1539 ... 1540 ); 1541 1542=item peer => IO 1543 1544Shortcut for constructing an address to connect to the given IO handle, which 1545must be a L<IO::Socket> or subclass, and is presumed to be a local listening 1546socket (perhaps on C<PF_UNIX> or C<PF_INET>). This is convenient for 1547connecting to a local filehandle, for example during a unit test or similar. 1548 1549=item local_addrs => ARRAY 1550 1551=item local_addr => HASH or ARRAY 1552 1553Optional. Similar to the C<addrs> or C<addr> parameters, these specify a local 1554address or set of addresses to C<bind(2)> the socket to before 1555C<connect(2)>ing it. 1556 1557=back 1558 1559When performing the resolution step too, the C<addrs> or C<addr> keys are 1560ignored, and instead the following keys are taken: 1561 1562=over 8 1563 1564=item host => STRING 1565 1566=item service => STRING 1567 1568The hostname and service name to connect to. 1569 1570=item local_host => STRING 1571 1572=item local_service => STRING 1573 1574Optional. The hostname and/or service name to C<bind(2)> the socket to locally 1575before connecting to the peer. 1576 1577=item family => INT 1578 1579=item socktype => INT 1580 1581=item protocol => INT 1582 1583=item flags => INT 1584 1585Optional. Other arguments to pass along with C<host> and C<service> to the 1586C<getaddrinfo> call. 1587 1588=item socktype => STRING 1589 1590Optionally may instead be one of the values C<'stream'>, C<'dgram'> or 1591C<'raw'> to stand for C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_RAW>. This 1592utility is provided to allow the caller to avoid a separate C<use Socket> only 1593for importing these constants. 1594 1595=back 1596 1597It is necessary to pass the C<socktype> hint to the resolver when resolving 1598the host/service names into an address, as some OS's C<getaddrinfo> functions 1599require this hint. A warning is emitted if neither C<socktype> nor C<protocol> 1600hint is defined when performing a C<getaddrinfo> lookup. To avoid this warning 1601while still specifying no particular C<socktype> hint (perhaps to invoke some 1602OS-specific behaviour), pass C<0> as the C<socktype> value. 1603 1604In either case, it also accepts the following arguments: 1605 1606=over 8 1607 1608=item handle => IO::Async::Handle 1609 1610Optional. If given a L<IO::Async::Handle> object or a subclass (such as 1611L<IO::Async::Stream> or L<IO::Async::Socket> its handle will be set to the 1612newly-connected socket on success, and that handle used as the result of the 1613future instead. 1614 1615=item on_fail => CODE 1616 1617Optional. After an individual C<socket(2)> or C<connect(2)> syscall has failed, 1618this callback is invoked to inform of the error. It is passed the name of the 1619syscall that failed, the arguments that were passed to it, and the error it 1620generated. I.e. 1621 1622 $on_fail->( "socket", $family, $socktype, $protocol, $! ); 1623 1624 $on_fail->( "bind", $sock, $address, $! ); 1625 1626 $on_fail->( "connect", $sock, $address, $! ); 1627 1628Because of the "try all" nature when given a list of multiple addresses, this 1629callback may be invoked multiple times, even before an eventual success. 1630 1631=back 1632 1633This method accepts an C<extensions> parameter; see the C<EXTENSIONS> section 1634below. 1635 1636=head2 connect (void) 1637 1638 $loop->connect( %params ) 1639 1640When not returning a future, additional parameters can be given containing the 1641continuations to invoke on success or failure. 1642 1643=over 8 1644 1645=item on_connected => CODE 1646 1647A continuation that is invoked on a successful C<connect(2)> call to a valid 1648socket. It will be passed the connected socket handle, as an C<IO::Socket> 1649object. 1650 1651 $on_connected->( $handle ) 1652 1653=item on_stream => CODE 1654 1655An alternative to C<on_connected>, a continuation that is passed an instance 1656of L<IO::Async::Stream> when the socket is connected. This is provided as a 1657convenience for the common case that a Stream object is required as the 1658transport for a Protocol object. 1659 1660 $on_stream->( $stream ) 1661 1662=item on_socket => CODE 1663 1664Similar to C<on_stream>, but constructs an instance of L<IO::Async::Socket>. 1665This is most useful for C<SOCK_DGRAM> or C<SOCK_RAW> sockets. 1666 1667 $on_socket->( $socket ) 1668 1669=item on_connect_error => CODE 1670 1671A continuation that is invoked after all of the addresses have been tried, and 1672none of them succeeded. It will be passed the most significant error that 1673occurred, and the name of the operation it occurred in. Errors from the 1674C<connect(2)> syscall are considered most significant, then C<bind(2)>, then 1675finally C<socket(2)>. 1676 1677 $on_connect_error->( $syscall, $! ) 1678 1679=item on_resolve_error => CODE 1680 1681A continuation that is invoked when the name resolution attempt fails. This is 1682invoked in the same way as the C<on_error> continuation for the C<resolve> 1683method. 1684 1685=back 1686 1687=cut 1688 1689sub connect 1690{ 1691 my $self = shift; 1692 my ( %params ) = @_; 1693 1694 my $extensions; 1695 if( $extensions = delete $params{extensions} and @$extensions ) { 1696 my ( $ext, @others ) = @$extensions; 1697 1698 my $method = "${ext}_connect"; 1699 # TODO: Try to 'require IO::Async::$ext' 1700 1701 $self->can( $method ) or croak "Extension method '$method' is not available"; 1702 1703 return $self->$method( 1704 %params, 1705 ( @others ? ( extensions => \@others ) : () ), 1706 ); 1707 } 1708 1709 my $handle = $params{handle}; 1710 1711 my $on_done; 1712 # Legacy callbacks 1713 if( my $on_connected = delete $params{on_connected} ) { 1714 $on_done = $on_connected; 1715 } 1716 elsif( my $on_stream = delete $params{on_stream} ) { 1717 defined $handle and croak "Cannot pass 'on_stream' with a handle object as well"; 1718 1719 require IO::Async::Stream; 1720 # TODO: It doesn't make sense to put a SOCK_DGRAM in an 1721 # IO::Async::Stream but currently we don't detect this 1722 $handle = IO::Async::Stream->new; 1723 $on_done = $on_stream; 1724 } 1725 elsif( my $on_socket = delete $params{on_socket} ) { 1726 defined $handle and croak "Cannot pass 'on_socket' with a handle object as well"; 1727 1728 require IO::Async::Socket; 1729 $handle = IO::Async::Socket->new; 1730 $on_done = $on_socket; 1731 } 1732 elsif( !defined wantarray ) { 1733 croak "Expected 'on_connected' or 'on_stream' callback or to return a Future"; 1734 } 1735 1736 my $on_connect_error; 1737 if( $on_connect_error = $params{on_connect_error} ) { 1738 # OK 1739 } 1740 elsif( !defined wantarray ) { 1741 croak "Expected 'on_connect_error' callback"; 1742 } 1743 1744 my $on_resolve_error; 1745 if( $on_resolve_error = $params{on_resolve_error} ) { 1746 # OK 1747 } 1748 elsif( !defined wantarray and exists $params{host} || exists $params{local_host} ) { 1749 croak "Expected 'on_resolve_error' callback or to return a Future"; 1750 } 1751 1752 my $connector = $self->{connector} ||= $self->__new_feature( "IO::Async::Internals::Connector" ); 1753 1754 my $future = $connector->connect( %params ); 1755 1756 $future = $future->then( sub { 1757 $handle->set_handle( shift ); 1758 return Future->done( $handle ) 1759 }) if $handle; 1760 1761 $future->on_done( $on_done ) if $on_done; 1762 $future->on_fail( sub { 1763 $on_connect_error->( @_[2,3] ) if $on_connect_error and $_[1] eq "connect"; 1764 $on_resolve_error->( $_[2] ) if $on_resolve_error and $_[1] eq "resolve"; 1765 } ); 1766 1767 return $future if defined wantarray; 1768 1769 # Caller is not going to keep hold of the Future, so we have to ensure it 1770 # stays alive somehow 1771 $future->on_ready( sub { undef $future } ); # intentional cycle 1772} 1773 1774=head2 listen 1775 1776 $listener = $loop->listen( %params )->get 1777 1778This method sets up a listening socket and arranges for an acceptor callback 1779to be invoked each time a new connection is accepted on the socket. Internally 1780it creates an instance of L<IO::Async::Listener> and adds it to the Loop if 1781not given one in the arguments. 1782 1783Addresses may be given directly, or they may be looked up using the system's 1784name resolver, or a socket handle may be given directly. 1785 1786If multiple addresses are given, or resolved from the service and hostname, 1787then each will be attempted in turn until one succeeds. 1788 1789In named resolver mode, the C<%params> hash takes the following keys: 1790 1791=over 8 1792 1793=item service => STRING 1794 1795The service name to listen on. 1796 1797=item host => STRING 1798 1799The hostname to listen on. Optional. Will listen on all addresses if not 1800supplied. 1801 1802=item family => INT 1803 1804=item socktype => INT 1805 1806=item protocol => INT 1807 1808=item flags => INT 1809 1810Optional. Other arguments to pass along with C<host> and C<service> to the 1811C<getaddrinfo> call. 1812 1813=item socktype => STRING 1814 1815Optionally may instead be one of the values C<'stream'>, C<'dgram'> or 1816C<'raw'> to stand for C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_RAW>. This 1817utility is provided to allow the caller to avoid a separate C<use Socket> only 1818for importing these constants. 1819 1820=back 1821 1822It is necessary to pass the C<socktype> hint to the resolver when resolving 1823the host/service names into an address, as some OS's C<getaddrinfo> functions 1824require this hint. A warning is emitted if neither C<socktype> nor C<protocol> 1825hint is defined when performing a C<getaddrinfo> lookup. To avoid this warning 1826while still specifying no particular C<socktype> hint (perhaps to invoke some 1827OS-specific behaviour), pass C<0> as the C<socktype> value. 1828 1829In plain address mode, the C<%params> hash takes the following keys: 1830 1831=over 8 1832 1833=item addrs => ARRAY 1834 1835Reference to an array of (possibly-multiple) address structures to attempt to 1836listen on. Each should be in the layout described for C<addr>. Such a layout 1837is returned by the C<getaddrinfo> named resolver. 1838 1839=item addr => ARRAY 1840 1841Shortcut for passing a single address to listen on; it may be passed directly 1842with this key, instead of in another array of its own. This should be in a 1843format recognised by L<IO::Async::OS>'s C<extract_addrinfo> method. See also 1844the C<EXAMPLES> section. 1845 1846=back 1847 1848In direct socket handle mode, the following keys are taken: 1849 1850=over 8 1851 1852=item handle => IO 1853 1854The listening socket handle. 1855 1856=back 1857 1858In either case, the following keys are also taken: 1859 1860=over 8 1861 1862=item on_fail => CODE 1863 1864Optional. A callback that is invoked if a syscall fails while attempting to 1865create a listening sockets. It is passed the name of the syscall that failed, 1866the arguments that were passed to it, and the error generated. I.e. 1867 1868 $on_fail->( "socket", $family, $socktype, $protocol, $! ); 1869 1870 $on_fail->( "sockopt", $sock, $optname, $optval, $! ); 1871 1872 $on_fail->( "bind", $sock, $address, $! ); 1873 1874 $on_fail->( "listen", $sock, $queuesize, $! ); 1875 1876=item queuesize => INT 1877 1878Optional. The queue size to pass to the C<listen(2)> calls. If not supplied, 1879then 3 will be given instead. 1880 1881=item reuseaddr => BOOL 1882 1883Optional. If true or not supplied then the C<SO_REUSEADDR> socket option will 1884be set. To prevent this, pass a false value such as 0. 1885 1886=item v6only => BOOL 1887 1888Optional. If defined, sets or clears the C<IPV6_V6ONLY> socket option on 1889C<PF_INET6> sockets. This option disables the ability of C<PF_INET6> socket to 1890accept connections from C<AF_INET> addresses. Not all operating systems allow 1891this option to be disabled. 1892 1893=back 1894 1895An alternative which gives more control over the listener, is to create the 1896L<IO::Async::Listener> object directly and add it explicitly to the Loop. 1897 1898This method accepts an C<extensions> parameter; see the C<EXTENSIONS> section 1899below. 1900 1901=head2 listen (void) 1902 1903 $loop->listen( %params ) 1904 1905When not returning a future, additional parameters can be given containing the 1906continuations to invoke on success or failure. 1907 1908=over 8 1909 1910=item on_notifier => CODE 1911 1912Optional. A callback that is invoked when the Listener object is ready to 1913receive connections. The callback is passed the Listener object itself. 1914 1915 $on_notifier->( $listener ) 1916 1917If this callback is required, it may instead be better to construct the 1918Listener object directly. 1919 1920=item on_listen => CODE 1921 1922Optional. A callback that is invoked when the listening socket is ready. 1923Typically this would be used in the name resolver case, in order to inspect 1924the socket's sockname address, or otherwise inspect the filehandle. 1925 1926 $on_listen->( $socket ) 1927 1928=item on_listen_error => CODE 1929 1930A continuation this is invoked after all of the addresses have been tried, and 1931none of them succeeded. It will be passed the most significant error that 1932occurred, and the name of the operation it occurred in. Errors from the 1933C<listen(2)> syscall are considered most significant, then C<bind(2)>, then 1934C<sockopt(2)>, then finally C<socket(2)>. 1935 1936=item on_resolve_error => CODE 1937 1938A continuation that is invoked when the name resolution attempt fails. This is 1939invoked in the same way as the C<on_error> continuation for the C<resolve> 1940method. 1941 1942=back 1943 1944=cut 1945 1946sub listen 1947{ 1948 my $self = shift; 1949 my ( %params ) = @_; 1950 1951 my $remove_on_error; 1952 my $listener = $params{listener} ||= do { 1953 $remove_on_error++; 1954 1955 require IO::Async::Listener; 1956 1957 # Our wrappings of these don't want $listener 1958 my %listenerparams; 1959 for (qw( on_accept on_stream on_socket )) { 1960 next unless exists $params{$_}; 1961 croak "Cannot ->listen with '$_' and 'listener'" if $params{listener}; 1962 1963 my $code = delete $params{$_}; 1964 $listenerparams{$_} = sub { 1965 shift; 1966 goto &$code; 1967 }; 1968 } 1969 1970 my $listener = IO::Async::Listener->new( %listenerparams ); 1971 $self->add( $listener ); 1972 $listener 1973 }; 1974 1975 my $extensions; 1976 if( $extensions = delete $params{extensions} and @$extensions ) { 1977 my ( $ext, @others ) = @$extensions; 1978 1979 # We happen to know we break older IO::Async::SSL 1980 if( $ext eq "SSL" and $IO::Async::SSL::VERSION < '0.12001' ) { 1981 croak "IO::Async::SSL version too old; need at least 0.12_001; found $IO::Async::SSL::VERSION"; 1982 } 1983 1984 my $method = "${ext}_listen"; 1985 # TODO: Try to 'require IO::Async::$ext' 1986 1987 $self->can( $method ) or croak "Extension method '$method' is not available"; 1988 1989 my $f = $self->$method( 1990 %params, 1991 ( @others ? ( extensions => \@others ) : () ), 1992 ); 1993 $f->on_fail( sub { $self->remove( $listener ) } ) if $remove_on_error; 1994 1995 return $f; 1996 } 1997 1998 my $on_notifier = delete $params{on_notifier}; # optional 1999 2000 my $on_listen_error = delete $params{on_listen_error}; 2001 my $on_resolve_error = delete $params{on_resolve_error}; 2002 2003 # Shortcut 2004 if( $params{addr} and not $params{addrs} ) { 2005 $params{addrs} = [ delete $params{addr} ]; 2006 } 2007 2008 my $f; 2009 if( my $handle = delete $params{handle} ) { 2010 $f = $self->_listen_handle( $listener, $handle, %params ); 2011 } 2012 elsif( my $addrs = delete $params{addrs} ) { 2013 $on_listen_error or defined wantarray or 2014 croak "Expected 'on_listen_error' or to return a Future"; 2015 $f = $self->_listen_addrs( $listener, $addrs, %params ); 2016 } 2017 elsif( defined $params{service} ) { 2018 $on_listen_error or defined wantarray or 2019 croak "Expected 'on_listen_error' or to return a Future"; 2020 $on_resolve_error or defined wantarray or 2021 croak "Expected 'on_resolve_error' or to return a Future"; 2022 $f = $self->_listen_hostservice( $listener, delete $params{host}, delete $params{service}, %params ); 2023 } 2024 else { 2025 croak "Expected either 'service' or 'addrs' or 'addr' arguments"; 2026 } 2027 2028 $f->on_done( $on_notifier ) if $on_notifier; 2029 if( my $on_listen = $params{on_listen} ) { 2030 $f->on_done( sub { $on_listen->( shift->read_handle ) } ); 2031 } 2032 $f->on_fail( sub { 2033 my ( $message, $how, @rest ) = @_; 2034 $on_listen_error->( @rest ) if $on_listen_error and $how eq "listen"; 2035 $on_resolve_error->( @rest ) if $on_resolve_error and $how eq "resolve"; 2036 }); 2037 $f->on_fail( sub { $self->remove( $listener ) } ) if $remove_on_error; 2038 2039 return $f if defined wantarray; 2040 2041 # Caller is not going to keep hold of the Future, so we have to ensure it 2042 # stays alive somehow 2043 $f->on_ready( sub { undef $f } ); # intentional cycle 2044} 2045 2046sub _listen_handle 2047{ 2048 my $self = shift; 2049 my ( $listener, $handle, %params ) = @_; 2050 2051 $listener->configure( handle => $handle ); 2052 return $self->new_future->done( $listener ); 2053} 2054 2055sub _listen_addrs 2056{ 2057 my $self = shift; 2058 my ( $listener, $addrs, %params ) = @_; 2059 2060 my $queuesize = $params{queuesize} || 3; 2061 2062 my $on_fail = $params{on_fail}; 2063 !defined $on_fail or ref $on_fail or croak "Expected 'on_fail' to be a reference"; 2064 2065 my $reuseaddr = 1; 2066 $reuseaddr = 0 if defined $params{reuseaddr} and not $params{reuseaddr}; 2067 2068 my $v6only = $params{v6only}; 2069 2070 my ( $listenerr, $binderr, $sockopterr, $socketerr ); 2071 2072 foreach my $addr ( @$addrs ) { 2073 my ( $family, $socktype, $proto, $address ) = IO::Async::OS->extract_addrinfo( $addr ); 2074 2075 my $sock; 2076 2077 unless( $sock = IO::Async::OS->socket( $family, $socktype, $proto ) ) { 2078 $socketerr = $!; 2079 $on_fail->( socket => $family, $socktype, $proto, $! ) if $on_fail; 2080 next; 2081 } 2082 2083 $sock->blocking( 0 ); 2084 2085 if( $reuseaddr ) { 2086 unless( $sock->sockopt( SO_REUSEADDR, 1 ) ) { 2087 $sockopterr = $!; 2088 $on_fail->( sockopt => $sock, SO_REUSEADDR, 1, $! ) if $on_fail; 2089 next; 2090 } 2091 } 2092 2093 if( defined $v6only and $family == AF_INET6 ) { 2094 unless( $sock->setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, $v6only ) ) { 2095 $sockopterr = $!; 2096 $on_fail->( sockopt => $sock, IPV6_V6ONLY, $v6only, $! ) if $on_fail; 2097 next; 2098 } 2099 } 2100 2101 unless( $sock->bind( $address ) ) { 2102 $binderr = $!; 2103 $on_fail->( bind => $sock, $address, $! ) if $on_fail; 2104 next; 2105 } 2106 2107 unless( $sock->listen( $queuesize ) ) { 2108 $listenerr = $!; 2109 $on_fail->( listen => $sock, $queuesize, $! ) if $on_fail; 2110 next; 2111 } 2112 2113 return $self->_listen_handle( $listener, $sock, %params ); 2114 } 2115 2116 my $f = $self->new_future; 2117 return $f->fail( "Cannot listen() - $listenerr", listen => listen => $listenerr ) if $listenerr; 2118 return $f->fail( "Cannot bind() - $binderr", listen => bind => $binderr ) if $binderr; 2119 return $f->fail( "Cannot setsockopt() - $sockopterr", listen => sockopt => $sockopterr ) if $sockopterr; 2120 return $f->fail( "Cannot socket() - $socketerr", listen => socket => $socketerr ) if $socketerr; 2121 die 'Oops; $loop->listen failed but no error cause was found'; 2122} 2123 2124sub _listen_hostservice 2125{ 2126 my $self = shift; 2127 my ( $listener, $host, $service, %params ) = @_; 2128 2129 $host ||= ""; 2130 defined $service or $service = ""; # might be 0 2131 2132 my %gai_hints; 2133 exists $params{$_} and $gai_hints{$_} = $params{$_} for qw( family socktype protocol flags ); 2134 2135 defined $gai_hints{socktype} or defined $gai_hints{protocol} or 2136 carp "Attempting to ->listen without either 'socktype' or 'protocol' hint is not portable"; 2137 2138 $self->resolver->getaddrinfo( 2139 host => $host, 2140 service => $service, 2141 passive => 1, 2142 %gai_hints, 2143 )->then( sub { 2144 my @addrs = @_; 2145 $self->_listen_addrs( $listener, \@addrs, %params ); 2146 }); 2147} 2148 2149=head1 OS ABSTRACTIONS 2150 2151Because the Magic Constructor searches for OS-specific subclasses of the Loop, 2152several abstractions of OS services are provided, in case specific OSes need 2153to give different implementations on that OS. 2154 2155=cut 2156 2157=head2 signame2num 2158 2159 $signum = $loop->signame2num( $signame ) 2160 2161Legacy wrappers around L<IO::Async::OS> functions. 2162 2163=cut 2164 2165sub signame2num { shift; IO::Async::OS->signame2num( @_ ) } 2166 2167=head2 time 2168 2169 $time = $loop->time 2170 2171Returns the current UNIX time in fractional seconds. This is currently 2172equivalent to C<Time::HiRes::time> but provided here as a utility for 2173programs to obtain the time current used by L<IO::Async> for its own timing 2174purposes. 2175 2176=cut 2177 2178sub time 2179{ 2180 my $self = shift; 2181 return Time::HiRes::time; 2182} 2183 2184=head2 fork 2185 2186 $pid = $loop->fork( %params ) 2187 2188This method creates a new child process to run a given code block, returning 2189its process ID. 2190 2191=over 8 2192 2193=item code => CODE 2194 2195A block of code to execute in the child process. It will be called in scalar 2196context inside an C<eval> block. The return value will be used as the 2197C<exit(2)> code from the child if it returns (or 255 if it returned C<undef> or 2198thows an exception). 2199 2200=item on_exit => CODE 2201 2202A optional continuation to be called when the child processes exits. It will 2203be invoked in the following way: 2204 2205 $on_exit->( $pid, $exitcode ) 2206 2207The second argument is passed the plain perl C<$?> value. 2208 2209This key is optional; if not supplied, the calling code should install a 2210handler using the C<watch_process> method. 2211 2212=item keep_signals => BOOL 2213 2214Optional boolean. If missing or false, any CODE references in the C<%SIG> hash 2215will be removed and restored back to C<DEFAULT> in the child process. If true, 2216no adjustment of the C<%SIG> hash will be performed. 2217 2218=back 2219 2220=cut 2221 2222sub fork 2223{ 2224 my $self = shift; 2225 my %params = @_; 2226 2227 HAVE_POSIX_FORK or croak "POSIX fork() is not available"; 2228 2229 my $code = $params{code} or croak "Expected 'code' as a CODE reference"; 2230 2231 my $kid = fork; 2232 defined $kid or croak "Cannot fork() - $!"; 2233 2234 if( $kid == 0 ) { 2235 unless( $params{keep_signals} ) { 2236 foreach( keys %SIG ) { 2237 next if m/^__(WARN|DIE)__$/; 2238 $SIG{$_} = "DEFAULT" if ref $SIG{$_} eq "CODE"; 2239 } 2240 } 2241 2242 # If the child process wants to use an IO::Async::Loop it needs to make 2243 # a new one, so this value is never useful 2244 undef our $ONE_TRUE_LOOP; 2245 2246 my $exitvalue = eval { $code->() }; 2247 2248 defined $exitvalue or $exitvalue = -1; 2249 2250 POSIX::_exit( $exitvalue ); 2251 } 2252 2253 if( defined $params{on_exit} ) { 2254 $self->watch_process( $kid => $params{on_exit} ); 2255 } 2256 2257 $METRICS and $METRICS->inc_counter( forks => ); 2258 2259 return $kid; 2260} 2261 2262=head2 create_thread 2263 2264 $tid = $loop->create_thread( %params ) 2265 2266This method creates a new (non-detached) thread to run the given code block, 2267returning its thread ID. 2268 2269=over 8 2270 2271=item code => CODE 2272 2273A block of code to execute in the thread. It is called in the context given by 2274the C<context> argument, and its return value will be available to the 2275C<on_joined> callback. It is called inside an C<eval> block; if it fails the 2276exception will be caught. 2277 2278=item context => "scalar" | "list" | "void" 2279 2280Optional. Gives the calling context that C<code> is invoked in. Defaults to 2281C<scalar> if not supplied. 2282 2283=item on_joined => CODE 2284 2285Callback to invoke when the thread function returns or throws an exception. 2286If it returned, this callback will be invoked with its result 2287 2288 $on_joined->( return => @result ) 2289 2290If it threw an exception the callback is invoked with the value of C<$@> 2291 2292 $on_joined->( died => $! ) 2293 2294=back 2295 2296=cut 2297 2298# It is basically impossible to have any semblance of order on global 2299# destruction, and even harder again to rely on when threads are going to be 2300# terminated and joined. Instead of ensuring we join them all, just detach any 2301# we no longer care about at END time 2302my %threads_to_detach; # {$tid} = $thread_weakly 2303END { 2304 $_ and $_->detach for values %threads_to_detach; 2305} 2306 2307sub create_thread 2308{ 2309 my $self = shift; 2310 my %params = @_; 2311 2312 HAVE_THREADS or croak "Threads are not available"; 2313 2314 eval { require threads } or croak "This Perl does not support threads"; 2315 2316 my $code = $params{code} or croak "Expected 'code' as a CODE reference"; 2317 my $on_joined = $params{on_joined} or croak "Expected 'on_joined' as a CODE reference"; 2318 2319 my $threadwatches = $self->{threadwatches}; 2320 2321 unless( $self->{thread_join_pipe} ) { 2322 ( my $rd, $self->{thread_join_pipe} ) = IO::Async::OS->pipepair or 2323 croak "Cannot pipepair - $!"; 2324 $rd->blocking( 0 ); 2325 $self->{thread_join_pipe}->autoflush(1); 2326 2327 $self->watch_io( 2328 handle => $rd, 2329 on_read_ready => sub { 2330 sysread $rd, my $buffer, 8192 or return; 2331 2332 # There's a race condition here in that we might have read from 2333 # the pipe after the returning thread has written to it but before 2334 # it has returned. We'll grab the actual $thread object and 2335 # forcibly ->join it here to ensure we wait for its result. 2336 2337 foreach my $tid ( unpack "N*", $buffer ) { 2338 my ( $thread, $on_joined ) = @{ delete $threadwatches->{$tid} } 2339 or die "ARGH: Can't find threadwatch for tid $tid\n"; 2340 $on_joined->( $thread->join ); 2341 delete $threads_to_detach{$tid}; 2342 } 2343 } 2344 ); 2345 } 2346 2347 my $wr = $self->{thread_join_pipe}; 2348 2349 my $context = $params{context} || "scalar"; 2350 2351 my ( $thread ) = threads->create( 2352 sub { 2353 my ( @ret, $died ); 2354 eval { 2355 $context eq "list" ? ( @ret = $code->() ) : 2356 $context eq "scalar" ? ( $ret[0] = $code->() ) : 2357 $code->(); 2358 1; 2359 } or $died = $@; 2360 2361 $wr->syswrite( pack "N", threads->tid ); 2362 2363 return died => $died if $died; 2364 return return => @ret; 2365 } 2366 ); 2367 2368 $threadwatches->{$thread->tid} = [ $thread, $on_joined ]; 2369 weaken( $threads_to_detach{$thread->tid} = $thread ); 2370 2371 return $thread->tid; 2372} 2373 2374=head1 LOW-LEVEL METHODS 2375 2376As C<IO::Async::Loop> is an abstract base class, specific subclasses of it are 2377required to implement certain methods that form the base level of 2378functionality. They are not recommended for applications to use; see instead 2379the various event objects or higher level methods listed above. 2380 2381These methods should be considered as part of the interface contract required 2382to implement a C<IO::Async::Loop> subclass. 2383 2384=cut 2385 2386=head2 API_VERSION 2387 2388 IO::Async::Loop->API_VERSION 2389 2390This method will be called by the magic constructor on the class before it is 2391constructed, to ensure that the specific implementation will support the 2392required API. This method should return the API version that the loop 2393implementation supports. The magic constructor will use that class, provided 2394it declares a version at least as new as the version documented here. 2395 2396The current API version is C<0.49>. 2397 2398This method may be implemented using C<constant>; e.g 2399 2400 use constant API_VERSION => '0.49'; 2401 2402=cut 2403 2404sub pre_wait 2405{ 2406 my $self = shift; 2407 $METRICS and $self->{processing_start} and 2408 $METRICS->report_timer( processing_time => Time::HiRes::tv_interval $self->{processing_start} ); 2409} 2410 2411sub post_wait 2412{ 2413 my $self = shift; 2414 $METRICS and $self->{processing_start} = [ Time::HiRes::gettimeofday ]; 2415} 2416 2417=head2 watch_io 2418 2419 $loop->watch_io( %params ) 2420 2421This method installs callback functions which will be invoked when the given 2422IO handle becomes read- or write-ready. 2423 2424The C<%params> hash takes the following keys: 2425 2426=over 8 2427 2428=item handle => IO 2429 2430The IO handle to watch. 2431 2432=item on_read_ready => CODE 2433 2434Optional. A CODE reference to call when the handle becomes read-ready. 2435 2436=item on_write_ready => CODE 2437 2438Optional. A CODE reference to call when the handle becomes write-ready. 2439 2440=back 2441 2442There can only be one filehandle of any given fileno registered at any one 2443time. For any one filehandle, there can only be one read-readiness and/or one 2444write-readiness callback at any one time. Registering a new one will remove an 2445existing one of that type. It is not required that both are provided. 2446 2447Applications should use a L<IO::Async::Handle> or L<IO::Async::Stream> instead 2448of using this method. 2449 2450If the filehandle does not yet have the C<O_NONBLOCK> flag set, it will be 2451enabled by this method. This will ensure that any subsequent C<sysread>, 2452C<syswrite>, or similar will not block on the filehandle. 2453 2454=cut 2455 2456# This class specifically does NOT implement this method, so that subclasses 2457# are forced to. The constructor will be checking.... 2458sub __watch_io 2459{ 2460 my $self = shift; 2461 my %params = @_; 2462 2463 my $handle = delete $params{handle} or croak "Expected 'handle'"; 2464 defined eval { $handle->fileno } or croak "Expected that 'handle' has defined ->fileno"; 2465 2466 # Silent "upgrade" to O_NONBLOCK 2467 $handle->blocking and $handle->blocking(0); 2468 2469 my $watch = ( $self->{iowatches}->{$handle->fileno} ||= [] ); 2470 2471 $watch->[0] = $handle; 2472 2473 if( exists $params{on_read_ready} ) { 2474 $watch->[1] = delete $params{on_read_ready}; 2475 } 2476 2477 if( exists $params{on_write_ready} ) { 2478 $watch->[2] = delete $params{on_write_ready}; 2479 } 2480 2481 if( exists $params{on_hangup} ) { 2482 $self->_CAN_ON_HANGUP or croak "Cannot watch_io for 'on_hangup' in ".ref($self); 2483 $watch->[3] = delete $params{on_hangup}; 2484 } 2485 2486 keys %params and croak "Unrecognised keys for ->watch_io - " . join( ", ", keys %params ); 2487} 2488 2489=head2 unwatch_io 2490 2491 $loop->unwatch_io( %params ) 2492 2493This method removes a watch on an IO handle which was previously installed by 2494C<watch_io>. 2495 2496The C<%params> hash takes the following keys: 2497 2498=over 8 2499 2500=item handle => IO 2501 2502The IO handle to remove the watch for. 2503 2504=item on_read_ready => BOOL 2505 2506If true, remove the watch for read-readiness. 2507 2508=item on_write_ready => BOOL 2509 2510If true, remove the watch for write-readiness. 2511 2512=back 2513 2514Either or both callbacks may be removed at once. It is not an error to attempt 2515to remove a callback that is not present. If both callbacks were provided to 2516the C<watch_io> method and only one is removed by this method, the other shall 2517remain. 2518 2519=cut 2520 2521sub __unwatch_io 2522{ 2523 my $self = shift; 2524 my %params = @_; 2525 2526 my $handle = delete $params{handle} or croak "Expected 'handle'"; 2527 2528 my $watch = $self->{iowatches}->{$handle->fileno} or return; 2529 2530 if( delete $params{on_read_ready} ) { 2531 undef $watch->[1]; 2532 } 2533 2534 if( delete $params{on_write_ready} ) { 2535 undef $watch->[2]; 2536 } 2537 2538 if( delete $params{on_hangup} ) { 2539 $self->_CAN_ON_HANGUP or croak "Cannot watch_io for 'on_hangup' in ".ref($self); 2540 undef $watch->[3]; 2541 } 2542 2543 if( not $watch->[1] and not $watch->[2] and not $watch->[3] ) { 2544 delete $self->{iowatches}->{$handle->fileno}; 2545 } 2546 2547 keys %params and croak "Unrecognised keys for ->unwatch_io - " . join( ", ", keys %params ); 2548} 2549 2550=head2 watch_signal 2551 2552 $loop->watch_signal( $signal, $code ) 2553 2554This method adds a new signal handler to watch the given signal. 2555 2556=over 8 2557 2558=item $signal 2559 2560The name of the signal to watch to. This should be a bare name like C<TERM>. 2561 2562=item $code 2563 2564A CODE reference to the handling callback. 2565 2566=back 2567 2568There can only be one callback per signal name. Registering a new one will 2569remove an existing one. 2570 2571Applications should use a L<IO::Async::Signal> object, or call 2572C<attach_signal> instead of using this method. 2573 2574This and C<unwatch_signal> are optional; a subclass may implement neither, or 2575both. If it implements neither then signal handling will be performed by the 2576base class using a self-connected pipe to interrupt the main IO blocking. 2577 2578=cut 2579 2580sub watch_signal 2581{ 2582 my $self = shift; 2583 my ( $signal, $code ) = @_; 2584 2585 HAVE_SIGNALS or croak "This OS cannot ->watch_signal"; 2586 2587 IO::Async::OS->loop_watch_signal( $self, $signal, $code ); 2588} 2589 2590=head2 unwatch_signal 2591 2592 $loop->unwatch_signal( $signal ) 2593 2594This method removes the signal callback for the given signal. 2595 2596=over 8 2597 2598=item $signal 2599 2600The name of the signal to watch to. This should be a bare name like C<TERM>. 2601 2602=back 2603 2604=cut 2605 2606sub unwatch_signal 2607{ 2608 my $self = shift; 2609 my ( $signal ) = @_; 2610 2611 HAVE_SIGNALS or croak "This OS cannot ->unwatch_signal"; 2612 2613 IO::Async::OS->loop_unwatch_signal( $self, $signal ); 2614} 2615 2616=head2 watch_time 2617 2618 $id = $loop->watch_time( %args ) 2619 2620This method installs a callback which will be called at the specified time. 2621The time may either be specified as an absolute value (the C<at> key), or 2622as a delay from the time it is installed (the C<after> key). 2623 2624The returned C<$id> value can be used to identify the timer in case it needs 2625to be cancelled by the C<unwatch_time> method. Note that this value may be 2626an object reference, so if it is stored, it should be released after it has 2627been fired or cancelled, so the object itself can be freed. 2628 2629The C<%params> hash takes the following keys: 2630 2631=over 8 2632 2633=item at => NUM 2634 2635The absolute system timestamp to run the event. 2636 2637=item after => NUM 2638 2639The delay after now at which to run the event, if C<at> is not supplied. A 2640zero or negative delayed timer should be executed as soon as possible; the 2641next time the C<loop_once> method is invoked. 2642 2643=item now => NUM 2644 2645The time to consider as now if calculating an absolute time based on C<after>; 2646defaults to C<time()> if not specified. 2647 2648=item code => CODE 2649 2650CODE reference to the continuation to run at the allotted time. 2651 2652=back 2653 2654Either one of C<at> or C<after> is required. 2655 2656For more powerful timer functionality as a L<IO::Async::Notifier> (so it can 2657be used as a child within another Notifier), see instead the 2658L<IO::Async::Timer> object and its subclasses. 2659 2660These C<*_time> methods are optional; a subclass may implement neither or both 2661of them. If it implements neither, then the base class will manage a queue of 2662timer events. This queue should be handled by the C<loop_once> method 2663implemented by the subclass, using the C<_adjust_timeout> and 2664C<_manage_queues> methods. 2665 2666This is the newer version of the API, replacing C<enqueue_timer>. It is 2667unspecified how this method pair interacts with the older 2668C<enqueue/requeue/cancel_timer> triplet. 2669 2670=cut 2671 2672sub watch_time 2673{ 2674 my $self = shift; 2675 my %args = @_; 2676 2677 # Renamed args 2678 if( exists $args{after} ) { 2679 $args{delay} = delete $args{after}; 2680 } 2681 elsif( exists $args{at} ) { 2682 $args{time} = delete $args{at}; 2683 } 2684 else { 2685 croak "Expected one of 'at' or 'after'"; 2686 } 2687 2688 if( $self->{old_timer} ) { 2689 $self->enqueue_timer( %args ); 2690 } 2691 else { 2692 my $timequeue = $self->{timequeue} ||= $self->__new_feature( "IO::Async::Internals::TimeQueue" ); 2693 2694 my $time = $self->_build_time( %args ); 2695 my $code = $args{code}; 2696 2697 $timequeue->enqueue( time => $time, code => $code ); 2698 } 2699} 2700 2701=head2 unwatch_time 2702 2703 $loop->unwatch_time( $id ) 2704 2705Removes a timer callback previously created by C<watch_time>. 2706 2707This is the newer version of the API, replacing C<cancel_timer>. It is 2708unspecified how this method pair interacts with the older 2709C<enqueue/requeue/cancel_timer> triplet. 2710 2711=cut 2712 2713sub unwatch_time 2714{ 2715 my $self = shift; 2716 my ( $id ) = @_; 2717 2718 if( $self->{old_timer} ) { 2719 $self->cancel_timer( $id ); 2720 } 2721 else { 2722 my $timequeue = $self->{timequeue} ||= $self->__new_feature( "IO::Async::Internals::TimeQueue" ); 2723 2724 $timequeue->cancel( $id ); 2725 } 2726} 2727 2728sub _build_time 2729{ 2730 my $self = shift; 2731 my %params = @_; 2732 2733 my $time; 2734 if( exists $params{time} ) { 2735 $time = $params{time}; 2736 } 2737 elsif( exists $params{delay} ) { 2738 my $now = exists $params{now} ? $params{now} : $self->time; 2739 2740 $time = $now + $params{delay}; 2741 } 2742 else { 2743 croak "Expected either 'time' or 'delay' keys"; 2744 } 2745 2746 return $time; 2747} 2748 2749=head2 enqueue_timer 2750 2751 $id = $loop->enqueue_timer( %params ) 2752 2753An older version of C<watch_time>. This method should not be used in new code 2754but is retained for legacy purposes. For simple watch/unwatch behaviour use 2755instead the new C<watch_time> method; though note it has differently-named 2756arguments. For requeueable timers, consider using an 2757L<IO::Async::Timer::Countdown> or L<IO::Async::Timer::Absolute> instead. 2758 2759=cut 2760 2761sub enqueue_timer 2762{ 2763 my $self = shift; 2764 my ( %params ) = @_; 2765 2766 # Renamed args 2767 $params{after} = delete $params{delay} if exists $params{delay}; 2768 $params{at} = delete $params{time} if exists $params{time}; 2769 2770 my $code = $params{code}; 2771 return [ $self->watch_time( %params ), $code ]; 2772} 2773 2774=head2 cancel_timer 2775 2776 $loop->cancel_timer( $id ) 2777 2778An older version of C<unwatch_time>. This method should not be used in new 2779code but is retained for legacy purposes. 2780 2781=cut 2782 2783sub cancel_timer 2784{ 2785 my $self = shift; 2786 my ( $id ) = @_; 2787 $self->unwatch_time( $id->[0] ); 2788} 2789 2790=head2 requeue_timer 2791 2792 $newid = $loop->requeue_timer( $id, %params ) 2793 2794Reschedule an existing timer, moving it to a new time. The old timer is 2795removed and will not be invoked. 2796 2797The C<%params> hash takes the same keys as C<enqueue_timer>, except for the 2798C<code> argument. 2799 2800The requeue operation may be implemented as a cancel + enqueue, which may 2801mean the ID changes. Be sure to store the returned C<$newid> value if it is 2802required. 2803 2804This method should not be used in new code but is retained for legacy 2805purposes. For requeueable, consider using an L<IO::Async::Timer::Countdown> or 2806L<IO::Async::Timer::Absolute> instead. 2807 2808=cut 2809 2810sub requeue_timer 2811{ 2812 my $self = shift; 2813 my ( $id, %params ) = @_; 2814 2815 $self->unwatch_time( $id->[0] ); 2816 return $self->enqueue_timer( %params, code => $id->[1] ); 2817} 2818 2819=head2 watch_idle 2820 2821 $id = $loop->watch_idle( %params ) 2822 2823This method installs a callback which will be called at some point in the near 2824future. 2825 2826The C<%params> hash takes the following keys: 2827 2828=over 8 2829 2830=item when => STRING 2831 2832Specifies the time at which the callback will be invoked. See below. 2833 2834=item code => CODE 2835 2836CODE reference to the continuation to run at the allotted time. 2837 2838=back 2839 2840The C<when> parameter defines the time at which the callback will later be 2841invoked. Must be one of the following values: 2842 2843=over 8 2844 2845=item later 2846 2847Callback is invoked after the current round of IO events have been processed 2848by the loop's underlying C<loop_once> method. 2849 2850If a new idle watch is installed from within a C<later> callback, the 2851installed one will not be invoked during this round. It will be deferred for 2852the next time C<loop_once> is called, after any IO events have been handled. 2853 2854=back 2855 2856If there are pending idle handlers, then the C<loop_once> method will use a 2857zero timeout; it will return immediately, having processed any IO events and 2858idle handlers. 2859 2860The returned C<$id> value can be used to identify the idle handler in case it 2861needs to be removed, by calling the C<unwatch_idle> method. Note this value 2862may be a reference, so if it is stored it should be released after the 2863callback has been invoked or cancled, so the referrant itself can be freed. 2864 2865This and C<unwatch_idle> are optional; a subclass may implement neither, or 2866both. If it implements neither then idle handling will be performed by the 2867base class, using the C<_adjust_timeout> and C<_manage_queues> methods. 2868 2869=cut 2870 2871sub watch_idle 2872{ 2873 my $self = shift; 2874 my %params = @_; 2875 2876 my $code = delete $params{code}; 2877 ref $code or croak "Expected 'code' to be a reference"; 2878 2879 my $when = delete $params{when} or croak "Expected 'when'"; 2880 2881 # Future-proofing for other idle modes 2882 $when eq "later" or croak "Expected 'when' to be 'later'"; 2883 2884 my $deferrals = $self->{deferrals}; 2885 2886 push @$deferrals, $code; 2887 return \$deferrals->[-1]; 2888} 2889 2890=head2 unwatch_idle 2891 2892 $loop->unwatch_idle( $id ) 2893 2894Cancels a previously-installed idle handler. 2895 2896=cut 2897 2898sub unwatch_idle 2899{ 2900 my $self = shift; 2901 my ( $id ) = @_; 2902 2903 my $deferrals = $self->{deferrals}; 2904 2905 my $idx; 2906 \$deferrals->[$_] == $id and ( $idx = $_ ), last for 0 .. $#$deferrals; 2907 2908 splice @$deferrals, $idx, 1, () if defined $idx; 2909} 2910 2911sub _reap_children 2912{ 2913 my ( $childwatches ) = @_; 2914 2915 while( 1 ) { 2916 my $zid = waitpid( -1, WNOHANG ); 2917 2918 # PIDs on MSWin32 can be negative 2919 last if !defined $zid or $zid == 0 or $zid == -1; 2920 my $status = $?; 2921 2922 if( defined $childwatches->{$zid} ) { 2923 $childwatches->{$zid}->( $zid, $status ); 2924 delete $childwatches->{$zid}; 2925 } 2926 2927 if( defined $childwatches->{0} ) { 2928 $childwatches->{0}->( $zid, $status ); 2929 # Don't delete it 2930 } 2931 } 2932} 2933 2934=head2 watch_process 2935 2936 $loop->watch_process( $pid, $code ) 2937 2938This method adds a new handler for the termination of the given child process 2939PID, or all child processes. 2940 2941=over 8 2942 2943=item $pid 2944 2945The PID to watch. Will report on all child processes if this is 0. 2946 2947=item $code 2948 2949A CODE reference to the exit handler. It will be invoked as 2950 2951 $code->( $pid, $? ) 2952 2953The second argument is passed the plain perl C<$?> value. 2954 2955=back 2956 2957After invocation, the handler for a PID-specific watch is automatically 2958removed. The all-child watch will remain until it is removed by 2959C<unwatch_process>. 2960 2961This and C<unwatch_process> are optional; a subclass may implement neither, or 2962both. If it implements neither then child watching will be performed by using 2963C<watch_signal> to install a C<SIGCHLD> handler, which will use C<waitpid> to 2964look for exited child processes. 2965 2966If both a PID-specific and an all-process watch are installed, there is no 2967ordering guarantee as to which will be called first. 2968 2969B<NOTE> that not all loop classes may be able to support the all-child watch. 2970The basic Select and Poll-based classes provided by this distribution do, and 2971those built on top of similar OS-specific mechanisms such as Linux's Epoll 2972probably will, but typically those built on top of other event systems such 2973as F<glib> or F<libuv> may not be able, as the underlying event system may not 2974provide the necessary hooks to support it. 2975 2976=cut 2977 2978sub watch_process 2979{ 2980 my $self = shift; 2981 my ( $pid, $code ) = @_; 2982 2983 if( $self->API_VERSION < 0.76 and 2984 ( $self->can( "watch_child" ) // 0 ) != \&watch_child ) { 2985 # Invoke legacy loop API 2986 return $self->watch_child( @_ ); 2987 } 2988 2989 my $childwatches = $self->{childwatches}; 2990 2991 croak "Already have a handler for $pid" if exists $childwatches->{$pid}; 2992 2993 if( HAVE_SIGNALS and !$self->{childwatch_sigid} ) { 2994 $self->{childwatch_sigid} = $self->attach_signal( 2995 CHLD => sub { _reap_children( $childwatches ) } 2996 ); 2997 2998 # There's a chance the child has already exited 2999 my $zid = waitpid( $pid, WNOHANG ); 3000 if( defined $zid and $zid > 0 ) { 3001 my $exitstatus = $?; 3002 $self->later( sub { $code->( $pid, $exitstatus ) } ); 3003 return; 3004 } 3005 } 3006 3007 $childwatches->{$pid} = $code; 3008} 3009 3010# Old name 3011sub watch_child { shift->watch_process( @_ ) } 3012 3013=head2 unwatch_process 3014 3015 $loop->unwatch_process( $pid ) 3016 3017This method removes a watch on an existing child process PID. 3018 3019=cut 3020 3021sub unwatch_process 3022{ 3023 my $self = shift; 3024 my ( $pid ) = @_; 3025 3026 if( $self->API_VERSION < 0.76 and 3027 ( $self->can( "unwatch_child" ) // 0 ) != \&unwatch_child ) { 3028 # Invoke legacy loop API 3029 return $self->unwatch_child( @_ ); 3030 } 3031 3032 my $childwatches = $self->{childwatches}; 3033 3034 delete $childwatches->{$pid}; 3035 3036 if( HAVE_SIGNALS and !keys %$childwatches ) { 3037 $self->detach_signal( CHLD => delete $self->{childwatch_sigid} ); 3038 } 3039} 3040 3041# Old name 3042sub unwatch_child { shift->unwatch_process( @_ ) } 3043 3044=head1 METHODS FOR SUBCLASSES 3045 3046The following methods are provided to access internal features which are 3047required by specific subclasses to implement the loop functionality. The use 3048cases of each will be documented in the above section. 3049 3050=cut 3051 3052=head2 _adjust_timeout 3053 3054 $loop->_adjust_timeout( \$timeout ) 3055 3056Shortens the timeout value passed in the scalar reference if it is longer in 3057seconds than the time until the next queued event on the timer queue. If there 3058are pending idle handlers, the timeout is reduced to zero. 3059 3060=cut 3061 3062sub _adjust_timeout 3063{ 3064 my $self = shift; 3065 my ( $timeref, %params ) = @_; 3066 3067 $$timeref = 0, return if @{ $self->{deferrals} }; 3068 3069 if( defined $self->{sigproxy} and !$params{no_sigwait} ) { 3070 $$timeref = $MAX_SIGWAIT_TIME if !defined $$timeref or $$timeref > $MAX_SIGWAIT_TIME; 3071 } 3072 if( !HAVE_SIGNALS and keys %{ $self->{childwatches} } ) { 3073 $$timeref = $MAX_CHILDWAIT_TIME if !defined $$timeref or $$timeref > $MAX_CHILDWAIT_TIME; 3074 } 3075 3076 my $timequeue = $self->{timequeue}; 3077 return unless defined $timequeue; 3078 3079 my $nexttime = $timequeue->next_time; 3080 return unless defined $nexttime; 3081 3082 my $now = exists $params{now} ? $params{now} : $self->time; 3083 my $timer_delay = $nexttime - $now; 3084 3085 if( $timer_delay < 0 ) { 3086 $$timeref = 0; 3087 } 3088 elsif( !defined $$timeref or $timer_delay < $$timeref ) { 3089 $$timeref = $timer_delay; 3090 } 3091} 3092 3093=head2 _manage_queues 3094 3095 $loop->_manage_queues 3096 3097Checks the timer queue for callbacks that should have been invoked by now, and 3098runs them all, removing them from the queue. It also invokes all of the 3099pending idle handlers. Any new idle handlers installed by these are not 3100invoked yet; they will wait for the next time this method is called. 3101 3102=cut 3103 3104sub _manage_queues 3105{ 3106 my $self = shift; 3107 3108 my $count = 0; 3109 3110 my $timequeue = $self->{timequeue}; 3111 $count += $timequeue->fire if $timequeue; 3112 3113 my $deferrals = $self->{deferrals}; 3114 $self->{deferrals} = []; 3115 3116 foreach my $code ( @$deferrals ) { 3117 $code->(); 3118 $count++; 3119 } 3120 3121 my $childwatches = $self->{childwatches}; 3122 if( !HAVE_SIGNALS and keys %$childwatches ) { 3123 _reap_children( $childwatches ); 3124 } 3125 3126 return $count; 3127} 3128 3129=head1 EXTENSIONS 3130 3131An Extension is a Perl module that provides extra methods in the 3132C<IO::Async::Loop> or other packages. They are intended to provide extra 3133functionality that easily integrates with the rest of the code. 3134 3135Certain base methods take an C<extensions> parameter; an ARRAY reference 3136containing a list of extension names. If such a list is passed to a method, it 3137will immediately call a method whose name is that of the base method, prefixed 3138by the first extension name in the list, separated by C<_>. If the 3139C<extensions> list contains more extension names, it will be passed the 3140remaining ones in another C<extensions> parameter. 3141 3142For example, 3143 3144 $loop->connect( 3145 extensions => [qw( FOO BAR )], 3146 %args 3147 ) 3148 3149will become 3150 3151 $loop->FOO_connect( 3152 extensions => [qw( BAR )], 3153 %args 3154 ) 3155 3156This is provided so that extension modules, such as L<IO::Async::SSL> can 3157easily be invoked indirectly, by passing extra arguments to C<connect> methods 3158or similar, without needing every module to be aware of the C<SSL> extension. 3159This functionality is generic and not limited to C<SSL>; other extensions may 3160also use it. 3161 3162The following methods take an C<extensions> parameter: 3163 3164 $loop->connect 3165 $loop->listen 3166 3167If an extension C<listen> method is invoked, it will be passed a C<listener> 3168parameter even if one was not provided to the original C<< $loop->listen >> 3169call, and it will not receive any of the C<on_*> event callbacks. It should 3170use the C<acceptor> parameter on the C<listener> object. 3171 3172=cut 3173 3174=head1 STALL WATCHDOG 3175 3176A well-behaved L<IO::Async> program should spend almost all of its time 3177blocked on input using the underlying C<IO::Async::Loop> instance. The stall 3178watchdog is an optional debugging feature to help detect CPU spinlocks and 3179other bugs, where control is not returned to the loop every so often. 3180 3181If the watchdog is enabled and an event handler consumes more than a given 3182amount of real time before returning to the event loop, it will be interrupted 3183by printing a stack trace and terminating the program. The watchdog is only in 3184effect while the loop itself is not blocking; it won't fail simply because the 3185loop instance is waiting for input or timers. 3186 3187It is implemented using C<SIGALRM>, so if enabled, this signal will no longer 3188be available to user code. (Though in any case, most uses of C<alarm()> and 3189C<SIGALRM> are better served by one of the L<IO::Async::Timer> subclasses). 3190 3191The following environment variables control its behaviour. 3192 3193=over 4 3194 3195=item IO_ASYNC_WATCHDOG => BOOL 3196 3197Enables the stall watchdog if set to a non-zero value. 3198 3199=item IO_ASYNC_WATCHDOG_INTERVAL => INT 3200 3201Watchdog interval, in seconds, to pass to the C<alarm(2)> call. Defaults to 10 3202seconds. 3203 3204=item IO_ASYNC_WATCHDOG_SIGABRT => BOOL 3205 3206If enabled, the watchdog signal handler will raise a C<SIGABRT>, which usually 3207has the effect of breaking out of a running program in debuggers such as 3208F<gdb>. If not set then the process is terminated by throwing an exception with 3209C<die>. 3210 3211=back 3212 3213=cut 3214 3215=head1 AUTHOR 3216 3217Paul Evans <leonerd@leonerd.org.uk> 3218 3219=cut 3220 32210x55AA; 3222