Movatterモバイル変換


[0]ホーム

URL:


 / 
IO-Async-0.803
River stage three • 121 direct dependents • 155 total dependents
/IO::Async::Loop

NAME

IO::Async::Loop - core loop of theIO::Async framework

SYNOPSIS

use IO::Async::Stream;use IO::Async::Timer::Countdown;use IO::Async::Loop;my $loop = IO::Async::Loop->new;$loop->add( IO::Async::Timer::Countdown->new(   delay => 10,   on_expire => sub { print "10 seconds have passed\n" },)->start );$loop->add( IO::Async::Stream->new_for_stdin(   on_read => sub {      my ( $self, $buffref, $eof ) = @_;      while( $$buffref =~ s/^(.*)\n// ) {         print "You typed a line $1\n";      }      return 0;   },) );$loop->run;

DESCRIPTION

This module provides an abstract class which implements the core loop of theIO::Async framework. Its primary purpose is to store a set ofIO::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:

IO::Async::Loop::Select
IO::Async::Loop::Poll

Or other subclasses that may appear on CPAN which are not part of the coreIO::Async distribution.

Ignoring SIGPIPE

Since version0.66 loading this module automatically ignoresSIGPIPE, as it is highly unlikely that the default-terminate action is the best course of action for anIO::Async-based program to take. If at load time the handler disposition is still set asDEFAULT, it is set to ignore. If already another handler has been placed there by the program code, it will be left undisturbed.

MAGIC CONSTRUCTOR

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,requireing the module then calling itsnew 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 interact with the main program's Loop, such as an integration module for another event system.

For example, the following two$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 constructorreally_new, or invoke one of the subclass-specific constructors directly.

The list of candidates is formed from the following choices, in this order:

  • $ENV{IO_ASYNC_LOOP}

    If this environment variable is set, it should contain a comma-separated list of subclass names. These names may or may not be fully-qualified; if a name does not contain:: then it will haveIO::Async::Loop:: prepended to it. This allows the end-user to specify a particular choice to fit the needs of his use of a program usingIO::Async.

  • $IO::Async::Loop::LOOP

    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 usingGlib, it would be better to use the module specifically and invoke its constructor directly.

  • IO::Async::OS->LOOP_PREFER_CLASSES

    TheIO::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.

  • $^O

    The module calledIO::Async::Loop::$^O is tried next. This allows specific OSes, such as the ever-trickyMSWin32, 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 theIO::Async::OS hint instead. At some future point it may be removed entirely, given as currently onlylinux uses it.

  • Poll and Select

    Finally, if no other choice has been made by now, the built-inPoll module is chosen. This should always work, but in case it doesn't, theSelect module will be chosen afterwards as a last-case attempt. If this also fails, then the magic constructor itself will throw an exception.

If any of the explicitly-requested loop types ($ENV{IO_ASYNC_LOOP} or$IO::Async::Loop::LOOP) fails to load then a warning is printed detailing the error.

Implementors of newIO::Async::Loop subclasses should see the notes aboutAPI_VERSION below.

NOTIFIER MANAGEMENT

The following methods manage the collection ofIO::Async::Notifier objects.

add

$loop->add( $notifier );

This method adds another notifier object to the stored collection. The object may be aIO::Async::Notifier, or any subclass of it.

When a notifier is added, any children it has are also added, recursively. In this way, entire sections of a program may be written within a tree of notifier objects, and added or removed on one piece.

remove

$loop->remove( $notifier );

This method removes a notifier object from the stored collection, and recursively and children notifiers it contains.

notifiers

@notifiers = $loop->notifiers;

Returns a list of all the notifier objects currently stored in the Loop.

LOOPING CONTROL

The following methods control the actual run cycle of the loop, and hence the program.

loop_once

$count = $loop->loop_once( $timeout );

This method performs a single wait loop using the specific subclass's underlying mechanism. If$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.

run

@result = $loop->run;$result = $loop->run;

Runs the actual IO event loop. This method blocks until thestop method is called, and returns the result that was passed tostop. 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 theIO::Async::Loop subclasses currently available on CPAN.

stop

$loop->stop( @result );

Stops the inner-mostrun method currently in progress, causing it to return the given@result.

This method is a recent addition and may not be supported by all theIO::Async::Loop subclasses currently available on CPAN.

loop_forever

$loop->loop_forever;

A synonym forrun, though this method does not return a result.

loop_stop

$loop->loop_stop;

A synonym forstop, though this method does not pass any results.

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 afork() 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 Linuxepoll or a BSDkqueue filehandle) would need recreating in the new child process before the program can continue.

FUTURE SUPPORT

The following methods relate toIO::Async::Future objects.

new_future

$future = $loop->new_future;

Returns a newIO::Async::Future instance with a reference to the Loop.

await

await $loop->await( $future );

Blocks until the given future is ready, as indicated by itsis_ready method. As a convenience it returns the future, to simplify code:

my @result = await $loop->await( $future );

await_all

$loop->await_all( @futures );

Blocks until all the given futures are ready, as indicated by theis_ready method. Equivalent to callingawait on aFuture->wait_all except that it doesn't create the surrounding future object.

delay_future

await $loop->delay_future( %args );

Returns a newIO::Async::Future instance which will become done at a given point in time. The%args should contain anat orafter key as per thewatch_time method. The returned future may be cancelled to cancel the timer. At the alloted time the future will succeed with an empty result list.

timeout_future

await $loop->timeout_future( %args );

Returns a newIO::Async::Future instance which will fail at a given point in time. The%args should contain anat orafter key as per thewatch_time method. The returned future may be cancelled to cancel the timer. At the alloted time, the future will fail with the string"Timeout".

FEATURES

Most of the following methods are higher-level wrappers around base functionality provided by the low-level API documented below. They may be used byIO::Async::Notifier subclasses or called directly by the program.

The following methods documented inawait expressions returnFuture instances.

attach_signal

$id = $loop->attach_signal( $signal, $code );

This method adds a new signal handler to watch the given signal. The same signal can be attached to multiple times; its callback functions will all be invoked, in no particular order.

The returned$id value can be used to identify the signal handler in case it needs to be removed by thedetach_signal method. Note that this value may be an object reference, so if it is stored, it should be released after it is cancelled, so the object itself can be freed.

$signal

The name of the signal to attach to. This should be a bare name likeTERM.

$code

A CODE reference to the handling callback.

Attaching toSIGCHLD is not recommended because of the way all child processes use it to report their termination. Instead, thewatch_process method should be used to watch for termination of a given child process. A warning will be printed ifSIGCHLD is passed here, but in future versions ofIO::Async this behaviour may be disallowed altogether.

See alsoPOSIX for theSIGname constants.

For a more flexible way to use signals from within Notifiers, see instead theIO::Async::Signal object.

detach_signal

$loop->detach_signal( $signal, $id );

Removes a previously-attached signal handler.

$signal

The name of the signal to remove from. This should be a bare name likeTERM.

$id

The value returned by theattach_signal method.

later

$loop->later( $code );$f = $loop->later;

Schedules a code reference to be invoked as soon as the current round of IO operations is complete.

The code reference is never invoked immediately, though the loop will not perform any blocking operations between when it is installed and when it is invoked. It may callselect,poll or equivalent with a zero-second timeout, and process any currently-pending IO conditions before the code is invoked, but it will not block for a non-zero amount of time.

This method is implemented using thewatch_idle method, with thewhen parameter set tolater. It will return an ID value that can be passed tounwatch_idle if required.

Since version 0.78: If no$code value is passed, aFuture will be returned instead. This allows for constructs such as:

await $loop->later;

spawn_child

$loop->spawn_child( %params );

This method creates a new child process to run a given code block or command. The%params hash takes the following keys:

command => ARRAY or STRING

Either a reference to an array containing the command and its arguments, or a plain string containing the command. This value is passed into perl'sexec function.

code => CODE

A block of code to execute in the child process. It will be called in scalar context inside aneval block.

setup => ARRAY

A reference to an array which gives file descriptors to set up in the child process before running the code or command. See below.

on_exit => CODE

A continuation to be called when the child processes exits. It will be invoked in the following way:

$on_exit->( $pid, $exitcode, $dollarbang, $dollarat )

The second argument is passed the plain perl$? value.

Exactly one of thecommand orcode keys must be specified.

If thecommand key is used, the given array or string is executed using theexec function.

If thecode key is used, the return value will be used as theexit(2) code from the child if it returns (or 255 if it returnedundef or thows an exception).

Case          | ($exitcode >> 8)       | $dollarbang | $dollarat--------------+------------------------+-------------+----------exec succeeds | exit code from program |     0       |    ""exec fails    |         255            |     $!      |    ""$code returns |     return value       |     $!      |    ""$code dies    |         255            |     $!      |    $@

It is usually more convenient to use theopen_process method in simple cases where an external program is being started in order to interact with it via file IO, or evenrun_child when only the final result is required, rather than interaction while it is running.

setup array

This array gives a list of file descriptor operations to perform in the child process after it has beenfork(2)ed from the parent, before running the code or command. It consists of name/value pairs which are ordered; the operations are performed in the order given.

fdn => ARRAY

Gives an operation on file descriptorn. The first element of the array defines the operation to be performed:

[ 'close' ]

The file descriptor will be closed.

[ 'dup', $io ]

The file descriptor will bedup2(2)ed from the given IO handle.

[ 'open', $mode, $file ]

The file descriptor will be opened from the named file in the given mode. The$mode string should be in the form usually given to theopen function; such as '<' or '>>'.

[ 'keep' ]

The file descriptor will not be closed; it will be left as-is.

A non-reference value may be passed as a shortcut, where it would contain the name of the operation with no arguments (i.e. for theclose andkeep operations).

IO => ARRAY

Shortcut for passingfdn, wheren is the fileno of the IO reference. In this case, the key must be a reference that implements thefileno method. This is mostly useful for

$handle => 'keep'
fdn => IO

A shortcut for thedup case given above.

stdin => ...
stdout => ...
stderr => ...

Shortcuts forfd0,fd1 andfd2 respectively.

env => HASH

A reference to a hash to set as the child process's environment.

Note that this will entirely set a new environment, completely replacing the existing one. If you want to simply add new keys or change the values of some keys without removing the other existing ones, you can simply copy%ENV into the hash before setting new keys:

env => {   %ENV,   ANOTHER => "key here",}
nice => INT

Change the child process's scheduling priority usingPOSIX::nice.

chdir => STRING

Change the child process's working directory usingchdir.

setuid => INT
setgid => INT

Change the child process's effective UID or GID.

setgroups => ARRAY

Change the child process's groups list, to those groups whose numbers are given in the ARRAY reference.

On most systems, only the privileged superuser change user or group IDs.IO::Async willNOT check before detaching the child process whether this is the case.

If setting both the primary GID and the supplementary groups list, it is suggested to set the primary GID first. Moreover, some operating systems may require that the supplementary groups list contains the primary GID.

If no directions for what to do withstdin,stdout andstderr are given, a default ofkeep is implied. All other file descriptors will be closed, unless akeep operation is given for them.

Ifsetuid is used, be sure to place it after any other operations that might require superuser privileges, such assetgid or opening special files.

my ( $pipeRd, $pipeWr ) = IO::Async::OS->pipepair;$loop->spawn_child(   command => "/usr/bin/my-command",   setup => [      stdin  => [ "open", "<", "/dev/null" ],      stdout => $pipeWr,      stderr => [ "open", ">>", "/var/log/mycmd.log" ],      chdir  => "/",   ]   on_exit => sub {      my ( $pid, $exitcode ) = @_;      my $status = ( $exitcode >> 8 );      print "Command exited with status $status\n";   },);$loop->spawn_child(   code => sub {      do_something; # executes in a child process      return 1;   },   on_exit => sub {      my ( $pid, $exitcode, $dollarbang, $dollarat ) = @_;      my $status = ( $exitcode >> 8 );      print "Child process exited with status $status\n";      print " OS error was $dollarbang, exception was $dollarat\n";   },);

open_process

$process = $loop->open_process( %params );

Since version 0.72.

This creates a new child process to run the given code block or command, and attaches filehandles to it that the parent will watch. This method is a light wrapper around constructing a newIO::Async::Process object, adding it to the loop, and returning it.

The%params hash is passed directly to theIO::Async::Process constructor.

open_child

$pid = $loop->open_child( %params );

A back-compatibility wrapper to calling"open_process" and returning the PID of the newly-constructedIO::Async::Process instance. Theon_finish continuation likewise will be invoked with the PID rather than the process instance.

$on_finish->( $pid, $exitcode );

Similarly, aon_error continuation is accepted, though note its arguments come in a different order to those of the Process'son_exception:

$on_error->( $pid, $exitcode, $errno, $exception );

This method should not be used in new code; instead use"open_process" directly.

run_process

@results = await $loop->run_process( %params );( $exitcode, $stdout ) = await $loop->run_process( ... );  # by default

Since version 0.73.

Creates a new child process to run the given code block or command, optionally capturing its STDOUT and STDERR streams. By default the returned future will yield the exit code and content of the STDOUT stream, but thecapture argument can be used to alter what is requested and returned.

command => ARRAY or STRING
code => CODE

The command or code to run in the child process (as per thespawn_child method)

stdin => STRING

Optional. String to pass in to the child process's STDIN stream.

setup => ARRAY

Optional reference to an array to pass to the underlyingspawn method.

capture => ARRAY

Optional reference to an array giving a list of names of values which should be returned by resolving future. Values will be returned in the same order as in the list. Valid choices are:exitcode,stdout,stderr.

cancel_signal => STRING

Optional. Name (or number) of the signal to send to the process if the returned future is cancelled. Defaults toTERM. Use empty string or zero disable sending a signal on cancellation.

fail_on_nonzero => BOOL

Optional. If true, the returned future will fail if the process exits with a nonzero status. The failure will contain a message, theprocess category name, and the capture values that were requested.

Future->fail( $message, process => @captures );

This method is intended mainly as an IO::Async-compatible replacement for the perlreadpipe function (`backticks`), allowing it to replace

my $output = `command here`;

with

my ( $exitcode, $output ) = await $loop->run_process(   command => "command here", );

my ( $exitcode, $stdout ) = await $loop->run_process(   command => "/bin/ps",);my $status = ( $exitcode >> 8 );print "ps exited with status $status\n";

run_child

$pid = $loop->run_child( %params );

A back-compatibility wrapper for"run_process", returning the PID and taking anon_finish continuation instead of returning a Future.

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.

Takes the following named arguments in addition to those taken byrun_process:

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$? value.

This method should not be used in new code; instead use"run_process" directly.

resolver

$resolver = $loop->resolver;

Returns the internally-storedIO::Async::Resolver object, used for name resolution operations by theresolve,connect andlisten methods.

set_resolver

$loop->set_resolver( $resolver );

Sets the internally-storedIO::Async::Resolver object. In most cases this method should not be required, but it may be used to provide an alternative resolver for special use-cases.

resolve

@result = await $loop->resolve( %params );

This method performs a single name resolution operation. It uses an internally-storedIO::Async::Resolver object. For more detail, see theresolve method on theIO::Async::Resolver class.

connect

$handle|$socket = await $loop->connect( %params );

This method performs a non-blocking connection to a given address or set of addresses, returning aIO::Async::Future which represents the operation. On completion, the future will yield the connected socket handle, or the givenIO::Async::Handle object.

There are two modes of operation. Firstly, a list of addresses can be provided which will be tried in turn. Alternatively as a convenience, if a host and service name are provided instead of a list of addresses, these will be resolved using the underlying loop'sresolve method into the list of addresses.

When attempting to connect to any among a list of addresses, there may be failures among the first attempts, before a valid connection is made. For example, the resolver may have returned some IPv6 addresses, but only IPv4 routes are valid on the system. In this case, the firstconnect(2) syscall will fail. This isn't yet a fatal error, if there are more addresses to try, perhaps some IPv4 ones.

For this reason, it is possible that the operation eventually succeeds even though some system calls initially fail. To be aware of individual failures, the optionalon_fail callback can be used. This will be invoked on each individualsocket(2) orconnect(2) failure, which may be useful for debugging or logging.

Because this module simply uses thegetaddrinfo resolver, it will be fully IPv6-aware if the underlying platform's resolver is. This allows programs to be fully IPv6-capable.

In plain address mode, the%params hash takes the following keys:

addrs => ARRAY

Reference to an array of (possibly-multiple) address structures to attempt to connect to. Each should be in the layout described foraddr. Such a layout is returned by thegetaddrinfo named resolver.

addr => HASH or ARRAY

Shortcut for passing a single address to connect to; it may be passed directly with this key, instead of in another array on its own. This should be in a format recognised byIO::Async::OS'sextract_addrinfo method.

This example shows how to use theSocket functions to construct one for TCP port 8001 on address 10.0.0.1:

$loop->connect(   addr => {      family   => "inet",      socktype => "stream",      port     => 8001,      ip       => "10.0.0.1",   },   ...);

This example shows another way to connect to a UNIX socket atecho.sock.

$loop->connect(   addr => {      family   => "unix",      socktype => "stream",      path     => "echo.sock",   },   ...);
peer => IO

Shortcut for constructing an address to connect to the given IO handle, which must be aIO::Socket or subclass, and is presumed to be a local listening socket (perhaps onPF_UNIX orPF_INET). This is convenient for connecting to a local filehandle, for example during a unit test or similar.

local_addrs => ARRAY
local_addr => HASH or ARRAY

Optional. Similar to theaddrs oraddr parameters, these specify a local address or set of addresses tobind(2) the socket to beforeconnect(2)ing it.

When performing the resolution step too, theaddrs oraddr keys are ignored, and instead the following keys are taken:

host => STRING
service => STRING

The hostname and service name to connect to.

local_host => STRING
local_service => STRING

Optional. The hostname and/or service name tobind(2) the socket to locally before connecting to the peer.

family => INT
socktype => INT
protocol => INT
flags => INT

Optional. Other arguments to pass along withhost andservice to thegetaddrinfo call.

socktype => STRING

Optionally may instead be one of the values'stream','dgram' or'raw' to stand forSOCK_STREAM,SOCK_DGRAM orSOCK_RAW. This utility is provided to allow the caller to avoid a separateuse Socket only for importing these constants.

It is necessary to pass thesocktype hint to the resolver when resolving the host/service names into an address, as some OS'sgetaddrinfo functions require this hint. A warning is emitted if neithersocktype norprotocol hint is defined when performing agetaddrinfo lookup. To avoid this warning while still specifying no particularsocktype hint (perhaps to invoke some OS-specific behaviour), pass0 as thesocktype value.

In either case, it also accepts the following arguments:

handle => IO::Async::Handle

Optional. If given aIO::Async::Handle object or a subclass (such asIO::Async::Stream orIO::Async::Socket its handle will be set to the newly-connected socket on success, and that handle used as the result of the future instead.

on_fail => CODE

Optional. After an individualsocket(2) orconnect(2) syscall has failed, this callback is invoked to inform of the error. It is passed the name of the syscall that failed, the arguments that were passed to it, and the error it generated. I.e.

$on_fail->( "socket", $family, $socktype, $protocol, $! );$on_fail->( "bind", $sock, $address, $! );$on_fail->( "connect", $sock, $address, $! );

Because of the "try all" nature when given a list of multiple addresses, this callback may be invoked multiple times, even before an eventual success.

This method accepts anextensions parameter; see theEXTENSIONS section below.

connect (void)

$loop->connect( %params );

When not returning a future, additional parameters can be given containing the continuations to invoke on success or failure.

on_connected => CODE

A continuation that is invoked on a successfulconnect(2) call to a valid socket. It will be passed the connected socket handle, as anIO::Socket object.

$on_connected->( $handle );
on_stream => CODE

An alternative toon_connected, a continuation that is passed an instance ofIO::Async::Stream when the socket is connected. This is provided as a convenience for the common case that a Stream object is required as the transport for a Protocol object.

$on_stream->( $stream )
on_socket => CODE

Similar toon_stream, but constructs an instance ofIO::Async::Socket. This is most useful forSOCK_DGRAM orSOCK_RAW sockets.

$on_socket->( $socket );
on_connect_error => CODE

A continuation that is invoked after all of the addresses have been tried, and none of them succeeded. It will be passed the most significant error that occurred, and the name of the operation it occurred in. Errors from theconnect(2) syscall are considered most significant, thenbind(2), then finallysocket(2).

$on_connect_error->( $syscall, $! );
on_resolve_error => CODE

A continuation that is invoked when the name resolution attempt fails. This is invoked in the same way as theon_error continuation for theresolve method.

listen

$listener = await $loop->listen( %params );

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 ofIO::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%params hash takes the following keys:

service => STRING

The service name to listen on.

host => STRING

The hostname to listen on. Optional. Will listen on all addresses if not supplied.

family => INT
socktype => INT
protocol => INT
flags => INT

Optional. Other arguments to pass along withhost andservice to thegetaddrinfo call.

socktype => STRING

Optionally may instead be one of the values'stream','dgram' or'raw' to stand forSOCK_STREAM,SOCK_DGRAM orSOCK_RAW. This utility is provided to allow the caller to avoid a separateuse Socket only for importing these constants.

It is necessary to pass thesocktype hint to the resolver when resolving the host/service names into an address, as some OS'sgetaddrinfo functions require this hint. A warning is emitted if neithersocktype norprotocol hint is defined when performing agetaddrinfo lookup. To avoid this warning while still specifying no particularsocktype hint (perhaps to invoke some OS-specific behaviour), pass0 as thesocktype value.

In plain address mode, the%params hash takes the following keys:

addrs => ARRAY

Reference to an array of (possibly-multiple) address structures to attempt to listen on. Each should be in the layout described foraddr. Such a layout is returned by thegetaddrinfo named resolver.

addr => ARRAY

Shortcut for passing a single address to listen on; it may be passed directly with this key, instead of in another array of its own. This should be in a format recognised byIO::Async::OS'sextract_addrinfo method. See also theEXAMPLES section.

In direct socket handle mode, the following keys are taken:

handle => IO

The listening socket handle.

In either case, the following keys are also taken:

on_fail => CODE

Optional. A callback that is invoked if a syscall fails while attempting to create a listening sockets. It is passed the name of the syscall that failed, the arguments that were passed to it, and the error generated. I.e.

$on_fail->( "socket", $family, $socktype, $protocol, $! );$on_fail->( "sockopt", $sock, $optname, $optval, $! );$on_fail->( "bind", $sock, $address, $! );$on_fail->( "listen", $sock, $queuesize, $! );
queuesize => INT

Optional. The queue size to pass to thelisten(2) calls. If not supplied, then 3 will be given instead.

reuseaddr => BOOL

Optional. If true or not supplied then theSO_REUSEADDR socket option will be set. To prevent this, pass a false value such as 0.

v6only => BOOL

Optional. If defined, sets or clears theIPV6_V6ONLY socket option onPF_INET6 sockets. This option disables the ability ofPF_INET6 socket to accept connections fromAF_INET addresses. Not all operating systems allow this option to be disabled.

An alternative which gives more control over the listener, is to create theIO::Async::Listener object directly and add it explicitly to the Loop.

This method accepts anextensions parameter; see theEXTENSIONS section below.

listen (void)

$loop->listen( %params );

When not returning a future, additional parameters can be given containing the continuations to invoke on success or failure.

on_notifier => CODE

Optional. A callback that is invoked when the Listener object is ready to receive connections. The callback is passed the Listener object itself.

$on_notifier->( $listener );

If this callback is required, it may instead be better to construct the Listener object directly.

on_listen => CODE

Optional. A callback that is invoked when the listening socket is ready. Typically this would be used in the name resolver case, in order to inspect the socket's sockname address, or otherwise inspect the filehandle.

$on_listen->( $socket )
on_listen_error => CODE

A continuation this is invoked after all of the addresses have been tried, and none of them succeeded. It will be passed the most significant error that occurred, and the name of the operation it occurred in. Errors from thelisten(2) syscall are considered most significant, thenbind(2), thensockopt(2), then finallysocket(2).

on_resolve_error => CODE

A continuation that is invoked when the name resolution attempt fails. This is invoked in the same way as theon_error continuation for theresolve method.

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.

signame2num

$signum = $loop->signame2num( $signame );

Legacy wrappers aroundIO::Async::OS functions.

time

$time = $loop->time;

Returns the current UNIX time in fractional seconds. This is currently equivalent toTime::HiRes::time but provided here as a utility for programs to obtain the time current used byIO::Async for its own timing purposes.

fork

$pid = $loop->fork( %params );

This method creates a new child process to run a given code block, returning its process ID.

code => CODE

A block of code to execute in the child process. It will be called in scalar context inside aneval block. The return value will be used as theexit(2) code from the child if it returns (or 255 if it returnedundef or thows an exception).

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$? value.

This key is optional; if not supplied, the calling code should install a handler using thewatch_process method.

keep_signals => BOOL

Optional boolean. If missing or false, any CODE references in the%SIG hash will be removed and restored back toDEFAULT in the child process. If true, no adjustment of the%SIG hash will be performed.

create_thread

$tid = $loop->create_thread( %params );

This method creates a new (non-detached) thread to run the given code block, returning its thread ID.

code => CODE

A block of code to execute in the thread. It is called in the context given by thecontext argument, and its return value will be available to theon_joined callback. It is called inside aneval block; if it fails the exception will be caught.

context => "scalar" | "list" | "void"

Optional. Gives the calling context thatcode is invoked in. Defaults toscalar if not supplied.

on_joined => CODE

Callback to invoke when the thread function returns or throws an exception. If it returned, this callback will be invoked with its result

$on_joined->( return => @result );

If it threw an exception the callback is invoked with the value of$@

$on_joined->( died => $! );

LOW-LEVEL METHODS

AsIO::Async::Loop is an abstract base class, specific subclasses of it are required to implement certain methods that form the base level of functionality. They are not recommended for applications to use; see instead the various event objects or higher level methods listed above.

These methods should be considered as part of the interface contract required to implement aIO::Async::Loop subclass.

API_VERSION

IO::Async::Loop->API_VERSION;

This method will be called by the magic constructor on the class before it is constructed, to ensure that the specific implementation will support the required API. This method should return the API version that the loop implementation supports. The magic constructor will use that class, provided it declares a version at least as new as the version documented here.

The current API version is0.49.

This method may be implemented usingconstant; e.g

use constant API_VERSION => '0.49';

watch_io

$loop->watch_io( %params );

This method installs callback functions which will be invoked when the given IO handle becomes read- or write-ready.

The%params hash takes the following keys:

handle => IO

The IO handle to watch.

on_read_ready => CODE

Optional. A CODE reference to call when the handle becomes read-ready.

on_write_ready => CODE

Optional. A CODE reference to call when the handle becomes write-ready.

There can only be one filehandle of any given fileno registered at any one time. For any one filehandle, there can only be one read-readiness and/or one write-readiness callback at any one time. Registering a new one will remove an existing one of that type. It is not required that both are provided.

Applications should use aIO::Async::Handle orIO::Async::Stream instead of using this method.

If the filehandle does not yet have theO_NONBLOCK flag set, it will be enabled by this method. This will ensure that any subsequentsysread,syswrite, or similar will not block on the filehandle.

unwatch_io

$loop->unwatch_io( %params );

This method removes a watch on an IO handle which was previously installed bywatch_io.

The%params hash takes the following keys:

handle => IO

The IO handle to remove the watch for.

on_read_ready => BOOL

If true, remove the watch for read-readiness.

on_write_ready => BOOL

If true, remove the watch for write-readiness.

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 thewatch_io method and only one is removed by this method, the other shall remain.

watch_signal

$loop->watch_signal( $signal, $code );

This method adds a new signal handler to watch the given signal.

$signal

The name of the signal to watch to. This should be a bare name likeTERM.

$code

A CODE reference to the handling callback.

There can only be one callback per signal name. Registering a new one will remove an existing one.

Applications should use aIO::Async::Signal object, or callattach_signal instead of using this method.

This andunwatch_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.

unwatch_signal

$loop->unwatch_signal( $signal );

This method removes the signal callback for the given signal.

$signal

The name of the signal to watch to. This should be a bare name likeTERM.

watch_time

$id = $loop->watch_time( %args );

This method installs a callback which will be called at the specified time. The time may either be specified as an absolute value (theat key), or as a delay from the time it is installed (theafter key).

The returned$id value can be used to identify the timer in case it needs to be cancelled by theunwatch_time method. Note that this value may be an object reference, so if it is stored, it should be released after it has been fired or cancelled, so the object itself can be freed.

The%params hash takes the following keys:

at => NUM

The absolute system timestamp to run the event.

after => NUM

The delay after now at which to run the event, ifat is not supplied. A zero or negative delayed timer should be executed as soon as possible; the next time theloop_once method is invoked.

now => NUM

The time to consider as now if calculating an absolute time based onafter; defaults totime() if not specified.

code => CODE

CODE reference to the continuation to run at the allotted time.

Either one ofat orafter is required.

For more powerful timer functionality as aIO::Async::Notifier (so it can be used as a child within another Notifier), see instead theIO::Async::Timer object and its subclasses.

These*_time methods are optional; a subclass may implement neither or both of them. If it implements neither, then the base class will manage a queue of timer events. This queue should be handled by theloop_once method implemented by the subclass, using the_adjust_timeout and_manage_queues methods.

This is the newer version of the API, replacingenqueue_timer. It is unspecified how this method pair interacts with the olderenqueue/requeue/cancel_timer triplet.

unwatch_time

$loop->unwatch_time( $id )

Removes a timer callback previously created bywatch_time.

This is the newer version of the API, replacingcancel_timer. It is unspecified how this method pair interacts with the olderenqueue/requeue/cancel_timer triplet.

enqueue_timer

$id = $loop->enqueue_timer( %params );

An older version ofwatch_time. This method should not be used in new code but is retained for legacy purposes. For simple watch/unwatch behaviour use instead the newwatch_time method; though note it has differently-named arguments. For requeueable timers, consider using anIO::Async::Timer::Countdown orIO::Async::Timer::Absolute instead.

cancel_timer

$loop->cancel_timer( $id );

An older version ofunwatch_time. This method should not be used in new code but is retained for legacy purposes.

requeue_timer

$newid = $loop->requeue_timer( $id, %params );

Reschedule an existing timer, moving it to a new time. The old timer is removed and will not be invoked.

The%params hash takes the same keys asenqueue_timer, except for thecode argument.

The requeue operation may be implemented as a cancel + enqueue, which may mean the ID changes. Be sure to store the returned$newid value if it is required.

This method should not be used in new code but is retained for legacy purposes. For requeueable, consider using anIO::Async::Timer::Countdown orIO::Async::Timer::Absolute instead.

watch_idle

$id = $loop->watch_idle( %params );

This method installs a callback which will be called at some point in the near future.

The%params hash takes the following keys:

when => STRING

Specifies the time at which the callback will be invoked. See below.

code => CODE

CODE reference to the continuation to run at the allotted time.

Thewhen parameter defines the time at which the callback will later be invoked. Must be one of the following values:

later

Callback is invoked after the current round of IO events have been processed by the loop's underlyingloop_once method.

If a new idle watch is installed from within alater callback, the installed one will not be invoked during this round. It will be deferred for the next timeloop_once is called, after any IO events have been handled.

If there are pending idle handlers, then theloop_once method will use a zero timeout; it will return immediately, having processed any IO events and idle handlers.

The returned$id value can be used to identify the idle handler in case it needs to be removed, by calling theunwatch_idle method. Note this value may be a reference, so if it is stored it should be released after the callback has been invoked or cancled, so the referrant itself can be freed.

This andunwatch_idle are optional; a subclass may implement neither, or both. If it implements neither then idle handling will be performed by the base class, using the_adjust_timeout and_manage_queues methods.

unwatch_idle

$loop->unwatch_idle( $id );

Cancels a previously-installed idle handler.

watch_process

$loop->watch_process( $pid, $code );

This method adds a new handler for the termination of the given child process PID, or all child processes.

$pid

The PID to watch. Will report on all child processes if this is 0.

$code

A CODE reference to the exit handler. It will be invoked as

$code->( $pid, $? )

The second argument is passed the plain perl$? value.

After invocation, the handler for a PID-specific watch is automatically removed. The all-child watch will remain until it is removed byunwatch_process.

This andunwatch_process are optional; a subclass may implement neither, or both. If it implements neither then child watching will be performed by usingwatch_signal to install aSIGCHLD handler, which will usewaitpid to look for exited child processes.

If both a PID-specific and an all-process watch are installed, there is no ordering guarantee as to which will be called first.

NOTE that not all loop classes may be able to support the all-child watch. The basic Select and Poll-based classes provided by this distribution do, and those built on top of similar OS-specific mechanisms such as Linux's Epoll probably will, but typically those built on top of other event systems such asglib orlibuv may not be able, as the underlying event system may not provide the necessary hooks to support it.

unwatch_process

$loop->unwatch_process( $pid );

This method removes a watch on an existing child process PID.

METHODS FOR SUBCLASSES

The following methods are provided to access internal features which are required by specific subclasses to implement the loop functionality. The use cases of each will be documented in the above section.

_adjust_timeout

$loop->_adjust_timeout( \$timeout );

Shortens the timeout value passed in the scalar reference if it is longer in seconds than the time until the next queued event on the timer queue. If there are pending idle handlers, the timeout is reduced to zero.

_manage_queues

$loop->_manage_queues;

Checks the timer queue for callbacks that should have been invoked by now, and runs them all, removing them from the queue. It also invokes all of the pending idle handlers. Any new idle handlers installed by these are not invoked yet; they will wait for the next time this method is called.

EXTENSIONS

An Extension is a Perl module that provides extra methods in theIO::Async::Loop or other packages. They are intended to provide extra functionality that easily integrates with the rest of the code.

Certain base methods take anextensions parameter; an ARRAY reference containing a list of extension names. If such a list is passed to a method, it will immediately call a method whose name is that of the base method, prefixed by the first extension name in the list, separated by_. If theextensions list contains more extension names, it will be passed the remaining ones in anotherextensions parameter.

For example,

$loop->connect(   extensions => [qw( FOO BAR )],   %args);

will become

$loop->FOO_connect(   extensions => [qw( BAR )],   %args);

This is provided so that extension modules, such asIO::Async::SSL can easily be invoked indirectly, by passing extra arguments toconnect methods or similar, without needing every module to be aware of theSSL extension. This functionality is generic and not limited toSSL; other extensions may also use it.

The following methods take anextensions parameter:

$loop->connect$loop->listen

If an extensionlisten method is invoked, it will be passed alistener parameter even if one was not provided to the original$loop->listen call, and it will not receive any of theon_* event callbacks. It should use theacceptor parameter on thelistener object.

STALL WATCHDOG

A well-behavedIO::Async program should spend almost all of its time blocked on input using the underlyingIO::Async::Loop instance. The stall watchdog is an optional debugging feature to help detect CPU spinlocks and other bugs, where control is not returned to the loop every so often.

If the watchdog is enabled and an event handler consumes more than a given amount of real time before returning to the event loop, it will be interrupted by printing a stack trace and terminating the program. The watchdog is only in effect while the loop itself is not blocking; it won't fail simply because the loop instance is waiting for input or timers.

It is implemented usingSIGALRM, so if enabled, this signal will no longer be available to user code. (Though in any case, most uses ofalarm() andSIGALRM are better served by one of theIO::Async::Timer subclasses).

The following environment variables control its behaviour.

IO_ASYNC_WATCHDOG => BOOL

Enables the stall watchdog if set to a non-zero value.

IO_ASYNC_WATCHDOG_INTERVAL => INT

Watchdog interval, in seconds, to pass to thealarm(2) call. Defaults to 10 seconds.

IO_ASYNC_WATCHDOG_SIGABRT => BOOL

If enabled, the watchdog signal handler will raise aSIGABRT, which usually has the effect of breaking out of a running program in debuggers such asgdb. If not set then the process is terminated by throwing an exception withdie.

AUTHOR

Paul Evans <leonerd@leonerd.org.uk>

Module Install Instructions

To install IO::Async, copy and paste the appropriate command in to your terminal.

cpanm

cpanm IO::Async

CPAN shell

perl -MCPAN -e shellinstall IO::Async

For more information on module installation, please visitthe detailed CPAN module installation guide.

Keyboard Shortcuts

Global
sFocus search bar
?Bring up this help dialog
GitHub
gpGo to pull requests
gigo to github issues (only if github is preferred repository)
POD
gaGo to author
gcGo to changes
giGo to issues
gdGo to dist
grGo to repository/SCM
gsGo to source
gbGo to file browse
Search terms
module: (e.g.module:Plugin)
distribution: (e.g.distribution:Dancer auth)
author: (e.g.author:SONGMU Redis)
version: (e.g.version:1.00)

[8]ページ先頭

©2009-2025 Movatter.jp