Acme-Sort-Sleep
view release on metacpan or search on metacpan
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
return 0;
},
) );
$loop->run;
=head1 DESCRIPTION
This module provides an abstract class which implements the core loop of the
L<IO::Async> framework. Its primary purpose is to store a set of
L<IO::Async::Notifier> objects or subclasses of them. It handles all of the
lower-level set manipulation actions, and leaves the actual IO readiness
testing/notification to the concrete class that implements it. It also
provides other functionality such as signal handling, child process managing,
and timers.
See also the two bundled Loop subclasses:
=over 4
=item L<IO::Async::Loop::Select>
=item L<IO::Async::Loop::Poll>
=back
Or other subclasses that may appear on CPAN which are not part of the core
L<IO::Async> distribution.
=head2 Ignoring SIGPIPE
Since version I<0.66> loading this module automatically ignores C<SIGPIPE>, as
it is highly unlikely that the default-terminate action is the best course of
action for an L<IO::Async>-based program to take. If at load time the handler
disposition is still set as C<DEFAULT>, it is set to ignore. If already
another handler has been placed there by the program code, it will be left
undisturbed.
=cut
# Internal constructor used by subclasses
sub __new
{
my $class = shift;
# Detect if the API version provided by the subclass is sufficient
$class->can( "API_VERSION" ) or
die "$class is too old for IO::Async $VERSION; it does not provide \->API_VERSION\n";
$class->API_VERSION >= NEED_API_VERSION or
die "$class is too old for IO::Async $VERSION; we need API version >= ".NEED_API_VERSION.", it provides ".$class->API_VERSION."\n";
WATCHDOG_ENABLE and !$class->_CAN_WATCHDOG and
warn "$class cannot implement IO_ASYNC_WATCHDOG\n";
my $self = bless {
notifiers => {}, # {nkey} = notifier
iowatches => {}, # {fd} = [ $on_read_ready, $on_write_ready, $on_hangup ]
sigattaches => {}, # {sig} => \@callbacks
childmanager => undef,
childwatches => {}, # {pid} => $code
threadwatches => {}, # {tid} => $code
timequeue => undef,
deferrals => [],
os => {}, # A generic scratchpad for IO::Async::OS to store whatever it wants
}, $class;
# It's possible this is a specific subclass constructor. We still want the
# magic IO::Async::Loop->new constructor to yield this if it's the first
# one
our $ONE_TRUE_LOOP ||= $self;
# Legacy support - temporary until all CPAN classes are updated; bump NEEDAPI version at that point
my $old_timer = $self->can( "enqueue_timer" ) != \&enqueue_timer;
if( $old_timer != ( $self->can( "cancel_timer" ) != \&cancel_timer ) ) {
die "$class should overload both ->enqueue_timer and ->cancel_timer, or neither";
}
if( $old_timer ) {
warnings::warnif( deprecated => "Enabling old_timer workaround for old loop class " . $class );
}
$self->{old_timer} = $old_timer;
return $self;
}
=head1 MAGIC CONSTRUCTOR
=head2 new
$loop = IO::Async::Loop->new
This function attempts to find a good subclass to use, then calls its
constructor. It works by making a list of likely candidate classes, then
trying each one in turn, C<require>ing the module then calling its C<new>
method. If either of these operations fails, the next subclass is tried. If
no class was successful, then an exception is thrown.
The constructed object is cached, and will be returned again by a subsequent
call. The cache will also be set by a constructor on a specific subclass. This
behaviour makes it possible to simply use the normal constructor in a module
that wishes to interract with the main program's Loop, such as an integration
module for another event system.
For example, the following two C<$loop> variables will refer to the same
object:
use IO::Async::Loop;
use IO::Async::Loop::Poll;
my $loop_poll = IO::Async::Loop::Poll->new;
my $loop = IO::Async::Loop->new;
While it is not advised to do so under normal circumstances, if the program
really wishes to construct more than one Loop object, it can call the
constructor C<really_new>, or invoke one of the subclass-specific constructors
directly.
The list of candidates is formed from the following choices, in this order:
=over 4
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
If this scalar is set, it should contain a comma-separated list of subclass
names. These may or may not be fully-qualified, as with the above case. This
allows a program author to suggest a loop module to use.
In cases where the module subclass is a hard requirement, such as GTK programs
using C<Glib>, it would be better to use the module specifically and invoke
its constructor directly.
=item * IO::Async::OS->LOOP_PREFER_CLASSES
The L<IO::Async::OS> hints module for the given OS is then consulted to see if
it suggests any other module classes specific to the given operating system.
=item * $^O
The module called C<IO::Async::Loop::$^O> is tried next. This allows specific
OSes, such as the ever-tricky C<MSWin32>, to provide an implementation that
might be more efficient than the generic ones, or even work at all.
This option is now discouraged in favour of the L<IO::Async::OS> hint instead.
At some future point it may be removed entirely, given as currently only
C<linux> uses it.
=item * Poll and Select
Finally, if no other choice has been made by now, the built-in C<Poll> module
is chosen. This should always work, but in case it doesn't, the C<Select>
module will be chosen afterwards as a last-case attempt. If this also fails,
then the magic constructor itself will throw an exception.
=back
If any of the explicitly-requested loop types (C<$ENV{IO_ASYNC_LOOP}> or
C<$IO::Async::Loop::LOOP>) fails to load then a warning is printed detailing
the error.
Implementors of new C<IO::Async::Loop> subclasses should see the notes about
C<API_VERSION> below.
=cut
sub __try_new
{
my ( $class ) = @_;
( my $file = "$class.pm" ) =~ s{::}{/}g;
eval {
local $SIG{__WARN__} = sub {};
require $file;
} or return;
my $self;
$self = eval { $class->new } and return $self;
# Oh dear. We've loaded the code OK but for some reason the constructor
# wasn't happy. Being polite we ought really to unload the file again,
# but perl doesn't actually provide us a way to do this.
return undef;
}
sub new
{
return our $ONE_TRUE_LOOP ||= shift->really_new;
}
# Ensure that the loop is DESTROYed recursively at exit time, before GD happens
END {
undef our $ONE_TRUE_LOOP;
}
sub really_new
{
shift; # We're going to ignore the class name actually given
my $self;
my @candidates;
push @candidates, split( m/,/, $ENV{IO_ASYNC_LOOP} ) if defined $ENV{IO_ASYNC_LOOP};
push @candidates, split( m/,/, $LOOP ) if defined $LOOP;
foreach my $class ( @candidates ) {
$class =~ m/::/ or $class = "IO::Async::Loop::$class";
$self = __try_new( $class ) and return $self;
my ( $topline ) = split m/\n/, $@; # Ignore all the other lines; they'll be require's verbose output
warn "Unable to use $class - $topline\n";
}
unless( $LOOP_NO_OS ) {
foreach my $class ( IO::Async::OS->LOOP_PREFER_CLASSES, "IO::Async::Loop::$^O" ) {
$class =~ m/::/ or $class = "IO::Async::Loop::$class";
$self = __try_new( $class ) and return $self;
# Don't complain about these ones
}
}
return IO::Async::Loop->new_builtin;
}
sub new_builtin
{
shift;
my $self;
foreach my $class ( IO::Async::OS->LOOP_BUILTIN_CLASSES ) {
$self = __try_new( "IO::Async::Loop::$class" ) and return $self;
}
croak "Cannot find a suitable candidate class";
}
#######################
# Notifier management #
#######################
=head1 NOTIFIER MANAGEMENT
The following methods manage the collection of L<IO::Async::Notifier> objects.
=cut
=head2 add
$loop->add( $notifier )
This method adds another notifier object to the stored collection. The object
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
if( defined $notifier->parent ) {
croak "Cannot add a child notifier directly - add its parent";
}
if( defined $notifier->loop ) {
croak "Cannot add a notifier that is already a member of a loop";
}
$self->_add_noparentcheck( $notifier );
}
sub _add_noparentcheck
{
my $self = shift;
my ( $notifier ) = @_;
my $nkey = refaddr $notifier;
$self->{notifiers}->{$nkey} = $notifier;
$notifier->__set_loop( $self );
$self->_add_noparentcheck( $_ ) for $notifier->children;
return;
}
=head2 remove
$loop->remove( $notifier )
This method removes a notifier object from the stored collection, and
recursively and children notifiers it contains.
=cut
sub remove
{
my $self = shift;
my ( $notifier ) = @_;
if( defined $notifier->parent ) {
croak "Cannot remove a child notifier directly - remove its parent";
}
$self->_remove_noparentcheck( $notifier );
}
sub _remove_noparentcheck
{
my $self = shift;
my ( $notifier ) = @_;
my $nkey = refaddr $notifier;
exists $self->{notifiers}->{$nkey} or croak "Notifier does not exist in collection";
delete $self->{notifiers}->{$nkey};
$notifier->__set_loop( undef );
$self->_remove_noparentcheck( $_ ) for $notifier->children;
return;
}
=head2 notifiers
@notifiers = $loop->notifiers
Returns a list of all the notifier objects currently stored in the Loop.
=cut
sub notifiers
{
my $self = shift;
# Sort so the order remains stable under additions/removals
return map { $self->{notifiers}->{$_} } sort keys %{ $self->{notifiers} };
}
###################
# Looping support #
###################
=head1 LOOPING CONTROL
The following methods control the actual run cycle of the loop, and hence the
program.
=cut
=head2 loop_once
$count = $loop->loop_once( $timeout )
This method performs a single wait loop using the specific subclass's
underlying mechanism. If C<$timeout> is undef, then no timeout is applied, and
it will wait until an event occurs. The intention of the return value is to
indicate the number of callbacks that this loop executed, though different
subclasses vary in how accurately they can report this. See the documentation
for this method in the specific subclass for more information.
=cut
sub loop_once
{
my $self = shift;
my ( $timeout ) = @_;
croak "Expected that $self overrides ->loop_once";
}
=head2 run
@result = $loop->run
$result = $loop->run
Runs the actual IO event loop. This method blocks until the C<stop> method is
called, and returns the result that was passed to C<stop>. In scalar context
only the first result is returned; the others will be discarded if more than
one value was provided. This method may be called recursively.
This method is a recent addition and may not be supported by all the
C<IO::Async::Loop> subclasses currently available on CPAN.
=cut
sub run
{
my $self = shift;
local $self->{running} = 1;
local $self->{result} = [];
while( $self->{running} ) {
$self->loop_once( undef );
}
return wantarray ? @{ $self->{result} } : $self->{result}[0];
}
=head2 stop
$loop->stop( @result )
Stops the inner-most C<run> method currently in progress, causing it to return
the given C<@result>.
This method is a recent addition and may not be supported by all the
C<IO::Async::Loop> subclasses currently available on CPAN.
=cut
sub stop
{
my $self = shift;
@{ $self->{result} } = @_;
undef $self->{running};
}
=head2 loop_forever
$loop->loop_forever
A synonym for C<run>, though this method does not return a result.
=cut
sub loop_forever
{
my $self = shift;
$self->run;
return;
}
=head2 loop_stop
$loop->loop_stop
A synonym for C<stop>, though this method does not pass any results.
=cut
sub loop_stop
{
my $self = shift;
$self->stop;
}
=head2 post_fork
$loop->post_fork
The base implementation of this method does nothing. It is provided in case
some Loop subclasses should take special measures after a C<fork()> system
call if the main body of the program should survive in both running processes.
This may be required, for example, in a long-running server daemon that forks
multiple copies on startup after opening initial listening sockets. A loop
implementation that uses some in-kernel resource that becomes shared after
forking (for example, a Linux C<epoll> or a BSD C<kqueue> filehandle) would
need recreating in the new child process before the program can continue.
=cut
sub post_fork
{
# empty
}
###########
# Futures #
###########
=head1 FUTURE SUPPORT
The following methods relate to L<IO::Async::Future> objects.
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
$on_error->( $process->pid, $exitcode, $errno, $exception );
};
}
$params{on_exit} and croak "Cannot pass 'on_exit' parameter through ChildManager->open";
require IO::Async::Process;
my $process = IO::Async::Process->new( %params );
$self->add( $process );
return $process->pid;
}
=head2 run_child
$pid = $loop->run_child( %params )
This creates a new child process to run the given code block or command,
capturing its STDOUT and STDERR streams. When the process exits, a
continuation is invoked being passed the exitcode, and content of the streams.
=over 8
=item command => ARRAY or STRING
=item code => CODE
The command or code to run in the child process (as per the C<spawn_child>
method)
=item on_finish => CODE
A continuation to be called when the child process exits and closed its STDOUT
and STDERR streams. It will be invoked in the following way:
$on_finish->( $pid, $exitcode, $stdout, $stderr )
The second argument is passed the plain perl C<$?> value.
=item stdin => STRING
Optional. String to pass in to the child process's STDIN stream.
=item setup => ARRAY
Optional reference to an array to pass to the underlying C<spawn> method.
=back
This method is intended mainly as an IO::Async-compatible replacement for the
perl C<readpipe> function (`backticks`), allowing it to replace
my $output = `command here`;
with
$loop->run_child(
command => "command here",
on_finish => sub {
my ( undef, $exitcode, $output ) = @_;
...
}
);
=cut
sub run_child
{
my $self = shift;
my %params = @_;
my $on_finish = delete $params{on_finish};
ref $on_finish or croak "Expected 'on_finish' to be a reference";
my $stdout;
my $stderr;
my %subparams;
if( my $child_stdin = delete $params{stdin} ) {
ref $child_stdin and croak "Expected 'stdin' not to be a reference";
$subparams{stdin} = { from => $child_stdin };
}
$subparams{code} = delete $params{code};
$subparams{command} = delete $params{command};
$subparams{setup} = delete $params{setup};
croak "Unrecognised parameters " . join( ", ", keys %params ) if keys %params;
require IO::Async::Process;
my $process = IO::Async::Process->new(
%subparams,
stdout => { into => \$stdout },
stderr => { into => \$stderr },
on_finish => sub {
my ( $process, $exitcode ) = @_;
$on_finish->( $process->pid, $exitcode, $stdout, $stderr );
},
);
$self->add( $process );
return $process->pid;
}
=head2 resolver
$loop->resolver
Returns the internally-stored L<IO::Async::Resolver> object, used for name
resolution operations by the C<resolve>, C<connect> and C<listen> methods.
=cut
sub resolver
{
my $self = shift;
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
my $on_done;
# Legacy callbacks
if( my $on_connected = delete $params{on_connected} ) {
$on_done = $on_connected;
}
elsif( my $on_stream = delete $params{on_stream} ) {
defined $handle and croak "Cannot pass 'on_stream' with a handle object as well";
require IO::Async::Stream;
# TODO: It doesn't make sense to put a SOCK_DGRAM in an
# IO::Async::Stream but currently we don't detect this
$handle = IO::Async::Stream->new;
$on_done = $on_stream;
}
elsif( my $on_socket = delete $params{on_socket} ) {
defined $handle and croak "Cannot pass 'on_socket' with a handle object as well";
require IO::Async::Socket;
$handle = IO::Async::Socket->new;
$on_done = $on_socket;
}
elsif( !defined wantarray ) {
croak "Expected 'on_connected' or 'on_stream' callback or to return a Future";
}
my $on_connect_error;
if( $on_connect_error = $params{on_connect_error} ) {
# OK
}
elsif( !defined wantarray ) {
croak "Expected 'on_connect_error' callback";
}
my $on_resolve_error;
if( $on_resolve_error = $params{on_resolve_error} ) {
# OK
}
elsif( !defined wantarray and exists $params{host} || exists $params{local_host} ) {
croak "Expected 'on_resolve_error' callback or to return a Future";
}
my $connector = $self->{connector} ||= $self->__new_feature( "IO::Async::Internals::Connector" );
my $future = $connector->connect( %params );
$future = $future->then( sub {
$handle->set_handle( shift );
return Future->done( $handle )
}) if $handle;
$future->on_done( $on_done ) if $on_done;
$future->on_fail( sub {
$on_connect_error->( @_[2,3] ) if $on_connect_error and $_[1] eq "connect";
$on_resolve_error->( $_[2] ) if $on_resolve_error and $_[1] eq "resolve";
} );
return $future if defined wantarray;
# Caller is not going to keep hold of the Future, so we have to ensure it
# stays alive somehow
$future->on_ready( sub { undef $future } ); # intentional cycle
}
=head2 listen
$listener = $loop->listen( %params )->get
This method sets up a listening socket and arranges for an acceptor callback
to be invoked each time a new connection is accepted on the socket. Internally
it creates an instance of L<IO::Async::Listener> and adds it to the Loop if
not given one in the arguments.
Addresses may be given directly, or they may be looked up using the system's
name resolver, or a socket handle may be given directly.
If multiple addresses are given, or resolved from the service and hostname,
then each will be attempted in turn until one succeeds.
In named resolver mode, the C<%params> hash takes the following keys:
=over 8
=item service => STRING
The service name to listen on.
=item host => STRING
The hostname to listen on. Optional. Will listen on all addresses if not
supplied.
=item family => INT
=item socktype => INT
=item protocol => INT
=item flags => INT
Optional. Other arguments to pass along with C<host> and C<service> to the
C<getaddrinfo> call.
=item socktype => STRING
Optionally may instead be one of the values C<'stream'>, C<'dgram'> or
C<'raw'> to stand for C<SOCK_STREAM>, C<SOCK_DGRAM> or C<SOCK_RAW>. This
utility is provided to allow the caller to avoid a separate C<use Socket> only
for importing these constants.
=back
It is necessary to pass the C<socktype> hint to the resolver when resolving
the host/service names into an address, as some OS's C<getaddrinfo> functions
require this hint. A warning is emitted if neither C<socktype> nor C<protocol>
hint is defined when performing a C<getaddrinfo> lookup. To avoid this warning
while still specifying no particular C<socktype> hint (perhaps to invoke some
OS-specific behaviour), pass C<0> as the C<socktype> value.
In plain address mode, the C<%params> hash takes the following keys:
=over 8
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
my $method = "${ext}_listen";
# TODO: Try to 'require IO::Async::$ext'
$self->can( $method ) or croak "Extension method '$method' is not available";
my $f = $self->$method(
%params,
( @others ? ( extensions => \@others ) : () ),
);
$f->on_fail( sub { $self->remove( $listener ) } ) if $remove_on_error;
return $f;
}
my $on_notifier = delete $params{on_notifier}; # optional
my $on_listen_error = delete $params{on_listen_error};
my $on_resolve_error = delete $params{on_resolve_error};
# Shortcut
if( $params{addr} and not $params{addrs} ) {
$params{addrs} = [ delete $params{addr} ];
}
my $f;
if( my $handle = delete $params{handle} ) {
$f = $self->_listen_handle( $listener, $handle, %params );
}
elsif( my $addrs = delete $params{addrs} ) {
$on_listen_error or defined wantarray or
croak "Expected 'on_listen_error' or to return a Future";
$f = $self->_listen_addrs( $listener, $addrs, %params );
}
elsif( defined $params{service} ) {
$on_listen_error or defined wantarray or
croak "Expected 'on_listen_error' or to return a Future";
$on_resolve_error or defined wantarray or
croak "Expected 'on_resolve_error' or to return a Future";
$f = $self->_listen_hostservice( $listener, delete $params{host}, delete $params{service}, %params );
}
else {
croak "Expected either 'service' or 'addrs' or 'addr' arguments";
}
$f->on_done( $on_notifier ) if $on_notifier;
if( my $on_listen = $params{on_listen} ) {
$f->on_done( sub { $on_listen->( shift->read_handle ) } );
}
$f->on_fail( sub {
my ( $message, $how, @rest ) = @_;
$on_listen_error->( @rest ) if $on_listen_error and $how eq "listen";
$on_resolve_error->( @rest ) if $on_resolve_error and $how eq "resolve";
});
$f->on_fail( sub { $self->remove( $listener ) } ) if $remove_on_error;
return $f if defined wantarray;
# Caller is not going to keep hold of the Future, so we have to ensure it
# stays alive somehow
$f->on_ready( sub { undef $f } ); # intentional cycle
}
sub _listen_handle
{
my $self = shift;
my ( $listener, $handle, %params ) = @_;
$listener->configure( handle => $handle );
return $self->new_future->done( $listener );
}
sub _listen_addrs
{
my $self = shift;
my ( $listener, $addrs, %params ) = @_;
my $queuesize = $params{queuesize} || 3;
my $on_fail = $params{on_fail};
!defined $on_fail or ref $on_fail or croak "Expected 'on_fail' to be a reference";
my $reuseaddr = 1;
$reuseaddr = 0 if defined $params{reuseaddr} and not $params{reuseaddr};
my $v6only = $params{v6only};
my ( $listenerr, $binderr, $sockopterr, $socketerr );
foreach my $addr ( @$addrs ) {
my ( $family, $socktype, $proto, $address ) = IO::Async::OS->extract_addrinfo( $addr );
my $sock;
unless( $sock = IO::Async::OS->socket( $family, $socktype, $proto ) ) {
$socketerr = $!;
$on_fail->( socket => $family, $socktype, $proto, $! ) if $on_fail;
next;
}
if( $reuseaddr ) {
unless( $sock->sockopt( SO_REUSEADDR, 1 ) ) {
$sockopterr = $!;
$on_fail->( sockopt => $sock, SO_REUSEADDR, 1, $! ) if $on_fail;
next;
}
}
if( defined $v6only and $family == AF_INET6 ) {
unless( $sock->setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, $v6only ) ) {
$sockopterr = $!;
$on_fail->( sockopt => $sock, IPV6_V6ONLY, $v6only, $! ) if $on_fail;
next;
}
}
unless( $sock->bind( $address ) ) {
$binderr = $!;
$on_fail->( bind => $sock, $address, $! ) if $on_fail;
next;
}
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
$self->resolver->getaddrinfo(
host => $host,
service => $service,
passive => 1,
%gai_hints,
)->then( sub {
my @addrs = @_;
$self->_listen_addrs( $listener, \@addrs, %params );
});
}
=head1 OS ABSTRACTIONS
Because the Magic Constructor searches for OS-specific subclasses of the Loop,
several abstractions of OS services are provided, in case specific OSes need
to give different implementations on that OS.
=cut
=head2 signame2num
$signum = $loop->signame2num( $signame )
Legacy wrappers around L<IO::Async::OS> functions.
=cut
sub signame2num { shift; IO::Async::OS->signame2num( @_ ) }
=head2 time
$time = $loop->time
Returns the current UNIX time in fractional seconds. This is currently
equivalent to C<Time::HiRes::time> but provided here as a utility for
programs to obtain the time current used by L<IO::Async> for its own timing
purposes.
=cut
sub time
{
my $self = shift;
return Time::HiRes::time;
}
=head2 fork
$pid = $loop->fork( %params )
This method creates a new child process to run a given code block, returning
its process ID.
=over 8
=item code => CODE
A block of code to execute in the child process. It will be called in scalar
context inside an C<eval> block. The return value will be used as the
C<exit(2)> code from the child if it returns (or 255 if it returned C<undef> or
thows an exception).
=item on_exit => CODE
A optional continuation to be called when the child processes exits. It will
be invoked in the following way:
$on_exit->( $pid, $exitcode )
The second argument is passed the plain perl C<$?> value.
This key is optional; if not supplied, the calling code should install a
handler using the C<watch_child> method.
=item keep_signals => BOOL
Optional boolean. If missing or false, any CODE references in the C<%SIG> hash
will be removed and restored back to C<DEFAULT> in the child process. If true,
no adjustment of the C<%SIG> hash will be performed.
=back
=cut
sub fork
{
my $self = shift;
my %params = @_;
HAVE_POSIX_FORK or croak "POSIX fork() is not available";
my $code = $params{code} or croak "Expected 'code' as a CODE reference";
my $kid = fork;
defined $kid or croak "Cannot fork() - $!";
if( $kid == 0 ) {
unless( $params{keep_signals} ) {
foreach( keys %SIG ) {
next if m/^__(WARN|DIE)__$/;
$SIG{$_} = "DEFAULT" if ref $SIG{$_} eq "CODE";
}
}
my $exitvalue = eval { $code->() };
defined $exitvalue or $exitvalue = -1;
POSIX::_exit( $exitvalue );
}
if( defined $params{on_exit} ) {
$self->watch_child( $kid => $params{on_exit} );
}
return $kid;
}
=head2 create_thread
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
$watch->[0] = $handle;
if( exists $params{on_read_ready} ) {
$watch->[1] = delete $params{on_read_ready};
}
if( exists $params{on_write_ready} ) {
$watch->[2] = delete $params{on_write_ready};
}
if( exists $params{on_hangup} ) {
$self->_CAN_ON_HANGUP or croak "Cannot watch_io for 'on_hangup' in ".ref($self);
$watch->[3] = delete $params{on_hangup};
}
keys %params and croak "Unrecognised keys for ->watch_io - " . join( ", ", keys %params );
}
=head2 unwatch_io
$loop->unwatch_io( %params )
This method removes a watch on an IO handle which was previously installed by
C<watch_io>.
The C<%params> hash takes the following keys:
=over 8
=item handle => IO
The IO handle to remove the watch for.
=item on_read_ready => BOOL
If true, remove the watch for read-readiness.
=item on_write_ready => BOOL
If true, remove the watch for write-readiness.
=back
Either or both callbacks may be removed at once. It is not an error to attempt
to remove a callback that is not present. If both callbacks were provided to
the C<watch_io> method and only one is removed by this method, the other shall
remain.
=cut
sub __unwatch_io
{
my $self = shift;
my %params = @_;
my $handle = delete $params{handle} or croak "Expected 'handle'";
my $watch = $self->{iowatches}->{$handle->fileno} or return;
if( delete $params{on_read_ready} ) {
undef $watch->[1];
}
if( delete $params{on_write_ready} ) {
undef $watch->[2];
}
if( delete $params{on_hangup} ) {
$self->_CAN_ON_HANGUP or croak "Cannot watch_io for 'on_hangup' in ".ref($self);
undef $watch->[3];
}
if( not $watch->[1] and not $watch->[2] and not $watch->[3] ) {
delete $self->{iowatches}->{$handle->fileno};
}
keys %params and croak "Unrecognised keys for ->unwatch_io - " . join( ", ", keys %params );
}
=head2 watch_signal
$loop->watch_signal( $signal, $code )
This method adds a new signal handler to watch the given signal.
=over 8
=item $signal
The name of the signal to watch to. This should be a bare name like C<TERM>.
=item $code
A CODE reference to the handling callback.
=back
There can only be one callback per signal name. Registering a new one will
remove an existing one.
Applications should use a L<IO::Async::Signal> object, or call
C<attach_signal> instead of using this method.
This and C<unwatch_signal> are optional; a subclass may implement neither, or
both. If it implements neither then signal handling will be performed by the
base class using a self-connected pipe to interrupt the main IO blocking.
=cut
sub watch_signal
{
my $self = shift;
my ( $signal, $code ) = @_;
HAVE_SIGNALS or croak "This OS cannot ->watch_signal";
IO::Async::OS->loop_watch_signal( $self, $signal, $code );
}
=head2 unwatch_signal
$loop->unwatch_signal( $signal )
This method removes the signal callback for the given signal.
=over 8
=item $signal
The name of the signal to watch to. This should be a bare name like C<TERM>.
( run in 0.620 second using v1.01-cache-2.11-cpan-d80b1682f3f )