Mirror of :pserver:anonymous@cvs.schmorp.de/schmorpforge libev http://software.schmorp.de/pkg/libev.html
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5682 lines
217 KiB

=encoding utf-8
=head1 NAME
libev - a high performance full-featured event loop written in C
=head1 SYNOPSIS
14 years ago
#include <ev.h>
=head2 EXAMPLE PROGRAM
14 years ago
// a single header file is required
#include <ev.h>
#include <stdio.h> // for puts
14 years ago
// every watcher type has its own typedef'd struct
// with the name ev_TYPE
14 years ago
ev_io stdin_watcher;
ev_timer timeout_watcher;
// all watcher callbacks have a similar signature
// this callback is called when data is readable on stdin
static void
stdin_cb (EV_P_ ev_io *w, int revents)
14 years ago
{
puts ("stdin ready");
// for one-shot events, one must manually stop the watcher
// with its corresponding stop function.
ev_io_stop (EV_A_ w);
// this causes all nested ev_run's to stop iterating
ev_break (EV_A_ EVBREAK_ALL);
14 years ago
}
// another callback, this time for a time-out
static void
timeout_cb (EV_P_ ev_timer *w, int revents)
14 years ago
{
puts ("timeout");
// this causes the innermost ev_run to stop iterating
ev_break (EV_A_ EVBREAK_ONE);
14 years ago
}
int
main (void)
{
// use the default event loop unless you have special needs
struct ev_loop *loop = EV_DEFAULT;
14 years ago
// initialise an io watcher, then start it
// this one will watch for stdin to become readable
ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
ev_io_start (loop, &stdin_watcher);
// initialise a timer watcher, then start it
// simple non-repeating 5.5 second timeout
ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
ev_timer_start (loop, &timeout_watcher);
// now wait for events to arrive
ev_run (loop, 0);
14 years ago
// break was called, so exit
14 years ago
return 0;
}
=head1 ABOUT THIS DOCUMENT
This document documents the libev software package.
The newest version of this document is also available as an html-formatted
web page you might find easier to navigate when reading it for the first
time: L<http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod>.
While this document tries to be as complete as possible in documenting
libev, its usage and the rationale behind its design, it is not a tutorial
on event-based programming, nor will it introduce event-based programming
with libev.
12 years ago
Familiarity with event based programming techniques in general is assumed
throughout this document.
=head1 WHAT TO READ WHEN IN A HURRY
This manual tries to be very detailed, but unfortunately, this also makes
it very long. If you just want to know the basics of libev, I suggest
reading L</ANATOMY OF A WATCHER>, then the L</EXAMPLE PROGRAM> above and
look up the missing functions in L</GLOBAL FUNCTIONS> and the C<ev_io> and
C<ev_timer> sections in L</WATCHER TYPES>.
=head1 ABOUT LIBEV
Libev is an event loop: you register interest in certain events (such as a
file descriptor being readable or a timeout occurring), and it will manage
these event sources and provide your program with events.
To do this, it must take more or less complete control over your process
(or thread) by executing the I<event loop> handler, and will then
communicate events via a callback mechanism.
You register interest in certain events by registering so-called I<event
watchers>, which are relatively small C structures you initialise with the
details of the event, and then hand it over to libev by I<starting> the
watcher.
=head2 FEATURES
Libev supports C<select>, C<poll>, the Linux-specific aio and C<epoll>
interfaces, the BSD-specific C<kqueue> and the Solaris-specific event port
mechanisms for file descriptor events (C<ev_io>), the Linux C<inotify>
interface (for C<ev_stat>), Linux eventfd/signalfd (for faster and cleaner
inter-thread wakeup (C<ev_async>)/signal handling (C<ev_signal>)) relative
timers (C<ev_timer>), absolute timers with customised rescheduling
(C<ev_periodic>), synchronous signals (C<ev_signal>), process status
change events (C<ev_child>), and event watchers dealing with the event
loop mechanism itself (C<ev_idle>, C<ev_embed>, C<ev_prepare> and
C<ev_check> watchers) as well as file watchers (C<ev_stat>) and even
limited support for fork events (C<ev_fork>).
It also is quite fast (see this
L<benchmark|http://libev.schmorp.de/bench.html> comparing it to libevent
for example).
=head2 CONVENTIONS
Libev is very configurable. In this manual the default (and most common)
configuration will be described, which supports multiple event loops. For
more info about various configuration options please have a look at
B<EMBED> section in this manual. If libev was configured without support
for multiple event loops, then all functions taking an initial argument of
name C<loop> (which is always of type C<struct ev_loop *>) will not have
this argument.
=head2 TIME REPRESENTATION
Libev represents time as a single floating point number, representing
the (fractional) number of seconds since the (POSIX) epoch (in practice
somewhere near the beginning of 1970, details are complicated, don't
ask). This type is called C<ev_tstamp>, which is what you should use
too. It usually aliases to the C<double> type in C. When you need to do
any calculations on it, you should treat it as some floating point value.
Unlike the name component C<stamp> might indicate, it is also used for
time differences (e.g. delays) throughout libev.
=head1 ERROR HANDLING
Libev knows three classes of errors: operating system errors, usage errors
and internal errors (bugs).
When libev catches an operating system error it cannot handle (for example
a system call indicating a condition libev cannot fix), it calls the callback
set via C<ev_set_syserr_cb>, which is supposed to fix the problem or
abort. The default is to print a diagnostic message and to call C<abort
()>.
When libev detects a usage error such as a negative timer interval, then
it will print a diagnostic message and abort (via the C<assert> mechanism,
so C<NDEBUG> will disable this checking): these are programming errors in
the libev caller and need to be fixed there.
Via the C<EV_FREQUENT> macro you can compile in and/or enable extensive
consistency checking code inside libev that can be used to check for
internal inconsistencies, suually caused by application bugs.
Libev also has a few internal error-checking C<assert>ions. These do not
trigger under normal circumstances, as they indicate either a bug in libev
or worse.
=head1 GLOBAL FUNCTIONS
These functions can be called anytime, even before initialising the
library in any way.
=over 4
=item ev_tstamp ev_time ()
Returns the current time as libev would use it. Please note that the
C<ev_now> function is usually faster and also often returns the timestamp
11 years ago
you actually want to know. Also interesting is the combination of
C<ev_now_update> and C<ev_now>.
=item ev_sleep (ev_tstamp interval)
Sleep for the given interval: The current thread will be blocked
until either it is interrupted or the given time interval has
passed (approximately - it might return a bit earlier even if not
interrupted). Returns immediately if C<< interval <= 0 >>.
Basically this is a sub-second-resolution C<sleep ()>.
The range of the C<interval> is limited - libev only guarantees to work
with sleep times of up to one day (C<< interval <= 86400 >>).
=item int ev_version_major ()
=item int ev_version_minor ()
You can find out the major and minor ABI version numbers of the library
you linked against by calling the functions C<ev_version_major> and
C<ev_version_minor>. If you want, you can compare against the global
symbols C<EV_VERSION_MAJOR> and C<EV_VERSION_MINOR>, which specify the
version of the library your program was compiled against.
These version numbers refer to the ABI version of the library, not the
release version.
Usually, it's a good idea to terminate if the major versions mismatch,
as this indicates an incompatible change. Minor versions are usually
compatible to older versions, so a larger minor version alone is usually
not a problem.
Example: Make sure we haven't accidentally been linked against the wrong
version (note, however, that this will not detect other ABI mismatches,
such as LFS or reentrancy).
14 years ago
assert (("libev version mismatch",
ev_version_major () == EV_VERSION_MAJOR
&& ev_version_minor () >= EV_VERSION_MINOR));
=item unsigned int ev_supported_backends ()
Return the set of all backends (i.e. their corresponding C<EV_BACKEND_*>
value) compiled into this binary of libev (independent of their
availability on the system you are running on). See C<ev_default_loop> for
a description of the set values.
Example: make sure we have the epoll method, because yeah this is cool and
a must have and can we have a torrent of it please!!!11
14 years ago
assert (("sorry, no epoll, no sex",
ev_supported_backends () & EVBACKEND_EPOLL));
=item unsigned int ev_recommended_backends ()
Return the set of all backends compiled into this binary of libev and
also recommended for this platform, meaning it will work for most file
descriptor types. This set is often smaller than the one returned by
C<ev_supported_backends>, as for example kqueue is broken on most BSDs
and will not be auto-detected unless you explicitly request it (assuming
you know what you are doing). This is the set of backends that libev will
probe for if you specify no backends explicitly.
=item unsigned int ev_embeddable_backends ()
Returns the set of backends that are embeddable in other event loops. This
value is platform-specific but can include backends not available on the
current system. To find which embeddable backends might be supported on
the current system, you would need to look at C<ev_embeddable_backends ()
& ev_supported_backends ()>, likewise for recommended ones.
See the description of C<ev_embed> watchers for more info.
=item ev_set_allocator (void *(*cb)(void *ptr, long size) throw ())
Sets the allocation function to use (the prototype is similar - the
semantics are identical to the C<realloc> C89/SuS/POSIX function). It is
used to allocate and free memory (no surprises here). If it returns zero
when memory needs to be allocated (C<size != 0>), the library might abort
or take some potentially destructive action.
Since some systems (at least OpenBSD and Darwin) fail to implement
correct C<realloc> semantics, libev will use a wrapper around the system
C<realloc> and C<free> functions by default.
You could override this function in high-availability programs to, say,
free some memory if it cannot allocate memory, to use a special allocator,
or even to sleep a while and retry until some memory is available.
Example: The following is the C<realloc> function that libev itself uses
which should work with C<realloc> and C<free> functions of all kinds and
is probably a good basis for your own implementation.
static void *
ev_realloc_emul (void *ptr, long size) EV_NOEXCEPT
{
if (size)
return realloc (ptr, size);
free (ptr);
return 0;
}
Example: Replace the libev allocator with one that waits a bit and then
retries.
static void *
14 years ago
persistent_realloc (void *ptr, size_t size)
{
if (!size)
{
free (ptr);
return 0;
}
for (;;)
{
void *newptr = realloc (ptr, size);
if (newptr)
return newptr;
sleep (60);
}
}
...
ev_set_allocator (persistent_realloc);
=item ev_set_syserr_cb (void (*cb)(const char *msg) throw ())
Set the callback function to call on a retryable system call error (such
as failed select, poll, epoll_wait). The message is a printable string
indicating the system call or subsystem causing the problem. If this
callback is set, then libev will expect it to remedy the situation, no
matter what, when it returns. That is, libev will generally retry the
requested operation, or, if the condition doesn't go away, do bad stuff
(such as abort).
Example: This is basically the same thing that libev does internally, too.
static void
fatal_error (const char *msg)
{
perror (msg);
abort ();
}
...
ev_set_syserr_cb (fatal_error);
=item ev_feed_signal (int signum)
This function can be used to "simulate" a signal receive. It is completely
safe to call this function at any time, from any context, including signal
handlers or random threads.
11 years ago
Its main use is to customise signal handling in your process, especially
in the presence of threads. For example, you could block signals
by default in all threads (and specifying C<EVFLAG_NOSIGMASK> when
creating any loops), and in one thread, use C<sigwait> or any other
mechanism to wait for signals, then "deliver" them to libev by calling
C<ev_feed_signal>.
=back
=head1 FUNCTIONS CONTROLLING EVENT LOOPS
An event loop is described by a C<struct ev_loop *> (the C<struct> is
I<not> optional in this case unless libev 3 compatibility is disabled, as
libev 3 had an C<ev_loop> function colliding with the struct name).
The library knows two types of such loops, the I<default> loop, which
supports child process events, and dynamically created event loops which
do not.
=over 4
=item struct ev_loop *ev_default_loop (unsigned int flags)
This returns the "default" event loop object, which is what you should
normally use when you just need "the event loop". Event loop objects and
the C<flags> parameter are described in more detail in the entry for
C<ev_loop_new>.
If the default loop is already initialised then this function simply
returns it (and ignores the flags. If that is troubling you, check
C<ev_backend ()> afterwards). Otherwise it will create it with the given
flags, which should almost always be C<0>, unless the caller is also the
one calling C<ev_run> or otherwise qualifies as "the main program".
If you don't know what event loop to use, use the one returned from this
function (or via the C<EV_DEFAULT> macro).
Note that this function is I<not> thread-safe, so if you want to use it
from multiple threads, you have to employ some kind of mutex (note also
that this case is unlikely, as loops cannot be shared easily between
threads anyway).
The default loop is the only loop that can handle C<ev_child> watchers,
and to do this, it always registers a handler for C<SIGCHLD>. If this is
a problem for your application you can either create a dynamic loop with
C<ev_loop_new> which doesn't do that, or you can simply overwrite the
C<SIGCHLD> signal handler I<after> calling C<ev_default_init>.
Example: This is the most typical usage.
if (!ev_default_loop (0))
fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?");
Example: Restrict libev to the select and poll backends, and do not allow
environment settings to be taken into account:
ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV);
=item struct ev_loop *ev_loop_new (unsigned int flags)
This will create and initialise a new event loop object. If the loop
could not be initialised, returns false.
This function is thread-safe, and one common way to use libev with
threads is indeed to create one loop per thread, and using the default
loop in the "main" or "initial" thread.
The flags argument can be used to specify special behaviour or specific
backends to use, and is usually specified as C<0> (or C<EVFLAG_AUTO>).
The following flags are supported:
=over 4
=item C<EVFLAG_AUTO>
The default flags value. Use this if you have no clue (it's the right
thing, believe me).
=item C<EVFLAG_NOENV>
If this flag bit is or'ed into the flag value (or the program runs setuid
or setgid) then libev will I<not> look at the environment variable
C<LIBEV_FLAGS>. Otherwise (the default), this environment variable will
override the flags completely if it is found in the environment. This is
useful to try out specific backends to test their performance, to work
around bugs, or to make libev threadsafe (accessing environment variables
cannot be done in a threadsafe way, but usually it works if no other
thread modifies them).
=item C<EVFLAG_FORKCHECK>
Instead of calling C<ev_loop_fork> manually after a fork, you can also
make libev check for a fork in each iteration by enabling this flag.
This works by calling C<getpid ()> on every iteration of the loop,
and thus this might slow down your event loop if you do a lot of loop
14 years ago
iterations and little real work, but is usually not noticeable (on my
GNU/Linux system for example, C<getpid> is actually a simple 5-insn
sequence without a system call and thus I<very> fast, but my GNU/Linux
system also has C<pthread_atfork> which is even faster). (Update: glibc
versions 2.25 apparently removed the C<getpid> optimisation again).
The big advantage of this flag is that you can forget about fork (and
forget about forgetting to tell libev about forking, although you still
have to ignore C<SIGPIPE>) when you use this flag.
This flag setting cannot be overridden or specified in the C<LIBEV_FLAGS>
environment variable.
=item C<EVFLAG_NOINOTIFY>
When this flag is specified, then libev will not attempt to use the
I<inotify> API for its C<ev_stat> watchers. Apart from debugging and
testing, this flag can be useful to conserve inotify file descriptors, as
otherwise each loop using C<ev_stat> watchers consumes one inotify handle.
=item C<EVFLAG_SIGNALFD>
When this flag is specified, then libev will attempt to use the
I<signalfd> API for its C<ev_signal> (and C<ev_child>) watchers. This API
delivers signals synchronously, which makes it both faster and might make
it possible to get the queued signal data. It can also simplify signal
handling with threads, as long as you properly block signals in your
threads that are not interested in handling them.
Signalfd will not be used by default as this changes your signal mask, and
there are a lot of shoddy libraries and programs (glib's threadpool for
example) that can't properly initialise their signal masks.
=item C<EVFLAG_NOSIGMASK>
When this flag is specified, then libev will avoid to modify the signal
11 years ago
mask. Specifically, this means you have to make sure signals are unblocked
when you want to receive them.
This behaviour is useful when you want to do your own signal handling, or
want to handle signals only in specific threads and want to avoid libev
unblocking the signals.
It's also required by POSIX in a threaded program, as libev calls
C<sigprocmask>, whose behaviour is officially unspecified.
This flag's behaviour will become the default in future versions of libev.
=item C<EVBACKEND_SELECT> (value 1, portable select backend)
This is your standard select(2) backend. Not I<completely> standard, as
libev tries to roll its own fd_set with no limits on the number of fds,
but if that fails, expect a fairly low limit on the number of fds when
using this backend. It doesn't scale too well (O(highest_fd)), but its
usually the fastest backend for a low number of (low-numbered :) fds.
To get good performance out of this backend you need a high amount of
parallelism (most of the file descriptors should be busy). If you are
writing a server, you should C<accept ()> in a loop to accept as many
connections as possible during one iteration. You might also want to have
a look at C<ev_set_io_collect_interval ()> to increase the amount of
readiness notifications you get per iteration.
This backend maps C<EV_READ> to the C<readfds> set and C<EV_WRITE> to the
C<writefds> set (and to work around Microsoft Windows bugs, also onto the
C<exceptfds> set on that platform).
=item C<EVBACKEND_POLL> (value 2, poll backend, available everywhere except on windows)
And this is your standard poll(2) backend. It's more complicated
than select, but handles sparse fds better and has no artificial
limit on the number of fds you can use (except it will slow down
considerably with a lot of inactive fds). It scales similarly to select,
i.e. O(total_fds). See the entry for C<EVBACKEND_SELECT>, above, for
performance tips.
This backend maps C<EV_READ> to C<POLLIN | POLLERR | POLLHUP>, and
C<EV_WRITE> to C<POLLOUT | POLLERR | POLLHUP>.
=item C<EVBACKEND_EPOLL> (value 4, Linux)
Use the Linux-specific epoll(7) interface (for both pre- and post-2.6.9
kernels).
For few fds, this backend is a bit little slower than poll and select, but
it scales phenomenally better. While poll and select usually scale like
O(total_fds) where total_fds is the total number of fds (or the highest
fd), epoll scales either O(1) or O(active_fds).
13 years ago
The epoll mechanism deserves honorable mention as the most misdesigned
of the more advanced event mechanisms: mere annoyances include silently
dropping file descriptors, requiring a system call per change per file
descriptor (and unnecessary guessing of parameters), problems with dup,
returning before the timeout value, resulting in additional iterations
(and only giving 5ms accuracy while select on the same platform gives
0.1ms) and so on. The biggest issue is fork races, however - if a program
forks then I<both> parent and child process have to recreate the epoll
set, which can take considerable time (one syscall per file descriptor)
and is of course hard to detect.
13 years ago
Epoll is also notoriously buggy - embedding epoll fds I<should> work,
but of course I<doesn't>, and epoll just loves to report events for
totally I<different> file descriptors (even already closed ones, so
one cannot even remove them from the set) than registered in the set
(especially on SMP systems). Libev tries to counter these spurious
notifications by employing an additional generation counter and comparing
that against the events to filter out spurious ones, recreating the set
11 years ago
when required. Epoll also erroneously rounds down timeouts, but gives you
no way to know when and by how much, so sometimes you have to busy-wait
because epoll returns immediately despite a nonzero timeout. And last
not least, it also refuses to work with some file descriptors which work
perfectly fine with C<select> (files, many character devices...).
Epoll is truly the train wreck among event poll mechanisms, a frankenpoll,
cobbled together in a hurry, no thought to design or interaction with
others. Oh, the pain, will it ever stop...
While stopping, setting and starting an I/O watcher in the same iteration
13 years ago
will result in some caching, there is still a system call per such
incident (because the same I<file descriptor> could point to a different
I<file description> now), so its best to avoid that. Also, C<dup ()>'ed
file descriptors might not work very well if you register events for both
file descriptors.
Best performance from this backend is achieved by not unregistering all
watchers for a file descriptor until it has been closed, if possible,
i.e. keep at least one watcher active per fd at all times. Stopping and
starting a watcher (without re-setting it) also usually doesn't cause
extra overhead. A fork can both result in spurious notifications as well
as in libev having to destroy and recreate the epoll object, which can
take considerable time and thus should be avoided.
All this means that, in practice, C<EVBACKEND_SELECT> can be as fast or
faster than epoll for maybe up to a hundred file descriptors, depending on
the usage. So sad.
While nominally embeddable in other event loops, this feature is broken in
a lot of kernel revisions, but probably(!) works in current versions.
This backend maps C<EV_READ> and C<EV_WRITE> in the same way as
C<EVBACKEND_POLL>.
=item C<EVBACKEND_LINUXAIO> (value 64, Linux)
Use the Linux-specific Linux AIO (I<not> C<< aio(7) >> but C<<
io_submit(2) >>) event interface available in post-4.18 kernels (but libev
only tries to use it in 4.19+).
This is another Linux train wreck of an event interface.
If this backend works for you (as of this writing, it was very
experimental), it is the best event interface available on Linux and might
be well worth enabling it - if it isn't available in your kernel this will
be detected and this backend will be skipped.
This backend can batch oneshot requests and supports a user-space ring
buffer to receive events. It also doesn't suffer from most of the design
problems of epoll (such as not being able to remove event sources from
the epoll set), and generally sounds too good to be true. Because, this
being the Linux kernel, of course it suffers from a whole new set of
limitations, forcing you to fall back to epoll, inheriting all its design
issues.
For one, it is not easily embeddable (but probably could be done using
an event fd at some extra overhead). It also is subject to a system wide
limit that can be configured in F</proc/sys/fs/aio-max-nr>. If no AIO
requests are left, this backend will be skipped during initialisation, and
will switch to epoll when the loop is active.
Most problematic in practice, however, is that not all file descriptors
work with it. For example, in Linux 5.1, TCP sockets, pipes, event fds,
files, F</dev/null> and many others are supported, but ttys do not work
properly (a known bug that the kernel developers don't care about, see
L<https://lore.kernel.org/patchwork/patch/1047453/>), so this is not
(yet?) a generic event polling interface.
Overall, it seems the Linux developers just don't want it to have a
generic event handling mechanism other than C<select> or C<poll>.
To work around all these problem, the current version of libev uses its
epoll backend as a fallback for file descriptor types that do not work. Or
falls back completely to epoll if the kernel acts up.
This backend maps C<EV_READ> and C<EV_WRITE> in the same way as
C<EVBACKEND_POLL>.
=item C<EVBACKEND_KQUEUE> (value 8, most BSD clones)
Kqueue deserves special mention, as at the time this backend was
implemented, it was broken on all BSDs except NetBSD (usually it doesn't
work reliably with anything but sockets and pipes, except on Darwin,
where of course it's completely useless). Unlike epoll, however, whose
brokenness is by design, these kqueue bugs can be (and mostly have been)
fixed without API changes to existing programs. For this reason it's not
being "auto-detected" on all platforms unless you explicitly specify it
in the flags (i.e. using C<EVBACKEND_KQUEUE>) or libev was compiled on a
known-to-be-good (-enough) system like NetBSD.
You still can embed kqueue into a normal poll or select backend and use it
only for sockets (after having made sure that sockets work with kqueue on
the target platform). See C<ev_embed> watchers for more info.
It scales in the same way as the epoll backend, but the interface to the
kernel is more efficient (which says nothing about its actual speed, of
course). While stopping, setting and starting an I/O watcher does never
cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to
two event changes per incident. Support for C<fork ()> is very bad (you
might have to leak fds on fork, but it's more sane than epoll) and it
drops fds silently in similarly hard-to-detect cases.
This backend usually performs well under most conditions.
While nominally embeddable in other event loops, this doesn't work
everywhere, so you might need to test for this. And since it is broken
almost everywhere, you should only use it when you have a lot of sockets
(for which it usually works), by embedding it into another event loop
(e.g. C<EVBACKEND_SELECT> or C<EVBACKEND_POLL> (but C<poll> is of course
also broken on OS X)) and, did I mention it, using it only for sockets.
This backend maps C<EV_READ> into an C<EVFILT_READ> kevent with
C<NOTE_EOF>, and C<EV_WRITE> into an C<EVFILT_WRITE> kevent with
C<NOTE_EOF>.
=item C<EVBACKEND_DEVPOLL> (value 16, Solaris 8)
This is not implemented yet (and might never be, unless you send me an
implementation). According to reports, C</dev/poll> only supports sockets
and is not embeddable, which would limit the usefulness of this backend
immensely.
=item C<EVBACKEND_PORT> (value 32, Solaris 10)
This uses the Solaris 10 event port mechanism. As with everything on Solaris,
it's really slow, but it still scales very well (O(active_fds)).
While this backend scales well, it requires one system call per active
file descriptor per loop iteration. For small and medium numbers of file
descriptors a "slow" C<EVBACKEND_SELECT> or C<EVBACKEND_POLL> backend
might perform better.
On the positive side, this backend actually performed fully to
specification in all tests and is fully embeddable, which is a rare feat
among the OS-specific backends (I vastly prefer correctness over speed
hacks).
On the negative side, the interface is I<bizarre> - so bizarre that
even sun itself gets it wrong in their code examples: The event polling
function sometimes returns events to the caller even though an error
occurred, but with no indication whether it has done so or not (yes, it's
even documented that way) - deadly for edge-triggered interfaces where you
absolutely have to know whether an event occurred or not because you have
to re-arm the watcher.
Fortunately libev seems to be able to work around these idiocies.
This backend maps C<EV_READ> and C<EV_WRITE> in the same way as
C<EVBACKEND_POLL>.
=item C<EVBACKEND_ALL>
Try all backends (even potentially broken ones that wouldn't be tried
with C<EVFLAG_AUTO>). Since this is a mask, you can do stuff such as
C<EVBACKEND_ALL & ~EVBACKEND_KQUEUE>.
It is definitely not recommended to use this flag, use whatever
C<ev_recommended_backends ()> returns, or simply do not specify a backend
at all.
=item C<EVBACKEND_MASK>
Not a backend at all, but a mask to select all backend bits from a
C<flags> value, in case you want to mask out any backends from a flags
value (e.g. when modifying the C<LIBEV_FLAGS> environment variable).
=back
If one or more of the backend flags are or'ed into the flags value,
then only these backends will be tried (in the reverse order as listed
here). If none are specified, all backends in C<ev_recommended_backends
()> will be tried.
Example: Try to create a event loop that uses epoll and nothing else.
14 years ago
struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV);
if (!epoller)
fatal ("no epoll found here, maybe it hides under your chair");
Example: Use whatever libev has to offer, but make sure that kqueue is
used if available.
struct ev_loop *loop = ev_loop_new (ev_recommended_backends () | EVBACKEND_KQUEUE);
Example: Similarly, on linux, you mgiht want to take advantage of the
linux aio backend if possible, but fall back to something else if that
isn't available.
struct ev_loop *loop = ev_loop_new (ev_recommended_backends () | EVBACKEND_LINUXAIO);
=item ev_loop_destroy (loop)
Destroys an event loop object (frees all memory and kernel state
etc.). None of the active event watchers will be stopped in the normal
sense, so e.g. C<ev_is_active> might still return true. It is your
responsibility to either stop all watchers cleanly yourself I<before>
calling this function, or cope with the fact afterwards (which is usually
the easiest thing, you can just ignore the watchers and/or C<free ()> them
for example).
Note that certain global state, such as signal state (and installed signal
handlers), will not be freed by this function, and related watchers (such
as signal and child watchers) would need to be stopped manually.
This function is normally used on loop objects allocated by
C<ev_loop_new>, but it can also be used on the default loop returned by
C<ev_default_loop>, in which case it is not thread-safe.
Note that it is not advisable to call this function on the default loop
except in the rare occasion where you really need to free its resources.
If you need dynamically allocated loops it is better to use C<ev_loop_new>
and C<ev_loop_destroy>.
=item ev_loop_fork (loop)
This function sets a flag that causes subsequent C<ev_run> iterations
to reinitialise the kernel state for backends that have one. Despite
the name, you can call it anytime you are allowed to start or stop
watchers (except inside an C<ev_prepare> callback), but it makes most
sense after forking, in the child process. You I<must> call it (or use
C<EVFLAG_FORKCHECK>) in the child before resuming or calling C<ev_run>.
In addition, if you want to reuse a loop (via this function or
C<EVFLAG_FORKCHECK>), you I<also> have to ignore C<SIGPIPE>.
Again, you I<have> to call it on I<any> loop that you want to re-use after
a fork, I<even if you do not plan to use the loop in the parent>. This is
because some kernel interfaces *cough* I<kqueue> *cough* do funny things
during fork.
On the other hand, you only need to call this function in the child
process if and only if you want to use the event loop in the child. If
you just fork+exec or create a new loop in the child, you don't have to
call it at all (in fact, C<epoll> is so badly broken that it makes a
difference, but libev will usually detect this case on its own and do a
costly reset of the backend).
The function itself is quite fast and it's usually not a problem to call
it just in case after a fork.
Example: Automate calling C<ev_loop_fork> on the default loop when
using pthreads.
static void
post_fork_child (void)
{
ev_loop_fork (EV_DEFAULT);
}
...
pthread_atfork (0, 0, post_fork_child);
=item int ev_is_default_loop (loop)
Returns true when the given loop is, in fact, the default loop, and false
otherwise.
=item unsigned int ev_iteration (loop)
Returns the current iteration count for the event loop, which is identical
to the number of times libev did poll for new events. It starts at C<0>
and happily wraps around with enough iterations.
This value can sometimes be useful as a generation counter of sorts (it
"ticks" the number of loop iterations), as it roughly corresponds with
C<ev_prepare> and C<ev_check> calls - and is incremented between the
prepare and check phases.
=item unsigned int ev_depth (loop)
Returns the number of times C<ev_run> was entered minus the number of
times C<ev_run> was exited normally, in other words, the recursion depth.
Outside C<ev_run>, this number is zero. In a callback, this number is
C<1>, unless C<ev_run> was invoked recursively (or from another thread),