+ ...
+ ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.);
+ ev_stat_start (loop, &passwd);
+ ev_timer_init (&timer, timer_cb, 0., 1.01);
+
+
+=head2 C<ev_idle> - when you've got nothing better to do...
+
+Idle watchers trigger events when no other events of the same or higher
+priority are pending (prepare, check and other idle watchers do not
+count).
+
+That is, as long as your process is busy handling sockets or timeouts
+(or even signals, imagine) of the same or higher priority it will not be
+triggered. But when your process is idle (or only lower-priority watchers
+are pending), the idle watchers are being called once per event loop
+iteration - until stopped, that is, or your process receives more events
+and becomes busy again with higher priority stuff.
+
+The most noteworthy effect is that as long as any idle watchers are
+active, the process will not block when waiting for new events.
+
+Apart from keeping your process non-blocking (which is a useful
+effect on its own sometimes), idle watchers are a good place to do
+"pseudo-background processing", or delay processing stuff to after the
+event loop has handled all outstanding events.
+
+=head3 Watcher-Specific Functions and Data Members
+
+=over 4
+
+=item ev_idle_init (ev_signal *, callback)
+
+Initialises and configures the idle watcher - it has no parameters of any
+kind. There is a C<ev_idle_set> macro, but using it is utterly pointless,
+believe me.
+
+=back
+
+=head3 Examples
+
+Example: Dynamically allocate an C<ev_idle> watcher, start it, and in the
+callback, free it. Also, use no error checking, as usual.
+
+ static void
+ idle_cb (struct ev_loop *loop, struct ev_idle *w, int revents)
+ {
+ free (w);
+ // now do something you wanted to do when the program has
+ // no longer asnything immediate to do.
+ }
+
+ struct ev_idle *idle_watcher = malloc (sizeof (struct ev_idle));
+ ev_idle_init (idle_watcher, idle_cb);
+ ev_idle_start (loop, idle_cb);
+
+
+=head2 C<ev_prepare> and C<ev_check> - customise your event loop!
+
+Prepare and check watchers are usually (but not always) used in tandem:
+prepare watchers get invoked before the process blocks and check watchers
+afterwards.
+
+You I<must not> call C<ev_loop> or similar functions that enter
+the current event loop from either C<ev_prepare> or C<ev_check>
+watchers. Other loops than the current one are fine, however. The
+rationale behind this is that you do not need to check for recursion in
+those watchers, i.e. the sequence will always be C<ev_prepare>, blocking,
+C<ev_check> so if you have one watcher of each kind they will always be
+called in pairs bracketing the blocking call.
+
+Their main purpose is to integrate other event mechanisms into libev and
+their use is somewhat advanced. This could be used, for example, to track
+variable changes, implement your own watchers, integrate net-snmp or a
+coroutine library and lots more. They are also occasionally useful if
+you cache some data and want to flush it before blocking (for example,
+in X programs you might want to do an C<XFlush ()> in an C<ev_prepare>
+watcher).
+
+This is done by examining in each prepare call which file descriptors need
+to be watched by the other library, registering C<ev_io> watchers for
+them and starting an C<ev_timer> watcher for any timeouts (many libraries
+provide just this functionality). Then, in the check watcher you check for
+any events that occured (by checking the pending status of all watchers
+and stopping them) and call back into the library. The I/O and timer
+callbacks will never actually be called (but must be valid nevertheless,
+because you never know, you know?).
+
+As another example, the Perl Coro module uses these hooks to integrate
+coroutines into libev programs, by yielding to other active coroutines
+during each prepare and only letting the process block if no coroutines
+are ready to run (it's actually more complicated: it only runs coroutines
+with priority higher than or equal to the event loop and one coroutine
+of lower priority, but only once, using idle watchers to keep the event
+loop from blocking if lower-priority coroutines are active, thus mapping
+low-priority coroutines to idle/background tasks).
+
+It is recommended to give C<ev_check> watchers highest (C<EV_MAXPRI>)
+priority, to ensure that they are being run before any other watchers
+after the poll. Also, C<ev_check> watchers (and C<ev_prepare> watchers,
+too) should not activate ("feed") events into libev. While libev fully
+supports this, they will be called before other C<ev_check> watchers
+did their job. As C<ev_check> watchers are often used to embed other
+(non-libev) event loops those other event loops might be in an unusable
+state until their C<ev_check> watcher ran (always remind yourself to
+coexist peacefully with others).
+
+=head3 Watcher-Specific Functions and Data Members
+
+=over 4
+
+=item ev_prepare_init (ev_prepare *, callback)
+
+=item ev_check_init (ev_check *, callback)
+
+Initialises and configures the prepare or check watcher - they have no
+parameters of any kind. There are C<ev_prepare_set> and C<ev_check_set>
+macros, but using them is utterly, utterly and completely pointless.
+
+=back
+
+=head3 Examples
+
+There are a number of principal ways to embed other event loops or modules
+into libev. Here are some ideas on how to include libadns into libev
+(there is a Perl module named C<EV::ADNS> that does this, which you could
+use for an actually working example. Another Perl module named C<EV::Glib>
+embeds a Glib main context into libev, and finally, C<Glib::EV> embeds EV
+into the Glib event loop).
+
+Method 1: Add IO watchers and a timeout watcher in a prepare handler,
+and in a check watcher, destroy them and call into libadns. What follows
+is pseudo-code only of course. This requires you to either use a low
+priority for the check watcher or use C<ev_clear_pending> explicitly, as
+the callbacks for the IO/timeout watchers might not have been called yet.
+
+ static ev_io iow [nfd];
+ static ev_timer tw;
+
+ static void
+ io_cb (ev_loop *loop, ev_io *w, int revents)
+ {
+ }
+
+ // create io watchers for each fd and a timer before blocking
+ static void
+ adns_prepare_cb (ev_loop *loop, ev_prepare *w, int revents)
+ {
+ int timeout = 3600000;
+ struct pollfd fds [nfd];
+ // actual code will need to loop here and realloc etc.
+ adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ()));
+
+ /* the callback is illegal, but won't be called as we stop during check */
+ ev_timer_init (&tw, 0, timeout * 1e-3);
+ ev_timer_start (loop, &tw);
+
+ // create one ev_io per pollfd
+ for (int i = 0; i < nfd; ++i)
+ {
+ ev_io_init (iow + i, io_cb, fds [i].fd,
+ ((fds [i].events & POLLIN ? EV_READ : 0)
+ | (fds [i].events & POLLOUT ? EV_WRITE : 0)));
+
+ fds [i].revents = 0;
+ ev_io_start (loop, iow + i);
+ }
+ }
+
+ // stop all watchers after blocking
+ static void
+ adns_check_cb (ev_loop *loop, ev_check *w, int revents)
+ {
+ ev_timer_stop (loop, &tw);
+
+ for (int i = 0; i < nfd; ++i)
+ {
+ // set the relevant poll flags
+ // could also call adns_processreadable etc. here
+ struct pollfd *fd = fds + i;
+ int revents = ev_clear_pending (iow + i);
+ if (revents & EV_READ ) fd->revents |= fd->events & POLLIN;
+ if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT;
+
+ // now stop the watcher
+ ev_io_stop (loop, iow + i);
+ }
+
+ adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop));
+ }
+
+Method 2: This would be just like method 1, but you run C<adns_afterpoll>
+in the prepare watcher and would dispose of the check watcher.
+
+Method 3: If the module to be embedded supports explicit event
+notification (adns does), you can also make use of the actual watcher
+callbacks, and only destroy/create the watchers in the prepare watcher.
+
+ static void
+ timer_cb (EV_P_ ev_timer *w, int revents)
+ {
+ adns_state ads = (adns_state)w->data;
+ update_now (EV_A);
+
+ adns_processtimeouts (ads, &tv_now);
+ }
+
+ static void
+ io_cb (EV_P_ ev_io *w, int revents)
+ {
+ adns_state ads = (adns_state)w->data;
+ update_now (EV_A);
+
+ if (revents & EV_READ ) adns_processreadable (ads, w->fd, &tv_now);
+ if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now);
+ }
+
+ // do not ever call adns_afterpoll
+
+Method 4: Do not use a prepare or check watcher because the module you
+want to embed is too inflexible to support it. Instead, youc na override
+their poll function. The drawback with this solution is that the main
+loop is now no longer controllable by EV. The C<Glib::EV> module does
+this.
+
+ static gint
+ event_poll_func (GPollFD *fds, guint nfds, gint timeout)
+ {
+ int got_events = 0;
+
+ for (n = 0; n < nfds; ++n)
+ // create/start io watcher that sets the relevant bits in fds[n] and increment got_events
+
+ if (timeout >= 0)
+ // create/start timer
+
+ // poll
+ ev_loop (EV_A_ 0);
+
+ // stop timer again
+ if (timeout >= 0)
+ ev_timer_stop (EV_A_ &to);
+
+ // stop io watchers again - their callbacks should have set
+ for (n = 0; n < nfds; ++n)
+ ev_io_stop (EV_A_ iow [n]);
+
+ return got_events;
+ }
+
+
+=head2 C<ev_embed> - when one backend isn't enough...
+
+This is a rather advanced watcher type that lets you embed one event loop
+into another (currently only C<ev_io> events are supported in the embedded
+loop, other types of watchers might be handled in a delayed or incorrect
+fashion and must not be used).
+
+There are primarily two reasons you would want that: work around bugs and
+prioritise I/O.
+
+As an example for a bug workaround, the kqueue backend might only support
+sockets on some platform, so it is unusable as generic backend, but you
+still want to make use of it because you have many sockets and it scales
+so nicely. In this case, you would create a kqueue-based loop and embed it
+into your default loop (which might use e.g. poll). Overall operation will
+be a bit slower because first libev has to poll and then call kevent, but
+at least you can use both at what they are best.
+
+As for prioritising I/O: rarely you have the case where some fds have
+to be watched and handled very quickly (with low latency), and even
+priorities and idle watchers might have too much overhead. In this case
+you would put all the high priority stuff in one loop and all the rest in
+a second one, and embed the second one in the first.
+
+As long as the watcher is active, the callback will be invoked every time
+there might be events pending in the embedded loop. The callback must then
+call C<ev_embed_sweep (mainloop, watcher)> to make a single sweep and invoke
+their callbacks (you could also start an idle watcher to give the embedded
+loop strictly lower priority for example). You can also set the callback
+to C<0>, in which case the embed watcher will automatically execute the
+embedded loop sweep.
+
+As long as the watcher is started it will automatically handle events. The
+callback will be invoked whenever some events have been handled. You can
+set the callback to C<0> to avoid having to specify one if you are not
+interested in that.
+
+Also, there have not currently been made special provisions for forking:
+when you fork, you not only have to call C<ev_loop_fork> on both loops,
+but you will also have to stop and restart any C<ev_embed> watchers
+yourself.
+
+Unfortunately, not all backends are embeddable, only the ones returned by
+C<ev_embeddable_backends> are, which, unfortunately, does not include any
+portable one.
+
+So when you want to use this feature you will always have to be prepared
+that you cannot get an embeddable loop. The recommended way to get around
+this is to have a separate variables for your embeddable loop, try to
+create it, and if that fails, use the normal loop for everything.
+
+=head3 Watcher-Specific Functions and Data Members
+
+=over 4
+
+=item ev_embed_init (ev_embed *, callback, struct ev_loop *embedded_loop)
+
+=item ev_embed_set (ev_embed *, callback, struct ev_loop *embedded_loop)
+
+Configures the watcher to embed the given loop, which must be
+embeddable. If the callback is C<0>, then C<ev_embed_sweep> will be
+invoked automatically, otherwise it is the responsibility of the callback
+to invoke it (it will continue to be called until the sweep has been done,
+if you do not want thta, you need to temporarily stop the embed watcher).
+
+=item ev_embed_sweep (loop, ev_embed *)
+
+Make a single, non-blocking sweep over the embedded loop. This works
+similarly to C<ev_loop (embedded_loop, EVLOOP_NONBLOCK)>, but in the most
+apropriate way for embedded loops.
+
+=item struct ev_loop *other [read-only]
+
+The embedded event loop.
+
+=back
+
+=head3 Examples
+
+Example: Try to get an embeddable event loop and embed it into the default
+event loop. If that is not possible, use the default loop. The default
+loop is stored in C<loop_hi>, while the mebeddable loop is stored in
+C<loop_lo> (which is C<loop_hi> in the acse no embeddable loop can be
+used).
+
+ struct ev_loop *loop_hi = ev_default_init (0);
+ struct ev_loop *loop_lo = 0;
+ struct ev_embed embed;
+
+ // see if there is a chance of getting one that works
+ // (remember that a flags value of 0 means autodetection)
+ loop_lo = ev_embeddable_backends () & ev_recommended_backends ()
+ ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ())
+ : 0;
+
+ // if we got one, then embed it, otherwise default to loop_hi
+ if (loop_lo)
+ {
+ ev_embed_init (&embed, 0, loop_lo);
+ ev_embed_start (loop_hi, &embed);
+ }
+ else
+ loop_lo = loop_hi;
+
+Example: Check if kqueue is available but not recommended and create
+a kqueue backend for use with sockets (which usually work with any
+kqueue implementation). Store the kqueue/socket-only event loop in
+C<loop_socket>. (One might optionally use C<EVFLAG_NOENV>, too).
+
+ struct ev_loop *loop = ev_default_init (0);
+ struct ev_loop *loop_socket = 0;
+ struct ev_embed embed;
+
+ if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE)
+ if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE))
+ {
+ ev_embed_init (&embed, 0, loop_socket);
+ ev_embed_start (loop, &embed);
+ }
+
+ if (!loop_socket)
+ loop_socket = loop;
+
+ // now use loop_socket for all sockets, and loop for everything else
+
+
+=head2 C<ev_fork> - the audacity to resume the event loop after a fork
+
+Fork watchers are called when a C<fork ()> was detected (usually because
+whoever is a good citizen cared to tell libev about it by calling
+C<ev_default_fork> or C<ev_loop_fork>). The invocation is done before the
+event loop blocks next and before C<ev_check> watchers are being called,
+and only in the child after the fork. If whoever good citizen calling
+C<ev_default_fork> cheats and calls it in the wrong process, the fork
+handlers will be invoked, too, of course.
+
+=head3 Watcher-Specific Functions and Data Members
+
+=over 4
+
+=item ev_fork_init (ev_signal *, callback)
+
+Initialises and configures the fork watcher - it has no parameters of any
+kind. There is a C<ev_fork_set> macro, but using it is utterly pointless,
+believe me.
+
+=back
+
+
+=head1 OTHER FUNCTIONS
+
+There are some other functions of possible interest. Described. Here. Now.
+
+=over 4
+
+=item ev_once (loop, int fd, int events, ev_tstamp timeout, callback)
+
+This function combines a simple timer and an I/O watcher, calls your
+callback on whichever event happens first and automatically stop both
+watchers. This is useful if you want to wait for a single event on an fd
+or timeout without having to allocate/configure/start/stop/free one or
+more watchers yourself.
+
+If C<fd> is less than 0, then no I/O watcher will be started and events
+is being ignored. Otherwise, an C<ev_io> watcher for the given C<fd> and
+C<events> set will be craeted and started.
+
+If C<timeout> is less than 0, then no timeout watcher will be
+started. Otherwise an C<ev_timer> watcher with after = C<timeout> (and
+repeat = 0) will be started. While C<0> is a valid timeout, it is of
+dubious value.
+
+The callback has the type C<void (*cb)(int revents, void *arg)> and gets
+passed an C<revents> set like normal event callbacks (a combination of
+C<EV_ERROR>, C<EV_READ>, C<EV_WRITE> or C<EV_TIMEOUT>) and the C<arg>
+value passed to C<ev_once>:
+
+ static void stdin_ready (int revents, void *arg)
+ {
+ if (revents & EV_TIMEOUT)
+ /* doh, nothing entered */;
+ else if (revents & EV_READ)
+ /* stdin might have data for us, joy! */;
+ }
+
+ ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);
+
+=item ev_feed_event (ev_loop *, watcher *, int revents)
+
+Feeds the given event set into the event loop, as if the specified event
+had happened for the specified watcher (which must be a pointer to an
+initialised but not necessarily started event watcher).
+
+=item ev_feed_fd_event (ev_loop *, int fd, int revents)
+
+Feed an event on the given fd, as if a file descriptor backend detected
+the given events it.
+
+=item ev_feed_signal_event (ev_loop *loop, int signum)
+
+Feed an event as if the given signal occured (C<loop> must be the default
+loop!).
+
+=back
+
+
+=head1 LIBEVENT EMULATION
+
+Libev offers a compatibility emulation layer for libevent. It cannot
+emulate the internals of libevent, so here are some usage hints:
+
+=over 4
+
+=item * Use it by including <event.h>, as usual.
+
+=item * The following members are fully supported: ev_base, ev_callback,
+ev_arg, ev_fd, ev_res, ev_events.
+
+=item * Avoid using ev_flags and the EVLIST_*-macros, while it is
+maintained by libev, it does not work exactly the same way as in libevent (consider
+it a private API).
+
+=item * Priorities are not currently supported. Initialising priorities
+will fail and all watchers will have the same priority, even though there
+is an ev_pri field.
+
+=item * Other members are not supported.
+
+=item * The libev emulation is I<not> ABI compatible to libevent, you need
+to use the libev header file and library.
+
+=back
+
+=head1 C++ SUPPORT
+
+Libev comes with some simplistic wrapper classes for C++ that mainly allow
+you to use some convinience methods to start/stop watchers and also change
+the callback model to a model using method callbacks on objects.
+
+To use it,
+
+ #include <ev++.h>
+
+This automatically includes F<ev.h> and puts all of its definitions (many
+of them macros) into the global namespace. All C++ specific things are
+put into the C<ev> namespace. It should support all the same embedding
+options as F<ev.h>, most notably C<EV_MULTIPLICITY>.
+
+Care has been taken to keep the overhead low. The only data member the C++
+classes add (compared to plain C-style watchers) is the event loop pointer
+that the watcher is associated with (or no additional members at all if
+you disable C<EV_MULTIPLICITY> when embedding libev).
+
+Currently, functions, and static and non-static member functions can be
+used as callbacks. Other types should be easy to add as long as they only
+need one additional pointer for context. If you need support for other
+types of functors please contact the author (preferably after implementing
+it).
+
+Here is a list of things available in the C<ev> namespace:
+
+=over 4
+
+=item C<ev::READ>, C<ev::WRITE> etc.
+
+These are just enum values with the same values as the C<EV_READ> etc.
+macros from F<ev.h>.
+
+=item C<ev::tstamp>, C<ev::now>
+
+Aliases to the same types/functions as with the C<ev_> prefix.
+
+=item C<ev::io>, C<ev::timer>, C<ev::periodic>, C<ev::idle>, C<ev::sig> etc.
+
+For each C<ev_TYPE> watcher in F<ev.h> there is a corresponding class of
+the same name in the C<ev> namespace, with the exception of C<ev_signal>
+which is called C<ev::sig> to avoid clashes with the C<signal> macro
+defines by many implementations.
+
+All of those classes have these methods:
+
+=over 4
+
+=item ev::TYPE::TYPE ()
+
+=item ev::TYPE::TYPE (struct ev_loop *)
+
+=item ev::TYPE::~TYPE
+
+The constructor (optionally) takes an event loop to associate the watcher
+with. If it is omitted, it will use C<EV_DEFAULT>.
+
+The constructor calls C<ev_init> for you, which means you have to call the
+C<set> method before starting it.
+
+It will not set a callback, however: You have to call the templated C<set>
+method to set a callback before you can start the watcher.
+
+(The reason why you have to use a method is a limitation in C++ which does
+not allow explicit template arguments for constructors).
+
+The destructor automatically stops the watcher if it is active.
+
+=item w->set<class, &class::method> (object *)
+
+This method sets the callback method to call. The method has to have a
+signature of C<void (*)(ev_TYPE &, int)>, it receives the watcher as
+first argument and the C<revents> as second. The object must be given as
+parameter and is stored in the C<data> member of the watcher.
+
+This method synthesizes efficient thunking code to call your method from
+the C callback that libev requires. If your compiler can inline your
+callback (i.e. it is visible to it at the place of the C<set> call and
+your compiler is good :), then the method will be fully inlined into the
+thunking function, making it as fast as a direct C callback.
+
+Example: simple class declaration and watcher initialisation
+
+ struct myclass
+ {
+ void io_cb (ev::io &w, int revents) { }
+ }
+
+ myclass obj;
+ ev::io iow;
+ iow.set <myclass, &myclass::io_cb> (&obj);
+
+=item w->set<function> (void *data = 0)
+
+Also sets a callback, but uses a static method or plain function as
+callback. The optional C<data> argument will be stored in the watcher's
+C<data> member and is free for you to use.
+
+The prototype of the C<function> must be C<void (*)(ev::TYPE &w, int)>.
+
+See the method-C<set> above for more details.
+
+Example:
+
+ static void io_cb (ev::io &w, int revents) { }
+ iow.set <io_cb> ();
+
+=item w->set (struct ev_loop *)
+
+Associates a different C<struct ev_loop> with this watcher. You can only
+do this when the watcher is inactive (and not pending either).
+
+=item w->set ([args])
+
+Basically the same as C<ev_TYPE_set>, with the same args. Must be
+called at least once. Unlike the C counterpart, an active watcher gets
+automatically stopped and restarted when reconfiguring it with this
+method.
+
+=item w->start ()
+
+Starts the watcher. Note that there is no C<loop> argument, as the
+constructor already stores the event loop.
+
+=item w->stop ()
+
+Stops the watcher if it is active. Again, no C<loop> argument.
+
+=item w->again () (C<ev::timer>, C<ev::periodic> only)
+
+For C<ev::timer> and C<ev::periodic>, this invokes the corresponding
+C<ev_TYPE_again> function.
+
+=item w->sweep () (C<ev::embed> only)
+
+Invokes C<ev_embed_sweep>.
+
+=item w->update () (C<ev::stat> only)
+
+Invokes C<ev_stat_stat>.
+
+=back
+
+=back
+
+Example: Define a class with an IO and idle watcher, start one of them in
+the constructor.
+
+ class myclass
+ {
+ ev_io io; void io_cb (ev::io &w, int revents);
+ ev_idle idle void idle_cb (ev::idle &w, int revents);
+
+ myclass ();
+ }
+
+ myclass::myclass (int fd)
+ {
+ io .set <myclass, &myclass::io_cb > (this);
+ idle.set <myclass, &myclass::idle_cb> (this);
+
+ io.start (fd, ev::READ);
+ }
+
+
+=head1 MACRO MAGIC
+
+Libev can be compiled with a variety of options, the most fundamantal
+of which is C<EV_MULTIPLICITY>. This option determines whether (most)
+functions and callbacks have an initial C<struct ev_loop *> argument.
+
+To make it easier to write programs that cope with either variant, the
+following macros are defined:
+
+=over 4
+
+=item C<EV_A>, C<EV_A_>
+
+This provides the loop I<argument> for functions, if one is required ("ev
+loop argument"). The C<EV_A> form is used when this is the sole argument,
+C<EV_A_> is used when other arguments are following. Example:
+
+ ev_unref (EV_A);
+ ev_timer_add (EV_A_ watcher);
+ ev_loop (EV_A_ 0);
+
+It assumes the variable C<loop> of type C<struct ev_loop *> is in scope,
+which is often provided by the following macro.
+
+=item C<EV_P>, C<EV_P_>
+
+This provides the loop I<parameter> for functions, if one is required ("ev
+loop parameter"). The C<EV_P> form is used when this is the sole parameter,
+C<EV_P_> is used when other parameters are following. Example:
+
+ // this is how ev_unref is being declared
+ static void ev_unref (EV_P);
+
+ // this is how you can declare your typical callback
+ static void cb (EV_P_ ev_timer *w, int revents)
+
+It declares a parameter C<loop> of type C<struct ev_loop *>, quite
+suitable for use with C<EV_A>.
+
+=item C<EV_DEFAULT>, C<EV_DEFAULT_>
+
+Similar to the other two macros, this gives you the value of the default
+loop, if multiple loops are supported ("ev loop default").
+
+=back
+
+Example: Declare and initialise a check watcher, utilising the above
+macros so it will work regardless of whether multiple loops are supported
+or not.
+
+ static void
+ check_cb (EV_P_ ev_timer *w, int revents)
+ {
+ ev_check_stop (EV_A_ w);
+ }
+
+ ev_check check;
+ ev_check_init (&check, check_cb);
+ ev_check_start (EV_DEFAULT_ &check);
+ ev_loop (EV_DEFAULT_ 0);
+
+=head1 EMBEDDING
+
+Libev can (and often is) directly embedded into host
+applications. Examples of applications that embed it include the Deliantra
+Game Server, the EV perl module, the GNU Virtual Private Ethernet (gvpe)
+and rxvt-unicode.
+
+The goal is to enable you to just copy the necessary files into your
+source directory without having to change even a single line in them, so
+you can easily upgrade by simply copying (or having a checked-out copy of
+libev somewhere in your source tree).
+
+=head2 FILESETS
+
+Depending on what features you need you need to include one or more sets of files
+in your app.
+
+=head3 CORE EVENT LOOP
+
+To include only the libev core (all the C<ev_*> functions), with manual
+configuration (no autoconf):
+
+ #define EV_STANDALONE 1
+ #include "ev.c"
+
+This will automatically include F<ev.h>, too, and should be done in a
+single C source file only to provide the function implementations. To use
+it, do the same for F<ev.h> in all files wishing to use this API (best
+done by writing a wrapper around F<ev.h> that you can include instead and
+where you can put other configuration options):
+
+ #define EV_STANDALONE 1
+ #include "ev.h"
+
+Both header files and implementation files can be compiled with a C++
+compiler (at least, thats a stated goal, and breakage will be treated
+as a bug).
+
+You need the following files in your source tree, or in a directory
+in your include path (e.g. in libev/ when using -Ilibev):
+
+ ev.h
+ ev.c
+ ev_vars.h
+ ev_wrap.h
+
+ ev_win32.c required on win32 platforms only
+
+ ev_select.c only when select backend is enabled (which is enabled by default)
+ ev_poll.c only when poll backend is enabled (disabled by default)
+ ev_epoll.c only when the epoll backend is enabled (disabled by default)
+ ev_kqueue.c only when the kqueue backend is enabled (disabled by default)
+ ev_port.c only when the solaris port backend is enabled (disabled by default)
+
+F<ev.c> includes the backend files directly when enabled, so you only need
+to compile this single file.
+
+=head3 LIBEVENT COMPATIBILITY API
+
+To include the libevent compatibility API, also include:
+
+ #include "event.c"
+
+in the file including F<ev.c>, and:
+
+ #include "event.h"
+
+in the files that want to use the libevent API. This also includes F<ev.h>.
+
+You need the following additional files for this:
+
+ event.h
+ event.c
+
+=head3 AUTOCONF SUPPORT
+
+Instead of using C<EV_STANDALONE=1> and providing your config in
+whatever way you want, you can also C<m4_include([libev.m4])> in your
+F<configure.ac> and leave C<EV_STANDALONE> undefined. F<ev.c> will then
+include F<config.h> and configure itself accordingly.
+
+For this of course you need the m4 file:
+
+ libev.m4
+
+=head2 PREPROCESSOR SYMBOLS/MACROS
+
+Libev can be configured via a variety of preprocessor symbols you have to define
+before including any of its files. The default is not to build for multiplicity
+and only include the select backend.
+
+=over 4
+
+=item EV_STANDALONE
+
+Must always be C<1> if you do not use autoconf configuration, which
+keeps libev from including F<config.h>, and it also defines dummy
+implementations for some libevent functions (such as logging, which is not
+supported). It will also not define any of the structs usually found in
+F<event.h> that are not directly supported by the libev core alone.
+
+=item EV_USE_MONOTONIC
+
+If defined to be C<1>, libev will try to detect the availability of the
+monotonic clock option at both compiletime and runtime. Otherwise no use
+of the monotonic clock option will be attempted. If you enable this, you
+usually have to link against librt or something similar. Enabling it when
+the functionality isn't available is safe, though, although you have
+to make sure you link against any libraries where the C<clock_gettime>
+function is hiding in (often F<-lrt>).
+
+=item EV_USE_REALTIME
+
+If defined to be C<1>, libev will try to detect the availability of the
+realtime clock option at compiletime (and assume its availability at
+runtime if successful). Otherwise no use of the realtime clock option will
+be attempted. This effectively replaces C<gettimeofday> by C<clock_get
+(CLOCK_REALTIME, ...)> and will not normally affect correctness. See the
+note about libraries in the description of C<EV_USE_MONOTONIC>, though.
+
+=item EV_USE_NANOSLEEP
+
+If defined to be C<1>, libev will assume that C<nanosleep ()> is available
+and will use it for delays. Otherwise it will use C<select ()>.
+
+=item EV_USE_SELECT
+
+If undefined or defined to be C<1>, libev will compile in support for the
+C<select>(2) backend. No attempt at autodetection will be done: if no
+other method takes over, select will be it. Otherwise the select backend
+will not be compiled in.
+
+=item EV_SELECT_USE_FD_SET
+
+If defined to C<1>, then the select backend will use the system C<fd_set>
+structure. This is useful if libev doesn't compile due to a missing
+C<NFDBITS> or C<fd_mask> definition or it misguesses the bitset layout on
+exotic systems. This usually limits the range of file descriptors to some
+low limit such as 1024 or might have other limitations (winsocket only
+allows 64 sockets). The C<FD_SETSIZE> macro, set before compilation, might
+influence the size of the C<fd_set> used.
+
+=item EV_SELECT_IS_WINSOCKET
+
+When defined to C<1>, the select backend will assume that
+select/socket/connect etc. don't understand file descriptors but
+wants osf handles on win32 (this is the case when the select to
+be used is the winsock select). This means that it will call
+C<_get_osfhandle> on the fd to convert it to an OS handle. Otherwise,
+it is assumed that all these functions actually work on fds, even
+on win32. Should not be defined on non-win32 platforms.
+
+=item EV_FD_TO_WIN32_HANDLE
+
+If C<EV_SELECT_IS_WINSOCKET> is enabled, then libev needs a way to map
+file descriptors to socket handles. When not defining this symbol (the
+default), then libev will call C<_get_osfhandle>, which is usually
+correct. In some cases, programs use their own file descriptor management,
+in which case they can provide this function to map fds to socket handles.
+
+=item EV_USE_POLL
+
+If defined to be C<1>, libev will compile in support for the C<poll>(2)
+backend. Otherwise it will be enabled on non-win32 platforms. It
+takes precedence over select.
+
+=item EV_USE_EPOLL
+
+If defined to be C<1>, libev will compile in support for the Linux
+C<epoll>(7) backend. Its availability will be detected at runtime,
+otherwise another method will be used as fallback. This is the
+preferred backend for GNU/Linux systems.
+
+=item EV_USE_KQUEUE
+
+If defined to be C<1>, libev will compile in support for the BSD style
+C<kqueue>(2) backend. Its actual availability will be detected at runtime,
+otherwise another method will be used as fallback. This is the preferred
+backend for BSD and BSD-like systems, although on most BSDs kqueue only
+supports some types of fds correctly (the only platform we found that
+supports ptys for example was NetBSD), so kqueue might be compiled in, but
+not be used unless explicitly requested. The best way to use it is to find
+out whether kqueue supports your type of fd properly and use an embedded
+kqueue loop.
+
+=item EV_USE_PORT
+
+If defined to be C<1>, libev will compile in support for the Solaris
+10 port style backend. Its availability will be detected at runtime,
+otherwise another method will be used as fallback. This is the preferred
+backend for Solaris 10 systems.
+
+=item EV_USE_DEVPOLL
+
+reserved for future expansion, works like the USE symbols above.
+
+=item EV_USE_INOTIFY
+
+If defined to be C<1>, libev will compile in support for the Linux inotify
+interface to speed up C<ev_stat> watchers. Its actual availability will
+be detected at runtime.
+
+=item EV_H
+
+The name of the F<ev.h> header file used to include it. The default if
+undefined is C<"ev.h"> in F<event.h>, F<ev.c> and F<ev++.h>. This can be
+used to virtually rename the F<ev.h> header file in case of conflicts.
+
+=item EV_CONFIG_H
+
+If C<EV_STANDALONE> isn't C<1>, this variable can be used to override
+F<ev.c>'s idea of where to find the F<config.h> file, similarly to
+C<EV_H>, above.
+
+=item EV_EVENT_H
+
+Similarly to C<EV_H>, this macro can be used to override F<event.c>'s idea
+of how the F<event.h> header can be found, the default is C<"event.h">.
+
+=item EV_PROTOTYPES
+
+If defined to be C<0>, then F<ev.h> will not define any function
+prototypes, but still define all the structs and other symbols. This is
+occasionally useful if you want to provide your own wrapper functions
+around libev functions.
+
+=item EV_MULTIPLICITY
+
+If undefined or defined to C<1>, then all event-loop-specific functions
+will have the C<struct ev_loop *> as first argument, and you can create
+additional independent event loops. Otherwise there will be no support
+for multiple event loops and there is no first event loop pointer
+argument. Instead, all functions act on the single default loop.
+
+=item EV_MINPRI
+
+=item EV_MAXPRI
+
+The range of allowed priorities. C<EV_MINPRI> must be smaller or equal to
+C<EV_MAXPRI>, but otherwise there are no non-obvious limitations. You can
+provide for more priorities by overriding those symbols (usually defined
+to be C<-2> and C<2>, respectively).
+
+When doing priority-based operations, libev usually has to linearly search
+all the priorities, so having many of them (hundreds) uses a lot of space
+and time, so using the defaults of five priorities (-2 .. +2) is usually
+fine.
+
+If your embedding app does not need any priorities, defining these both to
+C<0> will save some memory and cpu.
+
+=item EV_PERIODIC_ENABLE
+
+If undefined or defined to be C<1>, then periodic timers are supported. If
+defined to be C<0>, then they are not. Disabling them saves a few kB of
+code.
+
+=item EV_IDLE_ENABLE
+
+If undefined or defined to be C<1>, then idle watchers are supported. If
+defined to be C<0>, then they are not. Disabling them saves a few kB of
+code.
+
+=item EV_EMBED_ENABLE
+
+If undefined or defined to be C<1>, then embed watchers are supported. If
+defined to be C<0>, then they are not.
+
+=item EV_STAT_ENABLE
+
+If undefined or defined to be C<1>, then stat watchers are supported. If
+defined to be C<0>, then they are not.
+
+=item EV_FORK_ENABLE
+
+If undefined or defined to be C<1>, then fork watchers are supported. If
+defined to be C<0>, then they are not.
+
+=item EV_MINIMAL
+
+If you need to shave off some kilobytes of code at the expense of some
+speed, define this symbol to C<1>. Currently only used for gcc to override
+some inlining decisions, saves roughly 30% codesize of amd64.
+
+=item EV_PID_HASHSIZE
+
+C<ev_child> watchers use a small hash table to distribute workload by
+pid. The default size is C<16> (or C<1> with C<EV_MINIMAL>), usually more
+than enough. If you need to manage thousands of children you might want to
+increase this value (I<must> be a power of two).
+
+=item EV_INOTIFY_HASHSIZE
+
+C<ev_stat> watchers use a small hash table to distribute workload by
+inotify watch id. The default size is C<16> (or C<1> with C<EV_MINIMAL>),
+usually more than enough. If you need to manage thousands of C<ev_stat>
+watchers you might want to increase this value (I<must> be a power of
+two).
+
+=item EV_COMMON
+
+By default, all watchers have a C<void *data> member. By redefining
+this macro to a something else you can include more and other types of
+members. You have to define it each time you include one of the files,
+though, and it must be identical each time.
+
+For example, the perl EV module uses something like this:
+
+ #define EV_COMMON \
+ SV *self; /* contains this struct */ \
+ SV *cb_sv, *fh /* note no trailing ";" */
+
+=item EV_CB_DECLARE (type)
+
+=item EV_CB_INVOKE (watcher, revents)
+
+=item ev_set_cb (ev, cb)
+
+Can be used to change the callback member declaration in each watcher,
+and the way callbacks are invoked and set. Must expand to a struct member
+definition and a statement, respectively. See the F<ev.h> header file for
+their default definitions. One possible use for overriding these is to
+avoid the C<struct ev_loop *> as first argument in all cases, or to use
+method calls instead of plain function calls in C++.
+
+=head2 EXPORTED API SYMBOLS
+
+If you need to re-export the API (e.g. via a dll) and you need a list of
+exported symbols, you can use the provided F<Symbol.*> files which list
+all public symbols, one per line:
+
+ Symbols.ev for libev proper
+ Symbols.event for the libevent emulation
+
+This can also be used to rename all public symbols to avoid clashes with
+multiple versions of libev linked together (which is obviously bad in
+itself, but sometimes it is inconvinient to avoid this).
+
+A sed command like this will create wrapper C<#define>'s that you need to
+include before including F<ev.h>:
+
+ <Symbols.ev sed -e "s/.*/#define & myprefix_&/" >wrap.h
+
+This would create a file F<wrap.h> which essentially looks like this:
+
+ #define ev_backend myprefix_ev_backend
+ #define ev_check_start myprefix_ev_check_start
+ #define ev_check_stop myprefix_ev_check_stop
+ ...
+
+=head2 EXAMPLES
+
+For a real-world example of a program the includes libev
+verbatim, you can have a look at the EV perl module
+(L<http://software.schmorp.de/pkg/EV.html>). It has the libev files in
+the F<libev/> subdirectory and includes them in the F<EV/EVAPI.h> (public
+interface) and F<EV.xs> (implementation) files. Only the F<EV.xs> file
+will be compiled. It is pretty complex because it provides its own header
+file.
+
+The usage in rxvt-unicode is simpler. It has a F<ev_cpp.h> header file
+that everybody includes and which overrides some configure choices:
+
+ #define EV_MINIMAL 1
+ #define EV_USE_POLL 0
+ #define EV_MULTIPLICITY 0
+ #define EV_PERIODIC_ENABLE 0
+ #define EV_STAT_ENABLE 0
+ #define EV_FORK_ENABLE 0
+ #define EV_CONFIG_H <config.h>
+ #define EV_MINPRI 0
+ #define EV_MAXPRI 0
+
+ #include "ev++.h"
+
+And a F<ev_cpp.C> implementation file that contains libev proper and is compiled:
+
+ #include "ev_cpp.h"
+ #include "ev.c"
+
+
+=head1 COMPLEXITIES
+
+In this section the complexities of (many of) the algorithms used inside
+libev will be explained. For complexity discussions about backends see the
+documentation for C<ev_default_init>.
+
+All of the following are about amortised time: If an array needs to be
+extended, libev needs to realloc and move the whole array, but this
+happens asymptotically never with higher number of elements, so O(1) might
+mean it might do a lengthy realloc operation in rare cases, but on average
+it is much faster and asymptotically approaches constant time.
+
+=over 4
+
+=item Starting and stopping timer/periodic watchers: O(log skipped_other_timers)
+
+This means that, when you have a watcher that triggers in one hour and
+there are 100 watchers that would trigger before that then inserting will
+have to skip roughly seven (C<ld 100>) of these watchers.
+
+=item Changing timer/periodic watchers (by autorepeat or calling again): O(log skipped_other_timers)
+
+That means that changing a timer costs less than removing/adding them
+as only the relative motion in the event queue has to be paid for.
+
+=item Starting io/check/prepare/idle/signal/child watchers: O(1)
+
+These just add the watcher into an array or at the head of a list.
+
+=item Stopping check/prepare/idle watchers: O(1)
+
+=item Stopping an io/signal/child watcher: O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE))
+
+These watchers are stored in lists then need to be walked to find the
+correct watcher to remove. The lists are usually short (you don't usually
+have many watchers waiting for the same fd or signal).
+
+=item Finding the next timer in each loop iteration: O(1)
+
+By virtue of using a binary heap, the next timer is always found at the
+beginning of the storage array.
+
+=item Each change on a file descriptor per loop iteration: O(number_of_watchers_for_this_fd)
+
+A change means an I/O watcher gets started or stopped, which requires
+libev to recalculate its status (and possibly tell the kernel, depending
+on backend and wether C<ev_io_set> was used).
+
+=item Activating one watcher (putting it into the pending state): O(1)
+
+=item Priority handling: O(number_of_priorities)
+
+Priorities are implemented by allocating some space for each
+priority. When doing priority-based operations, libev usually has to
+linearly search all the priorities, but starting/stopping and activating
+watchers becomes O(1) w.r.t. prioritiy handling.
+
+=back
+
+
+=head1 Win32 platform limitations and workarounds
+
+Win32 doesn't support any of the standards (e.g. POSIX) that libev
+requires, and its I/O model is fundamentally incompatible with the POSIX
+model. Libev still offers limited functionality on this platform in
+the form of the C<EVBACKEND_SELECT> backend, and only supports socket
+descriptors. This only applies when using Win32 natively, not when using
+e.g. cygwin.
+
+There is no supported compilation method available on windows except
+embedding it into other applications.
+
+Due to the many, low, and arbitrary limits on the win32 platform and the
+abysmal performance of winsockets, using a large number of sockets is not
+recommended (and not reasonable). If your program needs to use more than
+a hundred or so sockets, then likely it needs to use a totally different
+implementation for windows, as libev offers the POSIX model, which cannot
+be implemented efficiently on windows (microsoft monopoly games).
+
+=over 4
+
+=item The winsocket select function
+
+The winsocket C<select> function doesn't follow POSIX in that it requires
+socket I<handles> and not socket I<file descriptors>. This makes select
+very inefficient, and also requires a mapping from file descriptors
+to socket handles. See the discussion of the C<EV_SELECT_USE_FD_SET>,
+C<EV_SELECT_IS_WINSOCKET> and C<EV_FD_TO_WIN32_HANDLE> preprocessor
+symbols for more info.
+
+The configuration for a "naked" win32 using the microsoft runtime
+libraries and raw winsocket select is:
+
+ #define EV_USE_SELECT 1
+ #define EV_SELECT_IS_WINSOCKET 1 /* forces EV_SELECT_USE_FD_SET, too */
+
+Note that winsockets handling of fd sets is O(n), so you can easily get a
+complexity in the O(n²) range when using win32.
+
+=item Limited number of file descriptors
+
+Windows has numerous arbitrary (and low) limits on things. Early versions
+of winsocket's select only supported waiting for a max. of C<64> handles
+(probably owning to the fact that all windows kernels can only wait for
+C<64> things at the same time internally; microsoft recommends spawning a
+chain of threads and wait for 63 handles and the previous thread in each).
+
+Newer versions support more handles, but you need to define C<FD_SETSIZE>
+to some high number (e.g. C<2048>) before compiling the winsocket select
+call (which might be in libev or elsewhere, for example, perl does its own
+select emulation on windows).
+
+Another limit is the number of file descriptors in the microsoft runtime
+libraries, which by default is C<64> (there must be a hidden I<64> fetish
+or something like this inside microsoft). You can increase this by calling
+C<_setmaxstdio>, which can increase this limit to C<2048> (another
+arbitrary limit), but is broken in many versions of the microsoft runtime
+libraries.
+
+This might get you to about C<512> or C<2048> sockets (depending on
+windows version and/or the phase of the moon). To get more, you need to
+wrap all I/O functions and provide your own fd management, but the cost of
+calling select (O(n²)) will likely make this unworkable.
+
+=back