1libev::ev(3)          User Contributed Perl Documentation         libev::ev(3)
2
3
4

NAME

6       libev - a high performance full-featured event loop written in C
7

SYNOPSIS

9          #include <ev.h>
10
11   EXAMPLE PROGRAM
12          // a single header file is required
13          #include <ev.h>
14
15          #include <stdio.h> // for puts
16
17          // every watcher type has its own typedef'd struct
18          // with the name ev_TYPE
19          ev_io stdin_watcher;
20          ev_timer timeout_watcher;
21
22          // all watcher callbacks have a similar signature
23          // this callback is called when data is readable on stdin
24          static void
25          stdin_cb (EV_P_ ev_io *w, int revents)
26          {
27            puts ("stdin ready");
28            // for one-shot events, one must manually stop the watcher
29            // with its corresponding stop function.
30            ev_io_stop (EV_A_ w);
31
32            // this causes all nested ev_run's to stop iterating
33            ev_break (EV_A_ EVBREAK_ALL);
34          }
35
36          // another callback, this time for a time-out
37          static void
38          timeout_cb (EV_P_ ev_timer *w, int revents)
39          {
40            puts ("timeout");
41            // this causes the innermost ev_run to stop iterating
42            ev_break (EV_A_ EVBREAK_ONE);
43          }
44
45          int
46          main (void)
47          {
48            // use the default event loop unless you have special needs
49            struct ev_loop *loop = EV_DEFAULT;
50
51            // initialise an io watcher, then start it
52            // this one will watch for stdin to become readable
53            ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
54            ev_io_start (loop, &stdin_watcher);
55
56            // initialise a timer watcher, then start it
57            // simple non-repeating 5.5 second timeout
58            ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
59            ev_timer_start (loop, &timeout_watcher);
60
61            // now wait for events to arrive
62            ev_run (loop, 0);
63
64            // break was called, so exit
65            return 0;
66          }
67

ABOUT THIS DOCUMENT

69       This document documents the libev software package.
70
71       The newest version of this document is also available as an html-
72       formatted web page you might find easier to navigate when reading it
73       for the first time:
74       <http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod>.
75
76       While this document tries to be as complete as possible in documenting
77       libev, its usage and the rationale behind its design, it is not a
78       tutorial on event-based programming, nor will it introduce event-based
79       programming with libev.
80
81       Familiarity with event based programming techniques in general is
82       assumed throughout this document.
83

WHAT TO READ WHEN IN A HURRY

85       This manual tries to be very detailed, but unfortunately, this also
86       makes it very long. If you just want to know the basics of libev, I
87       suggest reading "ANATOMY OF A WATCHER", then the "EXAMPLE PROGRAM"
88       above and look up the missing functions in "GLOBAL FUNCTIONS" and the
89       "ev_io" and "ev_timer" sections in "WATCHER TYPES".
90

ABOUT LIBEV

92       Libev is an event loop: you register interest in certain events (such
93       as a file descriptor being readable or a timeout occurring), and it
94       will manage these event sources and provide your program with events.
95
96       To do this, it must take more or less complete control over your
97       process (or thread) by executing the event loop handler, and will then
98       communicate events via a callback mechanism.
99
100       You register interest in certain events by registering so-called event
101       watchers, which are relatively small C structures you initialise with
102       the details of the event, and then hand it over to libev by starting
103       the watcher.
104
105   FEATURES
106       Libev supports "select", "poll", the Linux-specific aio and "epoll"
107       interfaces, the BSD-specific "kqueue" and the Solaris-specific event
108       port mechanisms for file descriptor events ("ev_io"), the Linux
109       "inotify" interface (for "ev_stat"), Linux eventfd/signalfd (for faster
110       and cleaner inter-thread wakeup ("ev_async")/signal handling
111       ("ev_signal")) relative timers ("ev_timer"), absolute timers with
112       customised rescheduling ("ev_periodic"), synchronous signals
113       ("ev_signal"), process status change events ("ev_child"), and event
114       watchers dealing with the event loop mechanism itself ("ev_idle",
115       "ev_embed", "ev_prepare" and "ev_check" watchers) as well as file
116       watchers ("ev_stat") and even limited support for fork events
117       ("ev_fork").
118
119       It also is quite fast (see this benchmark
120       <http://libev.schmorp.de/bench.html> comparing it to libevent for
121       example).
122
123   CONVENTIONS
124       Libev is very configurable. In this manual the default (and most
125       common) configuration will be described, which supports multiple event
126       loops. For more info about various configuration options please have a
127       look at EMBED section in this manual. If libev was configured without
128       support for multiple event loops, then all functions taking an initial
129       argument of name "loop" (which is always of type "struct ev_loop *")
130       will not have this argument.
131
132   TIME REPRESENTATION
133       Libev represents time as a single floating point number, representing
134       the (fractional) number of seconds since the (POSIX) epoch (in practice
135       somewhere near the beginning of 1970, details are complicated, don't
136       ask). This type is called "ev_tstamp", which is what you should use
137       too. It usually aliases to the "double" type in C. When you need to do
138       any calculations on it, you should treat it as some floating point
139       value.
140
141       Unlike the name component "stamp" might indicate, it is also used for
142       time differences (e.g. delays) throughout libev.
143

ERROR HANDLING

145       Libev knows three classes of errors: operating system errors, usage
146       errors and internal errors (bugs).
147
148       When libev catches an operating system error it cannot handle (for
149       example a system call indicating a condition libev cannot fix), it
150       calls the callback set via "ev_set_syserr_cb", which is supposed to fix
151       the problem or abort. The default is to print a diagnostic message and
152       to call "abort ()".
153
154       When libev detects a usage error such as a negative timer interval,
155       then it will print a diagnostic message and abort (via the "assert"
156       mechanism, so "NDEBUG" will disable this checking): these are
157       programming errors in the libev caller and need to be fixed there.
158
159       Via the "EV_FREQUENT" macro you can compile in and/or enable extensive
160       consistency checking code inside libev that can be used to check for
161       internal inconsistencies, suually caused by application bugs.
162
163       Libev also has a few internal error-checking "assert"ions. These do not
164       trigger under normal circumstances, as they indicate either a bug in
165       libev or worse.
166

GLOBAL FUNCTIONS

168       These functions can be called anytime, even before initialising the
169       library in any way.
170
171       ev_tstamp ev_time ()
172           Returns the current time as libev would use it. Please note that
173           the "ev_now" function is usually faster and also often returns the
174           timestamp you actually want to know. Also interesting is the
175           combination of "ev_now_update" and "ev_now".
176
177       ev_sleep (ev_tstamp interval)
178           Sleep for the given interval: The current thread will be blocked
179           until either it is interrupted or the given time interval has
180           passed (approximately - it might return a bit earlier even if not
181           interrupted). Returns immediately if "interval <= 0".
182
183           Basically this is a sub-second-resolution "sleep ()".
184
185           The range of the "interval" is limited - libev only guarantees to
186           work with sleep times of up to one day ("interval <= 86400").
187
188       int ev_version_major ()
189       int ev_version_minor ()
190           You can find out the major and minor ABI version numbers of the
191           library you linked against by calling the functions
192           "ev_version_major" and "ev_version_minor". If you want, you can
193           compare against the global symbols "EV_VERSION_MAJOR" and
194           "EV_VERSION_MINOR", which specify the version of the library your
195           program was compiled against.
196
197           These version numbers refer to the ABI version of the library, not
198           the release version.
199
200           Usually, it's a good idea to terminate if the major versions
201           mismatch, as this indicates an incompatible change. Minor versions
202           are usually compatible to older versions, so a larger minor version
203           alone is usually not a problem.
204
205           Example: Make sure we haven't accidentally been linked against the
206           wrong version (note, however, that this will not detect other ABI
207           mismatches, such as LFS or reentrancy).
208
209              assert (("libev version mismatch",
210                       ev_version_major () == EV_VERSION_MAJOR
211                       && ev_version_minor () >= EV_VERSION_MINOR));
212
213       unsigned int ev_supported_backends ()
214           Return the set of all backends (i.e. their corresponding
215           "EV_BACKEND_*" value) compiled into this binary of libev
216           (independent of their availability on the system you are running
217           on). See "ev_default_loop" for a description of the set values.
218
219           Example: make sure we have the epoll method, because yeah this is
220           cool and a must have and can we have a torrent of it please!!!11
221
222              assert (("sorry, no epoll, no sex",
223                       ev_supported_backends () & EVBACKEND_EPOLL));
224
225       unsigned int ev_recommended_backends ()
226           Return the set of all backends compiled into this binary of libev
227           and also recommended for this platform, meaning it will work for
228           most file descriptor types. This set is often smaller than the one
229           returned by "ev_supported_backends", as for example kqueue is
230           broken on most BSDs and will not be auto-detected unless you
231           explicitly request it (assuming you know what you are doing). This
232           is the set of backends that libev will probe for if you specify no
233           backends explicitly.
234
235       unsigned int ev_embeddable_backends ()
236           Returns the set of backends that are embeddable in other event
237           loops. This value is platform-specific but can include backends not
238           available on the current system. To find which embeddable backends
239           might be supported on the current system, you would need to look at
240           "ev_embeddable_backends () & ev_supported_backends ()", likewise
241           for recommended ones.
242
243           See the description of "ev_embed" watchers for more info.
244
245       ev_set_allocator (void *(*cb)(void *ptr, long size) throw ())
246           Sets the allocation function to use (the prototype is similar - the
247           semantics are identical to the "realloc" C89/SuS/POSIX function).
248           It is used to allocate and free memory (no surprises here). If it
249           returns zero when memory needs to be allocated ("size != 0"), the
250           library might abort or take some potentially destructive action.
251
252           Since some systems (at least OpenBSD and Darwin) fail to implement
253           correct "realloc" semantics, libev will use a wrapper around the
254           system "realloc" and "free" functions by default.
255
256           You could override this function in high-availability programs to,
257           say, free some memory if it cannot allocate memory, to use a
258           special allocator, or even to sleep a while and retry until some
259           memory is available.
260
261           Example: The following is the "realloc" function that libev itself
262           uses which should work with "realloc" and "free" functions of all
263           kinds and is probably a good basis for your own implementation.
264
265              static void *
266              ev_realloc_emul (void *ptr, long size) EV_NOEXCEPT
267              {
268                if (size)
269                  return realloc (ptr, size);
270
271                free (ptr);
272                return 0;
273              }
274
275           Example: Replace the libev allocator with one that waits a bit and
276           then retries.
277
278              static void *
279              persistent_realloc (void *ptr, size_t size)
280              {
281                if (!size)
282                  {
283                    free (ptr);
284                    return 0;
285                  }
286
287                for (;;)
288                  {
289                    void *newptr = realloc (ptr, size);
290
291                    if (newptr)
292                      return newptr;
293
294                    sleep (60);
295                  }
296              }
297
298              ...
299              ev_set_allocator (persistent_realloc);
300
301       ev_set_syserr_cb (void (*cb)(const char *msg) throw ())
302           Set the callback function to call on a retryable system call error
303           (such as failed select, poll, epoll_wait). The message is a
304           printable string indicating the system call or subsystem causing
305           the problem. If this callback is set, then libev will expect it to
306           remedy the situation, no matter what, when it returns. That is,
307           libev will generally retry the requested operation, or, if the
308           condition doesn't go away, do bad stuff (such as abort).
309
310           Example: This is basically the same thing that libev does
311           internally, too.
312
313              static void
314              fatal_error (const char *msg)
315              {
316                perror (msg);
317                abort ();
318              }
319
320              ...
321              ev_set_syserr_cb (fatal_error);
322
323       ev_feed_signal (int signum)
324           This function can be used to "simulate" a signal receive. It is
325           completely safe to call this function at any time, from any
326           context, including signal handlers or random threads.
327
328           Its main use is to customise signal handling in your process,
329           especially in the presence of threads. For example, you could block
330           signals by default in all threads (and specifying
331           "EVFLAG_NOSIGMASK" when creating any loops), and in one thread, use
332           "sigwait" or any other mechanism to wait for signals, then
333           "deliver" them to libev by calling "ev_feed_signal".
334

FUNCTIONS CONTROLLING EVENT LOOPS

336       An event loop is described by a "struct ev_loop *" (the "struct" is not
337       optional in this case unless libev 3 compatibility is disabled, as
338       libev 3 had an "ev_loop" function colliding with the struct name).
339
340       The library knows two types of such loops, the default loop, which
341       supports child process events, and dynamically created event loops
342       which do not.
343
344       struct ev_loop *ev_default_loop (unsigned int flags)
345           This returns the "default" event loop object, which is what you
346           should normally use when you just need "the event loop". Event loop
347           objects and the "flags" parameter are described in more detail in
348           the entry for "ev_loop_new".
349
350           If the default loop is already initialised then this function
351           simply returns it (and ignores the flags. If that is troubling you,
352           check "ev_backend ()" afterwards). Otherwise it will create it with
353           the given flags, which should almost always be 0, unless the caller
354           is also the one calling "ev_run" or otherwise qualifies as "the
355           main program".
356
357           If you don't know what event loop to use, use the one returned from
358           this function (or via the "EV_DEFAULT" macro).
359
360           Note that this function is not thread-safe, so if you want to use
361           it from multiple threads, you have to employ some kind of mutex
362           (note also that this case is unlikely, as loops cannot be shared
363           easily between threads anyway).
364
365           The default loop is the only loop that can handle "ev_child"
366           watchers, and to do this, it always registers a handler for
367           "SIGCHLD". If this is a problem for your application you can either
368           create a dynamic loop with "ev_loop_new" which doesn't do that, or
369           you can simply overwrite the "SIGCHLD" signal handler after calling
370           "ev_default_init".
371
372           Example: This is the most typical usage.
373
374              if (!ev_default_loop (0))
375                fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?");
376
377           Example: Restrict libev to the select and poll backends, and do not
378           allow environment settings to be taken into account:
379
380              ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV);
381
382       struct ev_loop *ev_loop_new (unsigned int flags)
383           This will create and initialise a new event loop object. If the
384           loop could not be initialised, returns false.
385
386           This function is thread-safe, and one common way to use libev with
387           threads is indeed to create one loop per thread, and using the
388           default loop in the "main" or "initial" thread.
389
390           The flags argument can be used to specify special behaviour or
391           specific backends to use, and is usually specified as 0 (or
392           "EVFLAG_AUTO").
393
394           The following flags are supported:
395
396           "EVFLAG_AUTO"
397               The default flags value. Use this if you have no clue (it's the
398               right thing, believe me).
399
400           "EVFLAG_NOENV"
401               If this flag bit is or'ed into the flag value (or the program
402               runs setuid or setgid) then libev will not look at the
403               environment variable "LIBEV_FLAGS". Otherwise (the default),
404               this environment variable will override the flags completely if
405               it is found in the environment. This is useful to try out
406               specific backends to test their performance, to work around
407               bugs, or to make libev threadsafe (accessing environment
408               variables cannot be done in a threadsafe way, but usually it
409               works if no other thread modifies them).
410
411           "EVFLAG_FORKCHECK"
412               Instead of calling "ev_loop_fork" manually after a fork, you
413               can also make libev check for a fork in each iteration by
414               enabling this flag.
415
416               This works by calling "getpid ()" on every iteration of the
417               loop, and thus this might slow down your event loop if you do a
418               lot of loop iterations and little real work, but is usually not
419               noticeable (on my GNU/Linux system for example, "getpid" is
420               actually a simple 5-insn sequence without a system call and
421               thus very fast, but my GNU/Linux system also has
422               "pthread_atfork" which is even faster). (Update: glibc versions
423               2.25 apparently removed the "getpid" optimisation again).
424
425               The big advantage of this flag is that you can forget about
426               fork (and forget about forgetting to tell libev about forking,
427               although you still have to ignore "SIGPIPE") when you use this
428               flag.
429
430               This flag setting cannot be overridden or specified in the
431               "LIBEV_FLAGS" environment variable.
432
433           "EVFLAG_NOINOTIFY"
434               When this flag is specified, then libev will not attempt to use
435               the inotify API for its "ev_stat" watchers. Apart from
436               debugging and testing, this flag can be useful to conserve
437               inotify file descriptors, as otherwise each loop using
438               "ev_stat" watchers consumes one inotify handle.
439
440           "EVFLAG_SIGNALFD"
441               When this flag is specified, then libev will attempt to use the
442               signalfd API for its "ev_signal" (and "ev_child") watchers.
443               This API delivers signals synchronously, which makes it both
444               faster and might make it possible to get the queued signal
445               data. It can also simplify signal handling with threads, as
446               long as you properly block signals in your threads that are not
447               interested in handling them.
448
449               Signalfd will not be used by default as this changes your
450               signal mask, and there are a lot of shoddy libraries and
451               programs (glib's threadpool for example) that can't properly
452               initialise their signal masks.
453
454           "EVFLAG_NOSIGMASK"
455               When this flag is specified, then libev will avoid to modify
456               the signal mask. Specifically, this means you have to make sure
457               signals are unblocked when you want to receive them.
458
459               This behaviour is useful when you want to do your own signal
460               handling, or want to handle signals only in specific threads
461               and want to avoid libev unblocking the signals.
462
463               It's also required by POSIX in a threaded program, as libev
464               calls "sigprocmask", whose behaviour is officially unspecified.
465
466               This flag's behaviour will become the default in future
467               versions of libev.
468
469           "EVBACKEND_SELECT"  (value 1, portable select backend)
470               This is your standard select(2) backend. Not completely
471               standard, as libev tries to roll its own fd_set with no limits
472               on the number of fds, but if that fails, expect a fairly low
473               limit on the number of fds when using this backend. It doesn't
474               scale too well (O(highest_fd)), but its usually the fastest
475               backend for a low number of (low-numbered :) fds.
476
477               To get good performance out of this backend you need a high
478               amount of parallelism (most of the file descriptors should be
479               busy). If you are writing a server, you should "accept ()" in a
480               loop to accept as many connections as possible during one
481               iteration. You might also want to have a look at
482               "ev_set_io_collect_interval ()" to increase the amount of
483               readiness notifications you get per iteration.
484
485               This backend maps "EV_READ" to the "readfds" set and "EV_WRITE"
486               to the "writefds" set (and to work around Microsoft Windows
487               bugs, also onto the "exceptfds" set on that platform).
488
489           "EVBACKEND_POLL"    (value 2, poll backend, available everywhere
490           except on windows)
491               And this is your standard poll(2) backend. It's more
492               complicated than select, but handles sparse fds better and has
493               no artificial limit on the number of fds you can use (except it
494               will slow down considerably with a lot of inactive fds). It
495               scales similarly to select, i.e. O(total_fds). See the entry
496               for "EVBACKEND_SELECT", above, for performance tips.
497
498               This backend maps "EV_READ" to "POLLIN | POLLERR | POLLHUP",
499               and "EV_WRITE" to "POLLOUT | POLLERR | POLLHUP".
500
501           "EVBACKEND_EPOLL"   (value 4, Linux)
502               Use the Linux-specific epoll(7) interface (for both pre- and
503               post-2.6.9 kernels).
504
505               For few fds, this backend is a bit little slower than poll and
506               select, but it scales phenomenally better. While poll and
507               select usually scale like O(total_fds) where total_fds is the
508               total number of fds (or the highest fd), epoll scales either
509               O(1) or O(active_fds).
510
511               The epoll mechanism deserves honorable mention as the most
512               misdesigned of the more advanced event mechanisms: mere
513               annoyances include silently dropping file descriptors,
514               requiring a system call per change per file descriptor (and
515               unnecessary guessing of parameters), problems with dup,
516               returning before the timeout value, resulting in additional
517               iterations (and only giving 5ms accuracy while select on the
518               same platform gives 0.1ms) and so on. The biggest issue is fork
519               races, however - if a program forks then both parent and child
520               process have to recreate the epoll set, which can take
521               considerable time (one syscall per file descriptor) and is of
522               course hard to detect.
523
524               Epoll is also notoriously buggy - embedding epoll fds should
525               work, but of course doesn't, and epoll just loves to report
526               events for totally different file descriptors (even already
527               closed ones, so one cannot even remove them from the set) than
528               registered in the set (especially on SMP systems). Libev tries
529               to counter these spurious notifications by employing an
530               additional generation counter and comparing that against the
531               events to filter out spurious ones, recreating the set when
532               required. Epoll also erroneously rounds down timeouts, but
533               gives you no way to know when and by how much, so sometimes you
534               have to busy-wait because epoll returns immediately despite a
535               nonzero timeout. And last not least, it also refuses to work
536               with some file descriptors which work perfectly fine with
537               "select" (files, many character devices...).
538
539               Epoll is truly the train wreck among event poll mechanisms, a
540               frankenpoll, cobbled together in a hurry, no thought to design
541               or interaction with others. Oh, the pain, will it ever stop...
542
543               While stopping, setting and starting an I/O watcher in the same
544               iteration will result in some caching, there is still a system
545               call per such incident (because the same file descriptor could
546               point to a different file description now), so its best to
547               avoid that. Also, "dup ()"'ed file descriptors might not work
548               very well if you register events for both file descriptors.
549
550               Best performance from this backend is achieved by not
551               unregistering all watchers for a file descriptor until it has
552               been closed, if possible, i.e. keep at least one watcher active
553               per fd at all times. Stopping and starting a watcher (without
554               re-setting it) also usually doesn't cause extra overhead. A
555               fork can both result in spurious notifications as well as in
556               libev having to destroy and recreate the epoll object, which
557               can take considerable time and thus should be avoided.
558
559               All this means that, in practice, "EVBACKEND_SELECT" can be as
560               fast or faster than epoll for maybe up to a hundred file
561               descriptors, depending on the usage. So sad.
562
563               While nominally embeddable in other event loops, this feature
564               is broken in a lot of kernel revisions, but probably(!) works
565               in current versions.
566
567               This backend maps "EV_READ" and "EV_WRITE" in the same way as
568               "EVBACKEND_POLL".
569
570           "EVBACKEND_LINUXAIO"   (value 64, Linux)
571               Use the Linux-specific Linux AIO (not aio(7) but io_submit(2))
572               event interface available in post-4.18 kernels (but libev only
573               tries to use it in 4.19+).
574
575               This is another Linux train wreck of an event interface.
576
577               If this backend works for you (as of this writing, it was very
578               experimental), it is the best event interface available on
579               Linux and might be well worth enabling it - if it isn't
580               available in your kernel this will be detected and this backend
581               will be skipped.
582
583               This backend can batch oneshot requests and supports a user-
584               space ring buffer to receive events. It also doesn't suffer
585               from most of the design problems of epoll (such as not being
586               able to remove event sources from the epoll set), and generally
587               sounds too good to be true. Because, this being the Linux
588               kernel, of course it suffers from a whole new set of
589               limitations, forcing you to fall back to epoll, inheriting all
590               its design issues.
591
592               For one, it is not easily embeddable (but probably could be
593               done using an event fd at some extra overhead). It also is
594               subject to a system wide limit that can be configured in
595               /proc/sys/fs/aio-max-nr. If no AIO requests are left, this
596               backend will be skipped during initialisation, and will switch
597               to epoll when the loop is active.
598
599               Most problematic in practice, however, is that not all file
600               descriptors work with it. For example, in Linux 5.1, TCP
601               sockets, pipes, event fds, files, /dev/null and many others are
602               supported, but ttys do not work properly (a known bug that the
603               kernel developers don't care about, see
604               <https://lore.kernel.org/patchwork/patch/1047453/>), so this is
605               not (yet?) a generic event polling interface.
606
607               Overall, it seems the Linux developers just don't want it to
608               have a generic event handling mechanism other than "select" or
609               "poll".
610
611               To work around all these problem, the current version of libev
612               uses its epoll backend as a fallback for file descriptor types
613               that do not work. Or falls back completely to epoll if the
614               kernel acts up.
615
616               This backend maps "EV_READ" and "EV_WRITE" in the same way as
617               "EVBACKEND_POLL".
618
619           "EVBACKEND_KQUEUE"  (value 8, most BSD clones)
620               Kqueue deserves special mention, as at the time this backend
621               was implemented, it was broken on all BSDs except NetBSD
622               (usually it doesn't work reliably with anything but sockets and
623               pipes, except on Darwin, where of course it's completely
624               useless). Unlike epoll, however, whose brokenness is by design,
625               these kqueue bugs can be (and mostly have been) fixed without
626               API changes to existing programs. For this reason it's not
627               being "auto-detected" on all platforms unless you explicitly
628               specify it in the flags (i.e. using "EVBACKEND_KQUEUE") or
629               libev was compiled on a known-to-be-good (-enough) system like
630               NetBSD.
631
632               You still can embed kqueue into a normal poll or select backend
633               and use it only for sockets (after having made sure that
634               sockets work with kqueue on the target platform). See
635               "ev_embed" watchers for more info.
636
637               It scales in the same way as the epoll backend, but the
638               interface to the kernel is more efficient (which says nothing
639               about its actual speed, of course). While stopping, setting and
640               starting an I/O watcher does never cause an extra system call
641               as with "EVBACKEND_EPOLL", it still adds up to two event
642               changes per incident. Support for "fork ()" is very bad (you
643               might have to leak fds on fork, but it's more sane than epoll)
644               and it drops fds silently in similarly hard-to-detect cases.
645
646               This backend usually performs well under most conditions.
647
648               While nominally embeddable in other event loops, this doesn't
649               work everywhere, so you might need to test for this. And since
650               it is broken almost everywhere, you should only use it when you
651               have a lot of sockets (for which it usually works), by
652               embedding it into another event loop (e.g. "EVBACKEND_SELECT"
653               or "EVBACKEND_POLL" (but "poll" is of course also broken on OS
654               X)) and, did I mention it, using it only for sockets.
655
656               This backend maps "EV_READ" into an "EVFILT_READ" kevent with
657               "NOTE_EOF", and "EV_WRITE" into an "EVFILT_WRITE" kevent with
658               "NOTE_EOF".
659
660           "EVBACKEND_DEVPOLL" (value 16, Solaris 8)
661               This is not implemented yet (and might never be, unless you
662               send me an implementation). According to reports, "/dev/poll"
663               only supports sockets and is not embeddable, which would limit
664               the usefulness of this backend immensely.
665
666           "EVBACKEND_PORT"    (value 32, Solaris 10)
667               This uses the Solaris 10 event port mechanism. As with
668               everything on Solaris, it's really slow, but it still scales
669               very well (O(active_fds)).
670
671               While this backend scales well, it requires one system call per
672               active file descriptor per loop iteration. For small and medium
673               numbers of file descriptors a "slow" "EVBACKEND_SELECT" or
674               "EVBACKEND_POLL" backend might perform better.
675
676               On the positive side, this backend actually performed fully to
677               specification in all tests and is fully embeddable, which is a
678               rare feat among the OS-specific backends (I vastly prefer
679               correctness over speed hacks).
680
681               On the negative side, the interface is bizarre - so bizarre
682               that even sun itself gets it wrong in their code examples: The
683               event polling function sometimes returns events to the caller
684               even though an error occurred, but with no indication whether
685               it has done so or not (yes, it's even documented that way) -
686               deadly for edge-triggered interfaces where you absolutely have
687               to know whether an event occurred or not because you have to
688               re-arm the watcher.
689
690               Fortunately libev seems to be able to work around these
691               idiocies.
692
693               This backend maps "EV_READ" and "EV_WRITE" in the same way as
694               "EVBACKEND_POLL".
695
696           "EVBACKEND_ALL"
697               Try all backends (even potentially broken ones that wouldn't be
698               tried with "EVFLAG_AUTO"). Since this is a mask, you can do
699               stuff such as "EVBACKEND_ALL & ~EVBACKEND_KQUEUE".
700
701               It is definitely not recommended to use this flag, use whatever
702               "ev_recommended_backends ()" returns, or simply do not specify
703               a backend at all.
704
705           "EVBACKEND_MASK"
706               Not a backend at all, but a mask to select all backend bits
707               from a "flags" value, in case you want to mask out any backends
708               from a flags value (e.g. when modifying the "LIBEV_FLAGS"
709               environment variable).
710
711           If one or more of the backend flags are or'ed into the flags value,
712           then only these backends will be tried (in the reverse order as
713           listed here). If none are specified, all backends in
714           "ev_recommended_backends ()" will be tried.
715
716           Example: Try to create a event loop that uses epoll and nothing
717           else.
718
719              struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV);
720              if (!epoller)
721                fatal ("no epoll found here, maybe it hides under your chair");
722
723           Example: Use whatever libev has to offer, but make sure that kqueue
724           is used if available.
725
726              struct ev_loop *loop = ev_loop_new (ev_recommended_backends () | EVBACKEND_KQUEUE);
727
728           Example: Similarly, on linux, you mgiht want to take advantage of
729           the linux aio backend if possible, but fall back to something else
730           if that isn't available.
731
732              struct ev_loop *loop = ev_loop_new (ev_recommended_backends () | EVBACKEND_LINUXAIO);
733
734       ev_loop_destroy (loop)
735           Destroys an event loop object (frees all memory and kernel state
736           etc.). None of the active event watchers will be stopped in the
737           normal sense, so e.g. "ev_is_active" might still return true. It is
738           your responsibility to either stop all watchers cleanly yourself
739           before calling this function, or cope with the fact afterwards
740           (which is usually the easiest thing, you can just ignore the
741           watchers and/or "free ()" them for example).
742
743           Note that certain global state, such as signal state (and installed
744           signal handlers), will not be freed by this function, and related
745           watchers (such as signal and child watchers) would need to be
746           stopped manually.
747
748           This function is normally used on loop objects allocated by
749           "ev_loop_new", but it can also be used on the default loop returned
750           by "ev_default_loop", in which case it is not thread-safe.
751
752           Note that it is not advisable to call this function on the default
753           loop except in the rare occasion where you really need to free its
754           resources.  If you need dynamically allocated loops it is better to
755           use "ev_loop_new" and "ev_loop_destroy".
756
757       ev_loop_fork (loop)
758           This function sets a flag that causes subsequent "ev_run"
759           iterations to reinitialise the kernel state for backends that have
760           one. Despite the name, you can call it anytime you are allowed to
761           start or stop watchers (except inside an "ev_prepare" callback),
762           but it makes most sense after forking, in the child process. You
763           must call it (or use "EVFLAG_FORKCHECK") in the child before
764           resuming or calling "ev_run".
765
766           In addition, if you want to reuse a loop (via this function or
767           "EVFLAG_FORKCHECK"), you also have to ignore "SIGPIPE".
768
769           Again, you have to call it on any loop that you want to re-use
770           after a fork, even if you do not plan to use the loop in the
771           parent. This is because some kernel interfaces *cough* kqueue
772           *cough* do funny things during fork.
773
774           On the other hand, you only need to call this function in the child
775           process if and only if you want to use the event loop in the child.
776           If you just fork+exec or create a new loop in the child, you don't
777           have to call it at all (in fact, "epoll" is so badly broken that it
778           makes a difference, but libev will usually detect this case on its
779           own and do a costly reset of the backend).
780
781           The function itself is quite fast and it's usually not a problem to
782           call it just in case after a fork.
783
784           Example: Automate calling "ev_loop_fork" on the default loop when
785           using pthreads.
786
787              static void
788              post_fork_child (void)
789              {
790                ev_loop_fork (EV_DEFAULT);
791              }
792
793              ...
794              pthread_atfork (0, 0, post_fork_child);
795
796       int ev_is_default_loop (loop)
797           Returns true when the given loop is, in fact, the default loop, and
798           false otherwise.
799
800       unsigned int ev_iteration (loop)
801           Returns the current iteration count for the event loop, which is
802           identical to the number of times libev did poll for new events. It
803           starts at 0 and happily wraps around with enough iterations.
804
805           This value can sometimes be useful as a generation counter of sorts
806           (it "ticks" the number of loop iterations), as it roughly
807           corresponds with "ev_prepare" and "ev_check" calls - and is
808           incremented between the prepare and check phases.
809
810       unsigned int ev_depth (loop)
811           Returns the number of times "ev_run" was entered minus the number
812           of times "ev_run" was exited normally, in other words, the
813           recursion depth.
814
815           Outside "ev_run", this number is zero. In a callback, this number
816           is 1, unless "ev_run" was invoked recursively (or from another
817           thread), in which case it is higher.
818
819           Leaving "ev_run" abnormally (setjmp/longjmp, cancelling the thread,
820           throwing an exception etc.), doesn't count as "exit" - consider
821           this as a hint to avoid such ungentleman-like behaviour unless it's
822           really convenient, in which case it is fully supported.
823
824       unsigned int ev_backend (loop)
825           Returns one of the "EVBACKEND_*" flags indicating the event backend
826           in use.
827
828       ev_tstamp ev_now (loop)
829           Returns the current "event loop time", which is the time the event
830           loop received events and started processing them. This timestamp
831           does not change as long as callbacks are being processed, and this
832           is also the base time used for relative timers. You can treat it as
833           the timestamp of the event occurring (or more correctly, libev
834           finding out about it).
835
836       ev_now_update (loop)
837           Establishes the current time by querying the kernel, updating the
838           time returned by "ev_now ()" in the progress. This is a costly
839           operation and is usually done automatically within "ev_run ()".
840
841           This function is rarely useful, but when some event callback runs
842           for a very long time without entering the event loop, updating
843           libev's idea of the current time is a good idea.
844
845           See also "The special problem of time updates" in the "ev_timer"
846           section.
847
848       ev_suspend (loop)
849       ev_resume (loop)
850           These two functions suspend and resume an event loop, for use when
851           the loop is not used for a while and timeouts should not be
852           processed.
853
854           A typical use case would be an interactive program such as a game:
855           When the user presses "^Z" to suspend the game and resumes it an
856           hour later it would be best to handle timeouts as if no time had
857           actually passed while the program was suspended. This can be
858           achieved by calling "ev_suspend" in your "SIGTSTP" handler, sending
859           yourself a "SIGSTOP" and calling "ev_resume" directly afterwards to
860           resume timer processing.
861
862           Effectively, all "ev_timer" watchers will be delayed by the time
863           spend between "ev_suspend" and "ev_resume", and all "ev_periodic"
864           watchers will be rescheduled (that is, they will lose any events
865           that would have occurred while suspended).
866
867           After calling "ev_suspend" you must not call any function on the
868           given loop other than "ev_resume", and you must not call
869           "ev_resume" without a previous call to "ev_suspend".
870
871           Calling "ev_suspend"/"ev_resume" has the side effect of updating
872           the event loop time (see "ev_now_update").
873
874       bool ev_run (loop, int flags)
875           Finally, this is it, the event handler. This function usually is
876           called after you have initialised all your watchers and you want to
877           start handling events. It will ask the operating system for any new
878           events, call the watcher callbacks, and then repeat the whole
879           process indefinitely: This is why event loops are called loops.
880
881           If the flags argument is specified as 0, it will keep handling
882           events until either no event watchers are active anymore or
883           "ev_break" was called.
884
885           The return value is false if there are no more active watchers
886           (which usually means "all jobs done" or "deadlock"), and true in
887           all other cases (which usually means " you should call "ev_run"
888           again").
889
890           Please note that an explicit "ev_break" is usually better than
891           relying on all watchers to be stopped when deciding when a program
892           has finished (especially in interactive programs), but having a
893           program that automatically loops as long as it has to and no longer
894           by virtue of relying on its watchers stopping correctly, that is
895           truly a thing of beauty.
896
897           This function is mostly exception-safe - you can break out of a
898           "ev_run" call by calling "longjmp" in a callback, throwing a C++
899           exception and so on. This does not decrement the "ev_depth" value,
900           nor will it clear any outstanding "EVBREAK_ONE" breaks.
901
902           A flags value of "EVRUN_NOWAIT" will look for new events, will
903           handle those events and any already outstanding ones, but will not
904           wait and block your process in case there are no events and will
905           return after one iteration of the loop. This is sometimes useful to
906           poll and handle new events while doing lengthy calculations, to
907           keep the program responsive.
908
909           A flags value of "EVRUN_ONCE" will look for new events (waiting if
910           necessary) and will handle those and any already outstanding ones.
911           It will block your process until at least one new event arrives
912           (which could be an event internal to libev itself, so there is no
913           guarantee that a user-registered callback will be called), and will
914           return after one iteration of the loop.
915
916           This is useful if you are waiting for some external event in
917           conjunction with something not expressible using other libev
918           watchers (i.e. "roll your own "ev_run""). However, a pair of
919           "ev_prepare"/"ev_check" watchers is usually a better approach for
920           this kind of thing.
921
922           Here are the gory details of what "ev_run" does (this is for your
923           understanding, not a guarantee that things will work exactly like
924           this in future versions):
925
926              - Increment loop depth.
927              - Reset the ev_break status.
928              - Before the first iteration, call any pending watchers.
929              LOOP:
930              - If EVFLAG_FORKCHECK was used, check for a fork.
931              - If a fork was detected (by any means), queue and call all fork watchers.
932              - Queue and call all prepare watchers.
933              - If ev_break was called, goto FINISH.
934              - If we have been forked, detach and recreate the kernel state
935                as to not disturb the other process.
936              - Update the kernel state with all outstanding changes.
937              - Update the "event loop time" (ev_now ()).
938              - Calculate for how long to sleep or block, if at all
939                (active idle watchers, EVRUN_NOWAIT or not having
940                any active watchers at all will result in not sleeping).
941              - Sleep if the I/O and timer collect interval say so.
942              - Increment loop iteration counter.
943              - Block the process, waiting for any events.
944              - Queue all outstanding I/O (fd) events.
945              - Update the "event loop time" (ev_now ()), and do time jump adjustments.
946              - Queue all expired timers.
947              - Queue all expired periodics.
948              - Queue all idle watchers with priority higher than that of pending events.
949              - Queue all check watchers.
950              - Call all queued watchers in reverse order (i.e. check watchers first).
951                Signals and child watchers are implemented as I/O watchers, and will
952                be handled here by queueing them when their watcher gets executed.
953              - If ev_break has been called, or EVRUN_ONCE or EVRUN_NOWAIT
954                were used, or there are no active watchers, goto FINISH, otherwise
955                continue with step LOOP.
956              FINISH:
957              - Reset the ev_break status iff it was EVBREAK_ONE.
958              - Decrement the loop depth.
959              - Return.
960
961           Example: Queue some jobs and then loop until no events are
962           outstanding anymore.
963
964              ... queue jobs here, make sure they register event watchers as long
965              ... as they still have work to do (even an idle watcher will do..)
966              ev_run (my_loop, 0);
967              ... jobs done or somebody called break. yeah!
968
969       ev_break (loop, how)
970           Can be used to make a call to "ev_run" return early (but only after
971           it has processed all outstanding events). The "how" argument must
972           be either "EVBREAK_ONE", which will make the innermost "ev_run"
973           call return, or "EVBREAK_ALL", which will make all nested "ev_run"
974           calls return.
975
976           This "break state" will be cleared on the next call to "ev_run".
977
978           It is safe to call "ev_break" from outside any "ev_run" calls, too,
979           in which case it will have no effect.
980
981       ev_ref (loop)
982       ev_unref (loop)
983           Ref/unref can be used to add or remove a reference count on the
984           event loop: Every watcher keeps one reference, and as long as the
985           reference count is nonzero, "ev_run" will not return on its own.
986
987           This is useful when you have a watcher that you never intend to
988           unregister, but that nevertheless should not keep "ev_run" from
989           returning. In such a case, call "ev_unref" after starting, and
990           "ev_ref" before stopping it.
991
992           As an example, libev itself uses this for its internal signal pipe:
993           It is not visible to the libev user and should not keep "ev_run"
994           from exiting if no event watchers registered by it are active. It
995           is also an excellent way to do this for generic recurring timers or
996           from within third-party libraries. Just remember to unref after
997           start and ref before stop (but only if the watcher wasn't active
998           before, or was active before, respectively. Note also that libev
999           might stop watchers itself (e.g. non-repeating timers) in which
1000           case you have to "ev_ref" in the callback).
1001
1002           Example: Create a signal watcher, but keep it from keeping "ev_run"
1003           running when nothing else is active.
1004
1005              ev_signal exitsig;
1006              ev_signal_init (&exitsig, sig_cb, SIGINT);
1007              ev_signal_start (loop, &exitsig);
1008              ev_unref (loop);
1009
1010           Example: For some weird reason, unregister the above signal handler
1011           again.
1012
1013              ev_ref (loop);
1014              ev_signal_stop (loop, &exitsig);
1015
1016       ev_set_io_collect_interval (loop, ev_tstamp interval)
1017       ev_set_timeout_collect_interval (loop, ev_tstamp interval)
1018           These advanced functions influence the time that libev will spend
1019           waiting for events. Both time intervals are by default 0, meaning
1020           that libev will try to invoke timer/periodic callbacks and I/O
1021           callbacks with minimum latency.
1022
1023           Setting these to a higher value (the "interval" must be >= 0)
1024           allows libev to delay invocation of I/O and timer/periodic
1025           callbacks to increase efficiency of loop iterations (or to increase
1026           power-saving opportunities).
1027
1028           The idea is that sometimes your program runs just fast enough to
1029           handle one (or very few) event(s) per loop iteration. While this
1030           makes the program responsive, it also wastes a lot of CPU time to
1031           poll for new events, especially with backends like "select ()"
1032           which have a high overhead for the actual polling but can deliver
1033           many events at once.
1034
1035           By setting a higher io collect interval you allow libev to spend
1036           more time collecting I/O events, so you can handle more events per
1037           iteration, at the cost of increasing latency. Timeouts (both
1038           "ev_periodic" and "ev_timer") will not be affected. Setting this to
1039           a non-null value will introduce an additional "ev_sleep ()" call
1040           into most loop iterations. The sleep time ensures that libev will
1041           not poll for I/O events more often then once per this interval, on
1042           average (as long as the host time resolution is good enough).
1043
1044           Likewise, by setting a higher timeout collect interval you allow
1045           libev to spend more time collecting timeouts, at the expense of
1046           increased latency/jitter/inexactness (the watcher callback will be
1047           called later). "ev_io" watchers will not be affected. Setting this
1048           to a non-null value will not introduce any overhead in libev.
1049
1050           Many (busy) programs can usually benefit by setting the I/O collect
1051           interval to a value near 0.1 or so, which is often enough for
1052           interactive servers (of course not for games), likewise for
1053           timeouts. It usually doesn't make much sense to set it to a lower
1054           value than 0.01, as this approaches the timing granularity of most
1055           systems. Note that if you do transactions with the outside world
1056           and you can't increase the parallelity, then this setting will
1057           limit your transaction rate (if you need to poll once per
1058           transaction and the I/O collect interval is 0.01, then you can't do
1059           more than 100 transactions per second).
1060
1061           Setting the timeout collect interval can improve the opportunity
1062           for saving power, as the program will "bundle" timer callback
1063           invocations that are "near" in time together, by delaying some,
1064           thus reducing the number of times the process sleeps and wakes up
1065           again. Another useful technique to reduce iterations/wake-ups is to
1066           use "ev_periodic" watchers and make sure they fire on, say, one-
1067           second boundaries only.
1068
1069           Example: we only need 0.1s timeout granularity, and we wish not to
1070           poll more often than 100 times per second:
1071
1072              ev_set_timeout_collect_interval (EV_DEFAULT_UC_ 0.1);
1073              ev_set_io_collect_interval (EV_DEFAULT_UC_ 0.01);
1074
1075       ev_invoke_pending (loop)
1076           This call will simply invoke all pending watchers while resetting
1077           their pending state. Normally, "ev_run" does this automatically
1078           when required, but when overriding the invoke callback this call
1079           comes handy. This function can be invoked from a watcher - this can
1080           be useful for example when you want to do some lengthy calculation
1081           and want to pass further event handling to another thread (you
1082           still have to make sure only one thread executes within
1083           "ev_invoke_pending" or "ev_run" of course).
1084
1085       int ev_pending_count (loop)
1086           Returns the number of pending watchers - zero indicates that no
1087           watchers are pending.
1088
1089       ev_set_invoke_pending_cb (loop, void (*invoke_pending_cb)(EV_P))
1090           This overrides the invoke pending functionality of the loop:
1091           Instead of invoking all pending watchers when there are any,
1092           "ev_run" will call this callback instead. This is useful, for
1093           example, when you want to invoke the actual watchers inside another
1094           context (another thread etc.).
1095
1096           If you want to reset the callback, use "ev_invoke_pending" as new
1097           callback.
1098
1099       ev_set_loop_release_cb (loop, void (*release)(EV_P) throw (), void
1100       (*acquire)(EV_P) throw ())
1101           Sometimes you want to share the same loop between multiple threads.
1102           This can be done relatively simply by putting mutex_lock/unlock
1103           calls around each call to a libev function.
1104
1105           However, "ev_run" can run an indefinite time, so it is not feasible
1106           to wait for it to return. One way around this is to wake up the
1107           event loop via "ev_break" and "ev_async_send", another way is to
1108           set these release and acquire callbacks on the loop.
1109
1110           When set, then "release" will be called just before the thread is
1111           suspended waiting for new events, and "acquire" is called just
1112           afterwards.
1113
1114           Ideally, "release" will just call your mutex_unlock function, and
1115           "acquire" will just call the mutex_lock function again.
1116
1117           While event loop modifications are allowed between invocations of
1118           "release" and "acquire" (that's their only purpose after all), no
1119           modifications done will affect the event loop, i.e. adding watchers
1120           will have no effect on the set of file descriptors being watched,
1121           or the time waited. Use an "ev_async" watcher to wake up "ev_run"
1122           when you want it to take note of any changes you made.
1123
1124           In theory, threads executing "ev_run" will be async-cancel safe
1125           between invocations of "release" and "acquire".
1126
1127           See also the locking example in the "THREADS" section later in this
1128           document.
1129
1130       ev_set_userdata (loop, void *data)
1131       void *ev_userdata (loop)
1132           Set and retrieve a single "void *" associated with a loop. When
1133           "ev_set_userdata" has never been called, then "ev_userdata" returns
1134           0.
1135
1136           These two functions can be used to associate arbitrary data with a
1137           loop, and are intended solely for the "invoke_pending_cb",
1138           "release" and "acquire" callbacks described above, but of course
1139           can be (ab-)used for any other purpose as well.
1140
1141       ev_verify (loop)
1142           This function only does something when "EV_VERIFY" support has been
1143           compiled in, which is the default for non-minimal builds. It tries
1144           to go through all internal structures and checks them for validity.
1145           If anything is found to be inconsistent, it will print an error
1146           message to standard error and call "abort ()".
1147
1148           This can be used to catch bugs inside libev itself: under normal
1149           circumstances, this function will never abort as of course libev
1150           keeps its data structures consistent.
1151

ANATOMY OF A WATCHER

1153       In the following description, uppercase "TYPE" in names stands for the
1154       watcher type, e.g. "ev_TYPE_start" can mean "ev_timer_start" for timer
1155       watchers and "ev_io_start" for I/O watchers.
1156
1157       A watcher is an opaque structure that you allocate and register to
1158       record your interest in some event. To make a concrete example, imagine
1159       you want to wait for STDIN to become readable, you would create an
1160       "ev_io" watcher for that:
1161
1162          static void my_cb (struct ev_loop *loop, ev_io *w, int revents)
1163          {
1164            ev_io_stop (w);
1165            ev_break (loop, EVBREAK_ALL);
1166          }
1167
1168          struct ev_loop *loop = ev_default_loop (0);
1169
1170          ev_io stdin_watcher;
1171
1172          ev_init (&stdin_watcher, my_cb);
1173          ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ);
1174          ev_io_start (loop, &stdin_watcher);
1175
1176          ev_run (loop, 0);
1177
1178       As you can see, you are responsible for allocating the memory for your
1179       watcher structures (and it is usually a bad idea to do this on the
1180       stack).
1181
1182       Each watcher has an associated watcher structure (called "struct
1183       ev_TYPE" or simply "ev_TYPE", as typedefs are provided for all watcher
1184       structs).
1185
1186       Each watcher structure must be initialised by a call to "ev_init
1187       (watcher *, callback)", which expects a callback to be provided. This
1188       callback is invoked each time the event occurs (or, in the case of I/O
1189       watchers, each time the event loop detects that the file descriptor
1190       given is readable and/or writable).
1191
1192       Each watcher type further has its own "ev_TYPE_set (watcher *, ...)"
1193       macro to configure it, with arguments specific to the watcher type.
1194       There is also a macro to combine initialisation and setting in one
1195       call: "ev_TYPE_init (watcher *, callback, ...)".
1196
1197       To make the watcher actually watch out for events, you have to start it
1198       with a watcher-specific start function ("ev_TYPE_start (loop, watcher
1199       *)"), and you can stop watching for events at any time by calling the
1200       corresponding stop function ("ev_TYPE_stop (loop, watcher *)".
1201
1202       As long as your watcher is active (has been started but not stopped)
1203       you must not touch the values stored in it. Most specifically you must
1204       never reinitialise it or call its "ev_TYPE_set" macro.
1205
1206       Each and every callback receives the event loop pointer as first, the
1207       registered watcher structure as second, and a bitset of received events
1208       as third argument.
1209
1210       The received events usually include a single bit per event type
1211       received (you can receive multiple events at the same time). The
1212       possible bit masks are:
1213
1214       "EV_READ"
1215       "EV_WRITE"
1216           The file descriptor in the "ev_io" watcher has become readable
1217           and/or writable.
1218
1219       "EV_TIMER"
1220           The "ev_timer" watcher has timed out.
1221
1222       "EV_PERIODIC"
1223           The "ev_periodic" watcher has timed out.
1224
1225       "EV_SIGNAL"
1226           The signal specified in the "ev_signal" watcher has been received
1227           by a thread.
1228
1229       "EV_CHILD"
1230           The pid specified in the "ev_child" watcher has received a status
1231           change.
1232
1233       "EV_STAT"
1234           The path specified in the "ev_stat" watcher changed its attributes
1235           somehow.
1236
1237       "EV_IDLE"
1238           The "ev_idle" watcher has determined that you have nothing better
1239           to do.
1240
1241       "EV_PREPARE"
1242       "EV_CHECK"
1243           All "ev_prepare" watchers are invoked just before "ev_run" starts
1244           to gather new events, and all "ev_check" watchers are queued (not
1245           invoked) just after "ev_run" has gathered them, but before it
1246           queues any callbacks for any received events. That means
1247           "ev_prepare" watchers are the last watchers invoked before the
1248           event loop sleeps or polls for new events, and "ev_check" watchers
1249           will be invoked before any other watchers of the same or lower
1250           priority within an event loop iteration.
1251
1252           Callbacks of both watcher types can start and stop as many watchers
1253           as they want, and all of them will be taken into account (for
1254           example, a "ev_prepare" watcher might start an idle watcher to keep
1255           "ev_run" from blocking).
1256
1257       "EV_EMBED"
1258           The embedded event loop specified in the "ev_embed" watcher needs
1259           attention.
1260
1261       "EV_FORK"
1262           The event loop has been resumed in the child process after fork
1263           (see "ev_fork").
1264
1265       "EV_CLEANUP"
1266           The event loop is about to be destroyed (see "ev_cleanup").
1267
1268       "EV_ASYNC"
1269           The given async watcher has been asynchronously notified (see
1270           "ev_async").
1271
1272       "EV_CUSTOM"
1273           Not ever sent (or otherwise used) by libev itself, but can be
1274           freely used by libev users to signal watchers (e.g. via
1275           "ev_feed_event").
1276
1277       "EV_ERROR"
1278           An unspecified error has occurred, the watcher has been stopped.
1279           This might happen because the watcher could not be properly started
1280           because libev ran out of memory, a file descriptor was found to be
1281           closed or any other problem. Libev considers these application
1282           bugs.
1283
1284           You best act on it by reporting the problem and somehow coping with
1285           the watcher being stopped. Note that well-written programs should
1286           not receive an error ever, so when your watcher receives it, this
1287           usually indicates a bug in your program.
1288
1289           Libev will usually signal a few "dummy" events together with an
1290           error, for example it might indicate that a fd is readable or
1291           writable, and if your callbacks is well-written it can just attempt
1292           the operation and cope with the error from read() or write(). This
1293           will not work in multi-threaded programs, though, as the fd could
1294           already be closed and reused for another thing, so beware.
1295
1296   GENERIC WATCHER FUNCTIONS
1297       "ev_init" (ev_TYPE *watcher, callback)
1298           This macro initialises the generic portion of a watcher. The
1299           contents of the watcher object can be arbitrary (so "malloc" will
1300           do). Only the generic parts of the watcher are initialised, you
1301           need to call the type-specific "ev_TYPE_set" macro afterwards to
1302           initialise the type-specific parts. For each type there is also a
1303           "ev_TYPE_init" macro which rolls both calls into one.
1304
1305           You can reinitialise a watcher at any time as long as it has been
1306           stopped (or never started) and there are no pending events
1307           outstanding.
1308
1309           The callback is always of type "void (*)(struct ev_loop *loop,
1310           ev_TYPE *watcher, int revents)".
1311
1312           Example: Initialise an "ev_io" watcher in two steps.
1313
1314              ev_io w;
1315              ev_init (&w, my_cb);
1316              ev_io_set (&w, STDIN_FILENO, EV_READ);
1317
1318       "ev_TYPE_set" (ev_TYPE *watcher, [args])
1319           This macro initialises the type-specific parts of a watcher. You
1320           need to call "ev_init" at least once before you call this macro,
1321           but you can call "ev_TYPE_set" any number of times. You must not,
1322           however, call this macro on a watcher that is active (it can be
1323           pending, however, which is a difference to the "ev_init" macro).
1324
1325           Although some watcher types do not have type-specific arguments
1326           (e.g. "ev_prepare") you still need to call its "set" macro.
1327
1328           See "ev_init", above, for an example.
1329
1330       "ev_TYPE_init" (ev_TYPE *watcher, callback, [args])
1331           This convenience macro rolls both "ev_init" and "ev_TYPE_set" macro
1332           calls into a single call. This is the most convenient method to
1333           initialise a watcher. The same limitations apply, of course.
1334
1335           Example: Initialise and set an "ev_io" watcher in one step.
1336
1337              ev_io_init (&w, my_cb, STDIN_FILENO, EV_READ);
1338
1339       "ev_TYPE_start" (loop, ev_TYPE *watcher)
1340           Starts (activates) the given watcher. Only active watchers will
1341           receive events. If the watcher is already active nothing will
1342           happen.
1343
1344           Example: Start the "ev_io" watcher that is being abused as example
1345           in this whole section.
1346
1347              ev_io_start (EV_DEFAULT_UC, &w);
1348
1349       "ev_TYPE_stop" (loop, ev_TYPE *watcher)
1350           Stops the given watcher if active, and clears the pending status
1351           (whether the watcher was active or not).
1352
1353           It is possible that stopped watchers are pending - for example,
1354           non-repeating timers are being stopped when they become pending -
1355           but calling "ev_TYPE_stop" ensures that the watcher is neither
1356           active nor pending. If you want to free or reuse the memory used by
1357           the watcher it is therefore a good idea to always call its
1358           "ev_TYPE_stop" function.
1359
1360       bool ev_is_active (ev_TYPE *watcher)
1361           Returns a true value iff the watcher is active (i.e. it has been
1362           started and not yet been stopped). As long as a watcher is active
1363           you must not modify it.
1364
1365       bool ev_is_pending (ev_TYPE *watcher)
1366           Returns a true value iff the watcher is pending, (i.e. it has
1367           outstanding events but its callback has not yet been invoked). As
1368           long as a watcher is pending (but not active) you must not call an
1369           init function on it (but "ev_TYPE_set" is safe), you must not
1370           change its priority, and you must make sure the watcher is
1371           available to libev (e.g. you cannot "free ()" it).
1372
1373       callback ev_cb (ev_TYPE *watcher)
1374           Returns the callback currently set on the watcher.
1375
1376       ev_set_cb (ev_TYPE *watcher, callback)
1377           Change the callback. You can change the callback at virtually any
1378           time (modulo threads).
1379
1380       ev_set_priority (ev_TYPE *watcher, int priority)
1381       int ev_priority (ev_TYPE *watcher)
1382           Set and query the priority of the watcher. The priority is a small
1383           integer between "EV_MAXPRI" (default: 2) and "EV_MINPRI" (default:
1384           "-2"). Pending watchers with higher priority will be invoked before
1385           watchers with lower priority, but priority will not keep watchers
1386           from being executed (except for "ev_idle" watchers).
1387
1388           If you need to suppress invocation when higher priority events are
1389           pending you need to look at "ev_idle" watchers, which provide this
1390           functionality.
1391
1392           You must not change the priority of a watcher as long as it is
1393           active or pending.
1394
1395           Setting a priority outside the range of "EV_MINPRI" to "EV_MAXPRI"
1396           is fine, as long as you do not mind that the priority value you
1397           query might or might not have been clamped to the valid range.
1398
1399           The default priority used by watchers when no priority has been set
1400           is always 0, which is supposed to not be too high and not be too
1401           low :).
1402
1403           See "WATCHER PRIORITY MODELS", below, for a more thorough treatment
1404           of priorities.
1405
1406       ev_invoke (loop, ev_TYPE *watcher, int revents)
1407           Invoke the "watcher" with the given "loop" and "revents". Neither
1408           "loop" nor "revents" need to be valid as long as the watcher
1409           callback can deal with that fact, as both are simply passed through
1410           to the callback.
1411
1412       int ev_clear_pending (loop, ev_TYPE *watcher)
1413           If the watcher is pending, this function clears its pending status
1414           and returns its "revents" bitset (as if its callback was invoked).
1415           If the watcher isn't pending it does nothing and returns 0.
1416
1417           Sometimes it can be useful to "poll" a watcher instead of waiting
1418           for its callback to be invoked, which can be accomplished with this
1419           function.
1420
1421       ev_feed_event (loop, ev_TYPE *watcher, int revents)
1422           Feeds the given event set into the event loop, as if the specified
1423           event had happened for the specified watcher (which must be a
1424           pointer to an initialised but not necessarily started event
1425           watcher). Obviously you must not free the watcher as long as it has
1426           pending events.
1427
1428           Stopping the watcher, letting libev invoke it, or calling
1429           "ev_clear_pending" will clear the pending event, even if the
1430           watcher was not started in the first place.
1431
1432           See also "ev_feed_fd_event" and "ev_feed_signal_event" for related
1433           functions that do not need a watcher.
1434
1435       See also the "ASSOCIATING CUSTOM DATA WITH A WATCHER" and "BUILDING
1436       YOUR OWN COMPOSITE WATCHERS" idioms.
1437
1438   WATCHER STATES
1439       There are various watcher states mentioned throughout this manual -
1440       active, pending and so on. In this section these states and the rules
1441       to transition between them will be described in more detail - and while
1442       these rules might look complicated, they usually do "the right thing".
1443
1444       initialised
1445           Before a watcher can be registered with the event loop it has to be
1446           initialised. This can be done with a call to "ev_TYPE_init", or
1447           calls to "ev_init" followed by the watcher-specific "ev_TYPE_set"
1448           function.
1449
1450           In this state it is simply some block of memory that is suitable
1451           for use in an event loop. It can be moved around, freed, reused
1452           etc. at will - as long as you either keep the memory contents
1453           intact, or call "ev_TYPE_init" again.
1454
1455       started/running/active
1456           Once a watcher has been started with a call to "ev_TYPE_start" it
1457           becomes property of the event loop, and is actively waiting for
1458           events. While in this state it cannot be accessed (except in a few
1459           documented ways), moved, freed or anything else - the only legal
1460           thing is to keep a pointer to it, and call libev functions on it
1461           that are documented to work on active watchers.
1462
1463       pending
1464           If a watcher is active and libev determines that an event it is
1465           interested in has occurred (such as a timer expiring), it will
1466           become pending. It will stay in this pending state until either it
1467           is stopped or its callback is about to be invoked, so it is not
1468           normally pending inside the watcher callback.
1469
1470           The watcher might or might not be active while it is pending (for
1471           example, an expired non-repeating timer can be pending but no
1472           longer active). If it is stopped, it can be freely accessed (e.g.
1473           by calling "ev_TYPE_set"), but it is still property of the event
1474           loop at this time, so cannot be moved, freed or reused. And if it
1475           is active the rules described in the previous item still apply.
1476
1477           It is also possible to feed an event on a watcher that is not
1478           active (e.g.  via "ev_feed_event"), in which case it becomes
1479           pending without being active.
1480
1481       stopped
1482           A watcher can be stopped implicitly by libev (in which case it
1483           might still be pending), or explicitly by calling its
1484           "ev_TYPE_stop" function. The latter will clear any pending state
1485           the watcher might be in, regardless of whether it was active or
1486           not, so stopping a watcher explicitly before freeing it is often a
1487           good idea.
1488
1489           While stopped (and not pending) the watcher is essentially in the
1490           initialised state, that is, it can be reused, moved, modified in
1491           any way you wish (but when you trash the memory block, you need to
1492           "ev_TYPE_init" it again).
1493
1494   WATCHER PRIORITY MODELS
1495       Many event loops support watcher priorities, which are usually small
1496       integers that influence the ordering of event callback invocation
1497       between watchers in some way, all else being equal.
1498
1499       In libev, Watcher priorities can be set using "ev_set_priority". See
1500       its description for the more technical details such as the actual
1501       priority range.
1502
1503       There are two common ways how these these priorities are being
1504       interpreted by event loops:
1505
1506       In the more common lock-out model, higher priorities "lock out"
1507       invocation of lower priority watchers, which means as long as higher
1508       priority watchers receive events, lower priority watchers are not being
1509       invoked.
1510
1511       The less common only-for-ordering model uses priorities solely to order
1512       callback invocation within a single event loop iteration: Higher
1513       priority watchers are invoked before lower priority ones, but they all
1514       get invoked before polling for new events.
1515
1516       Libev uses the second (only-for-ordering) model for all its watchers
1517       except for idle watchers (which use the lock-out model).
1518
1519       The rationale behind this is that implementing the lock-out model for
1520       watchers is not well supported by most kernel interfaces, and most
1521       event libraries will just poll for the same events again and again as
1522       long as their callbacks have not been executed, which is very
1523       inefficient in the common case of one high-priority watcher locking out
1524       a mass of lower priority ones.
1525
1526       Static (ordering) priorities are most useful when you have two or more
1527       watchers handling the same resource: a typical usage example is having
1528       an "ev_io" watcher to receive data, and an associated "ev_timer" to
1529       handle timeouts. Under load, data might be received while the program
1530       handles other jobs, but since timers normally get invoked first, the
1531       timeout handler will be executed before checking for data. In that
1532       case, giving the timer a lower priority than the I/O watcher ensures
1533       that I/O will be handled first even under adverse conditions (which is
1534       usually, but not always, what you want).
1535
1536       Since idle watchers use the "lock-out" model, meaning that idle
1537       watchers will only be executed when no same or higher priority watchers
1538       have received events, they can be used to implement the "lock-out"
1539       model when required.
1540
1541       For example, to emulate how many other event libraries handle
1542       priorities, you can associate an "ev_idle" watcher to each such
1543       watcher, and in the normal watcher callback, you just start the idle
1544       watcher. The real processing is done in the idle watcher callback. This
1545       causes libev to continuously poll and process kernel event data for the
1546       watcher, but when the lock-out case is known to be rare (which in turn
1547       is rare :), this is workable.
1548
1549       Usually, however, the lock-out model implemented that way will perform
1550       miserably under the type of load it was designed to handle. In that
1551       case, it might be preferable to stop the real watcher before starting
1552       the idle watcher, so the kernel will not have to process the event in
1553       case the actual processing will be delayed for considerable time.
1554
1555       Here is an example of an I/O watcher that should run at a strictly
1556       lower priority than the default, and which should only process data
1557       when no other events are pending:
1558
1559          ev_idle idle; // actual processing watcher
1560          ev_io io;     // actual event watcher
1561
1562          static void
1563          io_cb (EV_P_ ev_io *w, int revents)
1564          {
1565            // stop the I/O watcher, we received the event, but
1566            // are not yet ready to handle it.
1567            ev_io_stop (EV_A_ w);
1568
1569            // start the idle watcher to handle the actual event.
1570            // it will not be executed as long as other watchers
1571            // with the default priority are receiving events.
1572            ev_idle_start (EV_A_ &idle);
1573          }
1574
1575          static void
1576          idle_cb (EV_P_ ev_idle *w, int revents)
1577          {
1578            // actual processing
1579            read (STDIN_FILENO, ...);
1580
1581            // have to start the I/O watcher again, as
1582            // we have handled the event
1583            ev_io_start (EV_P_ &io);
1584          }
1585
1586          // initialisation
1587          ev_idle_init (&idle, idle_cb);
1588          ev_io_init (&io, io_cb, STDIN_FILENO, EV_READ);
1589          ev_io_start (EV_DEFAULT_ &io);
1590
1591       In the "real" world, it might also be beneficial to start a timer, so
1592       that low-priority connections can not be locked out forever under load.
1593       This enables your program to keep a lower latency for important
1594       connections during short periods of high load, while not completely
1595       locking out less important ones.
1596

WATCHER TYPES

1598       This section describes each watcher in detail, but will not repeat
1599       information given in the last section. Any initialisation/set macros,
1600       functions and members specific to the watcher type are explained.
1601
1602       Members are additionally marked with either [read-only], meaning that,
1603       while the watcher is active, you can look at the member and expect some
1604       sensible content, but you must not modify it (you can modify it while
1605       the watcher is stopped to your hearts content), or [read-write], which
1606       means you can expect it to have some sensible content while the watcher
1607       is active, but you can also modify it. Modifying it may not do
1608       something sensible or take immediate effect (or do anything at all),
1609       but libev will not crash or malfunction in any way.
1610
1611   "ev_io" - is this file descriptor readable or writable?
1612       I/O watchers check whether a file descriptor is readable or writable in
1613       each iteration of the event loop, or, more precisely, when reading
1614       would not block the process and writing would at least be able to write
1615       some data. This behaviour is called level-triggering because you keep
1616       receiving events as long as the condition persists. Remember you can
1617       stop the watcher if you don't want to act on the event and neither want
1618       to receive future events.
1619
1620       In general you can register as many read and/or write event watchers
1621       per fd as you want (as long as you don't confuse yourself). Setting all
1622       file descriptors to non-blocking mode is also usually a good idea (but
1623       not required if you know what you are doing).
1624
1625       Another thing you have to watch out for is that it is quite easy to
1626       receive "spurious" readiness notifications, that is, your callback
1627       might be called with "EV_READ" but a subsequent "read"(2) will actually
1628       block because there is no data. It is very easy to get into this
1629       situation even with a relatively standard program structure. Thus it is
1630       best to always use non-blocking I/O: An extra "read"(2) returning
1631       "EAGAIN" is far preferable to a program hanging until some data
1632       arrives.
1633
1634       If you cannot run the fd in non-blocking mode (for example you should
1635       not play around with an Xlib connection), then you have to separately
1636       re-test whether a file descriptor is really ready with a known-to-be
1637       good interface such as poll (fortunately in the case of Xlib, it
1638       already does this on its own, so its quite safe to use). Some people
1639       additionally use "SIGALRM" and an interval timer, just to be sure you
1640       won't block indefinitely.
1641
1642       But really, best use non-blocking mode.
1643
1644       The special problem of disappearing file descriptors
1645
1646       Some backends (e.g. kqueue, epoll, linuxaio) need to be told about
1647       closing a file descriptor (either due to calling "close" explicitly or
1648       any other means, such as "dup2"). The reason is that you register
1649       interest in some file descriptor, but when it goes away, the operating
1650       system will silently drop this interest. If another file descriptor
1651       with the same number then is registered with libev, there is no
1652       efficient way to see that this is, in fact, a different file
1653       descriptor.
1654
1655       To avoid having to explicitly tell libev about such cases, libev
1656       follows the following policy:  Each time "ev_io_set" is being called,
1657       libev will assume that this is potentially a new file descriptor,
1658       otherwise it is assumed that the file descriptor stays the same. That
1659       means that you have to call "ev_io_set" (or "ev_io_init") when you
1660       change the descriptor even if the file descriptor number itself did not
1661       change.
1662
1663       This is how one would do it normally anyway, the important point is
1664       that the libev application should not optimise around libev but should
1665       leave optimisations to libev.
1666
1667       The special problem of dup'ed file descriptors
1668
1669       Some backends (e.g. epoll), cannot register events for file
1670       descriptors, but only events for the underlying file descriptions. That
1671       means when you have "dup ()"'ed file descriptors or weirder
1672       constellations, and register events for them, only one file descriptor
1673       might actually receive events.
1674
1675       There is no workaround possible except not registering events for
1676       potentially "dup ()"'ed file descriptors, or to resort to
1677       "EVBACKEND_SELECT" or "EVBACKEND_POLL".
1678
1679       The special problem of files
1680
1681       Many people try to use "select" (or libev) on file descriptors
1682       representing files, and expect it to become ready when their program
1683       doesn't block on disk accesses (which can take a long time on their
1684       own).
1685
1686       However, this cannot ever work in the "expected" way - you get a
1687       readiness notification as soon as the kernel knows whether and how much
1688       data is there, and in the case of open files, that's always the case,
1689       so you always get a readiness notification instantly, and your read (or
1690       possibly write) will still block on the disk I/O.
1691
1692       Another way to view it is that in the case of sockets, pipes, character
1693       devices and so on, there is another party (the sender) that delivers
1694       data on its own, but in the case of files, there is no such thing: the
1695       disk will not send data on its own, simply because it doesn't know what
1696       you wish to read - you would first have to request some data.
1697
1698       Since files are typically not-so-well supported by advanced
1699       notification mechanism, libev tries hard to emulate POSIX behaviour
1700       with respect to files, even though you should not use it. The reason
1701       for this is convenience: sometimes you want to watch STDIN or STDOUT,
1702       which is usually a tty, often a pipe, but also sometimes files or
1703       special devices (for example, "epoll" on Linux works with /dev/random
1704       but not with /dev/urandom), and even though the file might better be
1705       served with asynchronous I/O instead of with non-blocking I/O, it is
1706       still useful when it "just works" instead of freezing.
1707
1708       So avoid file descriptors pointing to files when you know it (e.g. use
1709       libeio), but use them when it is convenient, e.g. for STDIN/STDOUT, or
1710       when you rarely read from a file instead of from a socket, and want to
1711       reuse the same code path.
1712
1713       The special problem of fork
1714
1715       Some backends (epoll, kqueue, probably linuxaio) do not support "fork
1716       ()" at all or exhibit useless behaviour. Libev fully supports fork, but
1717       needs to be told about it in the child if you want to continue to use
1718       it in the child.
1719
1720       To support fork in your child processes, you have to call "ev_loop_fork
1721       ()" after a fork in the child, enable "EVFLAG_FORKCHECK", or resort to
1722       "EVBACKEND_SELECT" or "EVBACKEND_POLL".
1723
1724       The special problem of SIGPIPE
1725
1726       While not really specific to libev, it is easy to forget about
1727       "SIGPIPE": when writing to a pipe whose other end has been closed, your
1728       program gets sent a SIGPIPE, which, by default, aborts your program.
1729       For most programs this is sensible behaviour, for daemons, this is
1730       usually undesirable.
1731
1732       So when you encounter spurious, unexplained daemon exits, make sure you
1733       ignore SIGPIPE (and maybe make sure you log the exit status of your
1734       daemon somewhere, as that would have given you a big clue).
1735
1736       The special problem of accept()ing when you can't
1737
1738       Many implementations of the POSIX "accept" function (for example, found
1739       in post-2004 Linux) have the peculiar behaviour of not removing a
1740       connection from the pending queue in all error cases.
1741
1742       For example, larger servers often run out of file descriptors (because
1743       of resource limits), causing "accept" to fail with "ENFILE" but not
1744       rejecting the connection, leading to libev signalling readiness on the
1745       next iteration again (the connection still exists after all), and
1746       typically causing the program to loop at 100% CPU usage.
1747
1748       Unfortunately, the set of errors that cause this issue differs between
1749       operating systems, there is usually little the app can do to remedy the
1750       situation, and no known thread-safe method of removing the connection
1751       to cope with overload is known (to me).
1752
1753       One of the easiest ways to handle this situation is to just ignore it -
1754       when the program encounters an overload, it will just loop until the
1755       situation is over. While this is a form of busy waiting, no OS offers
1756       an event-based way to handle this situation, so it's the best one can
1757       do.
1758
1759       A better way to handle the situation is to log any errors other than
1760       "EAGAIN" and "EWOULDBLOCK", making sure not to flood the log with such
1761       messages, and continue as usual, which at least gives the user an idea
1762       of what could be wrong ("raise the ulimit!"). For extra points one
1763       could stop the "ev_io" watcher on the listening fd "for a while", which
1764       reduces CPU usage.
1765
1766       If your program is single-threaded, then you could also keep a dummy
1767       file descriptor for overload situations (e.g. by opening /dev/null),
1768       and when you run into "ENFILE" or "EMFILE", close it, run "accept",
1769       close that fd, and create a new dummy fd. This will gracefully refuse
1770       clients under typical overload conditions.
1771
1772       The last way to handle it is to simply log the error and "exit", as is
1773       often done with "malloc" failures, but this results in an easy
1774       opportunity for a DoS attack.
1775
1776       Watcher-Specific Functions
1777
1778       ev_io_init (ev_io *, callback, int fd, int events)
1779       ev_io_set (ev_io *, int fd, int events)
1780           Configures an "ev_io" watcher. The "fd" is the file descriptor to
1781           receive events for and "events" is either "EV_READ", "EV_WRITE" or
1782           "EV_READ | EV_WRITE", to express the desire to receive the given
1783           events.
1784
1785       int fd [read-only]
1786           The file descriptor being watched.
1787
1788       int events [read-only]
1789           The events being watched.
1790
1791       Examples
1792
1793       Example: Call "stdin_readable_cb" when STDIN_FILENO has become, well
1794       readable, but only once. Since it is likely line-buffered, you could
1795       attempt to read a whole line in the callback.
1796
1797          static void
1798          stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents)
1799          {
1800             ev_io_stop (loop, w);
1801            .. read from stdin here (or from w->fd) and handle any I/O errors
1802          }
1803
1804          ...
1805          struct ev_loop *loop = ev_default_init (0);
1806          ev_io stdin_readable;
1807          ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ);
1808          ev_io_start (loop, &stdin_readable);
1809          ev_run (loop, 0);
1810
1811   "ev_timer" - relative and optionally repeating timeouts
1812       Timer watchers are simple relative timers that generate an event after
1813       a given time, and optionally repeating in regular intervals after that.
1814
1815       The timers are based on real time, that is, if you register an event
1816       that times out after an hour and you reset your system clock to January
1817       last year, it will still time out after (roughly) one hour. "Roughly"
1818       because detecting time jumps is hard, and some inaccuracies are
1819       unavoidable (the monotonic clock option helps a lot here).
1820
1821       The callback is guaranteed to be invoked only after its timeout has
1822       passed (not at, so on systems with very low-resolution clocks this
1823       might introduce a small delay, see "the special problem of being too
1824       early", below). If multiple timers become ready during the same loop
1825       iteration then the ones with earlier time-out values are invoked before
1826       ones of the same priority with later time-out values (but this is no
1827       longer true when a callback calls "ev_run" recursively).
1828
1829       Be smart about timeouts
1830
1831       Many real-world problems involve some kind of timeout, usually for
1832       error recovery. A typical example is an HTTP request - if the other
1833       side hangs, you want to raise some error after a while.
1834
1835       What follows are some ways to handle this problem, from obvious and
1836       inefficient to smart and efficient.
1837
1838       In the following, a 60 second activity timeout is assumed - a timeout
1839       that gets reset to 60 seconds each time there is activity (e.g. each
1840       time some data or other life sign was received).
1841
1842       1. Use a timer and stop, reinitialise and start it on activity.
1843           This is the most obvious, but not the most simple way: In the
1844           beginning, start the watcher:
1845
1846              ev_timer_init (timer, callback, 60., 0.);
1847              ev_timer_start (loop, timer);
1848
1849           Then, each time there is some activity, "ev_timer_stop" it,
1850           initialise it and start it again:
1851
1852              ev_timer_stop (loop, timer);
1853              ev_timer_set (timer, 60., 0.);
1854              ev_timer_start (loop, timer);
1855
1856           This is relatively simple to implement, but means that each time
1857           there is some activity, libev will first have to remove the timer
1858           from its internal data structure and then add it again. Libev tries
1859           to be fast, but it's still not a constant-time operation.
1860
1861       2. Use a timer and re-start it with "ev_timer_again" inactivity.
1862           This is the easiest way, and involves using "ev_timer_again"
1863           instead of "ev_timer_start".
1864
1865           To implement this, configure an "ev_timer" with a "repeat" value of
1866           60 and then call "ev_timer_again" at start and each time you
1867           successfully read or write some data. If you go into an idle state
1868           where you do not expect data to travel on the socket, you can
1869           "ev_timer_stop" the timer, and "ev_timer_again" will automatically
1870           restart it if need be.
1871
1872           That means you can ignore both the "ev_timer_start" function and
1873           the "after" argument to "ev_timer_set", and only ever use the
1874           "repeat" member and "ev_timer_again".
1875
1876           At start:
1877
1878              ev_init (timer, callback);
1879              timer->repeat = 60.;
1880              ev_timer_again (loop, timer);
1881
1882           Each time there is some activity:
1883
1884              ev_timer_again (loop, timer);
1885
1886           It is even possible to change the time-out on the fly, regardless
1887           of whether the watcher is active or not:
1888
1889              timer->repeat = 30.;
1890              ev_timer_again (loop, timer);
1891
1892           This is slightly more efficient then stopping/starting the timer
1893           each time you want to modify its timeout value, as libev does not
1894           have to completely remove and re-insert the timer from/into its
1895           internal data structure.
1896
1897           It is, however, even simpler than the "obvious" way to do it.
1898
1899       3. Let the timer time out, but then re-arm it as required.
1900           This method is more tricky, but usually most efficient: Most
1901           timeouts are relatively long compared to the intervals between
1902           other activity - in our example, within 60 seconds, there are
1903           usually many I/O events with associated activity resets.
1904
1905           In this case, it would be more efficient to leave the "ev_timer"
1906           alone, but remember the time of last activity, and check for a real
1907           timeout only within the callback:
1908
1909              ev_tstamp timeout = 60.;
1910              ev_tstamp last_activity; // time of last activity
1911              ev_timer timer;
1912
1913              static void
1914              callback (EV_P_ ev_timer *w, int revents)
1915              {
1916                // calculate when the timeout would happen
1917                ev_tstamp after = last_activity - ev_now (EV_A) + timeout;
1918
1919                // if negative, it means we the timeout already occurred
1920                if (after < 0.)
1921                  {
1922                    // timeout occurred, take action
1923                  }
1924                else
1925                  {
1926                    // callback was invoked, but there was some recent
1927                    // activity. simply restart the timer to time out
1928                    // after "after" seconds, which is the earliest time
1929                    // the timeout can occur.
1930                    ev_timer_set (w, after, 0.);
1931                    ev_timer_start (EV_A_ w);
1932                  }
1933              }
1934
1935           To summarise the callback: first calculate in how many seconds the
1936           timeout will occur (by calculating the absolute time when it would
1937           occur, "last_activity + timeout", and subtracting the current time,
1938           "ev_now (EV_A)" from that).
1939
1940           If this value is negative, then we are already past the timeout,
1941           i.e. we timed out, and need to do whatever is needed in this case.
1942
1943           Otherwise, we now the earliest time at which the timeout would
1944           trigger, and simply start the timer with this timeout value.
1945
1946           In other words, each time the callback is invoked it will check
1947           whether the timeout occurred. If not, it will simply reschedule
1948           itself to check again at the earliest time it could time out.
1949           Rinse. Repeat.
1950
1951           This scheme causes more callback invocations (about one every 60
1952           seconds minus half the average time between activity), but
1953           virtually no calls to libev to change the timeout.
1954
1955           To start the machinery, simply initialise the watcher and set
1956           "last_activity" to the current time (meaning there was some
1957           activity just now), then call the callback, which will "do the
1958           right thing" and start the timer:
1959
1960              last_activity = ev_now (EV_A);
1961              ev_init (&timer, callback);
1962              callback (EV_A_ &timer, 0);
1963
1964           When there is some activity, simply store the current time in
1965           "last_activity", no libev calls at all:
1966
1967              if (activity detected)
1968                last_activity = ev_now (EV_A);
1969
1970           When your timeout value changes, then the timeout can be changed by
1971           simply providing a new value, stopping the timer and calling the
1972           callback, which will again do the right thing (for example, time
1973           out immediately :).
1974
1975              timeout = new_value;
1976              ev_timer_stop (EV_A_ &timer);
1977              callback (EV_A_ &timer, 0);
1978
1979           This technique is slightly more complex, but in most cases where
1980           the time-out is unlikely to be triggered, much more efficient.
1981
1982       4. Wee, just use a double-linked list for your timeouts.
1983           If there is not one request, but many thousands (millions...), all
1984           employing some kind of timeout with the same timeout value, then
1985           one can do even better:
1986
1987           When starting the timeout, calculate the timeout value and put the
1988           timeout at the end of the list.
1989
1990           Then use an "ev_timer" to fire when the timeout at the beginning of
1991           the list is expected to fire (for example, using the technique #3).
1992
1993           When there is some activity, remove the timer from the list,
1994           recalculate the timeout, append it to the end of the list again,
1995           and make sure to update the "ev_timer" if it was taken from the
1996           beginning of the list.
1997
1998           This way, one can manage an unlimited number of timeouts in O(1)
1999           time for starting, stopping and updating the timers, at the expense
2000           of a major complication, and having to use a constant timeout. The
2001           constant timeout ensures that the list stays sorted.
2002
2003       So which method the best?
2004
2005       Method #2 is a simple no-brain-required solution that is adequate in
2006       most situations. Method #3 requires a bit more thinking, but handles
2007       many cases better, and isn't very complicated either. In most case,
2008       choosing either one is fine, with #3 being better in typical
2009       situations.
2010
2011       Method #1 is almost always a bad idea, and buys you nothing. Method #4
2012       is rather complicated, but extremely efficient, something that really
2013       pays off after the first million or so of active timers, i.e. it's
2014       usually overkill :)
2015
2016       The special problem of being too early
2017
2018       If you ask a timer to call your callback after three seconds, then you
2019       expect it to be invoked after three seconds - but of course, this
2020       cannot be guaranteed to infinite precision. Less obviously, it cannot
2021       be guaranteed to any precision by libev - imagine somebody suspending
2022       the process with a STOP signal for a few hours for example.
2023
2024       So, libev tries to invoke your callback as soon as possible after the
2025       delay has occurred, but cannot guarantee this.
2026
2027       A less obvious failure mode is calling your callback too early: many
2028       event loops compare timestamps with a "elapsed delay >= requested
2029       delay", but this can cause your callback to be invoked much earlier
2030       than you would expect.
2031
2032       To see why, imagine a system with a clock that only offers full second
2033       resolution (think windows if you can't come up with a broken enough OS
2034       yourself). If you schedule a one-second timer at the time 500.9, then
2035       the event loop will schedule your timeout to elapse at a system time of
2036       500 (500.9 truncated to the resolution) + 1, or 501.
2037
2038       If an event library looks at the timeout 0.1s later, it will see "501
2039       >= 501" and invoke the callback 0.1s after it was started, even though
2040       a one-second delay was requested - this is being "too early", despite
2041       best intentions.
2042
2043       This is the reason why libev will never invoke the callback if the
2044       elapsed delay equals the requested delay, but only when the elapsed
2045       delay is larger than the requested delay. In the example above, libev
2046       would only invoke the callback at system time 502, or 1.1s after the
2047       timer was started.
2048
2049       So, while libev cannot guarantee that your callback will be invoked
2050       exactly when requested, it can and does guarantee that the requested
2051       delay has actually elapsed, or in other words, it always errs on the
2052       "too late" side of things.
2053
2054       The special problem of time updates
2055
2056       Establishing the current time is a costly operation (it usually takes
2057       at least one system call): EV therefore updates its idea of the current
2058       time only before and after "ev_run" collects new events, which causes a
2059       growing difference between "ev_now ()" and "ev_time ()" when handling
2060       lots of events in one iteration.
2061
2062       The relative timeouts are calculated relative to the "ev_now ()" time.
2063       This is usually the right thing as this timestamp refers to the time of
2064       the event triggering whatever timeout you are modifying/starting. If
2065       you suspect event processing to be delayed and you need to base the
2066       timeout on the current time, use something like the following to adjust
2067       for it:
2068
2069          ev_timer_set (&timer, after + (ev_time () - ev_now ()), 0.);
2070
2071       If the event loop is suspended for a long time, you can also force an
2072       update of the time returned by "ev_now ()" by calling "ev_now_update
2073       ()", although that will push the event time of all outstanding events
2074       further into the future.
2075
2076       The special problem of unsynchronised clocks
2077
2078       Modern systems have a variety of clocks - libev itself uses the normal
2079       "wall clock" clock and, if available, the monotonic clock (to avoid
2080       time jumps).
2081
2082       Neither of these clocks is synchronised with each other or any other
2083       clock on the system, so "ev_time ()" might return a considerably
2084       different time than "gettimeofday ()" or "time ()". On a GNU/Linux
2085       system, for example, a call to "gettimeofday" might return a second
2086       count that is one higher than a directly following call to "time".
2087
2088       The moral of this is to only compare libev-related timestamps with
2089       "ev_time ()" and "ev_now ()", at least if you want better precision
2090       than a second or so.
2091
2092       One more problem arises due to this lack of synchronisation: if libev
2093       uses the system monotonic clock and you compare timestamps from
2094       "ev_time" or "ev_now" from when you started your timer and when your
2095       callback is invoked, you will find that sometimes the callback is a bit
2096       "early".
2097
2098       This is because "ev_timer"s work in real time, not wall clock time, so
2099       libev makes sure your callback is not invoked before the delay
2100       happened, measured according to the real time, not the system clock.
2101
2102       If your timeouts are based on a physical timescale (e.g. "time out this
2103       connection after 100 seconds") then this shouldn't bother you as it is
2104       exactly the right behaviour.
2105
2106       If you want to compare wall clock/system timestamps to your timers,
2107       then you need to use "ev_periodic"s, as these are based on the wall
2108       clock time, where your comparisons will always generate correct
2109       results.
2110
2111       The special problems of suspended animation
2112
2113       When you leave the server world it is quite customary to hit machines
2114       that can suspend/hibernate - what happens to the clocks during such a
2115       suspend?
2116
2117       Some quick tests made with a Linux 2.6.28 indicate that a suspend
2118       freezes all processes, while the clocks ("times", "CLOCK_MONOTONIC")
2119       continue to run until the system is suspended, but they will not
2120       advance while the system is suspended. That means, on resume, it will
2121       be as if the program was frozen for a few seconds, but the suspend time
2122       will not be counted towards "ev_timer" when a monotonic clock source is
2123       used. The real time clock advanced as expected, but if it is used as
2124       sole clocksource, then a long suspend would be detected as a time jump
2125       by libev, and timers would be adjusted accordingly.
2126
2127       I would not be surprised to see different behaviour in different
2128       between operating systems, OS versions or even different hardware.
2129
2130       The other form of suspend (job control, or sending a SIGSTOP) will see
2131       a time jump in the monotonic clocks and the realtime clock. If the
2132       program is suspended for a very long time, and monotonic clock sources
2133       are in use, then you can expect "ev_timer"s to expire as the full
2134       suspension time will be counted towards the timers. When no monotonic
2135       clock source is in use, then libev will again assume a timejump and
2136       adjust accordingly.
2137
2138       It might be beneficial for this latter case to call "ev_suspend" and
2139       "ev_resume" in code that handles "SIGTSTP", to at least get
2140       deterministic behaviour in this case (you can do nothing against
2141       "SIGSTOP").
2142
2143       Watcher-Specific Functions and Data Members
2144
2145       ev_timer_init (ev_timer *, callback, ev_tstamp after, ev_tstamp repeat)
2146       ev_timer_set (ev_timer *, ev_tstamp after, ev_tstamp repeat)
2147           Configure the timer to trigger after "after" seconds (fractional
2148           and negative values are supported). If "repeat" is 0., then it will
2149           automatically be stopped once the timeout is reached. If it is
2150           positive, then the timer will automatically be configured to
2151           trigger again "repeat" seconds later, again, and again, until
2152           stopped manually.
2153
2154           The timer itself will do a best-effort at avoiding drift, that is,
2155           if you configure a timer to trigger every 10 seconds, then it will
2156           normally trigger at exactly 10 second intervals. If, however, your
2157           program cannot keep up with the timer (because it takes longer than
2158           those 10 seconds to do stuff) the timer will not fire more than
2159           once per event loop iteration.
2160
2161       ev_timer_again (loop, ev_timer *)
2162           This will act as if the timer timed out, and restarts it again if
2163           it is repeating. It basically works like calling "ev_timer_stop",
2164           updating the timeout to the "repeat" value and calling
2165           "ev_timer_start".
2166
2167           The exact semantics are as in the following rules, all of which
2168           will be applied to the watcher:
2169
2170           If the timer is pending, the pending status is always cleared.
2171           If the timer is started but non-repeating, stop it (as if it timed
2172           out, without invoking it).
2173           If the timer is repeating, make the "repeat" value the new timeout
2174           and start the timer, if necessary.
2175
2176           This sounds a bit complicated, see "Be smart about timeouts",
2177           above, for a usage example.
2178
2179       ev_tstamp ev_timer_remaining (loop, ev_timer *)
2180           Returns the remaining time until a timer fires. If the timer is
2181           active, then this time is relative to the current event loop time,
2182           otherwise it's the timeout value currently configured.
2183
2184           That is, after an "ev_timer_set (w, 5, 7)", "ev_timer_remaining"
2185           returns 5. When the timer is started and one second passes,
2186           "ev_timer_remaining" will return 4. When the timer expires and is
2187           restarted, it will return roughly 7 (likely slightly less as
2188           callback invocation takes some time, too), and so on.
2189
2190       ev_tstamp repeat [read-write]
2191           The current "repeat" value. Will be used each time the watcher
2192           times out or "ev_timer_again" is called, and determines the next
2193           timeout (if any), which is also when any modifications are taken
2194           into account.
2195
2196       Examples
2197
2198       Example: Create a timer that fires after 60 seconds.
2199
2200          static void
2201          one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents)
2202          {
2203            .. one minute over, w is actually stopped right here
2204          }
2205
2206          ev_timer mytimer;
2207          ev_timer_init (&mytimer, one_minute_cb, 60., 0.);
2208          ev_timer_start (loop, &mytimer);
2209
2210       Example: Create a timeout timer that times out after 10 seconds of
2211       inactivity.
2212
2213          static void
2214          timeout_cb (struct ev_loop *loop, ev_timer *w, int revents)
2215          {
2216            .. ten seconds without any activity
2217          }
2218
2219          ev_timer mytimer;
2220          ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */
2221          ev_timer_again (&mytimer); /* start timer */
2222          ev_run (loop, 0);
2223
2224          // and in some piece of code that gets executed on any "activity":
2225          // reset the timeout to start ticking again at 10 seconds
2226          ev_timer_again (&mytimer);
2227
2228   "ev_periodic" - to cron or not to cron?
2229       Periodic watchers are also timers of a kind, but they are very
2230       versatile (and unfortunately a bit complex).
2231
2232       Unlike "ev_timer", periodic watchers are not based on real time (or
2233       relative time, the physical time that passes) but on wall clock time
2234       (absolute time, the thing you can read on your calendar or clock). The
2235       difference is that wall clock time can run faster or slower than real
2236       time, and time jumps are not uncommon (e.g. when you adjust your wrist-
2237       watch).
2238
2239       You can tell a periodic watcher to trigger after some specific point in
2240       time: for example, if you tell a periodic watcher to trigger "in 10
2241       seconds" (by specifying e.g. "ev_now () + 10.", that is, an absolute
2242       time not a delay) and then reset your system clock to January of the
2243       previous year, then it will take a year or more to trigger the event
2244       (unlike an "ev_timer", which would still trigger roughly 10 seconds
2245       after starting it, as it uses a relative timeout).
2246
2247       "ev_periodic" watchers can also be used to implement vastly more
2248       complex timers, such as triggering an event on each "midnight, local
2249       time", or other complicated rules. This cannot easily be done with
2250       "ev_timer" watchers, as those cannot react to time jumps.
2251
2252       As with timers, the callback is guaranteed to be invoked only when the
2253       point in time where it is supposed to trigger has passed. If multiple
2254       timers become ready during the same loop iteration then the ones with
2255       earlier time-out values are invoked before ones with later time-out
2256       values (but this is no longer true when a callback calls "ev_run"
2257       recursively).
2258
2259       Watcher-Specific Functions and Data Members
2260
2261       ev_periodic_init (ev_periodic *, callback, ev_tstamp offset, ev_tstamp
2262       interval, reschedule_cb)
2263       ev_periodic_set (ev_periodic *, ev_tstamp offset, ev_tstamp interval,
2264       reschedule_cb)
2265           Lots of arguments, let's sort it out... There are basically three
2266           modes of operation, and we will explain them from simplest to most
2267           complex:
2268
2269           ·   absolute timer (offset = absolute time, interval = 0,
2270               reschedule_cb = 0)
2271
2272               In this configuration the watcher triggers an event after the
2273               wall clock time "offset" has passed. It will not repeat and
2274               will not adjust when a time jump occurs, that is, if it is to
2275               be run at January 1st 2011 then it will be stopped and invoked
2276               when the system clock reaches or surpasses this point in time.
2277
2278           ·   repeating interval timer (offset = offset within interval,
2279               interval > 0, reschedule_cb = 0)
2280
2281               In this mode the watcher will always be scheduled to time out
2282               at the next "offset + N * interval" time (for some integer N,
2283               which can also be negative) and then repeat, regardless of any
2284               time jumps. The "offset" argument is merely an offset into the
2285               "interval" periods.
2286
2287               This can be used to create timers that do not drift with
2288               respect to the system clock, for example, here is an
2289               "ev_periodic" that triggers each hour, on the hour (with
2290               respect to UTC):
2291
2292                  ev_periodic_set (&periodic, 0., 3600., 0);
2293
2294               This doesn't mean there will always be 3600 seconds in between
2295               triggers, but only that the callback will be called when the
2296               system time shows a full hour (UTC), or more correctly, when
2297               the system time is evenly divisible by 3600.
2298
2299               Another way to think about it (for the mathematically inclined)
2300               is that "ev_periodic" will try to run the callback in this mode
2301               at the next possible time where "time = offset (mod interval)",
2302               regardless of any time jumps.
2303
2304               The "interval" MUST be positive, and for numerical stability,
2305               the interval value should be higher than "1/8192" (which is
2306               around 100 microseconds) and "offset" should be higher than 0
2307               and should have at most a similar magnitude as the current time
2308               (say, within a factor of ten). Typical values for offset are,
2309               in fact, 0 or something between 0 and "interval", which is also
2310               the recommended range.
2311
2312               Note also that there is an upper limit to how often a timer can
2313               fire (CPU speed for example), so if "interval" is very small
2314               then timing stability will of course deteriorate. Libev itself
2315               tries to be exact to be about one millisecond (if the OS
2316               supports it and the machine is fast enough).
2317
2318           ·   manual reschedule mode (offset ignored, interval ignored,
2319               reschedule_cb = callback)
2320
2321               In this mode the values for "interval" and "offset" are both
2322               being ignored. Instead, each time the periodic watcher gets
2323               scheduled, the reschedule callback will be called with the
2324               watcher as first, and the current time as second argument.
2325
2326               NOTE: This callback MUST NOT stop or destroy any periodic
2327               watcher, ever, or make ANY other event loop modifications
2328               whatsoever, unless explicitly allowed by documentation here.
2329
2330               If you need to stop it, return "now + 1e30" (or so, fudge
2331               fudge) and stop it afterwards (e.g. by starting an "ev_prepare"
2332               watcher, which is the only event loop modification you are
2333               allowed to do).
2334
2335               The callback prototype is "ev_tstamp
2336               (*reschedule_cb)(ev_periodic *w, ev_tstamp now)", e.g.:
2337
2338                  static ev_tstamp
2339                  my_rescheduler (ev_periodic *w, ev_tstamp now)
2340                  {
2341                    return now + 60.;
2342                  }
2343
2344               It must return the next time to trigger, based on the passed
2345               time value (that is, the lowest time value larger than to the
2346               second argument). It will usually be called just before the
2347               callback will be triggered, but might be called at other times,
2348               too.
2349
2350               NOTE: This callback must always return a time that is higher
2351               than or equal to the passed "now" value.
2352
2353               This can be used to create very complex timers, such as a timer
2354               that triggers on "next midnight, local time". To do this, you
2355               would calculate the next midnight after "now" and return the
2356               timestamp value for this. Here is a (completely untested, no
2357               error checking) example on how to do this:
2358
2359                  #include <time.h>
2360
2361                  static ev_tstamp
2362                  my_rescheduler (ev_periodic *w, ev_tstamp now)
2363                  {
2364                    time_t tnow = (time_t)now;
2365                    struct tm tm;
2366                    localtime_r (&tnow, &tm);
2367
2368                    tm.tm_sec = tm.tm_min = tm.tm_hour = 0; // midnight current day
2369                    ++tm.tm_mday; // midnight next day
2370
2371                    return mktime (&tm);
2372                  }
2373
2374               Note: this code might run into trouble on days that have more
2375               then two midnights (beginning and end).
2376
2377       ev_periodic_again (loop, ev_periodic *)
2378           Simply stops and restarts the periodic watcher again. This is only
2379           useful when you changed some parameters or the reschedule callback
2380           would return a different time than the last time it was called
2381           (e.g. in a crond like program when the crontabs have changed).
2382
2383       ev_tstamp ev_periodic_at (ev_periodic *)
2384           When active, returns the absolute time that the watcher is supposed
2385           to trigger next. This is not the same as the "offset" argument to
2386           "ev_periodic_set", but indeed works even in interval and manual
2387           rescheduling modes.
2388
2389       ev_tstamp offset [read-write]
2390           When repeating, this contains the offset value, otherwise this is
2391           the absolute point in time (the "offset" value passed to
2392           "ev_periodic_set", although libev might modify this value for
2393           better numerical stability).
2394
2395           Can be modified any time, but changes only take effect when the
2396           periodic timer fires or "ev_periodic_again" is being called.
2397
2398       ev_tstamp interval [read-write]
2399           The current interval value. Can be modified any time, but changes
2400           only take effect when the periodic timer fires or
2401           "ev_periodic_again" is being called.
2402
2403       ev_tstamp (*reschedule_cb)(ev_periodic *w, ev_tstamp now) [read-write]
2404           The current reschedule callback, or 0, if this functionality is
2405           switched off. Can be changed any time, but changes only take effect
2406           when the periodic timer fires or "ev_periodic_again" is being
2407           called.
2408
2409       Examples
2410
2411       Example: Call a callback every hour, or, more precisely, whenever the
2412       system time is divisible by 3600. The callback invocation times have
2413       potentially a lot of jitter, but good long-term stability.
2414
2415          static void
2416          clock_cb (struct ev_loop *loop, ev_periodic *w, int revents)
2417          {
2418            ... its now a full hour (UTC, or TAI or whatever your clock follows)
2419          }
2420
2421          ev_periodic hourly_tick;
2422          ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0);
2423          ev_periodic_start (loop, &hourly_tick);
2424
2425       Example: The same as above, but use a reschedule callback to do it:
2426
2427          #include <math.h>
2428
2429          static ev_tstamp
2430          my_scheduler_cb (ev_periodic *w, ev_tstamp now)
2431          {
2432            return now + (3600. - fmod (now, 3600.));
2433          }
2434
2435          ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb);
2436
2437       Example: Call a callback every hour, starting now:
2438
2439          ev_periodic hourly_tick;
2440          ev_periodic_init (&hourly_tick, clock_cb,
2441                            fmod (ev_now (loop), 3600.), 3600., 0);
2442          ev_periodic_start (loop, &hourly_tick);
2443
2444   "ev_signal" - signal me when a signal gets signalled!
2445       Signal watchers will trigger an event when the process receives a
2446       specific signal one or more times. Even though signals are very
2447       asynchronous, libev will try its best to deliver signals synchronously,
2448       i.e. as part of the normal event processing, like any other event.
2449
2450       If you want signals to be delivered truly asynchronously, just use
2451       "sigaction" as you would do without libev and forget about sharing the
2452       signal. You can even use "ev_async" from a signal handler to
2453       synchronously wake up an event loop.
2454
2455       You can configure as many watchers as you like for the same signal, but
2456       only within the same loop, i.e. you can watch for "SIGINT" in your
2457       default loop and for "SIGIO" in another loop, but you cannot watch for
2458       "SIGINT" in both the default loop and another loop at the same time. At
2459       the moment, "SIGCHLD" is permanently tied to the default loop.
2460
2461       Only after the first watcher for a signal is started will libev
2462       actually register something with the kernel. It thus coexists with your
2463       own signal handlers as long as you don't register any with libev for
2464       the same signal.
2465
2466       If possible and supported, libev will install its handlers with
2467       "SA_RESTART" (or equivalent) behaviour enabled, so system calls should
2468       not be unduly interrupted. If you have a problem with system calls
2469       getting interrupted by signals you can block all signals in an
2470       "ev_check" watcher and unblock them in an "ev_prepare" watcher.
2471
2472       The special problem of inheritance over fork/execve/pthread_create
2473
2474       Both the signal mask ("sigprocmask") and the signal disposition
2475       ("sigaction") are unspecified after starting a signal watcher (and
2476       after stopping it again), that is, libev might or might not block the
2477       signal, and might or might not set or restore the installed signal
2478       handler (but see "EVFLAG_NOSIGMASK").
2479
2480       While this does not matter for the signal disposition (libev never sets
2481       signals to "SIG_IGN", so handlers will be reset to "SIG_DFL" on
2482       "execve"), this matters for the signal mask: many programs do not
2483       expect certain signals to be blocked.
2484
2485       This means that before calling "exec" (from the child) you should reset
2486       the signal mask to whatever "default" you expect (all clear is a good
2487       choice usually).
2488
2489       The simplest way to ensure that the signal mask is reset in the child
2490       is to install a fork handler with "pthread_atfork" that resets it. That
2491       will catch fork calls done by libraries (such as the libc) as well.
2492
2493       In current versions of libev, the signal will not be blocked
2494       indefinitely unless you use the "signalfd" API ("EV_SIGNALFD"). While
2495       this reduces the window of opportunity for problems, it will not go
2496       away, as libev has to modify the signal mask, at least temporarily.
2497
2498       So I can't stress this enough: If you do not reset your signal mask
2499       when you expect it to be empty, you have a race condition in your code.
2500       This is not a libev-specific thing, this is true for most event
2501       libraries.
2502
2503       The special problem of threads signal handling
2504
2505       POSIX threads has problematic signal handling semantics, specifically,
2506       a lot of functionality (sigfd, sigwait etc.) only really works if all
2507       threads in a process block signals, which is hard to achieve.
2508
2509       When you want to use sigwait (or mix libev signal handling with your
2510       own for the same signals), you can tackle this problem by globally
2511       blocking all signals before creating any threads (or creating them with
2512       a fully set sigprocmask) and also specifying the "EVFLAG_NOSIGMASK"
2513       when creating loops. Then designate one thread as "signal receiver
2514       thread" which handles these signals. You can pass on any signals that
2515       libev might be interested in by calling "ev_feed_signal".
2516
2517       Watcher-Specific Functions and Data Members
2518
2519       ev_signal_init (ev_signal *, callback, int signum)
2520       ev_signal_set (ev_signal *, int signum)
2521           Configures the watcher to trigger on the given signal number
2522           (usually one of the "SIGxxx" constants).
2523
2524       int signum [read-only]
2525           The signal the watcher watches out for.
2526
2527       Examples
2528
2529       Example: Try to exit cleanly on SIGINT.
2530
2531          static void
2532          sigint_cb (struct ev_loop *loop, ev_signal *w, int revents)
2533          {
2534            ev_break (loop, EVBREAK_ALL);
2535          }
2536
2537          ev_signal signal_watcher;
2538          ev_signal_init (&signal_watcher, sigint_cb, SIGINT);
2539          ev_signal_start (loop, &signal_watcher);
2540
2541   "ev_child" - watch out for process status changes
2542       Child watchers trigger when your process receives a SIGCHLD in response
2543       to some child status changes (most typically when a child of yours dies
2544       or exits). It is permissible to install a child watcher after the child
2545       has been forked (which implies it might have already exited), as long
2546       as the event loop isn't entered (or is continued from a watcher), i.e.,
2547       forking and then immediately registering a watcher for the child is
2548       fine, but forking and registering a watcher a few event loop iterations
2549       later or in the next callback invocation is not.
2550
2551       Only the default event loop is capable of handling signals, and
2552       therefore you can only register child watchers in the default event
2553       loop.
2554
2555       Due to some design glitches inside libev, child watchers will always be
2556       handled at maximum priority (their priority is set to "EV_MAXPRI" by
2557       libev)
2558
2559       Process Interaction
2560
2561       Libev grabs "SIGCHLD" as soon as the default event loop is initialised.
2562       This is necessary to guarantee proper behaviour even if the first child
2563       watcher is started after the child exits. The occurrence of "SIGCHLD"
2564       is recorded asynchronously, but child reaping is done synchronously as
2565       part of the event loop processing. Libev always reaps all children,
2566       even ones not watched.
2567
2568       Overriding the Built-In Processing
2569
2570       Libev offers no special support for overriding the built-in child
2571       processing, but if your application collides with libev's default child
2572       handler, you can override it easily by installing your own handler for
2573       "SIGCHLD" after initialising the default loop, and making sure the
2574       default loop never gets destroyed. You are encouraged, however, to use
2575       an event-based approach to child reaping and thus use libev's support
2576       for that, so other libev users can use "ev_child" watchers freely.
2577
2578       Stopping the Child Watcher
2579
2580       Currently, the child watcher never gets stopped, even when the child
2581       terminates, so normally one needs to stop the watcher in the callback.
2582       Future versions of libev might stop the watcher automatically when a
2583       child exit is detected (calling "ev_child_stop" twice is not a
2584       problem).
2585
2586       Watcher-Specific Functions and Data Members
2587
2588       ev_child_init (ev_child *, callback, int pid, int trace)
2589       ev_child_set (ev_child *, int pid, int trace)
2590           Configures the watcher to wait for status changes of process "pid"
2591           (or any process if "pid" is specified as 0). The callback can look
2592           at the "rstatus" member of the "ev_child" watcher structure to see
2593           the status word (use the macros from "sys/wait.h" and see your
2594           systems "waitpid" documentation). The "rpid" member contains the
2595           pid of the process causing the status change. "trace" must be
2596           either 0 (only activate the watcher when the process terminates) or
2597           1 (additionally activate the watcher when the process is stopped or
2598           continued).
2599
2600       int pid [read-only]
2601           The process id this watcher watches out for, or 0, meaning any
2602           process id.
2603
2604       int rpid [read-write]
2605           The process id that detected a status change.
2606
2607       int rstatus [read-write]
2608           The process exit/trace status caused by "rpid" (see your systems
2609           "waitpid" and "sys/wait.h" documentation for details).
2610
2611       Examples
2612
2613       Example: "fork()" a new process and install a child handler to wait for
2614       its completion.
2615
2616          ev_child cw;
2617
2618          static void
2619          child_cb (EV_P_ ev_child *w, int revents)
2620          {
2621            ev_child_stop (EV_A_ w);
2622            printf ("process %d exited with status %x\n", w->rpid, w->rstatus);
2623          }
2624
2625          pid_t pid = fork ();
2626
2627          if (pid < 0)
2628            // error
2629          else if (pid == 0)
2630            {
2631              // the forked child executes here
2632              exit (1);
2633            }
2634          else
2635            {
2636              ev_child_init (&cw, child_cb, pid, 0);
2637              ev_child_start (EV_DEFAULT_ &cw);
2638            }
2639
2640   "ev_stat" - did the file attributes just change?
2641       This watches a file system path for attribute changes. That is, it
2642       calls "stat" on that path in regular intervals (or when the OS says it
2643       changed) and sees if it changed compared to the last time, invoking the
2644       callback if it did. Starting the watcher "stat"'s the file, so only
2645       changes that happen after the watcher has been started will be
2646       reported.
2647
2648       The path does not need to exist: changing from "path exists" to "path
2649       does not exist" is a status change like any other. The condition "path
2650       does not exist" (or more correctly "path cannot be stat'ed") is
2651       signified by the "st_nlink" field being zero (which is otherwise always
2652       forced to be at least one) and all the other fields of the stat buffer
2653       having unspecified contents.
2654
2655       The path must not end in a slash or contain special components such as
2656       "." or "..". The path should be absolute: If it is relative and your
2657       working directory changes, then the behaviour is undefined.
2658
2659       Since there is no portable change notification interface available, the
2660       portable implementation simply calls stat(2) regularly on the path to
2661       see if it changed somehow. You can specify a recommended polling
2662       interval for this case. If you specify a polling interval of 0 (highly
2663       recommended!) then a suitable, unspecified default value will be used
2664       (which you can expect to be around five seconds, although this might
2665       change dynamically). Libev will also impose a minimum interval which is
2666       currently around 0.1, but that's usually overkill.
2667
2668       This watcher type is not meant for massive numbers of stat watchers, as
2669       even with OS-supported change notifications, this can be resource-
2670       intensive.
2671
2672       At the time of this writing, the only OS-specific interface implemented
2673       is the Linux inotify interface (implementing kqueue support is left as
2674       an exercise for the reader. Note, however, that the author sees no way
2675       of implementing "ev_stat" semantics with kqueue, except as a hint).
2676
2677       ABI Issues (Largefile Support)
2678
2679       Libev by default (unless the user overrides this) uses the default
2680       compilation environment, which means that on systems with large file
2681       support disabled by default, you get the 32 bit version of the stat
2682       structure. When using the library from programs that change the ABI to
2683       use 64 bit file offsets the programs will fail. In that case you have
2684       to compile libev with the same flags to get binary compatibility. This
2685       is obviously the case with any flags that change the ABI, but the
2686       problem is most noticeably displayed with ev_stat and large file
2687       support.
2688
2689       The solution for this is to lobby your distribution maker to make large
2690       file interfaces available by default (as e.g. FreeBSD does) and not
2691       optional. Libev cannot simply switch on large file support because it
2692       has to exchange stat structures with application programs compiled
2693       using the default compilation environment.
2694
2695       Inotify and Kqueue
2696
2697       When "inotify (7)" support has been compiled into libev and present at
2698       runtime, it will be used to speed up change detection where possible.
2699       The inotify descriptor will be created lazily when the first "ev_stat"
2700       watcher is being started.
2701
2702       Inotify presence does not change the semantics of "ev_stat" watchers
2703       except that changes might be detected earlier, and in some cases, to
2704       avoid making regular "stat" calls. Even in the presence of inotify
2705       support there are many cases where libev has to resort to regular
2706       "stat" polling, but as long as kernel 2.6.25 or newer is used (2.6.24
2707       and older have too many bugs), the path exists (i.e. stat succeeds),
2708       and the path resides on a local filesystem (libev currently assumes
2709       only ext2/3, jfs, reiserfs and xfs are fully working) libev usually
2710       gets away without polling.
2711
2712       There is no support for kqueue, as apparently it cannot be used to
2713       implement this functionality, due to the requirement of having a file
2714       descriptor open on the object at all times, and detecting renames,
2715       unlinks etc. is difficult.
2716
2717       "stat ()" is a synchronous operation
2718
2719       Libev doesn't normally do any kind of I/O itself, and so is not
2720       blocking the process. The exception are "ev_stat" watchers - those call
2721       "stat ()", which is a synchronous operation.
2722
2723       For local paths, this usually doesn't matter: unless the system is very
2724       busy or the intervals between stat's are large, a stat call will be
2725       fast, as the path data is usually in memory already (except when
2726       starting the watcher).
2727
2728       For networked file systems, calling "stat ()" can block an indefinite
2729       time due to network issues, and even under good conditions, a stat call
2730       often takes multiple milliseconds.
2731
2732       Therefore, it is best to avoid using "ev_stat" watchers on networked
2733       paths, although this is fully supported by libev.
2734
2735       The special problem of stat time resolution
2736
2737       The "stat ()" system call only supports full-second resolution
2738       portably, and even on systems where the resolution is higher, most file
2739       systems still only support whole seconds.
2740
2741       That means that, if the time is the only thing that changes, you can
2742       easily miss updates: on the first update, "ev_stat" detects a change
2743       and calls your callback, which does something. When there is another
2744       update within the same second, "ev_stat" will be unable to detect
2745       unless the stat data does change in other ways (e.g. file size).
2746
2747       The solution to this is to delay acting on a change for slightly more
2748       than a second (or till slightly after the next full second boundary),
2749       using a roughly one-second-delay "ev_timer" (e.g. "ev_timer_set (w, 0.,
2750       1.02); ev_timer_again (loop, w)").
2751
2752       The .02 offset is added to work around small timing inconsistencies of
2753       some operating systems (where the second counter of the current time
2754       might be be delayed. One such system is the Linux kernel, where a call
2755       to "gettimeofday" might return a timestamp with a full second later
2756       than a subsequent "time" call - if the equivalent of "time ()" is used
2757       to update file times then there will be a small window where the kernel
2758       uses the previous second to update file times but libev might already
2759       execute the timer callback).
2760
2761       Watcher-Specific Functions and Data Members
2762
2763       ev_stat_init (ev_stat *, callback, const char *path, ev_tstamp
2764       interval)
2765       ev_stat_set (ev_stat *, const char *path, ev_tstamp interval)
2766           Configures the watcher to wait for status changes of the given
2767           "path". The "interval" is a hint on how quickly a change is
2768           expected to be detected and should normally be specified as 0 to
2769           let libev choose a suitable value. The memory pointed to by "path"
2770           must point to the same path for as long as the watcher is active.
2771
2772           The callback will receive an "EV_STAT" event when a change was
2773           detected, relative to the attributes at the time the watcher was
2774           started (or the last change was detected).
2775
2776       ev_stat_stat (loop, ev_stat *)
2777           Updates the stat buffer immediately with new values. If you change
2778           the watched path in your callback, you could call this function to
2779           avoid detecting this change (while introducing a race condition if
2780           you are not the only one changing the path). Can also be useful
2781           simply to find out the new values.
2782
2783       ev_statdata attr [read-only]
2784           The most-recently detected attributes of the file. Although the
2785           type is "ev_statdata", this is usually the (or one of the) "struct
2786           stat" types suitable for your system, but you can only rely on the
2787           POSIX-standardised members to be present. If the "st_nlink" member
2788           is 0, then there was some error while "stat"ing the file.
2789
2790       ev_statdata prev [read-only]
2791           The previous attributes of the file. The callback gets invoked
2792           whenever "prev" != "attr", or, more precisely, one or more of these
2793           members differ: "st_dev", "st_ino", "st_mode", "st_nlink",
2794           "st_uid", "st_gid", "st_rdev", "st_size", "st_atime", "st_mtime",
2795           "st_ctime".
2796
2797       ev_tstamp interval [read-only]
2798           The specified interval.
2799
2800       const char *path [read-only]
2801           The file system path that is being watched.
2802
2803       Examples
2804
2805       Example: Watch "/etc/passwd" for attribute changes.
2806
2807          static void
2808          passwd_cb (struct ev_loop *loop, ev_stat *w, int revents)
2809          {
2810            /* /etc/passwd changed in some way */
2811            if (w->attr.st_nlink)
2812              {
2813                printf ("passwd current size  %ld\n", (long)w->attr.st_size);
2814                printf ("passwd current atime %ld\n", (long)w->attr.st_mtime);
2815                printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime);
2816              }
2817            else
2818              /* you shalt not abuse printf for puts */
2819              puts ("wow, /etc/passwd is not there, expect problems. "
2820                    "if this is windows, they already arrived\n");
2821          }
2822
2823          ...
2824          ev_stat passwd;
2825
2826          ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.);
2827          ev_stat_start (loop, &passwd);
2828
2829       Example: Like above, but additionally use a one-second delay so we do
2830       not miss updates (however, frequent updates will delay processing, too,
2831       so one might do the work both on "ev_stat" callback invocation and on
2832       "ev_timer" callback invocation).
2833
2834          static ev_stat passwd;
2835          static ev_timer timer;
2836
2837          static void
2838          timer_cb (EV_P_ ev_timer *w, int revents)
2839          {
2840            ev_timer_stop (EV_A_ w);
2841
2842            /* now it's one second after the most recent passwd change */
2843          }
2844
2845          static void
2846          stat_cb (EV_P_ ev_stat *w, int revents)
2847          {
2848            /* reset the one-second timer */
2849            ev_timer_again (EV_A_ &timer);
2850          }
2851
2852          ...
2853          ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.);
2854          ev_stat_start (loop, &passwd);
2855          ev_timer_init (&timer, timer_cb, 0., 1.02);
2856
2857   "ev_idle" - when you've got nothing better to do...
2858       Idle watchers trigger events when no other events of the same or higher
2859       priority are pending (prepare, check and other idle watchers do not
2860       count as receiving "events").
2861
2862       That is, as long as your process is busy handling sockets or timeouts
2863       (or even signals, imagine) of the same or higher priority it will not
2864       be triggered. But when your process is idle (or only lower-priority
2865       watchers are pending), the idle watchers are being called once per
2866       event loop iteration - until stopped, that is, or your process receives
2867       more events and becomes busy again with higher priority stuff.
2868
2869       The most noteworthy effect is that as long as any idle watchers are
2870       active, the process will not block when waiting for new events.
2871
2872       Apart from keeping your process non-blocking (which is a useful effect
2873       on its own sometimes), idle watchers are a good place to do "pseudo-
2874       background processing", or delay processing stuff to after the event
2875       loop has handled all outstanding events.
2876
2877       Abusing an "ev_idle" watcher for its side-effect
2878
2879       As long as there is at least one active idle watcher, libev will never
2880       sleep unnecessarily. Or in other words, it will loop as fast as
2881       possible.  For this to work, the idle watcher doesn't need to be
2882       invoked at all - the lowest priority will do.
2883
2884       This mode of operation can be useful together with an "ev_check"
2885       watcher, to do something on each event loop iteration - for example to
2886       balance load between different connections.
2887
2888       See "Abusing an ev_check watcher for its side-effect" for a longer
2889       example.
2890
2891       Watcher-Specific Functions and Data Members
2892
2893       ev_idle_init (ev_idle *, callback)
2894           Initialises and configures the idle watcher - it has no parameters
2895           of any kind. There is a "ev_idle_set" macro, but using it is
2896           utterly pointless, believe me.
2897
2898       Examples
2899
2900       Example: Dynamically allocate an "ev_idle" watcher, start it, and in
2901       the callback, free it. Also, use no error checking, as usual.
2902
2903          static void
2904          idle_cb (struct ev_loop *loop, ev_idle *w, int revents)
2905          {
2906            // stop the watcher
2907            ev_idle_stop (loop, w);
2908
2909            // now we can free it
2910            free (w);
2911
2912            // now do something you wanted to do when the program has
2913            // no longer anything immediate to do.
2914          }
2915
2916          ev_idle *idle_watcher = malloc (sizeof (ev_idle));
2917          ev_idle_init (idle_watcher, idle_cb);
2918          ev_idle_start (loop, idle_watcher);
2919
2920   "ev_prepare" and "ev_check" - customise your event loop!
2921       Prepare and check watchers are often (but not always) used in pairs:
2922       prepare watchers get invoked before the process blocks and check
2923       watchers afterwards.
2924
2925       You must not call "ev_run" (or similar functions that enter the current
2926       event loop) or "ev_loop_fork" from either "ev_prepare" or "ev_check"
2927       watchers. Other loops than the current one are fine, however. The
2928       rationale behind this is that you do not need to check for recursion in
2929       those watchers, i.e. the sequence will always be "ev_prepare",
2930       blocking, "ev_check" so if you have one watcher of each kind they will
2931       always be called in pairs bracketing the blocking call.
2932
2933       Their main purpose is to integrate other event mechanisms into libev
2934       and their use is somewhat advanced. They could be used, for example, to
2935       track variable changes, implement your own watchers, integrate net-snmp
2936       or a coroutine library and lots more. They are also occasionally useful
2937       if you cache some data and want to flush it before blocking (for
2938       example, in X programs you might want to do an "XFlush ()" in an
2939       "ev_prepare" watcher).
2940
2941       This is done by examining in each prepare call which file descriptors
2942       need to be watched by the other library, registering "ev_io" watchers
2943       for them and starting an "ev_timer" watcher for any timeouts (many
2944       libraries provide exactly this functionality). Then, in the check
2945       watcher, you check for any events that occurred (by checking the
2946       pending status of all watchers and stopping them) and call back into
2947       the library. The I/O and timer callbacks will never actually be called
2948       (but must be valid nevertheless, because you never know, you know?).
2949
2950       As another example, the Perl Coro module uses these hooks to integrate
2951       coroutines into libev programs, by yielding to other active coroutines
2952       during each prepare and only letting the process block if no coroutines
2953       are ready to run (it's actually more complicated: it only runs
2954       coroutines with priority higher than or equal to the event loop and one
2955       coroutine of lower priority, but only once, using idle watchers to keep
2956       the event loop from blocking if lower-priority coroutines are active,
2957       thus mapping low-priority coroutines to idle/background tasks).
2958
2959       When used for this purpose, it is recommended to give "ev_check"
2960       watchers highest ("EV_MAXPRI") priority, to ensure that they are being
2961       run before any other watchers after the poll (this doesn't matter for
2962       "ev_prepare" watchers).
2963
2964       Also, "ev_check" watchers (and "ev_prepare" watchers, too) should not
2965       activate ("feed") events into libev. While libev fully supports this,
2966       they might get executed before other "ev_check" watchers did their job.
2967       As "ev_check" watchers are often used to embed other (non-libev) event
2968       loops those other event loops might be in an unusable state until their
2969       "ev_check" watcher ran (always remind yourself to coexist peacefully
2970       with others).
2971
2972       Abusing an "ev_check" watcher for its side-effect
2973
2974       "ev_check" (and less often also "ev_prepare") watchers can also be
2975       useful because they are called once per event loop iteration. For
2976       example, if you want to handle a large number of connections fairly,
2977       you normally only do a bit of work for each active connection, and if
2978       there is more work to do, you wait for the next event loop iteration,
2979       so other connections have a chance of making progress.
2980
2981       Using an "ev_check" watcher is almost enough: it will be called on the
2982       next event loop iteration. However, that isn't as soon as possible -
2983       without external events, your "ev_check" watcher will not be invoked.
2984
2985       This is where "ev_idle" watchers come in handy - all you need is a
2986       single global idle watcher that is active as long as you have one
2987       active "ev_check" watcher. The "ev_idle" watcher makes sure the event
2988       loop will not sleep, and the "ev_check" watcher makes sure a callback
2989       gets invoked. Neither watcher alone can do that.
2990
2991       Watcher-Specific Functions and Data Members
2992
2993       ev_prepare_init (ev_prepare *, callback)
2994       ev_check_init (ev_check *, callback)
2995           Initialises and configures the prepare or check watcher - they have
2996           no parameters of any kind. There are "ev_prepare_set" and
2997           "ev_check_set" macros, but using them is utterly, utterly, utterly
2998           and completely pointless.
2999
3000       Examples
3001
3002       There are a number of principal ways to embed other event loops or
3003       modules into libev. Here are some ideas on how to include libadns into
3004       libev (there is a Perl module named "EV::ADNS" that does this, which
3005       you could use as a working example. Another Perl module named
3006       "EV::Glib" embeds a Glib main context into libev, and finally,
3007       "Glib::EV" embeds EV into the Glib event loop).
3008
3009       Method 1: Add IO watchers and a timeout watcher in a prepare handler,
3010       and in a check watcher, destroy them and call into libadns. What
3011       follows is pseudo-code only of course. This requires you to either use
3012       a low priority for the check watcher or use "ev_clear_pending"
3013       explicitly, as the callbacks for the IO/timeout watchers might not have
3014       been called yet.
3015
3016          static ev_io iow [nfd];
3017          static ev_timer tw;
3018
3019          static void
3020          io_cb (struct ev_loop *loop, ev_io *w, int revents)
3021          {
3022          }
3023
3024          // create io watchers for each fd and a timer before blocking
3025          static void
3026          adns_prepare_cb (struct ev_loop *loop, ev_prepare *w, int revents)
3027          {
3028            int timeout = 3600000;
3029            struct pollfd fds [nfd];
3030            // actual code will need to loop here and realloc etc.
3031            adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ()));
3032
3033            /* the callback is illegal, but won't be called as we stop during check */
3034            ev_timer_init (&tw, 0, timeout * 1e-3, 0.);
3035            ev_timer_start (loop, &tw);
3036
3037            // create one ev_io per pollfd
3038            for (int i = 0; i < nfd; ++i)
3039              {
3040                ev_io_init (iow + i, io_cb, fds [i].fd,
3041                  ((fds [i].events & POLLIN ? EV_READ : 0)
3042                   | (fds [i].events & POLLOUT ? EV_WRITE : 0)));
3043
3044                fds [i].revents = 0;
3045                ev_io_start (loop, iow + i);
3046              }
3047          }
3048
3049          // stop all watchers after blocking
3050          static void
3051          adns_check_cb (struct ev_loop *loop, ev_check *w, int revents)
3052          {
3053            ev_timer_stop (loop, &tw);
3054
3055            for (int i = 0; i < nfd; ++i)
3056              {
3057                // set the relevant poll flags
3058                // could also call adns_processreadable etc. here
3059                struct pollfd *fd = fds + i;
3060                int revents = ev_clear_pending (iow + i);
3061                if (revents & EV_READ ) fd->revents |= fd->events & POLLIN;
3062                if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT;
3063
3064                // now stop the watcher
3065                ev_io_stop (loop, iow + i);
3066              }
3067
3068            adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop));
3069          }
3070
3071       Method 2: This would be just like method 1, but you run
3072       "adns_afterpoll" in the prepare watcher and would dispose of the check
3073       watcher.
3074
3075       Method 3: If the module to be embedded supports explicit event
3076       notification (libadns does), you can also make use of the actual
3077       watcher callbacks, and only destroy/create the watchers in the prepare
3078       watcher.
3079
3080          static void
3081          timer_cb (EV_P_ ev_timer *w, int revents)
3082          {
3083            adns_state ads = (adns_state)w->data;
3084            update_now (EV_A);
3085
3086            adns_processtimeouts (ads, &tv_now);
3087          }
3088
3089          static void
3090          io_cb (EV_P_ ev_io *w, int revents)
3091          {
3092            adns_state ads = (adns_state)w->data;
3093            update_now (EV_A);
3094
3095            if (revents & EV_READ ) adns_processreadable  (ads, w->fd, &tv_now);
3096            if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now);
3097          }
3098
3099          // do not ever call adns_afterpoll
3100
3101       Method 4: Do not use a prepare or check watcher because the module you
3102       want to embed is not flexible enough to support it. Instead, you can
3103       override their poll function. The drawback with this solution is that
3104       the main loop is now no longer controllable by EV. The "Glib::EV"
3105       module uses this approach, effectively embedding EV as a client into
3106       the horrible libglib event loop.
3107
3108          static gint
3109          event_poll_func (GPollFD *fds, guint nfds, gint timeout)
3110          {
3111            int got_events = 0;
3112
3113            for (n = 0; n < nfds; ++n)
3114              // create/start io watcher that sets the relevant bits in fds[n] and increment got_events
3115
3116            if (timeout >= 0)
3117              // create/start timer
3118
3119            // poll
3120            ev_run (EV_A_ 0);
3121
3122            // stop timer again
3123            if (timeout >= 0)
3124              ev_timer_stop (EV_A_ &to);
3125
3126            // stop io watchers again - their callbacks should have set
3127            for (n = 0; n < nfds; ++n)
3128              ev_io_stop (EV_A_ iow [n]);
3129
3130            return got_events;
3131          }
3132
3133   "ev_embed" - when one backend isn't enough...
3134       This is a rather advanced watcher type that lets you embed one event
3135       loop into another (currently only "ev_io" events are supported in the
3136       embedded loop, other types of watchers might be handled in a delayed or
3137       incorrect fashion and must not be used).
3138
3139       There are primarily two reasons you would want that: work around bugs
3140       and prioritise I/O.
3141
3142       As an example for a bug workaround, the kqueue backend might only
3143       support sockets on some platform, so it is unusable as generic backend,
3144       but you still want to make use of it because you have many sockets and
3145       it scales so nicely. In this case, you would create a kqueue-based loop
3146       and embed it into your default loop (which might use e.g. poll).
3147       Overall operation will be a bit slower because first libev has to call
3148       "poll" and then "kevent", but at least you can use both mechanisms for
3149       what they are best: "kqueue" for scalable sockets and "poll" if you
3150       want it to work :)
3151
3152       As for prioritising I/O: under rare circumstances you have the case
3153       where some fds have to be watched and handled very quickly (with low
3154       latency), and even priorities and idle watchers might have too much
3155       overhead. In this case you would put all the high priority stuff in one
3156       loop and all the rest in a second one, and embed the second one in the
3157       first.
3158
3159       As long as the watcher is active, the callback will be invoked every
3160       time there might be events pending in the embedded loop. The callback
3161       must then call "ev_embed_sweep (mainloop, watcher)" to make a single
3162       sweep and invoke their callbacks (the callback doesn't need to invoke
3163       the "ev_embed_sweep" function directly, it could also start an idle
3164       watcher to give the embedded loop strictly lower priority for example).
3165
3166       You can also set the callback to 0, in which case the embed watcher
3167       will automatically execute the embedded loop sweep whenever necessary.
3168
3169       Fork detection will be handled transparently while the "ev_embed"
3170       watcher is active, i.e., the embedded loop will automatically be forked
3171       when the embedding loop forks. In other cases, the user is responsible
3172       for calling "ev_loop_fork" on the embedded loop.
3173
3174       Unfortunately, not all backends are embeddable: only the ones returned
3175       by "ev_embeddable_backends" are, which, unfortunately, does not include
3176       any portable one.
3177
3178       So when you want to use this feature you will always have to be
3179       prepared that you cannot get an embeddable loop. The recommended way to
3180       get around this is to have a separate variables for your embeddable
3181       loop, try to create it, and if that fails, use the normal loop for
3182       everything.
3183
3184       "ev_embed" and fork
3185
3186       While the "ev_embed" watcher is running, forks in the embedding loop
3187       will automatically be applied to the embedded loop as well, so no
3188       special fork handling is required in that case. When the watcher is not
3189       running, however, it is still the task of the libev user to call
3190       "ev_loop_fork ()" as applicable.
3191
3192       Watcher-Specific Functions and Data Members
3193
3194       ev_embed_init (ev_embed *, callback, struct ev_loop *embedded_loop)
3195       ev_embed_set (ev_embed *, struct ev_loop *embedded_loop)
3196           Configures the watcher to embed the given loop, which must be
3197           embeddable. If the callback is 0, then "ev_embed_sweep" will be
3198           invoked automatically, otherwise it is the responsibility of the
3199           callback to invoke it (it will continue to be called until the
3200           sweep has been done, if you do not want that, you need to
3201           temporarily stop the embed watcher).
3202
3203       ev_embed_sweep (loop, ev_embed *)
3204           Make a single, non-blocking sweep over the embedded loop. This
3205           works similarly to "ev_run (embedded_loop, EVRUN_NOWAIT)", but in
3206           the most appropriate way for embedded loops.
3207
3208       struct ev_loop *other [read-only]
3209           The embedded event loop.
3210
3211       Examples
3212
3213       Example: Try to get an embeddable event loop and embed it into the
3214       default event loop. If that is not possible, use the default loop. The
3215       default loop is stored in "loop_hi", while the embeddable loop is
3216       stored in "loop_lo" (which is "loop_hi" in the case no embeddable loop
3217       can be used).
3218
3219          struct ev_loop *loop_hi = ev_default_init (0);
3220          struct ev_loop *loop_lo = 0;
3221          ev_embed embed;
3222
3223          // see if there is a chance of getting one that works
3224          // (remember that a flags value of 0 means autodetection)
3225          loop_lo = ev_embeddable_backends () & ev_recommended_backends ()
3226            ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ())
3227            : 0;
3228
3229          // if we got one, then embed it, otherwise default to loop_hi
3230          if (loop_lo)
3231            {
3232              ev_embed_init (&embed, 0, loop_lo);
3233              ev_embed_start (loop_hi, &embed);
3234            }
3235          else
3236            loop_lo = loop_hi;
3237
3238       Example: Check if kqueue is available but not recommended and create a
3239       kqueue backend for use with sockets (which usually work with any kqueue
3240       implementation). Store the kqueue/socket-only event loop in
3241       "loop_socket". (One might optionally use "EVFLAG_NOENV", too).
3242
3243          struct ev_loop *loop = ev_default_init (0);
3244          struct ev_loop *loop_socket = 0;
3245          ev_embed embed;
3246
3247          if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE)
3248            if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE))
3249              {
3250                ev_embed_init (&embed, 0, loop_socket);
3251                ev_embed_start (loop, &embed);
3252              }
3253
3254          if (!loop_socket)
3255            loop_socket = loop;
3256
3257          // now use loop_socket for all sockets, and loop for everything else
3258
3259   "ev_fork" - the audacity to resume the event loop after a fork
3260       Fork watchers are called when a "fork ()" was detected (usually because
3261       whoever is a good citizen cared to tell libev about it by calling
3262       "ev_loop_fork"). The invocation is done before the event loop blocks
3263       next and before "ev_check" watchers are being called, and only in the
3264       child after the fork. If whoever good citizen calling "ev_default_fork"
3265       cheats and calls it in the wrong process, the fork handlers will be
3266       invoked, too, of course.
3267
3268       The special problem of life after fork - how is it possible?
3269
3270       Most uses of "fork ()" consist of forking, then some simple calls to
3271       set up/change the process environment, followed by a call to "exec()".
3272       This sequence should be handled by libev without any problems.
3273
3274       This changes when the application actually wants to do event handling
3275       in the child, or both parent in child, in effect "continuing" after the
3276       fork.
3277
3278       The default mode of operation (for libev, with application help to
3279       detect forks) is to duplicate all the state in the child, as would be
3280       expected when either the parent or the child process continues.
3281
3282       When both processes want to continue using libev, then this is usually
3283       the wrong result. In that case, usually one process (typically the
3284       parent) is supposed to continue with all watchers in place as before,
3285       while the other process typically wants to start fresh, i.e. without
3286       any active watchers.
3287
3288       The cleanest and most efficient way to achieve that with libev is to
3289       simply create a new event loop, which of course will be "empty", and
3290       use that for new watchers. This has the advantage of not touching more
3291       memory than necessary, and thus avoiding the copy-on-write, and the
3292       disadvantage of having to use multiple event loops (which do not
3293       support signal watchers).
3294
3295       When this is not possible, or you want to use the default loop for
3296       other reasons, then in the process that wants to start "fresh", call
3297       "ev_loop_destroy (EV_DEFAULT)" followed by "ev_default_loop (...)".
3298       Destroying the default loop will "orphan" (not stop) all registered
3299       watchers, so you have to be careful not to execute code that modifies
3300       those watchers. Note also that in that case, you have to re-register
3301       any signal watchers.
3302
3303       Watcher-Specific Functions and Data Members
3304
3305       ev_fork_init (ev_fork *, callback)
3306           Initialises and configures the fork watcher - it has no parameters
3307           of any kind. There is a "ev_fork_set" macro, but using it is
3308           utterly pointless, really.
3309
3310   "ev_cleanup" - even the best things end
3311       Cleanup watchers are called just before the event loop is being
3312       destroyed by a call to "ev_loop_destroy".
3313
3314       While there is no guarantee that the event loop gets destroyed, cleanup
3315       watchers provide a convenient method to install cleanup hooks for your
3316       program, worker threads and so on - you just to make sure to destroy
3317       the loop when you want them to be invoked.
3318
3319       Cleanup watchers are invoked in the same way as any other watcher.
3320       Unlike all other watchers, they do not keep a reference to the event
3321       loop (which makes a lot of sense if you think about it). Like all other
3322       watchers, you can call libev functions in the callback, except
3323       "ev_cleanup_start".
3324
3325       Watcher-Specific Functions and Data Members
3326
3327       ev_cleanup_init (ev_cleanup *, callback)
3328           Initialises and configures the cleanup watcher - it has no
3329           parameters of any kind. There is a "ev_cleanup_set" macro, but
3330           using it is utterly pointless, I assure you.
3331
3332       Example: Register an atexit handler to destroy the default loop, so any
3333       cleanup functions are called.
3334
3335          static void
3336          program_exits (void)
3337          {
3338            ev_loop_destroy (EV_DEFAULT_UC);
3339          }
3340
3341          ...
3342          atexit (program_exits);
3343
3344   "ev_async" - how to wake up an event loop
3345       In general, you cannot use an "ev_loop" from multiple threads or other
3346       asynchronous sources such as signal handlers (as opposed to multiple
3347       event loops - those are of course safe to use in different threads).
3348
3349       Sometimes, however, you need to wake up an event loop you do not
3350       control, for example because it belongs to another thread. This is what
3351       "ev_async" watchers do: as long as the "ev_async" watcher is active,
3352       you can signal it by calling "ev_async_send", which is thread- and
3353       signal safe.
3354
3355       This functionality is very similar to "ev_signal" watchers, as signals,
3356       too, are asynchronous in nature, and signals, too, will be compressed
3357       (i.e. the number of callback invocations may be less than the number of
3358       "ev_async_send" calls). In fact, you could use signal watchers as a
3359       kind of "global async watchers" by using a watcher on an otherwise
3360       unused signal, and "ev_feed_signal" to signal this watcher from another
3361       thread, even without knowing which loop owns the signal.
3362
3363       Queueing
3364
3365       "ev_async" does not support queueing of data in any way. The reason is
3366       that the author does not know of a simple (or any) algorithm for a
3367       multiple-writer-single-reader queue that works in all cases and doesn't
3368       need elaborate support such as pthreads or unportable memory access
3369       semantics.
3370
3371       That means that if you want to queue data, you have to provide your own
3372       queue. But at least I can tell you how to implement locking around your
3373       queue:
3374
3375       queueing from a signal handler context
3376           To implement race-free queueing, you simply add to the queue in the
3377           signal handler but you block the signal handler in the watcher
3378           callback. Here is an example that does that for some fictitious
3379           SIGUSR1 handler:
3380
3381              static ev_async mysig;
3382
3383              static void
3384              sigusr1_handler (void)
3385              {
3386                sometype data;
3387
3388                // no locking etc.
3389                queue_put (data);
3390                ev_async_send (EV_DEFAULT_ &mysig);
3391              }
3392
3393              static void
3394              mysig_cb (EV_P_ ev_async *w, int revents)
3395              {
3396                sometype data;
3397                sigset_t block, prev;
3398
3399                sigemptyset (&block);
3400                sigaddset (&block, SIGUSR1);
3401                sigprocmask (SIG_BLOCK, &block, &prev);
3402
3403                while (queue_get (&data))
3404                  process (data);
3405
3406                if (sigismember (&prev, SIGUSR1)
3407                  sigprocmask (SIG_UNBLOCK, &block, 0);
3408              }
3409
3410           (Note: pthreads in theory requires you to use "pthread_setmask"
3411           instead of "sigprocmask" when you use threads, but libev doesn't do
3412           it either...).
3413
3414       queueing from a thread context
3415           The strategy for threads is different, as you cannot (easily) block
3416           threads but you can easily preempt them, so to queue safely you
3417           need to employ a traditional mutex lock, such as in this pthread
3418           example:
3419
3420              static ev_async mysig;
3421              static pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
3422
3423              static void
3424              otherthread (void)
3425              {
3426                // only need to lock the actual queueing operation
3427                pthread_mutex_lock (&mymutex);
3428                queue_put (data);
3429                pthread_mutex_unlock (&mymutex);
3430
3431                ev_async_send (EV_DEFAULT_ &mysig);
3432              }
3433
3434              static void
3435              mysig_cb (EV_P_ ev_async *w, int revents)
3436              {
3437                pthread_mutex_lock (&mymutex);
3438
3439                while (queue_get (&data))
3440                  process (data);
3441
3442                pthread_mutex_unlock (&mymutex);
3443              }
3444
3445       Watcher-Specific Functions and Data Members
3446
3447       ev_async_init (ev_async *, callback)
3448           Initialises and configures the async watcher - it has no parameters
3449           of any kind. There is a "ev_async_set" macro, but using it is
3450           utterly pointless, trust me.
3451
3452       ev_async_send (loop, ev_async *)
3453           Sends/signals/activates the given "ev_async" watcher, that is,
3454           feeds an "EV_ASYNC" event on the watcher into the event loop, and
3455           instantly returns.
3456
3457           Unlike "ev_feed_event", this call is safe to do from other threads,
3458           signal or similar contexts (see the discussion of "EV_ATOMIC_T" in
3459           the embedding section below on what exactly this means).
3460
3461           Note that, as with other watchers in libev, multiple events might
3462           get compressed into a single callback invocation (another way to
3463           look at this is that "ev_async" watchers are level-triggered: they
3464           are set on "ev_async_send", reset when the event loop detects
3465           that).
3466
3467           This call incurs the overhead of at most one extra system call per
3468           event loop iteration, if the event loop is blocked, and no syscall
3469           at all if the event loop (or your program) is processing events.
3470           That means that repeated calls are basically free (there is no need
3471           to avoid calls for performance reasons) and that the overhead
3472           becomes smaller (typically zero) under load.
3473
3474       bool = ev_async_pending (ev_async *)
3475           Returns a non-zero value when "ev_async_send" has been called on
3476           the watcher but the event has not yet been processed (or even
3477           noted) by the event loop.
3478
3479           "ev_async_send" sets a flag in the watcher and wakes up the loop.
3480           When the loop iterates next and checks for the watcher to have
3481           become active, it will reset the flag again. "ev_async_pending" can
3482           be used to very quickly check whether invoking the loop might be a
3483           good idea.
3484
3485           Not that this does not check whether the watcher itself is pending,
3486           only whether it has been requested to make this watcher pending:
3487           there is a time window between the event loop checking and
3488           resetting the async notification, and the callback being invoked.
3489

OTHER FUNCTIONS

3491       There are some other functions of possible interest. Described. Here.
3492       Now.
3493
3494       ev_once (loop, int fd, int events, ev_tstamp timeout, callback, arg)
3495           This function combines a simple timer and an I/O watcher, calls
3496           your callback on whichever event happens first and automatically
3497           stops both watchers. This is useful if you want to wait for a
3498           single event on an fd or timeout without having to
3499           allocate/configure/start/stop/free one or more watchers yourself.
3500
3501           If "fd" is less than 0, then no I/O watcher will be started and the
3502           "events" argument is being ignored. Otherwise, an "ev_io" watcher
3503           for the given "fd" and "events" set will be created and started.
3504
3505           If "timeout" is less than 0, then no timeout watcher will be
3506           started. Otherwise an "ev_timer" watcher with after = "timeout"
3507           (and repeat = 0) will be started. 0 is a valid timeout.
3508
3509           The callback has the type "void (*cb)(int revents, void *arg)" and
3510           is passed an "revents" set like normal event callbacks (a
3511           combination of "EV_ERROR", "EV_READ", "EV_WRITE" or "EV_TIMER") and
3512           the "arg" value passed to "ev_once". Note that it is possible to
3513           receive both a timeout and an io event at the same time - you
3514           probably should give io events precedence.
3515
3516           Example: wait up to ten seconds for data to appear on STDIN_FILENO.
3517
3518              static void stdin_ready (int revents, void *arg)
3519              {
3520                if (revents & EV_READ)
3521                  /* stdin might have data for us, joy! */;
3522                else if (revents & EV_TIMER)
3523                  /* doh, nothing entered */;
3524              }
3525
3526              ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);
3527
3528       ev_feed_fd_event (loop, int fd, int revents)
3529           Feed an event on the given fd, as if a file descriptor backend
3530           detected the given events.
3531
3532       ev_feed_signal_event (loop, int signum)
3533           Feed an event as if the given signal occurred. See also
3534           "ev_feed_signal", which is async-safe.
3535

COMMON OR USEFUL IDIOMS (OR BOTH)

3537       This section explains some common idioms that are not immediately
3538       obvious. Note that examples are sprinkled over the whole manual, and
3539       this section only contains stuff that wouldn't fit anywhere else.
3540
3541   ASSOCIATING CUSTOM DATA WITH A WATCHER
3542       Each watcher has, by default, a "void *data" member that you can read
3543       or modify at any time: libev will completely ignore it. This can be
3544       used to associate arbitrary data with your watcher. If you need more
3545       data and don't want to allocate memory separately and store a pointer
3546       to it in that data member, you can also "subclass" the watcher type and
3547       provide your own data:
3548
3549          struct my_io
3550          {
3551            ev_io io;
3552            int otherfd;
3553            void *somedata;
3554            struct whatever *mostinteresting;
3555          };
3556
3557          ...
3558          struct my_io w;
3559          ev_io_init (&w.io, my_cb, fd, EV_READ);
3560
3561       And since your callback will be called with a pointer to the watcher,
3562       you can cast it back to your own type:
3563
3564          static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
3565          {
3566            struct my_io *w = (struct my_io *)w_;
3567            ...
3568          }
3569
3570       More interesting and less C-conformant ways of casting your callback
3571       function type instead have been omitted.
3572
3573   BUILDING YOUR OWN COMPOSITE WATCHERS
3574       Another common scenario is to use some data structure with multiple
3575       embedded watchers, in effect creating your own watcher that combines
3576       multiple libev event sources into one "super-watcher":
3577
3578          struct my_biggy
3579          {
3580            int some_data;
3581            ev_timer t1;
3582            ev_timer t2;
3583          }
3584
3585       In this case getting the pointer to "my_biggy" is a bit more
3586       complicated: Either you store the address of your "my_biggy" struct in
3587       the "data" member of the watcher (for woozies or C++ coders), or you
3588       need to use some pointer arithmetic using "offsetof" inside your
3589       watchers (for real programmers):
3590
3591          #include <stddef.h>
3592
3593          static void
3594          t1_cb (EV_P_ ev_timer *w, int revents)
3595          {
3596            struct my_biggy big = (struct my_biggy *)
3597              (((char *)w) - offsetof (struct my_biggy, t1));
3598          }
3599
3600          static void
3601          t2_cb (EV_P_ ev_timer *w, int revents)
3602          {
3603            struct my_biggy big = (struct my_biggy *)
3604              (((char *)w) - offsetof (struct my_biggy, t2));
3605          }
3606
3607   AVOIDING FINISHING BEFORE RETURNING
3608       Often you have structures like this in event-based programs:
3609
3610         callback ()
3611         {
3612           free (request);
3613         }
3614
3615         request = start_new_request (..., callback);
3616
3617       The intent is to start some "lengthy" operation. The "request" could be
3618       used to cancel the operation, or do other things with it.
3619
3620       It's not uncommon to have code paths in "start_new_request" that
3621       immediately invoke the callback, for example, to report errors. Or you
3622       add some caching layer that finds that it can skip the lengthy aspects
3623       of the operation and simply invoke the callback with the result.
3624
3625       The problem here is that this will happen before "start_new_request"
3626       has returned, so "request" is not set.
3627
3628       Even if you pass the request by some safer means to the callback, you
3629       might want to do something to the request after starting it, such as
3630       canceling it, which probably isn't working so well when the callback
3631       has already been invoked.
3632
3633       A common way around all these issues is to make sure that
3634       "start_new_request" always returns before the callback is invoked. If
3635       "start_new_request" immediately knows the result, it can artificially
3636       delay invoking the callback by using a "prepare" or "idle" watcher for
3637       example, or more sneakily, by reusing an existing (stopped) watcher and
3638       pushing it into the pending queue:
3639
3640          ev_set_cb (watcher, callback);
3641          ev_feed_event (EV_A_ watcher, 0);
3642
3643       This way, "start_new_request" can safely return before the callback is
3644       invoked, while not delaying callback invocation too much.
3645
3646   MODEL/NESTED EVENT LOOP INVOCATIONS AND EXIT CONDITIONS
3647       Often (especially in GUI toolkits) there are places where you have
3648       modal interaction, which is most easily implemented by recursively
3649       invoking "ev_run".
3650
3651       This brings the problem of exiting - a callback might want to finish
3652       the main "ev_run" call, but not the nested one (e.g. user clicked
3653       "Quit", but a modal "Are you sure?" dialog is still waiting), or just
3654       the nested one and not the main one (e.g. user clocked "Ok" in a modal
3655       dialog), or some other combination: In these cases, a simple "ev_break"
3656       will not work.
3657
3658       The solution is to maintain "break this loop" variable for each
3659       "ev_run" invocation, and use a loop around "ev_run" until the condition
3660       is triggered, using "EVRUN_ONCE":
3661
3662          // main loop
3663          int exit_main_loop = 0;
3664
3665          while (!exit_main_loop)
3666            ev_run (EV_DEFAULT_ EVRUN_ONCE);
3667
3668          // in a modal watcher
3669          int exit_nested_loop = 0;
3670
3671          while (!exit_nested_loop)
3672            ev_run (EV_A_ EVRUN_ONCE);
3673
3674       To exit from any of these loops, just set the corresponding exit
3675       variable:
3676
3677          // exit modal loop
3678          exit_nested_loop = 1;
3679
3680          // exit main program, after modal loop is finished
3681          exit_main_loop = 1;
3682
3683          // exit both
3684          exit_main_loop = exit_nested_loop = 1;
3685
3686   THREAD LOCKING EXAMPLE
3687       Here is a fictitious example of how to run an event loop in a different
3688       thread from where callbacks are being invoked and watchers are
3689       created/added/removed.
3690
3691       For a real-world example, see the "EV::Loop::Async" perl module, which
3692       uses exactly this technique (which is suited for many high-level
3693       languages).
3694
3695       The example uses a pthread mutex to protect the loop data, a condition
3696       variable to wait for callback invocations, an async watcher to notify
3697       the event loop thread and an unspecified mechanism to wake up the main
3698       thread.
3699
3700       First, you need to associate some data with the event loop:
3701
3702          typedef struct {
3703            mutex_t lock; /* global loop lock */
3704            ev_async async_w;
3705            thread_t tid;
3706            cond_t invoke_cv;
3707          } userdata;
3708
3709          void prepare_loop (EV_P)
3710          {
3711             // for simplicity, we use a static userdata struct.
3712             static userdata u;
3713
3714             ev_async_init (&u->async_w, async_cb);
3715             ev_async_start (EV_A_ &u->async_w);
3716
3717             pthread_mutex_init (&u->lock, 0);
3718             pthread_cond_init (&u->invoke_cv, 0);
3719
3720             // now associate this with the loop
3721             ev_set_userdata (EV_A_ u);
3722             ev_set_invoke_pending_cb (EV_A_ l_invoke);
3723             ev_set_loop_release_cb (EV_A_ l_release, l_acquire);
3724
3725             // then create the thread running ev_run
3726             pthread_create (&u->tid, 0, l_run, EV_A);
3727          }
3728
3729       The callback for the "ev_async" watcher does nothing: the watcher is
3730       used solely to wake up the event loop so it takes notice of any new
3731       watchers that might have been added:
3732
3733          static void
3734          async_cb (EV_P_ ev_async *w, int revents)
3735          {
3736             // just used for the side effects
3737          }
3738
3739       The "l_release" and "l_acquire" callbacks simply unlock/lock the mutex
3740       protecting the loop data, respectively.
3741
3742          static void
3743          l_release (EV_P)
3744          {
3745            userdata *u = ev_userdata (EV_A);
3746            pthread_mutex_unlock (&u->lock);
3747          }
3748
3749          static void
3750          l_acquire (EV_P)
3751          {
3752            userdata *u = ev_userdata (EV_A);
3753            pthread_mutex_lock (&u->lock);
3754          }
3755
3756       The event loop thread first acquires the mutex, and then jumps straight
3757       into "ev_run":
3758
3759          void *
3760          l_run (void *thr_arg)
3761          {
3762            struct ev_loop *loop = (struct ev_loop *)thr_arg;
3763
3764            l_acquire (EV_A);
3765            pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
3766            ev_run (EV_A_ 0);
3767            l_release (EV_A);
3768
3769            return 0;
3770          }
3771
3772       Instead of invoking all pending watchers, the "l_invoke" callback will
3773       signal the main thread via some unspecified mechanism (signals? pipe
3774       writes? "Async::Interrupt"?) and then waits until all pending watchers
3775       have been called (in a while loop because a) spurious wakeups are
3776       possible and b) skipping inter-thread-communication when there are no
3777       pending watchers is very beneficial):
3778
3779          static void
3780          l_invoke (EV_P)
3781          {
3782            userdata *u = ev_userdata (EV_A);
3783
3784            while (ev_pending_count (EV_A))
3785              {
3786                wake_up_other_thread_in_some_magic_or_not_so_magic_way ();
3787                pthread_cond_wait (&u->invoke_cv, &u->lock);
3788              }
3789          }
3790
3791       Now, whenever the main thread gets told to invoke pending watchers, it
3792       will grab the lock, call "ev_invoke_pending" and then signal the loop
3793       thread to continue:
3794
3795          static void
3796          real_invoke_pending (EV_P)
3797          {
3798            userdata *u = ev_userdata (EV_A);
3799
3800            pthread_mutex_lock (&u->lock);
3801            ev_invoke_pending (EV_A);
3802            pthread_cond_signal (&u->invoke_cv);
3803            pthread_mutex_unlock (&u->lock);
3804          }
3805
3806       Whenever you want to start/stop a watcher or do other modifications to
3807       an event loop, you will now have to lock:
3808
3809          ev_timer timeout_watcher;
3810          userdata *u = ev_userdata (EV_A);
3811
3812          ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
3813
3814          pthread_mutex_lock (&u->lock);
3815          ev_timer_start (EV_A_ &timeout_watcher);
3816          ev_async_send (EV_A_ &u->async_w);
3817          pthread_mutex_unlock (&u->lock);
3818
3819       Note that sending the "ev_async" watcher is required because otherwise
3820       an event loop currently blocking in the kernel will have no knowledge
3821       about the newly added timer. By waking up the loop it will pick up any
3822       new watchers in the next event loop iteration.
3823
3824   THREADS, COROUTINES, CONTINUATIONS, QUEUES... INSTEAD OF CALLBACKS
3825       While the overhead of a callback that e.g. schedules a thread is small,
3826       it is still an overhead. If you embed libev, and your main usage is
3827       with some kind of threads or coroutines, you might want to customise
3828       libev so that doesn't need callbacks anymore.
3829
3830       Imagine you have coroutines that you can switch to using a function
3831       "switch_to (coro)", that libev runs in a coroutine called "libev_coro"
3832       and that due to some magic, the currently active coroutine is stored in
3833       a global called "current_coro". Then you can build your own "wait for
3834       libev event" primitive by changing "EV_CB_DECLARE" and "EV_CB_INVOKE"
3835       (note the differing ";" conventions):
3836
3837          #define EV_CB_DECLARE(type)   struct my_coro *cb;
3838          #define EV_CB_INVOKE(watcher) switch_to ((watcher)->cb)
3839
3840       That means instead of having a C callback function, you store the
3841       coroutine to switch to in each watcher, and instead of having libev
3842       call your callback, you instead have it switch to that coroutine.
3843
3844       A coroutine might now wait for an event with a function called
3845       "wait_for_event". (the watcher needs to be started, as always, but it
3846       doesn't matter when, or whether the watcher is active or not when this
3847       function is called):
3848
3849          void
3850          wait_for_event (ev_watcher *w)
3851          {
3852            ev_set_cb (w, current_coro);
3853            switch_to (libev_coro);
3854          }
3855
3856       That basically suspends the coroutine inside "wait_for_event" and
3857       continues the libev coroutine, which, when appropriate, switches back
3858       to this or any other coroutine.
3859
3860       You can do similar tricks if you have, say, threads with an event queue
3861       - instead of storing a coroutine, you store the queue object and
3862       instead of switching to a coroutine, you push the watcher onto the
3863       queue and notify any waiters.
3864
3865       To embed libev, see "EMBEDDING", but in short, it's easiest to create
3866       two files, my_ev.h and my_ev.c that include the respective libev files:
3867
3868          // my_ev.h
3869          #define EV_CB_DECLARE(type)   struct my_coro *cb;
3870          #define EV_CB_INVOKE(watcher) switch_to ((watcher)->cb)
3871          #include "../libev/ev.h"
3872
3873          // my_ev.c
3874          #define EV_H "my_ev.h"
3875          #include "../libev/ev.c"
3876
3877       And then use my_ev.h when you would normally use ev.h, and compile
3878       my_ev.c into your project. When properly specifying include paths, you
3879       can even use ev.h as header file name directly.
3880

LIBEVENT EMULATION

3882       Libev offers a compatibility emulation layer for libevent. It cannot
3883       emulate the internals of libevent, so here are some usage hints:
3884
3885       ·   Only the libevent-1.4.1-beta API is being emulated.
3886
3887           This was the newest libevent version available when libev was
3888           implemented, and is still mostly unchanged in 2010.
3889
3890       ·   Use it by including <event.h>, as usual.
3891
3892       ·   The following members are fully supported: ev_base, ev_callback,
3893           ev_arg, ev_fd, ev_res, ev_events.
3894
3895       ·   Avoid using ev_flags and the EVLIST_*-macros, while it is
3896           maintained by libev, it does not work exactly the same way as in
3897           libevent (consider it a private API).
3898
3899       ·   Priorities are not currently supported. Initialising priorities
3900           will fail and all watchers will have the same priority, even though
3901           there is an ev_pri field.
3902
3903       ·   In libevent, the last base created gets the signals, in libev, the
3904           base that registered the signal gets the signals.
3905
3906       ·   Other members are not supported.
3907
3908       ·   The libev emulation is not ABI compatible to libevent, you need to
3909           use the libev header file and library.
3910

C++ SUPPORT

3912   C API
3913       The normal C API should work fine when used from C++: both ev.h and the
3914       libev sources can be compiled as C++. Therefore, code that uses the C
3915       API will work fine.
3916
3917       Proper exception specifications might have to be added to callbacks
3918       passed to libev: exceptions may be thrown only from watcher callbacks,
3919       all other callbacks (allocator, syserr, loop acquire/release and
3920       periodic reschedule callbacks) must not throw exceptions, and might
3921       need a "noexcept" specification. If you have code that needs to be
3922       compiled as both C and C++ you can use the "EV_NOEXCEPT" macro for
3923       this:
3924
3925          static void
3926          fatal_error (const char *msg) EV_NOEXCEPT
3927          {
3928            perror (msg);
3929            abort ();
3930          }
3931
3932          ...
3933          ev_set_syserr_cb (fatal_error);
3934
3935       The only API functions that can currently throw exceptions are
3936       "ev_run", "ev_invoke", "ev_invoke_pending" and "ev_loop_destroy" (the
3937       latter because it runs cleanup watchers).
3938
3939       Throwing exceptions in watcher callbacks is only supported if libev
3940       itself is compiled with a C++ compiler or your C and C++ environments
3941       allow throwing exceptions through C libraries (most do).
3942
3943   C++ API
3944       Libev comes with some simplistic wrapper classes for C++ that mainly
3945       allow you to use some convenience methods to start/stop watchers and
3946       also change the callback model to a model using method callbacks on
3947       objects.
3948
3949       To use it,
3950
3951          #include <ev++.h>
3952
3953       This automatically includes ev.h and puts all of its definitions (many
3954       of them macros) into the global namespace. All C++ specific things are
3955       put into the "ev" namespace. It should support all the same embedding
3956       options as ev.h, most notably "EV_MULTIPLICITY".
3957
3958       Care has been taken to keep the overhead low. The only data member the
3959       C++ classes add (compared to plain C-style watchers) is the event loop
3960       pointer that the watcher is associated with (or no additional members
3961       at all if you disable "EV_MULTIPLICITY" when embedding libev).
3962
3963       Currently, functions, static and non-static member functions and
3964       classes with "operator ()" can be used as callbacks. Other types should
3965       be easy to add as long as they only need one additional pointer for
3966       context. If you need support for other types of functors please contact
3967       the author (preferably after implementing it).
3968
3969       For all this to work, your C++ compiler either has to use the same
3970       calling conventions as your C compiler (for static member functions),
3971       or you have to embed libev and compile libev itself as C++.
3972
3973       Here is a list of things available in the "ev" namespace:
3974
3975       "ev::READ", "ev::WRITE" etc.
3976           These are just enum values with the same values as the "EV_READ"
3977           etc.  macros from ev.h.
3978
3979       "ev::tstamp", "ev::now"
3980           Aliases to the same types/functions as with the "ev_" prefix.
3981
3982       "ev::io", "ev::timer", "ev::periodic", "ev::idle", "ev::sig" etc.
3983           For each "ev_TYPE" watcher in ev.h there is a corresponding class
3984           of the same name in the "ev" namespace, with the exception of
3985           "ev_signal" which is called "ev::sig" to avoid clashes with the
3986           "signal" macro defined by many implementations.
3987
3988           All of those classes have these methods:
3989
3990           ev::TYPE::TYPE ()
3991           ev::TYPE::TYPE (loop)
3992           ev::TYPE::~TYPE
3993               The constructor (optionally) takes an event loop to associate
3994               the watcher with. If it is omitted, it will use "EV_DEFAULT".
3995
3996               The constructor calls "ev_init" for you, which means you have
3997               to call the "set" method before starting it.
3998
3999               It will not set a callback, however: You have to call the
4000               templated "set" method to set a callback before you can start
4001               the watcher.
4002
4003               (The reason why you have to use a method is a limitation in C++
4004               which does not allow explicit template arguments for
4005               constructors).
4006
4007               The destructor automatically stops the watcher if it is active.
4008
4009           w->set<class, &class::method> (object *)
4010               This method sets the callback method to call. The method has to
4011               have a signature of "void (*)(ev_TYPE &, int)", it receives the
4012               watcher as first argument and the "revents" as second. The
4013               object must be given as parameter and is stored in the "data"
4014               member of the watcher.
4015
4016               This method synthesizes efficient thunking code to call your
4017               method from the C callback that libev requires. If your
4018               compiler can inline your callback (i.e. it is visible to it at
4019               the place of the "set" call and your compiler is good :), then
4020               the method will be fully inlined into the thunking function,
4021               making it as fast as a direct C callback.
4022
4023               Example: simple class declaration and watcher initialisation
4024
4025                  struct myclass
4026                  {
4027                    void io_cb (ev::io &w, int revents) { }
4028                  }
4029
4030                  myclass obj;
4031                  ev::io iow;
4032                  iow.set <myclass, &myclass::io_cb> (&obj);
4033
4034           w->set (object *)
4035               This is a variation of a method callback - leaving out the
4036               method to call will default the method to "operator ()", which
4037               makes it possible to use functor objects without having to
4038               manually specify the "operator ()" all the time. Incidentally,
4039               you can then also leave out the template argument list.
4040
4041               The "operator ()" method prototype must be "void operator
4042               ()(watcher &w, int revents)".
4043
4044               See the method-"set" above for more details.
4045
4046               Example: use a functor object as callback.
4047
4048                  struct myfunctor
4049                  {
4050                    void operator() (ev::io &w, int revents)
4051                    {
4052                      ...
4053                    }
4054                  }
4055
4056                  myfunctor f;
4057
4058                  ev::io w;
4059                  w.set (&f);
4060
4061           w->set<function> (void *data = 0)
4062               Also sets a callback, but uses a static method or plain
4063               function as callback. The optional "data" argument will be
4064               stored in the watcher's "data" member and is free for you to
4065               use.
4066
4067               The prototype of the "function" must be "void (*)(ev::TYPE &w,
4068               int)".
4069
4070               See the method-"set" above for more details.
4071
4072               Example: Use a plain function as callback.
4073
4074                  static void io_cb (ev::io &w, int revents) { }
4075                  iow.set <io_cb> ();
4076
4077           w->set (loop)
4078               Associates a different "struct ev_loop" with this watcher. You
4079               can only do this when the watcher is inactive (and not pending
4080               either).
4081
4082           w->set ([arguments])
4083               Basically the same as "ev_TYPE_set" (except for "ev::embed"
4084               watchers>), with the same arguments. Either this method or a
4085               suitable start method must be called at least once. Unlike the
4086               C counterpart, an active watcher gets automatically stopped and
4087               restarted when reconfiguring it with this method.
4088
4089               For "ev::embed" watchers this method is called "set_embed", to
4090               avoid clashing with the "set (loop)" method.
4091
4092           w->start ()
4093               Starts the watcher. Note that there is no "loop" argument, as
4094               the constructor already stores the event loop.
4095
4096           w->start ([arguments])
4097               Instead of calling "set" and "start" methods separately, it is
4098               often convenient to wrap them in one call. Uses the same type
4099               of arguments as the configure "set" method of the watcher.
4100
4101           w->stop ()
4102               Stops the watcher if it is active. Again, no "loop" argument.
4103
4104           w->again () ("ev::timer", "ev::periodic" only)
4105               For "ev::timer" and "ev::periodic", this invokes the
4106               corresponding "ev_TYPE_again" function.
4107
4108           w->sweep () ("ev::embed" only)
4109               Invokes "ev_embed_sweep".
4110
4111           w->update () ("ev::stat" only)
4112               Invokes "ev_stat_stat".
4113
4114       Example: Define a class with two I/O and idle watchers, start the I/O
4115       watchers in the constructor.
4116
4117          class myclass
4118          {
4119            ev::io   io  ; void io_cb   (ev::io   &w, int revents);
4120            ev::io   io2 ; void io2_cb  (ev::io   &w, int revents);
4121            ev::idle idle; void idle_cb (ev::idle &w, int revents);
4122
4123            myclass (int fd)
4124            {
4125              io  .set <myclass, &myclass::io_cb  > (this);
4126              io2 .set <myclass, &myclass::io2_cb > (this);
4127              idle.set <myclass, &myclass::idle_cb> (this);
4128
4129              io.set (fd, ev::WRITE); // configure the watcher
4130              io.start ();            // start it whenever convenient
4131
4132              io2.start (fd, ev::READ); // set + start in one call
4133            }
4134          };
4135

OTHER LANGUAGE BINDINGS

4137       Libev does not offer other language bindings itself, but bindings for a
4138       number of languages exist in the form of third-party packages. If you
4139       know any interesting language binding in addition to the ones listed
4140       here, drop me a note.
4141
4142       Perl
4143           The EV module implements the full libev API and is actually used to
4144           test libev. EV is developed together with libev. Apart from the EV
4145           core module, there are additional modules that implement libev-
4146           compatible interfaces to "libadns" ("EV::ADNS", but "AnyEvent::DNS"
4147           is preferred nowadays), "Net::SNMP" ("Net::SNMP::EV") and the
4148           "libglib" event core ("Glib::EV" and "EV::Glib").
4149
4150           It can be found and installed via CPAN, its homepage is at
4151           <http://software.schmorp.de/pkg/EV>.
4152
4153       Python
4154           Python bindings can be found at <http://code.google.com/p/pyev/>.
4155           It seems to be quite complete and well-documented.
4156
4157       Ruby
4158           Tony Arcieri has written a ruby extension that offers access to a
4159           subset of the libev API and adds file handle abstractions,
4160           asynchronous DNS and more on top of it. It can be found via gem
4161           servers. Its homepage is at <http://rev.rubyforge.org/>.
4162
4163           Roger Pack reports that using the link order "-lws2_32
4164           -lmsvcrt-ruby-190" makes rev work even on mingw.
4165
4166       Haskell
4167           A haskell binding to libev is available at
4168           <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hlibev>.
4169
4170       D   Leandro Lucarella has written a D language binding (ev.d) for
4171           libev, to be found at
4172           <http://www.llucax.com.ar/proj/ev.d/index.html>.
4173
4174       Ocaml
4175           Erkki Seppala has written Ocaml bindings for libev, to be found at
4176           <http://modeemi.cs.tut.fi/~flux/software/ocaml-ev/>.
4177
4178       Lua Brian Maher has written a partial interface to libev for lua (at
4179           the time of this writing, only "ev_io" and "ev_timer"), to be found
4180           at <http://github.com/brimworks/lua-ev>.
4181
4182       Javascript
4183           Node.js (<http://nodejs.org>) uses libev as the underlying event
4184           library.
4185
4186       Others
4187           There are others, and I stopped counting.
4188

MACRO MAGIC

4190       Libev can be compiled with a variety of options, the most fundamental
4191       of which is "EV_MULTIPLICITY". This option determines whether (most)
4192       functions and callbacks have an initial "struct ev_loop *" argument.
4193
4194       To make it easier to write programs that cope with either variant, the
4195       following macros are defined:
4196
4197       "EV_A", "EV_A_"
4198           This provides the loop argument for functions, if one is required
4199           ("ev loop argument"). The "EV_A" form is used when this is the sole
4200           argument, "EV_A_" is used when other arguments are following.
4201           Example:
4202
4203              ev_unref (EV_A);
4204              ev_timer_add (EV_A_ watcher);
4205              ev_run (EV_A_ 0);
4206
4207           It assumes the variable "loop" of type "struct ev_loop *" is in
4208           scope, which is often provided by the following macro.
4209
4210       "EV_P", "EV_P_"
4211           This provides the loop parameter for functions, if one is required
4212           ("ev loop parameter"). The "EV_P" form is used when this is the
4213           sole parameter, "EV_P_" is used when other parameters are
4214           following. Example:
4215
4216              // this is how ev_unref is being declared
4217              static void ev_unref (EV_P);
4218
4219              // this is how you can declare your typical callback
4220              static void cb (EV_P_ ev_timer *w, int revents)
4221
4222           It declares a parameter "loop" of type "struct ev_loop *", quite
4223           suitable for use with "EV_A".
4224
4225       "EV_DEFAULT", "EV_DEFAULT_"
4226           Similar to the other two macros, this gives you the value of the
4227           default loop, if multiple loops are supported ("ev loop default").
4228           The default loop will be initialised if it isn't already
4229           initialised.
4230
4231           For non-multiplicity builds, these macros do nothing, so you always
4232           have to initialise the loop somewhere.
4233
4234       "EV_DEFAULT_UC", "EV_DEFAULT_UC_"
4235           Usage identical to "EV_DEFAULT" and "EV_DEFAULT_", but requires
4236           that the default loop has been initialised ("UC" == unchecked).
4237           Their behaviour is undefined when the default loop has not been
4238           initialised by a previous execution of "EV_DEFAULT", "EV_DEFAULT_"
4239           or "ev_default_init (...)".
4240
4241           It is often prudent to use "EV_DEFAULT" when initialising the first
4242           watcher in a function but use "EV_DEFAULT_UC" afterwards.
4243
4244       Example: Declare and initialise a check watcher, utilising the above
4245       macros so it will work regardless of whether multiple loops are
4246       supported or not.
4247
4248          static void
4249          check_cb (EV_P_ ev_timer *w, int revents)
4250          {
4251            ev_check_stop (EV_A_ w);
4252          }
4253
4254          ev_check check;
4255          ev_check_init (&check, check_cb);
4256          ev_check_start (EV_DEFAULT_ &check);
4257          ev_run (EV_DEFAULT_ 0);
4258

EMBEDDING

4260       Libev can (and often is) directly embedded into host applications.
4261       Examples of applications that embed it include the Deliantra Game
4262       Server, the EV perl module, the GNU Virtual Private Ethernet (gvpe) and
4263       rxvt-unicode.
4264
4265       The goal is to enable you to just copy the necessary files into your
4266       source directory without having to change even a single line in them,
4267       so you can easily upgrade by simply copying (or having a checked-out
4268       copy of libev somewhere in your source tree).
4269
4270   FILESETS
4271       Depending on what features you need you need to include one or more
4272       sets of files in your application.
4273
4274       CORE EVENT LOOP
4275
4276       To include only the libev core (all the "ev_*" functions), with manual
4277       configuration (no autoconf):
4278
4279          #define EV_STANDALONE 1
4280          #include "ev.c"
4281
4282       This will automatically include ev.h, too, and should be done in a
4283       single C source file only to provide the function implementations. To
4284       use it, do the same for ev.h in all files wishing to use this API (best
4285       done by writing a wrapper around ev.h that you can include instead and
4286       where you can put other configuration options):
4287
4288          #define EV_STANDALONE 1
4289          #include "ev.h"
4290
4291       Both header files and implementation files can be compiled with a C++
4292       compiler (at least, that's a stated goal, and breakage will be treated
4293       as a bug).
4294
4295       You need the following files in your source tree, or in a directory in
4296       your include path (e.g. in libev/ when using -Ilibev):
4297
4298          ev.h
4299          ev.c
4300          ev_vars.h
4301          ev_wrap.h
4302
4303          ev_win32.c      required on win32 platforms only
4304
4305          ev_select.c     only when select backend is enabled
4306          ev_poll.c       only when poll backend is enabled
4307          ev_epoll.c      only when the epoll backend is enabled
4308          ev_linuxaio.c   only when the linux aio backend is enabled
4309          ev_kqueue.c     only when the kqueue backend is enabled
4310          ev_port.c       only when the solaris port backend is enabled
4311
4312       ev.c includes the backend files directly when enabled, so you only need
4313       to compile this single file.
4314
4315       LIBEVENT COMPATIBILITY API
4316
4317       To include the libevent compatibility API, also include:
4318
4319          #include "event.c"
4320
4321       in the file including ev.c, and:
4322
4323          #include "event.h"
4324
4325       in the files that want to use the libevent API. This also includes
4326       ev.h.
4327
4328       You need the following additional files for this:
4329
4330          event.h
4331          event.c
4332
4333       AUTOCONF SUPPORT
4334
4335       Instead of using "EV_STANDALONE=1" and providing your configuration in
4336       whatever way you want, you can also "m4_include([libev.m4])" in your
4337       configure.ac and leave "EV_STANDALONE" undefined. ev.c will then
4338       include config.h and configure itself accordingly.
4339
4340       For this of course you need the m4 file:
4341
4342          libev.m4
4343
4344   PREPROCESSOR SYMBOLS/MACROS
4345       Libev can be configured via a variety of preprocessor symbols you have
4346       to define before including (or compiling) any of its files. The default
4347       in the absence of autoconf is documented for every option.
4348
4349       Symbols marked with "(h)" do not change the ABI, and can have different
4350       values when compiling libev vs. including ev.h, so it is permissible to
4351       redefine them before including ev.h without breaking compatibility to a
4352       compiled library. All other symbols change the ABI, which means all
4353       users of libev and the libev code itself must be compiled with
4354       compatible settings.
4355
4356       EV_COMPAT3 (h)
4357           Backwards compatibility is a major concern for libev. This is why
4358           this release of libev comes with wrappers for the functions and
4359           symbols that have been renamed between libev version 3 and 4.
4360
4361           You can disable these wrappers (to test compatibility with future
4362           versions) by defining "EV_COMPAT3" to 0 when compiling your
4363           sources. This has the additional advantage that you can drop the
4364           "struct" from "struct ev_loop" declarations, as libev will provide
4365           an "ev_loop" typedef in that case.
4366
4367           In some future version, the default for "EV_COMPAT3" will become 0,
4368           and in some even more future version the compatibility code will be
4369           removed completely.
4370
4371       EV_STANDALONE (h)
4372           Must always be 1 if you do not use autoconf configuration, which
4373           keeps libev from including config.h, and it also defines dummy
4374           implementations for some libevent functions (such as logging, which
4375           is not supported). It will also not define any of the structs
4376           usually found in event.h that are not directly supported by the
4377           libev core alone.
4378
4379           In standalone mode, libev will still try to automatically deduce
4380           the configuration, but has to be more conservative.
4381
4382       EV_USE_FLOOR
4383           If defined to be 1, libev will use the "floor ()" function for its
4384           periodic reschedule calculations, otherwise libev will fall back on
4385           a portable (slower) implementation. If you enable this, you usually
4386           have to link against libm or something equivalent. Enabling this
4387           when the "floor" function is not available will fail, so the safe
4388           default is to not enable this.
4389
4390       EV_USE_MONOTONIC
4391           If defined to be 1, libev will try to detect the availability of
4392           the monotonic clock option at both compile time and runtime.
4393           Otherwise no use of the monotonic clock option will be attempted.
4394           If you enable this, you usually have to link against librt or
4395           something similar. Enabling it when the functionality isn't
4396           available is safe, though, although you have to make sure you link
4397           against any libraries where the "clock_gettime" function is hiding
4398           in (often -lrt). See also "EV_USE_CLOCK_SYSCALL".
4399
4400       EV_USE_REALTIME
4401           If defined to be 1, libev will try to detect the availability of
4402           the real-time clock option at compile time (and assume its
4403           availability at runtime if successful). Otherwise no use of the
4404           real-time clock option will be attempted. This effectively replaces
4405           "gettimeofday" by "clock_get (CLOCK_REALTIME, ...)" and will not
4406           normally affect correctness. See the note about libraries in the
4407           description of "EV_USE_MONOTONIC", though. Defaults to the opposite
4408           value of "EV_USE_CLOCK_SYSCALL".
4409
4410       EV_USE_CLOCK_SYSCALL
4411           If defined to be 1, libev will try to use a direct syscall instead
4412           of calling the system-provided "clock_gettime" function. This
4413           option exists because on GNU/Linux, "clock_gettime" is in "librt",
4414           but "librt" unconditionally pulls in "libpthread", slowing down
4415           single-threaded programs needlessly. Using a direct syscall is
4416           slightly slower (in theory), because no optimised vdso
4417           implementation can be used, but avoids the pthread dependency.
4418           Defaults to 1 on GNU/Linux with glibc 2.x or higher, as it
4419           simplifies linking (no need for "-lrt").
4420
4421       EV_USE_NANOSLEEP
4422           If defined to be 1, libev will assume that "nanosleep ()" is
4423           available and will use it for delays. Otherwise it will use "select
4424           ()".
4425
4426       EV_USE_EVENTFD
4427           If defined to be 1, then libev will assume that "eventfd ()" is
4428           available and will probe for kernel support at runtime. This will
4429           improve "ev_signal" and "ev_async" performance and reduce resource
4430           consumption.  If undefined, it will be enabled if the headers
4431           indicate GNU/Linux + Glibc 2.7 or newer, otherwise disabled.
4432
4433       EV_USE_SELECT
4434           If undefined or defined to be 1, libev will compile in support for
4435           the "select"(2) backend. No attempt at auto-detection will be done:
4436           if no other method takes over, select will be it. Otherwise the
4437           select backend will not be compiled in.
4438
4439       EV_SELECT_USE_FD_SET
4440           If defined to 1, then the select backend will use the system
4441           "fd_set" structure. This is useful if libev doesn't compile due to
4442           a missing "NFDBITS" or "fd_mask" definition or it mis-guesses the
4443           bitset layout on exotic systems. This usually limits the range of
4444           file descriptors to some low limit such as 1024 or might have other
4445           limitations (winsocket only allows 64 sockets). The "FD_SETSIZE"
4446           macro, set before compilation, configures the maximum size of the
4447           "fd_set".
4448
4449       EV_SELECT_IS_WINSOCKET
4450           When defined to 1, the select backend will assume that
4451           select/socket/connect etc. don't understand file descriptors but
4452           wants osf handles on win32 (this is the case when the select to be
4453           used is the winsock select). This means that it will call
4454           "_get_osfhandle" on the fd to convert it to an OS handle.
4455           Otherwise, it is assumed that all these functions actually work on
4456           fds, even on win32. Should not be defined on non-win32 platforms.
4457
4458       EV_FD_TO_WIN32_HANDLE(fd)
4459           If "EV_SELECT_IS_WINSOCKET" is enabled, then libev needs a way to
4460           map file descriptors to socket handles. When not defining this
4461           symbol (the default), then libev will call "_get_osfhandle", which
4462           is usually correct. In some cases, programs use their own file
4463           descriptor management, in which case they can provide this function
4464           to map fds to socket handles.
4465
4466       EV_WIN32_HANDLE_TO_FD(handle)
4467           If "EV_SELECT_IS_WINSOCKET" then libev maps handles to file
4468           descriptors using the standard "_open_osfhandle" function. For
4469           programs implementing their own fd to handle mapping, overwriting
4470           this function makes it easier to do so. This can be done by
4471           defining this macro to an appropriate value.
4472
4473       EV_WIN32_CLOSE_FD(fd)
4474           If programs implement their own fd to handle mapping on win32, then
4475           this macro can be used to override the "close" function, useful to
4476           unregister file descriptors again. Note that the replacement
4477           function has to close the underlying OS handle.
4478
4479       EV_USE_WSASOCKET
4480           If defined to be 1, libev will use "WSASocket" to create its
4481           internal communication socket, which works better in some
4482           environments. Otherwise, the normal "socket" function will be used,
4483           which works better in other environments.
4484
4485       EV_USE_POLL
4486           If defined to be 1, libev will compile in support for the "poll"(2)
4487           backend. Otherwise it will be enabled on non-win32 platforms. It
4488           takes precedence over select.
4489
4490       EV_USE_EPOLL
4491           If defined to be 1, libev will compile in support for the Linux
4492           "epoll"(7) backend. Its availability will be detected at runtime,
4493           otherwise another method will be used as fallback. This is the
4494           preferred backend for GNU/Linux systems. If undefined, it will be
4495           enabled if the headers indicate GNU/Linux + Glibc 2.4 or newer,
4496           otherwise disabled.
4497
4498       EV_USE_LINUXAIO
4499           If defined to be 1, libev will compile in support for the Linux aio
4500           backend. Due to it's currenbt limitations it has to be requested
4501           explicitly.  If undefined, it will be enabled on linux, otherwise
4502           disabled.
4503
4504       EV_USE_KQUEUE
4505           If defined to be 1, libev will compile in support for the BSD style
4506           "kqueue"(2) backend. Its actual availability will be detected at
4507           runtime, otherwise another method will be used as fallback. This is
4508           the preferred backend for BSD and BSD-like systems, although on
4509           most BSDs kqueue only supports some types of fds correctly (the
4510           only platform we found that supports ptys for example was NetBSD),
4511           so kqueue might be compiled in, but not be used unless explicitly
4512           requested. The best way to use it is to find out whether kqueue
4513           supports your type of fd properly and use an embedded kqueue loop.
4514
4515       EV_USE_PORT
4516           If defined to be 1, libev will compile in support for the Solaris
4517           10 port style backend. Its availability will be detected at
4518           runtime, otherwise another method will be used as fallback. This is
4519           the preferred backend for Solaris 10 systems.
4520
4521       EV_USE_DEVPOLL
4522           Reserved for future expansion, works like the USE symbols above.
4523
4524       EV_USE_INOTIFY
4525           If defined to be 1, libev will compile in support for the Linux
4526           inotify interface to speed up "ev_stat" watchers. Its actual
4527           availability will be detected at runtime. If undefined, it will be
4528           enabled if the headers indicate GNU/Linux + Glibc 2.4 or newer,
4529           otherwise disabled.
4530
4531       EV_NO_SMP
4532           If defined to be 1, libev will assume that memory is always
4533           coherent between threads, that is, threads can be used, but threads
4534           never run on different cpus (or different cpu cores). This reduces
4535           dependencies and makes libev faster.
4536
4537       EV_NO_THREADS
4538           If defined to be 1, libev will assume that it will never be called
4539           from different threads (that includes signal handlers), which is a
4540           stronger assumption than "EV_NO_SMP", above. This reduces
4541           dependencies and makes libev faster.
4542
4543       EV_ATOMIC_T
4544           Libev requires an integer type (suitable for storing 0 or 1) whose
4545           access is atomic with respect to other threads or signal contexts.
4546           No such type is easily found in the C language, so you can provide
4547           your own type that you know is safe for your purposes. It is used
4548           both for signal handler "locking" as well as for signal and thread
4549           safety in "ev_async" watchers.
4550
4551           In the absence of this define, libev will use "sig_atomic_t
4552           volatile" (from signal.h), which is usually good enough on most
4553           platforms.
4554
4555       EV_H (h)
4556           The name of the ev.h header file used to include it. The default if
4557           undefined is "ev.h" in event.h, ev.c and ev++.h. This can be used
4558           to virtually rename the ev.h header file in case of conflicts.
4559
4560       EV_CONFIG_H (h)
4561           If "EV_STANDALONE" isn't 1, this variable can be used to override
4562           ev.c's idea of where to find the config.h file, similarly to
4563           "EV_H", above.
4564
4565       EV_EVENT_H (h)
4566           Similarly to "EV_H", this macro can be used to override event.c's
4567           idea of how the event.h header can be found, the default is
4568           "event.h".
4569
4570       EV_PROTOTYPES (h)
4571           If defined to be 0, then ev.h will not define any function
4572           prototypes, but still define all the structs and other symbols.
4573           This is occasionally useful if you want to provide your own wrapper
4574           functions around libev functions.
4575
4576       EV_MULTIPLICITY
4577           If undefined or defined to 1, then all event-loop-specific
4578           functions will have the "struct ev_loop *" as first argument, and
4579           you can create additional independent event loops. Otherwise there
4580           will be no support for multiple event loops and there is no first
4581           event loop pointer argument. Instead, all functions act on the
4582           single default loop.
4583
4584           Note that "EV_DEFAULT" and "EV_DEFAULT_" will no longer provide a
4585           default loop when multiplicity is switched off - you always have to
4586           initialise the loop manually in this case.
4587
4588       EV_MINPRI
4589       EV_MAXPRI
4590           The range of allowed priorities. "EV_MINPRI" must be smaller or
4591           equal to "EV_MAXPRI", but otherwise there are no non-obvious
4592           limitations. You can provide for more priorities by overriding
4593           those symbols (usually defined to be "-2" and 2, respectively).
4594
4595           When doing priority-based operations, libev usually has to linearly
4596           search all the priorities, so having many of them (hundreds) uses a
4597           lot of space and time, so using the defaults of five priorities (-2
4598           .. +2) is usually fine.
4599
4600           If your embedding application does not need any priorities,
4601           defining these both to 0 will save some memory and CPU.
4602
4603       EV_PERIODIC_ENABLE, EV_IDLE_ENABLE, EV_EMBED_ENABLE, EV_STAT_ENABLE,
4604       EV_PREPARE_ENABLE, EV_CHECK_ENABLE, EV_FORK_ENABLE, EV_SIGNAL_ENABLE,
4605       EV_ASYNC_ENABLE, EV_CHILD_ENABLE.
4606           If undefined or defined to be 1 (and the platform supports it),
4607           then the respective watcher type is supported. If defined to be 0,
4608           then it is not. Disabling watcher types mainly saves code size.
4609
4610       EV_FEATURES
4611           If you need to shave off some kilobytes of code at the expense of
4612           some speed (but with the full API), you can define this symbol to
4613           request certain subsets of functionality. The default is to enable
4614           all features that can be enabled on the platform.
4615
4616           A typical way to use this symbol is to define it to 0 (or to a
4617           bitset with some broad features you want) and then selectively re-
4618           enable additional parts you want, for example if you want
4619           everything minimal, but multiple event loop support, async and
4620           child watchers and the poll backend, use this:
4621
4622              #define EV_FEATURES 0
4623              #define EV_MULTIPLICITY 1
4624              #define EV_USE_POLL 1
4625              #define EV_CHILD_ENABLE 1
4626              #define EV_ASYNC_ENABLE 1
4627
4628           The actual value is a bitset, it can be a combination of the
4629           following values (by default, all of these are enabled):
4630
4631           1 - faster/larger code
4632               Use larger code to speed up some operations.
4633
4634               Currently this is used to override some inlining decisions
4635               (enlarging the code size by roughly 30% on amd64).
4636
4637               When optimising for size, use of compiler flags such as "-Os"
4638               with gcc is recommended, as well as "-DNDEBUG", as libev
4639               contains a number of assertions.
4640
4641               The default is off when "__OPTIMIZE_SIZE__" is defined by your
4642               compiler (e.g. gcc with "-Os").
4643
4644           2 - faster/larger data structures
4645               Replaces the small 2-heap for timer management by a faster
4646               4-heap, larger hash table sizes and so on. This will usually
4647               further increase code size and can additionally have an effect
4648               on the size of data structures at runtime.
4649
4650               The default is off when "__OPTIMIZE_SIZE__" is defined by your
4651               compiler (e.g. gcc with "-Os").
4652
4653           4 - full API configuration
4654               This enables priorities (sets "EV_MAXPRI"=2 and
4655               "EV_MINPRI"=-2), and enables multiplicity
4656               ("EV_MULTIPLICITY"=1).
4657
4658           8 - full API
4659               This enables a lot of the "lesser used" API functions. See
4660               "ev.h" for details on which parts of the API are still
4661               available without this feature, and do not complain if this
4662               subset changes over time.
4663
4664           16 - enable all optional watcher types
4665               Enables all optional watcher types.  If you want to selectively
4666               enable only some watcher types other than I/O and timers (e.g.
4667               prepare, embed, async, child...) you can enable them manually
4668               by defining "EV_watchertype_ENABLE" to 1 instead.
4669
4670           32 - enable all backends
4671               This enables all backends - without this feature, you need to
4672               enable at least one backend manually ("EV_USE_SELECT" is a good
4673               choice).
4674
4675           64 - enable OS-specific "helper" APIs
4676               Enable inotify, eventfd, signalfd and similar OS-specific
4677               helper APIs by default.
4678
4679           Compiling with "gcc -Os -DEV_STANDALONE -DEV_USE_EPOLL=1
4680           -DEV_FEATURES=0" reduces the compiled size of libev from 24.7Kb
4681           code/2.8Kb data to 6.5Kb code/0.3Kb data on my GNU/Linux amd64
4682           system, while still giving you I/O watchers, timers and monotonic
4683           clock support.
4684
4685           With an intelligent-enough linker (gcc+binutils are intelligent
4686           enough when you use "-Wl,--gc-sections -ffunction-sections")
4687           functions unused by your program might be left out as well - a
4688           binary starting a timer and an I/O watcher then might come out at
4689           only 5Kb.
4690
4691       EV_API_STATIC
4692           If this symbol is defined (by default it is not), then all
4693           identifiers will have static linkage. This means that libev will
4694           not export any identifiers, and you cannot link against libev
4695           anymore. This can be useful when you embed libev, only want to use
4696           libev functions in a single file, and do not want its identifiers
4697           to be visible.
4698
4699           To use this, define "EV_API_STATIC" and include ev.c in the file
4700           that wants to use libev.
4701
4702           This option only works when libev is compiled with a C compiler, as
4703           C++ doesn't support the required declaration syntax.
4704
4705       EV_AVOID_STDIO
4706           If this is set to 1 at compiletime, then libev will avoid using
4707           stdio functions (printf, scanf, perror etc.). This will increase
4708           the code size somewhat, but if your program doesn't otherwise
4709           depend on stdio and your libc allows it, this avoids linking in the
4710           stdio library which is quite big.
4711
4712           Note that error messages might become less precise when this option
4713           is enabled.
4714
4715       EV_NSIG
4716           The highest supported signal number, +1 (or, the number of
4717           signals): Normally, libev tries to deduce the maximum number of
4718           signals automatically, but sometimes this fails, in which case it
4719           can be specified. Also, using a lower number than detected (32
4720           should be good for about any system in existence) can save some
4721           memory, as libev statically allocates some 12-24 bytes per signal
4722           number.
4723
4724       EV_PID_HASHSIZE
4725           "ev_child" watchers use a small hash table to distribute workload
4726           by pid. The default size is 16 (or 1 with "EV_FEATURES" disabled),
4727           usually more than enough. If you need to manage thousands of
4728           children you might want to increase this value (must be a power of
4729           two).
4730
4731       EV_INOTIFY_HASHSIZE
4732           "ev_stat" watchers use a small hash table to distribute workload by
4733           inotify watch id. The default size is 16 (or 1 with "EV_FEATURES"
4734           disabled), usually more than enough. If you need to manage
4735           thousands of "ev_stat" watchers you might want to increase this
4736           value (must be a power of two).
4737
4738       EV_USE_4HEAP
4739           Heaps are not very cache-efficient. To improve the cache-efficiency
4740           of the timer and periodics heaps, libev uses a 4-heap when this
4741           symbol is defined to 1. The 4-heap uses more complicated (longer)
4742           code but has noticeably faster performance with many (thousands) of
4743           watchers.
4744
4745           The default is 1, unless "EV_FEATURES" overrides it, in which case
4746           it will be 0.
4747
4748       EV_HEAP_CACHE_AT
4749           Heaps are not very cache-efficient. To improve the cache-efficiency
4750           of the timer and periodics heaps, libev can cache the timestamp
4751           (at) within the heap structure (selected by defining
4752           "EV_HEAP_CACHE_AT" to 1), which uses 8-12 bytes more per watcher
4753           and a few hundred bytes more code, but avoids random read accesses
4754           on heap changes. This improves performance noticeably with many
4755           (hundreds) of watchers.
4756
4757           The default is 1, unless "EV_FEATURES" overrides it, in which case
4758           it will be 0.
4759
4760       EV_VERIFY
4761           Controls how much internal verification (see "ev_verify ()") will
4762           be done: If set to 0, no internal verification code will be
4763           compiled in. If set to 1, then verification code will be compiled
4764           in, but not called. If set to 2, then the internal verification
4765           code will be called once per loop, which can slow down libev. If
4766           set to 3, then the verification code will be called very
4767           frequently, which will slow down libev considerably.
4768
4769           Verification errors are reported via C's "assert" mechanism, so if
4770           you disable that (e.g. by defining "NDEBUG") then no errors will be
4771           reported.
4772
4773           The default is 1, unless "EV_FEATURES" overrides it, in which case
4774           it will be 0.
4775
4776       EV_COMMON
4777           By default, all watchers have a "void *data" member. By redefining
4778           this macro to something else you can include more and other types
4779           of members. You have to define it each time you include one of the
4780           files, though, and it must be identical each time.
4781
4782           For example, the perl EV module uses something like this:
4783
4784              #define EV_COMMON                       \
4785                SV *self; /* contains this struct */  \
4786                SV *cb_sv, *fh /* note no trailing ";" */
4787
4788       EV_CB_DECLARE (type)
4789       EV_CB_INVOKE (watcher, revents)
4790       ev_set_cb (ev, cb)
4791           Can be used to change the callback member declaration in each
4792           watcher, and the way callbacks are invoked and set. Must expand to
4793           a struct member definition and a statement, respectively. See the
4794           ev.h header file for their default definitions. One possible use
4795           for overriding these is to avoid the "struct ev_loop *" as first
4796           argument in all cases, or to use method calls instead of plain
4797           function calls in C++.
4798
4799   EXPORTED API SYMBOLS
4800       If you need to re-export the API (e.g. via a DLL) and you need a list
4801       of exported symbols, you can use the provided Symbol.* files which list
4802       all public symbols, one per line:
4803
4804          Symbols.ev      for libev proper
4805          Symbols.event   for the libevent emulation
4806
4807       This can also be used to rename all public symbols to avoid clashes
4808       with multiple versions of libev linked together (which is obviously bad
4809       in itself, but sometimes it is inconvenient to avoid this).
4810
4811       A sed command like this will create wrapper "#define"'s that you need
4812       to include before including ev.h:
4813
4814          <Symbols.ev sed -e "s/.*/#define & myprefix_&/" >wrap.h
4815
4816       This would create a file wrap.h which essentially looks like this:
4817
4818          #define ev_backend     myprefix_ev_backend
4819          #define ev_check_start myprefix_ev_check_start
4820          #define ev_check_stop  myprefix_ev_check_stop
4821          ...
4822
4823   EXAMPLES
4824       For a real-world example of a program the includes libev verbatim, you
4825       can have a look at the EV perl module
4826       (<http://software.schmorp.de/pkg/EV.html>). It has the libev files in
4827       the libev/ subdirectory and includes them in the EV/EVAPI.h (public
4828       interface) and EV.xs (implementation) files. Only the EV.xs file will
4829       be compiled. It is pretty complex because it provides its own header
4830       file.
4831
4832       The usage in rxvt-unicode is simpler. It has a ev_cpp.h header file
4833       that everybody includes and which overrides some configure choices:
4834
4835          #define EV_FEATURES 8
4836          #define EV_USE_SELECT 1
4837          #define EV_PREPARE_ENABLE 1
4838          #define EV_IDLE_ENABLE 1
4839          #define EV_SIGNAL_ENABLE 1
4840          #define EV_CHILD_ENABLE 1
4841          #define EV_USE_STDEXCEPT 0
4842          #define EV_CONFIG_H <config.h>
4843
4844          #include "ev++.h"
4845
4846       And a ev_cpp.C implementation file that contains libev proper and is
4847       compiled:
4848
4849          #include "ev_cpp.h"
4850          #include "ev.c"
4851

INTERACTION WITH OTHER PROGRAMS, LIBRARIES OR THE ENVIRONMENT

4853   THREADS AND COROUTINES
4854       THREADS
4855
4856       All libev functions are reentrant and thread-safe unless explicitly
4857       documented otherwise, but libev implements no locking itself. This
4858       means that you can use as many loops as you want in parallel, as long
4859       as there are no concurrent calls into any libev function with the same
4860       loop parameter ("ev_default_*" calls have an implicit default loop
4861       parameter, of course): libev guarantees that different event loops
4862       share no data structures that need any locking.
4863
4864       Or to put it differently: calls with different loop parameters can be
4865       done concurrently from multiple threads, calls with the same loop
4866       parameter must be done serially (but can be done from different
4867       threads, as long as only one thread ever is inside a call at any point
4868       in time, e.g. by using a mutex per loop).
4869
4870       Specifically to support threads (and signal handlers), libev implements
4871       so-called "ev_async" watchers, which allow some limited form of
4872       concurrency on the same event loop, namely waking it up "from the
4873       outside".
4874
4875       If you want to know which design (one loop, locking, or multiple loops
4876       without or something else still) is best for your problem, then I
4877       cannot help you, but here is some generic advice:
4878
4879       ·   most applications have a main thread: use the default libev loop in
4880           that thread, or create a separate thread running only the default
4881           loop.
4882
4883           This helps integrating other libraries or software modules that use
4884           libev themselves and don't care/know about threading.
4885
4886       ·   one loop per thread is usually a good model.
4887
4888           Doing this is almost never wrong, sometimes a better-performance
4889           model exists, but it is always a good start.
4890
4891       ·   other models exist, such as the leader/follower pattern, where one
4892           loop is handed through multiple threads in a kind of round-robin
4893           fashion.
4894
4895           Choosing a model is hard - look around, learn, know that usually
4896           you can do better than you currently do :-)
4897
4898       ·   often you need to talk to some other thread which blocks in the
4899           event loop.
4900
4901           "ev_async" watchers can be used to wake them up from other threads
4902           safely (or from signal contexts...).
4903
4904           An example use would be to communicate signals or other events that
4905           only work in the default loop by registering the signal watcher
4906           with the default loop and triggering an "ev_async" watcher from the
4907           default loop watcher callback into the event loop interested in the
4908           signal.
4909
4910       See also "THREAD LOCKING EXAMPLE".
4911
4912       COROUTINES
4913
4914       Libev is very accommodating to coroutines ("cooperative threads"):
4915       libev fully supports nesting calls to its functions from different
4916       coroutines (e.g. you can call "ev_run" on the same loop from two
4917       different coroutines, and switch freely between both coroutines running
4918       the loop, as long as you don't confuse yourself). The only exception is
4919       that you must not do this from "ev_periodic" reschedule callbacks.
4920
4921       Care has been taken to ensure that libev does not keep local state
4922       inside "ev_run", and other calls do not usually allow for coroutine
4923       switches as they do not call any callbacks.
4924
4925   COMPILER WARNINGS
4926       Depending on your compiler and compiler settings, you might get no or a
4927       lot of warnings when compiling libev code. Some people are apparently
4928       scared by this.
4929
4930       However, these are unavoidable for many reasons. For one, each compiler
4931       has different warnings, and each user has different tastes regarding
4932       warning options. "Warn-free" code therefore cannot be a goal except
4933       when targeting a specific compiler and compiler-version.
4934
4935       Another reason is that some compiler warnings require elaborate
4936       workarounds, or other changes to the code that make it less clear and
4937       less maintainable.
4938
4939       And of course, some compiler warnings are just plain stupid, or simply
4940       wrong (because they don't actually warn about the condition their
4941       message seems to warn about). For example, certain older gcc versions
4942       had some warnings that resulted in an extreme number of false
4943       positives. These have been fixed, but some people still insist on
4944       making code warn-free with such buggy versions.
4945
4946       While libev is written to generate as few warnings as possible, "warn-
4947       free" code is not a goal, and it is recommended not to build libev with
4948       any compiler warnings enabled unless you are prepared to cope with them
4949       (e.g. by ignoring them). Remember that warnings are just that:
4950       warnings, not errors, or proof of bugs.
4951
4952   VALGRIND
4953       Valgrind has a special section here because it is a popular tool that
4954       is highly useful. Unfortunately, valgrind reports are very hard to
4955       interpret.
4956
4957       If you think you found a bug (memory leak, uninitialised data access
4958       etc.)  in libev, then check twice: If valgrind reports something like:
4959
4960          ==2274==    definitely lost: 0 bytes in 0 blocks.
4961          ==2274==      possibly lost: 0 bytes in 0 blocks.
4962          ==2274==    still reachable: 256 bytes in 1 blocks.
4963
4964       Then there is no memory leak, just as memory accounted to global
4965       variables is not a memleak - the memory is still being referenced, and
4966       didn't leak.
4967
4968       Similarly, under some circumstances, valgrind might report kernel bugs
4969       as if it were a bug in libev (e.g. in realloc or in the poll backend,
4970       although an acceptable workaround has been found here), or it might be
4971       confused.
4972
4973       Keep in mind that valgrind is a very good tool, but only a tool. Don't
4974       make it into some kind of religion.
4975
4976       If you are unsure about something, feel free to contact the mailing
4977       list with the full valgrind report and an explanation on why you think
4978       this is a bug in libev (best check the archives, too :). However, don't
4979       be annoyed when you get a brisk "this is no bug" answer and take the
4980       chance of learning how to interpret valgrind properly.
4981
4982       If you need, for some reason, empty reports from valgrind for your
4983       project I suggest using suppression lists.
4984

PORTABILITY NOTES

4986   GNU/LINUX 32 BIT LIMITATIONS
4987       GNU/Linux is the only common platform that supports 64 bit file/large
4988       file interfaces but disables them by default.
4989
4990       That means that libev compiled in the default environment doesn't
4991       support files larger than 2GiB or so, which mainly affects "ev_stat"
4992       watchers.
4993
4994       Unfortunately, many programs try to work around this GNU/Linux issue by
4995       enabling the large file API, which makes them incompatible with the
4996       standard libev compiled for their system.
4997
4998       Likewise, libev cannot enable the large file API itself as this would
4999       suddenly make it incompatible to the default compile time environment,
5000       i.e. all programs not using special compile switches.
5001
5002   OS/X AND DARWIN BUGS
5003       The whole thing is a bug if you ask me - basically any system interface
5004       you touch is broken, whether it is locales, poll, kqueue or even the
5005       OpenGL drivers.
5006
5007       "kqueue" is buggy
5008
5009       The kqueue syscall is broken in all known versions - most versions
5010       support only sockets, many support pipes.
5011
5012       Libev tries to work around this by not using "kqueue" by default on
5013       this rotten platform, but of course you can still ask for it when
5014       creating a loop - embedding a socket-only kqueue loop into a select-
5015       based one is probably going to work well.
5016
5017       "poll" is buggy
5018
5019       Instead of fixing "kqueue", Apple replaced their (working) "poll"
5020       implementation by something calling "kqueue" internally around the
5021       10.5.6 release, so now "kqueue" and "poll" are broken.
5022
5023       Libev tries to work around this by not using "poll" by default on this
5024       rotten platform, but of course you can still ask for it when creating a
5025       loop.
5026
5027       "select" is buggy
5028
5029       All that's left is "select", and of course Apple found a way to fuck
5030       this one up as well: On OS/X, "select" actively limits the number of
5031       file descriptors you can pass in to 1024 - your program suddenly
5032       crashes when you use more.
5033
5034       There is an undocumented "workaround" for this - defining
5035       "_DARWIN_UNLIMITED_SELECT", which libev tries to use, so select should
5036       work on OS/X.
5037
5038   SOLARIS PROBLEMS AND WORKAROUNDS
5039       "errno" reentrancy
5040
5041       The default compile environment on Solaris is unfortunately so thread-
5042       unsafe that you can't even use components/libraries compiled without
5043       "-D_REENTRANT" in a threaded program, which, of course, isn't defined
5044       by default. A valid, if stupid, implementation choice.
5045
5046       If you want to use libev in threaded environments you have to make sure
5047       it's compiled with "_REENTRANT" defined.
5048
5049       Event port backend
5050
5051       The scalable event interface for Solaris is called "event ports".
5052       Unfortunately, this mechanism is very buggy in all major releases. If
5053       you run into high CPU usage, your program freezes or you get a large
5054       number of spurious wakeups, make sure you have all the relevant and
5055       latest kernel patches applied. No, I don't know which ones, but there
5056       are multiple ones to apply, and afterwards, event ports actually work
5057       great.
5058
5059       If you can't get it to work, you can try running the program by setting
5060       the environment variable "LIBEV_FLAGS=3" to only allow "poll" and
5061       "select" backends.
5062
5063   AIX POLL BUG
5064       AIX unfortunately has a broken "poll.h" header. Libev works around this
5065       by trying to avoid the poll backend altogether (i.e. it's not even
5066       compiled in), which normally isn't a big problem as "select" works fine
5067       with large bitsets on AIX, and AIX is dead anyway.
5068
5069   WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS
5070       General issues
5071
5072       Win32 doesn't support any of the standards (e.g. POSIX) that libev
5073       requires, and its I/O model is fundamentally incompatible with the
5074       POSIX model. Libev still offers limited functionality on this platform
5075       in the form of the "EVBACKEND_SELECT" backend, and only supports socket
5076       descriptors. This only applies when using Win32 natively, not when
5077       using e.g. cygwin. Actually, it only applies to the microsofts own
5078       compilers, as every compiler comes with a slightly differently
5079       broken/incompatible environment.
5080
5081       Lifting these limitations would basically require the full re-
5082       implementation of the I/O system. If you are into this kind of thing,
5083       then note that glib does exactly that for you in a very portable way
5084       (note also that glib is the slowest event library known to man).
5085
5086       There is no supported compilation method available on windows except
5087       embedding it into other applications.
5088
5089       Sensible signal handling is officially unsupported by Microsoft - libev
5090       tries its best, but under most conditions, signals will simply not
5091       work.
5092
5093       Not a libev limitation but worth mentioning: windows apparently doesn't
5094       accept large writes: instead of resulting in a partial write, windows
5095       will either accept everything or return "ENOBUFS" if the buffer is too
5096       large, so make sure you only write small amounts into your sockets
5097       (less than a megabyte seems safe, but this apparently depends on the
5098       amount of memory available).
5099
5100       Due to the many, low, and arbitrary limits on the win32 platform and
5101       the abysmal performance of winsockets, using a large number of sockets
5102       is not recommended (and not reasonable). If your program needs to use
5103       more than a hundred or so sockets, then likely it needs to use a
5104       totally different implementation for windows, as libev offers the POSIX
5105       readiness notification model, which cannot be implemented efficiently
5106       on windows (due to Microsoft monopoly games).
5107
5108       A typical way to use libev under windows is to embed it (see the
5109       embedding section for details) and use the following evwrap.h header
5110       file instead of ev.h:
5111
5112          #define EV_STANDALONE              /* keeps ev from requiring config.h */
5113          #define EV_SELECT_IS_WINSOCKET 1   /* configure libev for windows select */
5114
5115          #include "ev.h"
5116
5117       And compile the following evwrap.c file into your project (make sure
5118       you do not compile the ev.c or any other embedded source files!):
5119
5120          #include "evwrap.h"
5121          #include "ev.c"
5122
5123       The winsocket "select" function
5124
5125       The winsocket "select" function doesn't follow POSIX in that it
5126       requires socket handles and not socket file descriptors (it is also
5127       extremely buggy). This makes select very inefficient, and also requires
5128       a mapping from file descriptors to socket handles (the Microsoft C
5129       runtime provides the function "_open_osfhandle" for this). See the
5130       discussion of the "EV_SELECT_USE_FD_SET", "EV_SELECT_IS_WINSOCKET" and
5131       "EV_FD_TO_WIN32_HANDLE" preprocessor symbols for more info.
5132
5133       The configuration for a "naked" win32 using the Microsoft runtime
5134       libraries and raw winsocket select is:
5135
5136          #define EV_USE_SELECT 1
5137          #define EV_SELECT_IS_WINSOCKET 1   /* forces EV_SELECT_USE_FD_SET, too */
5138
5139       Note that winsockets handling of fd sets is O(n), so you can easily get
5140       a complexity in the O(n²) range when using win32.
5141
5142       Limited number of file descriptors
5143
5144       Windows has numerous arbitrary (and low) limits on things.
5145
5146       Early versions of winsocket's select only supported waiting for a
5147       maximum of 64 handles (probably owning to the fact that all windows
5148       kernels can only wait for 64 things at the same time internally;
5149       Microsoft recommends spawning a chain of threads and wait for 63
5150       handles and the previous thread in each. Sounds great!).
5151
5152       Newer versions support more handles, but you need to define
5153       "FD_SETSIZE" to some high number (e.g. 2048) before compiling the
5154       winsocket select call (which might be in libev or elsewhere, for
5155       example, perl and many other interpreters do their own select emulation
5156       on windows).
5157
5158       Another limit is the number of file descriptors in the Microsoft
5159       runtime libraries, which by default is 64 (there must be a hidden 64
5160       fetish or something like this inside Microsoft). You can increase this
5161       by calling "_setmaxstdio", which can increase this limit to 2048
5162       (another arbitrary limit), but is broken in many versions of the
5163       Microsoft runtime libraries. This might get you to about 512 or 2048
5164       sockets (depending on windows version and/or the phase of the moon). To
5165       get more, you need to wrap all I/O functions and provide your own fd
5166       management, but the cost of calling select (O(n²)) will likely make
5167       this unworkable.
5168
5169   PORTABILITY REQUIREMENTS
5170       In addition to a working ISO-C implementation and of course the
5171       backend-specific APIs, libev relies on a few additional extensions:
5172
5173       "void (*)(ev_watcher_type *, int revents)" must have compatible calling
5174       conventions regardless of "ev_watcher_type *".
5175           Libev assumes not only that all watcher pointers have the same
5176           internal structure (guaranteed by POSIX but not by ISO C for
5177           example), but it also assumes that the same (machine) code can be
5178           used to call any watcher callback: The watcher callbacks have
5179           different type signatures, but libev calls them using an
5180           "ev_watcher *" internally.
5181
5182       null pointers and integer zero are represented by 0 bytes
5183           Libev uses "memset" to initialise structs and arrays to 0 bytes,
5184           and relies on this setting pointers and integers to null.
5185
5186       pointer accesses must be thread-atomic
5187           Accessing a pointer value must be atomic, it must both be readable
5188           and writable in one piece - this is the case on all current
5189           architectures.
5190
5191       "sig_atomic_t volatile" must be thread-atomic as well
5192           The type "sig_atomic_t volatile" (or whatever is defined as
5193           "EV_ATOMIC_T") must be atomic with respect to accesses from
5194           different threads. This is not part of the specification for
5195           "sig_atomic_t", but is believed to be sufficiently portable.
5196
5197       "sigprocmask" must work in a threaded environment
5198           Libev uses "sigprocmask" to temporarily block signals. This is not
5199           allowed in a threaded program ("pthread_sigmask" has to be used).
5200           Typical pthread implementations will either allow "sigprocmask" in
5201           the "main thread" or will block signals process-wide, both
5202           behaviours would be compatible with libev. Interaction between
5203           "sigprocmask" and "pthread_sigmask" could complicate things,
5204           however.
5205
5206           The most portable way to handle signals is to block signals in all
5207           threads except the initial one, and run the signal handling loop in
5208           the initial thread as well.
5209
5210       "long" must be large enough for common memory allocation sizes
5211           To improve portability and simplify its API, libev uses "long"
5212           internally instead of "size_t" when allocating its data structures.
5213           On non-POSIX systems (Microsoft...) this might be unexpectedly low,
5214           but is still at least 31 bits everywhere, which is enough for
5215           hundreds of millions of watchers.
5216
5217       "double" must hold a time value in seconds with enough accuracy
5218           The type "double" is used to represent timestamps. It is required
5219           to have at least 51 bits of mantissa (and 9 bits of exponent),
5220           which is good enough for at least into the year 4000 with
5221           millisecond accuracy (the design goal for libev). This requirement
5222           is overfulfilled by implementations using IEEE 754, which is
5223           basically all existing ones.
5224
5225           With IEEE 754 doubles, you get microsecond accuracy until at least
5226           the year 2255 (and millisecond accuracy till the year 287396 - by
5227           then, libev is either obsolete or somebody patched it to use "long
5228           double" or something like that, just kidding).
5229
5230       If you know of other additional requirements drop me a note.
5231

ALGORITHMIC COMPLEXITIES

5233       In this section the complexities of (many of) the algorithms used
5234       inside libev will be documented. For complexity discussions about
5235       backends see the documentation for "ev_default_init".
5236
5237       All of the following are about amortised time: If an array needs to be
5238       extended, libev needs to realloc and move the whole array, but this
5239       happens asymptotically rarer with higher number of elements, so O(1)
5240       might mean that libev does a lengthy realloc operation in rare cases,
5241       but on average it is much faster and asymptotically approaches constant
5242       time.
5243
5244       Starting and stopping timer/periodic watchers: O(log
5245       skipped_other_timers)
5246           This means that, when you have a watcher that triggers in one hour
5247           and there are 100 watchers that would trigger before that, then
5248           inserting will have to skip roughly seven ("ld 100") of these
5249           watchers.
5250
5251       Changing timer/periodic watchers (by autorepeat or calling again):
5252       O(log skipped_other_timers)
5253           That means that changing a timer costs less than removing/adding
5254           them, as only the relative motion in the event queue has to be paid
5255           for.
5256
5257       Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1)
5258           These just add the watcher into an array or at the head of a list.
5259
5260       Stopping check/prepare/idle/fork/async watchers: O(1)
5261       Stopping an io/signal/child watcher:
5262       O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE))
5263           These watchers are stored in lists, so they need to be walked to
5264           find the correct watcher to remove. The lists are usually short
5265           (you don't usually have many watchers waiting for the same fd or
5266           signal: one is typical, two is rare).
5267
5268       Finding the next timer in each loop iteration: O(1)
5269           By virtue of using a binary or 4-heap, the next timer is always
5270           found at a fixed position in the storage array.
5271
5272       Each change on a file descriptor per loop iteration:
5273       O(number_of_watchers_for_this_fd)
5274           A change means an I/O watcher gets started or stopped, which
5275           requires libev to recalculate its status (and possibly tell the
5276           kernel, depending on backend and whether "ev_io_set" was used).
5277
5278       Activating one watcher (putting it into the pending state): O(1)
5279       Priority handling: O(number_of_priorities)
5280           Priorities are implemented by allocating some space for each
5281           priority. When doing priority-based operations, libev usually has
5282           to linearly search all the priorities, but starting/stopping and
5283           activating watchers becomes O(1) with respect to priority handling.
5284
5285       Sending an ev_async: O(1)
5286       Processing ev_async_send: O(number_of_async_watchers)
5287       Processing signals: O(max_signal_number)
5288           Sending involves a system call iff there were no other
5289           "ev_async_send" calls in the current loop iteration and the loop is
5290           currently blocked. Checking for async and signal events involves
5291           iterating over all running async watchers or all signal numbers.
5292

PORTING FROM LIBEV 3.X TO 4.X

5294       The major version 4 introduced some incompatible changes to the API.
5295
5296       At the moment, the "ev.h" header file provides compatibility
5297       definitions for all changes, so most programs should still compile. The
5298       compatibility layer might be removed in later versions of libev, so
5299       better update to the new API early than late.
5300
5301       "EV_COMPAT3" backwards compatibility mechanism
5302           The backward compatibility mechanism can be controlled by
5303           "EV_COMPAT3". See "PREPROCESSOR SYMBOLS/MACROS" in the "EMBEDDING"
5304           section.
5305
5306       "ev_default_destroy" and "ev_default_fork" have been removed
5307           These calls can be replaced easily by their "ev_loop_xxx"
5308           counterparts:
5309
5310              ev_loop_destroy (EV_DEFAULT_UC);
5311              ev_loop_fork (EV_DEFAULT);
5312
5313       function/symbol renames
5314           A number of functions and symbols have been renamed:
5315
5316             ev_loop         => ev_run
5317             EVLOOP_NONBLOCK => EVRUN_NOWAIT
5318             EVLOOP_ONESHOT  => EVRUN_ONCE
5319
5320             ev_unloop       => ev_break
5321             EVUNLOOP_CANCEL => EVBREAK_CANCEL
5322             EVUNLOOP_ONE    => EVBREAK_ONE
5323             EVUNLOOP_ALL    => EVBREAK_ALL
5324
5325             EV_TIMEOUT      => EV_TIMER
5326
5327             ev_loop_count   => ev_iteration
5328             ev_loop_depth   => ev_depth
5329             ev_loop_verify  => ev_verify
5330
5331           Most functions working on "struct ev_loop" objects don't have an
5332           "ev_loop_" prefix, so it was removed; "ev_loop", "ev_unloop" and
5333           associated constants have been renamed to not collide with the
5334           "struct ev_loop" anymore and "EV_TIMER" now follows the same naming
5335           scheme as all other watcher types. Note that "ev_loop_fork" is
5336           still called "ev_loop_fork" because it would otherwise clash with
5337           the "ev_fork" typedef.
5338
5339       "EV_MINIMAL" mechanism replaced by "EV_FEATURES"
5340           The preprocessor symbol "EV_MINIMAL" has been replaced by a
5341           different mechanism, "EV_FEATURES". Programs using "EV_MINIMAL"
5342           usually compile and work, but the library code will of course be
5343           larger.
5344

GLOSSARY

5346       active
5347           A watcher is active as long as it has been started and not yet
5348           stopped.  See "WATCHER STATES" for details.
5349
5350       application
5351           In this document, an application is whatever is using libev.
5352
5353       backend
5354           The part of the code dealing with the operating system interfaces.
5355
5356       callback
5357           The address of a function that is called when some event has been
5358           detected. Callbacks are being passed the event loop, the watcher
5359           that received the event, and the actual event bitset.
5360
5361       callback/watcher invocation
5362           The act of calling the callback associated with a watcher.
5363
5364       event
5365           A change of state of some external event, such as data now being
5366           available for reading on a file descriptor, time having passed or
5367           simply not having any other events happening anymore.
5368
5369           In libev, events are represented as single bits (such as "EV_READ"
5370           or "EV_TIMER").
5371
5372       event library
5373           A software package implementing an event model and loop.
5374
5375       event loop
5376           An entity that handles and processes external events and converts
5377           them into callback invocations.
5378
5379       event model
5380           The model used to describe how an event loop handles and processes
5381           watchers and events.
5382
5383       pending
5384           A watcher is pending as soon as the corresponding event has been
5385           detected. See "WATCHER STATES" for details.
5386
5387       real time
5388           The physical time that is observed. It is apparently strictly
5389           monotonic :)
5390
5391       wall-clock time
5392           The time and date as shown on clocks. Unlike real time, it can
5393           actually be wrong and jump forwards and backwards, e.g. when you
5394           adjust your clock.
5395
5396       watcher
5397           A data structure that describes interest in certain events.
5398           Watchers need to be started (attached to an event loop) before they
5399           can receive events.
5400

AUTHOR

5402       Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael
5403       Magnusson and Emanuele Giaquinta, and minor corrections by many others.
5404
5405
5406
5407perl v5.30.0                      2019-07-30                      libev::ev(3)
Impressum