AnyEvent
view release on metacpan or search on metacpan
When this is the case, you can call this method, which will update
the event loop's idea of "current time".
A typical example would be a script in a web server (e.g.
"mod_perl") - when mod_perl executes the script, then the event loop
will have the wrong idea about the "current time" (being potentially
far in the past, when the script ran the last time). In that case
you should arrange a call to "AnyEvent->now_update" each time the
web server process wakes up again (e.g. at the start of your script,
or in a handler).
Note that updating the time *might* cause some events to be handled.
SIGNAL WATCHERS
$w = AnyEvent->signal (signal => <uppercase_signal_name>, cb => <callback>);
You can watch for signals using a signal watcher, "signal" is the signal
*name* in uppercase and without any "SIG" prefix, "cb" is the Perl
callback to be invoked whenever a signal occurs.
Although the callback might get passed parameters, their value and
presence is undefined and you cannot rely on them. Portable AnyEvent
callbacks cannot use arguments passed to signal watcher callbacks.
Multiple signal occurrences can be clumped together into one callback
invocation, and callback invocation will be synchronous. Synchronous
means that it might take a while until the signal gets handled by the
process, but it is guaranteed not to interrupt any other callbacks.
The main advantage of using these watchers is that you can share a
signal between multiple watchers, and AnyEvent will ensure that signals
will not interrupt your program at bad times.
This watcher might use %SIG (depending on the event loop used), so
programs overwriting those signals directly will likely not work
correctly.
Example: exit on SIGINT
my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
Restart Behaviour
While restart behaviour is up to the event loop implementation, most
will not restart syscalls (that includes Async::Interrupt and AnyEvent's
pure perl implementation).
Safe/Unsafe Signals
Perl signals can be either "safe" (synchronous to opcode handling) or
"unsafe" (asynchronous) - the former might delay signal delivery
indefinitely, the latter might corrupt your memory.
AnyEvent signal handlers are, in addition, synchronous to the event
loop, i.e. they will not interrupt your running perl program but will
only be called as part of the normal event handling (just like timer,
I/O etc. callbacks, too).
Signal Races, Delays and Workarounds
Many event loops (e.g. Glib, Tk, Qt, IO::Async) do not support attaching
callbacks to signals in a generic way, which is a pity, as you cannot do
race-free signal handling in perl, requiring C libraries for this.
AnyEvent will try to do its best, which means in some cases, signals
will be delayed. The maximum time a signal might be delayed is 10
seconds by default, but can be overriden via
$ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY} or $AnyEvent::MAX_SIGNAL_LATENCY
- see the "ENVIRONMENT VARIABLES" section for details.
All these problems can be avoided by installing the optional
Async::Interrupt module, which works with most event loops. It will not
work with inherently broken event loops such as Event or Event::Lib (and
not with POE currently). For those, you just have to suffer the delays.
CHILD PROCESS WATCHERS
$w = AnyEvent->child (pid => <process id>, cb => <callback>);
You can also watch for a child process exit and catch its exit status.
The child process is specified by the "pid" argument (on some backends,
using 0 watches for any child process exit, on others this will croak).
The watcher will be triggered only when the child process has finished
and an exit status is available, not on any trace events
(stopped/continued).
The callback will be called with the pid and exit status (as returned by
waitpid), so unlike other watcher types, you *can* rely on child watcher
callback arguments.
This watcher type works by installing a signal handler for "SIGCHLD",
and since it cannot be shared, nothing else should use SIGCHLD or reap
random child processes (waiting for specific child processes, e.g.
inside "system", is just fine).
There is a slight catch to child watchers, however: you usually start
them *after* the child process was created, and this means the process
could have exited already (and no SIGCHLD will be sent anymore).
Not all event models handle this correctly (neither POE nor IO::Async
do, see their AnyEvent::Impl manpages for details), but even for event
models that *do* handle this correctly, they usually need to be loaded
before the process exits (i.e. before you fork in the first place).
AnyEvent's pure perl event loop handles all cases correctly regardless
of when you start the watcher.
This means you cannot create a child watcher as the very first thing in
an AnyEvent program, you *have* to create at least one watcher before
you "fork" the child (alternatively, you can call "AnyEvent::detect").
As most event loops do not support waiting for child events, they will
be emulated by AnyEvent in most cases, in which case the latency and
race problems mentioned in the description of signal watchers apply.
Example: fork a process and wait for it
my $done = AnyEvent->condvar;
# this forks and immediately calls exit in the child. this
# normally has all sorts of bad consequences for your parent,
# so take this as an example only. always fork and exec,
# or call POSIX::_exit, in real code.
my $pid = fork or exit 5;
my $w = AnyEvent->child (
If an error condition has been set by calling "->croak", then this
function will call "croak".
In list context, all parameters passed to "send" will be returned,
in scalar context only the first one will be returned.
Note that doing a blocking wait in a callback is not supported by
any event loop, that is, recursive invocation of a blocking "->recv"
is not allowed and the "recv" call will "croak" if such a condition
is detected. This requirement can be dropped by relying on
Coro::AnyEvent , which allows you to do a blocking "->recv" from any
thread that doesn't run the event loop itself. Coro::AnyEvent is
loaded automatically when Coro is used with AnyEvent, so code does
not need to do anything special to take advantage of that: any code
that would normally block your program because it calls "recv", be
executed in an "async" thread instead without blocking other
threads.
Not all event models support a blocking wait - some die in that case
(programs might want to do that to stay interactive), so *if you are
using this from a module, never require a blocking wait*. Instead,
let the caller decide whether the call will block or not (for
example, by coupling condition variables with some kind of request
results and supporting callbacks so the caller knows that getting
the result will not block, while still supporting blocking waits if
the caller so desires).
You can ensure that "->recv" never blocks by setting a callback and
only calling "->recv" from within that callback (or at a later
time). This will work even when the event loop does not support
blocking waits otherwise.
$bool = $cv->ready
Returns true when the condition is "true", i.e. whether "send" or
"croak" have been called.
$cb = $cv->cb ($cb->($cv))
This is a mutator function that returns the callback set (or "undef"
if not) and optionally replaces it before doing so.
The callback will be called when the condition becomes "true", i.e.
when "send" or "croak" are called, with the only argument being the
condition variable itself. If the condition is already true, the
callback is called immediately when it is set. Calling "recv" inside
the callback or at any later time is guaranteed not to block.
Additionally, when the callback is invoked, it is also removed from
the condvar (reset to "undef"), so the condvar does not keep a
reference to the callback after invocation.
SUPPORTED EVENT LOOPS/BACKENDS
The following backend classes are part of the AnyEvent distribution
(every class has its own manpage):
Backends that are autoprobed when no other event loop can be found.
EV is the preferred backend when no other event loop seems to be in
use. If EV is not installed, then AnyEvent will fall back to its own
pure-perl implementation, which is available everywhere as it comes
with AnyEvent itself.
AnyEvent::Impl::EV based on EV (interface to libev, best choice).
AnyEvent::Impl::Perl pure-perl AnyEvent::Loop, fast and portable.
Backends that are transparently being picked up when they are used.
These will be used if they are already loaded when the first watcher
is created, in which case it is assumed that the application is
using them. This means that AnyEvent will automatically pick the
right backend when the main program loads an event module before
anything starts to create watchers. Nothing special needs to be done
by the main program.
AnyEvent::Impl::Event based on Event, very stable, few glitches.
AnyEvent::Impl::Glib based on Glib, slow but very stable.
AnyEvent::Impl::Tk based on Tk, very broken.
AnyEvent::Impl::UV based on UV, innovated square wheels.
AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse.
AnyEvent::Impl::POE based on POE, very slow, some limitations.
AnyEvent::Impl::Irssi used when running within irssi.
AnyEvent::Impl::IOAsync based on IO::Async.
AnyEvent::Impl::Cocoa based on Cocoa::EventLoop.
AnyEvent::Impl::FLTK based on FLTK (fltk 2 binding).
Backends with special needs.
Qt requires the Qt::Application to be instantiated first, but will
otherwise be picked up automatically. As long as the main program
instantiates the application before any AnyEvent watchers are
created, everything should just work.
AnyEvent::Impl::Qt based on Qt.
Event loops that are indirectly supported via other backends.
Some event loops can be supported via other modules:
There is no direct support for WxWidgets (Wx) or Prima.
WxWidgets has no support for watching file handles. However, you can
use WxWidgets through the POE adaptor, as POE has a Wx backend that
simply polls 20 times per second, which was considered to be too
horrible to even consider for AnyEvent.
Prima is not supported as nobody seems to be using it, but it has a
POE backend, so it can be supported through POE.
AnyEvent knows about both Prima and Wx, however, and will try to
load POE when detecting them, in the hope that POE will pick them
up, in which case everything will be automatic.
Known event loops outside the AnyEvent distribution
The following event loops or programs support AnyEvent by providing
their own AnyEvent backend. They will be picked up automatically.
urxvt::anyevent available to rxvt-unicode extensions
GLOBAL VARIABLES AND FUNCTIONS
These are not normally required to use AnyEvent, but can be useful to
write AnyEvent extension modules.
$AnyEvent::MODEL
Contains "undef" until the first watcher is being created, before
the backend has been autodetected.
connect.
This is where "AnyEvent::postpone" should be used. Instead of
calling the callback directly on error:
$cb->(undef), return # signal error to callback, BAD!
if $some_error_condition;
It should use "postpone":
AnyEvent::postpone { $cb->(undef) }, return # signal error to callback, later
if $some_error_condition;
AnyEvent::log $level, $msg[, @args]
Log the given $msg at the given $level.
If AnyEvent::Log is not loaded then this function makes a simple
test to see whether the message will be logged. If the test succeeds
it will load AnyEvent::Log and call "AnyEvent::Log::log" -
consequently, look at the AnyEvent::Log documentation for details.
If the test fails it will simply return. Right now this happens when
a numerical loglevel is used and it is larger than the level
specified via $ENV{PERL_ANYEVENT_VERBOSE}.
If you want to sprinkle loads of logging calls around your code,
consider creating a logger callback with the "AnyEvent::Log::logger"
function, which can reduce typing, codesize and can reduce the
logging overhead enourmously.
AnyEvent::fh_block $filehandle
AnyEvent::fh_unblock $filehandle
Sets blocking or non-blocking behaviour for the given filehandle.
WHAT TO DO IN A MODULE
As a module author, you should "use AnyEvent" and call AnyEvent methods
freely, but you should not load a specific event module or rely on it.
Be careful when you create watchers in the module body - AnyEvent will
decide which event module to use as soon as the first method is called,
so by calling AnyEvent in your module body you force the user of your
module to load the event module first.
Never call "->recv" on a condition variable unless you *know* that the
"->send" method has been called on it already. This is because it will
stall the whole program, and the whole point of using events is to stay
interactive.
It is fine, however, to call "->recv" when the user of your module
requests it (i.e. if you create a http request object ad have a method
called "results" that returns the results, it may call "->recv" freely,
as the user of your module knows what she is doing. Always).
WHAT TO DO IN THE MAIN PROGRAM
There will always be a single main program - the only place that should
dictate which event model to use.
If the program is not event-based, it need not do anything special, even
when it depends on a module that uses an AnyEvent. If the program itself
uses AnyEvent, but does not care which event loop is used, all it needs
to do is "use AnyEvent". In either case, AnyEvent will choose the best
available loop implementation.
If the main program relies on a specific event model - for example, in
Gtk2 programs you have to rely on the Glib module - you should load the
event module before loading AnyEvent or any module that uses it:
generally speaking, you should load it as early as possible. The reason
is that modules might create watchers when they are loaded, and AnyEvent
will decide on the event model to use as soon as it creates watchers,
and it might choose the wrong one unless you load the correct one
yourself.
You can chose to use a pure-perl implementation by loading the
"AnyEvent::Loop" module, which gives you similar behaviour everywhere,
but letting AnyEvent chose the model is generally better.
MAINLOOP EMULATION
Sometimes (often for short test scripts, or even standalone programs who
only want to use AnyEvent), you do not want to run a specific event
loop.
In that case, you can use a condition variable like this:
AnyEvent->condvar->recv;
This has the effect of entering the event loop and looping forever.
Note that usually your program has some exit condition, in which case it
is better to use the "traditional" approach of storing a condition
variable somewhere, waiting for it, and sending it when the program
should exit cleanly.
OTHER MODULES
The following is a non-exhaustive list of additional modules that use
AnyEvent as a client and can therefore be mixed easily with other
AnyEvent modules and other event loops in the same program. Some of the
modules come as part of AnyEvent, the others are available via CPAN (see
<http://search.cpan.org/search?m=module&q=anyevent%3A%3A*> for a longer
non-exhaustive list), and the list is heavily biased towards modules of
the AnyEvent author himself :)
AnyEvent::Util (part of the AnyEvent distribution)
Contains various utility functions that replace often-used blocking
functions such as "inet_aton" with event/callback-based versions.
AnyEvent::Socket (part of the AnyEvent distribution)
Provides various utility functions for (internet protocol) sockets,
addresses and name resolution. Also functions to create non-blocking
tcp connections or tcp servers, with IPv6 and SRV record support and
more.
AnyEvent::Handle (part of the AnyEvent distribution)
Provide read and write buffers, manages watchers for reads and
writes, supports raw and formatted I/O, I/O queued and fully
transparent and non-blocking SSL/TLS (via AnyEvent::TLS).
AnyEvent::DNS (part of the AnyEvent distribution)
Provides rich asynchronous DNS resolver capabilities.
AnyEvent::HTTP, AnyEvent::IRC, AnyEvent::XMPP, AnyEvent::GPSD,
AnyEvent::IGS, AnyEvent::FCP
AnyEvent currently installs handlers for these signals:
SIGCHLD
A handler for "SIGCHLD" is installed by AnyEvent's child watcher
emulation for event loops that do not support them natively. Also,
some event loops install a similar handler.
Additionally, when AnyEvent is loaded and SIGCHLD is set to IGNORE,
then AnyEvent will reset it to default, to avoid losing child exit
statuses.
SIGPIPE
A no-op handler is installed for "SIGPIPE" when $SIG{PIPE} is
"undef" when AnyEvent gets loaded.
The rationale for this is that AnyEvent users usually do not really
depend on SIGPIPE delivery (which is purely an optimisation for
shell use, or badly-written programs), but "SIGPIPE" can cause
spurious and rare program exits as a lot of people do not expect
"SIGPIPE" when writing to some random socket.
The rationale for installing a no-op handler as opposed to ignoring
it is that this way, the handler will be restored to defaults on
exec.
Feel free to install your own handler, or reset it to defaults.
RECOMMENDED/OPTIONAL MODULES
One of AnyEvent's main goals is to be 100% Pure-Perl(tm): only perl (and
its built-in modules) are required to use it.
That does not mean that AnyEvent won't take advantage of some additional
modules if they are installed.
This section explains which additional modules will be used, and how
they affect AnyEvent's operation.
Async::Interrupt
This slightly arcane module is used to implement fast signal
handling: To my knowledge, there is no way to do completely
race-free and quick signal handling in pure perl. To ensure that
signals still get delivered, AnyEvent will start an interval timer
to wake up perl (and catch the signals) with some delay (default is
10 seconds, look for $AnyEvent::MAX_SIGNAL_LATENCY).
If this module is available, then it will be used to implement
signal catching, which means that signals will not be delayed, and
the event loop will not be interrupted regularly, which is more
efficient (and good for battery life on laptops).
This affects not just the pure-perl event loop, but also other event
loops that have no signal handling on their own (e.g. Glib, Tk, Qt).
Some event loops (POE, Event, Event::Lib) offer signal watchers
natively, and either employ their own workarounds (POE) or use
AnyEvent's workaround (using $AnyEvent::MAX_SIGNAL_LATENCY).
Installing Async::Interrupt does nothing for those backends.
EV This module isn't really "optional", as it is simply one of the
backend event loops that AnyEvent can use. However, it is simply the
best event loop available in terms of features, speed and stability:
It supports the AnyEvent API optimally, implements all the watcher
types in XS, does automatic timer adjustments even when no monotonic
clock is available, can take avdantage of advanced kernel interfaces
such as "epoll" and "kqueue", and is the fastest backend *by far*.
You can even embed Glib/Gtk2 in it (or vice versa, see EV::Glib and
Glib::EV).
If you only use backends that rely on another event loop (e.g.
"Tk"), then this module will do nothing for you.
Guard
The guard module, when used, will be used to implement
"AnyEvent::Util::guard". This speeds up guards considerably (and
uses a lot less memory), but otherwise doesn't affect guard
operation much. It is purely used for performance.
JSON and JSON::XS
One of these modules is required when you want to read or write JSON
data via AnyEvent::Handle. JSON is also written in pure-perl, but
can take advantage of the ultra-high-speed JSON::XS module when it
is installed.
Net::SSLeay
Implementing TLS/SSL in Perl is certainly interesting, but not very
worthwhile: If this module is installed, then AnyEvent::Handle (with
the help of AnyEvent::TLS), gains the ability to do TLS/SSL.
Time::HiRes
This module is part of perl since release 5.008. It will be used
when the chosen event library does not come with a timing source of
its own. The pure-perl event loop (AnyEvent::Loop) will additionally
load it to try to use a monotonic clock for timing stability.
AnyEvent::AIO (and IO::AIO)
The default implementation of AnyEvent::IO is to do I/O
synchronously, stopping programs while they access the disk, which
is fine for a lot of programs.
Installing AnyEvent::AIO (and its IO::AIO dependency) makes it
switch to a true asynchronous implementation, so event processing
can continue even while waiting for disk I/O.
FORK
Most event libraries are not fork-safe. The ones who are usually are
because they rely on inefficient but fork-safe "select" or "poll" calls
- higher performance APIs such as BSD's kqueue or the dreaded Linux
epoll are usually badly thought-out hacks that are incompatible with
fork in one way or another. Only EV is fully fork-aware and ensures that
you continue event-processing in both parent and child (or both, if you
know what you are doing).
This means that, in general, you cannot fork and do event processing in
the child if the event library was initialised before the fork (which
usually happens when the first AnyEvent watcher is created, or the
library is loaded).
If you have to fork, you must either do so *before* creating your first
watcher OR you must not use AnyEvent at all in the child OR you must do
something completely out of the scope of AnyEvent (see below).
( run in 1.970 second using v1.01-cache-2.11-cpan-39bf76dae61 )