1LIBEV(3)       libev - high performance full featured event loop      LIBEV(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_loop's to stop iterating
33            ev_unloop (EV_A_ EVUNLOOP_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_loop to stop iterating
42            ev_unloop (EV_A_ EVUNLOOP_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_loop (0);
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_loop (loop, 0);
63
64            // unloop 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       Familarity with event based programming techniques in general is
82       assumed throughout this document.
83

ABOUT LIBEV

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

ERROR HANDLING

134       Libev knows three classes of errors: operating system errors, usage
135       errors and internal errors (bugs).
136
137       When libev catches an operating system error it cannot handle (for
138       example a system call indicating a condition libev cannot fix), it
139       calls the callback set via "ev_set_syserr_cb", which is supposed to fix
140       the problem or abort. The default is to print a diagnostic message and
141       to call "abort ()".
142
143       When libev detects a usage error such as a negative timer interval,
144       then it will print a diagnostic message and abort (via the "assert"
145       mechanism, so "NDEBUG" will disable this checking): these are
146       programming errors in the libev caller and need to be fixed there.
147
148       Libev also has a few internal error-checking "assert"ions, and also has
149       extensive consistency checking code. These do not trigger under normal
150       circumstances, as they indicate either a bug in libev or worse.
151

GLOBAL FUNCTIONS

153       These functions can be called anytime, even before initialising the
154       library in any way.
155
156       ev_tstamp ev_time ()
157           Returns the current time as libev would use it. Please note that
158           the "ev_now" function is usually faster and also often returns the
159           timestamp you actually want to know.
160
161       ev_sleep (ev_tstamp interval)
162           Sleep for the given interval: The current thread will be blocked
163           until either it is interrupted or the given time interval has
164           passed. Basically this is a sub-second-resolution "sleep ()".
165
166       int ev_version_major ()
167       int ev_version_minor ()
168           You can find out the major and minor ABI version numbers of the
169           library you linked against by calling the functions
170           "ev_version_major" and "ev_version_minor". If you want, you can
171           compare against the global symbols "EV_VERSION_MAJOR" and
172           "EV_VERSION_MINOR", which specify the version of the library your
173           program was compiled against.
174
175           These version numbers refer to the ABI version of the library, not
176           the release version.
177
178           Usually, it's a good idea to terminate if the major versions
179           mismatch, as this indicates an incompatible change. Minor versions
180           are usually compatible to older versions, so a larger minor version
181           alone is usually not a problem.
182
183           Example: Make sure we haven't accidentally been linked against the
184           wrong version.
185
186              assert (("libev version mismatch",
187                       ev_version_major () == EV_VERSION_MAJOR
188                       && ev_version_minor () >= EV_VERSION_MINOR));
189
190       unsigned int ev_supported_backends ()
191           Return the set of all backends (i.e. their corresponding
192           "EV_BACKEND_*" value) compiled into this binary of libev
193           (independent of their availability on the system you are running
194           on). See "ev_default_loop" for a description of the set values.
195
196           Example: make sure we have the epoll method, because yeah this is
197           cool and a must have and can we have a torrent of it please!!!11
198
199              assert (("sorry, no epoll, no sex",
200                       ev_supported_backends () & EVBACKEND_EPOLL));
201
202       unsigned int ev_recommended_backends ()
203           Return the set of all backends compiled into this binary of libev
204           and also recommended for this platform. This set is often smaller
205           than the one returned by "ev_supported_backends", as for example
206           kqueue is broken on most BSDs and will not be auto-detected unless
207           you explicitly request it (assuming you know what you are doing).
208           This is the set of backends that libev will probe for if you
209           specify no backends explicitly.
210
211       unsigned int ev_embeddable_backends ()
212           Returns the set of backends that are embeddable in other event
213           loops. This is the theoretical, all-platform, value. To find which
214           backends might be supported on the current system, you would need
215           to look at "ev_embeddable_backends () & ev_supported_backends ()",
216           likewise for recommended ones.
217
218           See the description of "ev_embed" watchers for more info.
219
220       ev_set_allocator (void *(*cb)(void *ptr, long size)) [NOT REENTRANT]
221           Sets the allocation function to use (the prototype is similar - the
222           semantics are identical to the "realloc" C89/SuS/POSIX function).
223           It is used to allocate and free memory (no surprises here). If it
224           returns zero when memory needs to be allocated ("size != 0"), the
225           library might abort or take some potentially destructive action.
226
227           Since some systems (at least OpenBSD and Darwin) fail to implement
228           correct "realloc" semantics, libev will use a wrapper around the
229           system "realloc" and "free" functions by default.
230
231           You could override this function in high-availability programs to,
232           say, free some memory if it cannot allocate memory, to use a
233           special allocator, or even to sleep a while and retry until some
234           memory is available.
235
236           Example: Replace the libev allocator with one that waits a bit and
237           then retries (example requires a standards-compliant "realloc").
238
239              static void *
240              persistent_realloc (void *ptr, size_t size)
241              {
242                for (;;)
243                  {
244                    void *newptr = realloc (ptr, size);
245
246                    if (newptr)
247                      return newptr;
248
249                    sleep (60);
250                  }
251              }
252
253              ...
254              ev_set_allocator (persistent_realloc);
255
256       ev_set_syserr_cb (void (*cb)(const char *msg)); [NOT REENTRANT]
257           Set the callback function to call on a retryable system call error
258           (such as failed select, poll, epoll_wait). The message is a
259           printable string indicating the system call or subsystem causing
260           the problem. If this callback is set, then libev will expect it to
261           remedy the situation, no matter what, when it returns. That is,
262           libev will generally retry the requested operation, or, if the
263           condition doesn't go away, do bad stuff (such as abort).
264
265           Example: This is basically the same thing that libev does
266           internally, too.
267
268              static void
269              fatal_error (const char *msg)
270              {
271                perror (msg);
272                abort ();
273              }
274
275              ...
276              ev_set_syserr_cb (fatal_error);
277

FUNCTIONS CONTROLLING THE EVENT LOOP

279       An event loop is described by a "struct ev_loop *" (the "struct" is not
280       optional in this case, as there is also an "ev_loop" function).
281
282       The library knows two types of such loops, the default loop, which
283       supports signals and child events, and dynamically created loops which
284       do not.
285
286       struct ev_loop *ev_default_loop (unsigned int flags)
287           This will initialise the default event loop if it hasn't been
288           initialised yet and return it. If the default loop could not be
289           initialised, returns false. If it already was initialised it simply
290           returns it (and ignores the flags. If that is troubling you, check
291           "ev_backend ()" afterwards).
292
293           If you don't know what event loop to use, use the one returned from
294           this function.
295
296           Note that this function is not thread-safe, so if you want to use
297           it from multiple threads, you have to lock (note also that this is
298           unlikely, as loops cannot be shared easily between threads anyway).
299
300           The default loop is the only loop that can handle "ev_signal" and
301           "ev_child" watchers, and to do this, it always registers a handler
302           for "SIGCHLD". If this is a problem for your application you can
303           either create a dynamic loop with "ev_loop_new" that doesn't do
304           that, or you can simply overwrite the "SIGCHLD" signal handler
305           after calling "ev_default_init".
306
307           The flags argument can be used to specify special behaviour or
308           specific backends to use, and is usually specified as 0 (or
309           "EVFLAG_AUTO").
310
311           The following flags are supported:
312
313           "EVFLAG_AUTO"
314               The default flags value. Use this if you have no clue (it's the
315               right thing, believe me).
316
317           "EVFLAG_NOENV"
318               If this flag bit is or'ed into the flag value (or the program
319               runs setuid or setgid) then libev will not look at the
320               environment variable "LIBEV_FLAGS". Otherwise (the default),
321               this environment variable will override the flags completely if
322               it is found in the environment. This is useful to try out
323               specific backends to test their performance, or to work around
324               bugs.
325
326           "EVFLAG_FORKCHECK"
327               Instead of calling "ev_default_fork" or "ev_loop_fork" manually
328               after a fork, you can also make libev check for a fork in each
329               iteration by enabling this flag.
330
331               This works by calling "getpid ()" on every iteration of the
332               loop, and thus this might slow down your event loop if you do a
333               lot of loop iterations and little real work, but is usually not
334               noticeable (on my GNU/Linux system for example, "getpid" is
335               actually a simple 5-insn sequence without a system call and
336               thus very fast, but my GNU/Linux system also has
337               "pthread_atfork" which is even faster).
338
339               The big advantage of this flag is that you can forget about
340               fork (and forget about forgetting to tell libev about forking)
341               when you use this flag.
342
343               This flag setting cannot be overridden or specified in the
344               "LIBEV_FLAGS" environment variable.
345
346           "EVFLAG_NOINOTIFY"
347               When this flag is specified, then libev will not attempt to use
348               the inotify API for it's "ev_stat" watchers. Apart from
349               debugging and testing, this flag can be useful to conserve
350               inotify file descriptors, as otherwise each loop using
351               "ev_stat" watchers consumes one inotify handle.
352
353           "EVFLAG_SIGNALFD"
354               When this flag is specified, then libev will attempt to use the
355               signalfd API for it's "ev_signal" (and "ev_child") watchers.
356               This API delivers signals synchronously, which makes it both
357               faster and might make it possible to get the queued signal
358               data. It can also simplify signal handling with threads, as
359               long as you properly block signals in your threads that are not
360               interested in handling them.
361
362               Signalfd will not be used by default as this changes your
363               signal mask, and there are a lot of shoddy libraries and
364               programs (glib's threadpool for example) that can't properly
365               initialise their signal masks.
366
367           "EVBACKEND_SELECT"  (value 1, portable select backend)
368               This is your standard select(2) backend. Not completely
369               standard, as libev tries to roll its own fd_set with no limits
370               on the number of fds, but if that fails, expect a fairly low
371               limit on the number of fds when using this backend. It doesn't
372               scale too well (O(highest_fd)), but its usually the fastest
373               backend for a low number of (low-numbered :) fds.
374
375               To get good performance out of this backend you need a high
376               amount of parallelism (most of the file descriptors should be
377               busy). If you are writing a server, you should "accept ()" in a
378               loop to accept as many connections as possible during one
379               iteration. You might also want to have a look at
380               "ev_set_io_collect_interval ()" to increase the amount of
381               readiness notifications you get per iteration.
382
383               This backend maps "EV_READ" to the "readfds" set and "EV_WRITE"
384               to the "writefds" set (and to work around Microsoft Windows
385               bugs, also onto the "exceptfds" set on that platform).
386
387           "EVBACKEND_POLL"    (value 2, poll backend, available everywhere
388           except on windows)
389               And this is your standard poll(2) backend. It's more
390               complicated than select, but handles sparse fds better and has
391               no artificial limit on the number of fds you can use (except it
392               will slow down considerably with a lot of inactive fds). It
393               scales similarly to select, i.e. O(total_fds). See the entry
394               for "EVBACKEND_SELECT", above, for performance tips.
395
396               This backend maps "EV_READ" to "POLLIN | POLLERR | POLLHUP",
397               and "EV_WRITE" to "POLLOUT | POLLERR | POLLHUP".
398
399           "EVBACKEND_EPOLL"   (value 4, Linux)
400               Use the linux-specific epoll(7) interface (for both pre- and
401               post-2.6.9 kernels).
402
403               For few fds, this backend is a bit little slower than poll and
404               select, but it scales phenomenally better. While poll and
405               select usually scale like O(total_fds) where n is the total
406               number of fds (or the highest fd), epoll scales either O(1) or
407               O(active_fds).
408
409               The epoll mechanism deserves honorable mention as the most
410               misdesigned of the more advanced event mechanisms: mere
411               annoyances include silently dropping file descriptors,
412               requiring a system call per change per file descriptor (and
413               unnecessary guessing of parameters), problems with dup and so
414               on. The biggest issue is fork races, however - if a program
415               forks then both parent and child process have to recreate the
416               epoll set, which can take considerable time (one syscall per
417               file descriptor) and is of course hard to detect.
418
419               Epoll is also notoriously buggy - embedding epoll fds should
420               work, but of course doesn't, and epoll just loves to report
421               events for totally different file descriptors (even already
422               closed ones, so one cannot even remove them from the set) than
423               registered in the set (especially on SMP systems). Libev tries
424               to counter these spurious notifications by employing an
425               additional generation counter and comparing that against the
426               events to filter out spurious ones, recreating the set when
427               required.
428
429               While stopping, setting and starting an I/O watcher in the same
430               iteration will result in some caching, there is still a system
431               call per such incident (because the same file descriptor could
432               point to a different file description now), so its best to
433               avoid that. Also, "dup ()"'ed file descriptors might not work
434               very well if you register events for both file descriptors.
435
436               Best performance from this backend is achieved by not
437               unregistering all watchers for a file descriptor until it has
438               been closed, if possible, i.e. keep at least one watcher active
439               per fd at all times. Stopping and starting a watcher (without
440               re-setting it) also usually doesn't cause extra overhead. A
441               fork can both result in spurious notifications as well as in
442               libev having to destroy and recreate the epoll object, which
443               can take considerable time and thus should be avoided.
444
445               All this means that, in practice, "EVBACKEND_SELECT" can be as
446               fast or faster than epoll for maybe up to a hundred file
447               descriptors, depending on the usage. So sad.
448
449               While nominally embeddable in other event loops, this feature
450               is broken in all kernel versions tested so far.
451
452               This backend maps "EV_READ" and "EV_WRITE" in the same way as
453               "EVBACKEND_POLL".
454
455           "EVBACKEND_KQUEUE"  (value 8, most BSD clones)
456               Kqueue deserves special mention, as at the time of this
457               writing, it was broken on all BSDs except NetBSD (usually it
458               doesn't work reliably with anything but sockets and pipes,
459               except on Darwin, where of course it's completely useless).
460               Unlike epoll, however, whose brokenness is by design, these
461               kqueue bugs can (and eventually will) be fixed without API
462               changes to existing programs. For this reason it's not being
463               "auto-detected" unless you explicitly specify it in the flags
464               (i.e. using "EVBACKEND_KQUEUE") or libev was compiled on a
465               known-to-be-good (-enough) system like NetBSD.
466
467               You still can embed kqueue into a normal poll or select backend
468               and use it only for sockets (after having made sure that
469               sockets work with kqueue on the target platform). See
470               "ev_embed" watchers for more info.
471
472               It scales in the same way as the epoll backend, but the
473               interface to the kernel is more efficient (which says nothing
474               about its actual speed, of course). While stopping, setting and
475               starting an I/O watcher does never cause an extra system call
476               as with "EVBACKEND_EPOLL", it still adds up to two event
477               changes per incident. Support for "fork ()" is very bad (but
478               sane, unlike epoll) and it drops fds silently in similarly
479               hard-to-detect cases
480
481               This backend usually performs well under most conditions.
482
483               While nominally embeddable in other event loops, this doesn't
484               work everywhere, so you might need to test for this. And since
485               it is broken almost everywhere, you should only use it when you
486               have a lot of sockets (for which it usually works), by
487               embedding it into another event loop (e.g. "EVBACKEND_SELECT"
488               or "EVBACKEND_POLL" (but "poll" is of course also broken on OS
489               X)) and, did I mention it, using it only for sockets.
490
491               This backend maps "EV_READ" into an "EVFILT_READ" kevent with
492               "NOTE_EOF", and "EV_WRITE" into an "EVFILT_WRITE" kevent with
493               "NOTE_EOF".
494
495           "EVBACKEND_DEVPOLL" (value 16, Solaris 8)
496               This is not implemented yet (and might never be, unless you
497               send me an implementation). According to reports, "/dev/poll"
498               only supports sockets and is not embeddable, which would limit
499               the usefulness of this backend immensely.
500
501           "EVBACKEND_PORT"    (value 32, Solaris 10)
502               This uses the Solaris 10 event port mechanism. As with
503               everything on Solaris, it's really slow, but it still scales
504               very well (O(active_fds)).
505
506               Please note that Solaris event ports can deliver a lot of
507               spurious notifications, so you need to use non-blocking I/O or
508               other means to avoid blocking when no data (or space) is
509               available.
510
511               While this backend scales well, it requires one system call per
512               active file descriptor per loop iteration. For small and medium
513               numbers of file descriptors a "slow" "EVBACKEND_SELECT" or
514               "EVBACKEND_POLL" backend might perform better.
515
516               On the positive side, with the exception of the spurious
517               readiness notifications, this backend actually performed fully
518               to specification in all tests and is fully embeddable, which is
519               a rare feat among the OS-specific backends (I vastly prefer
520               correctness over speed hacks).
521
522               This backend maps "EV_READ" and "EV_WRITE" in the same way as
523               "EVBACKEND_POLL".
524
525           "EVBACKEND_ALL"
526               Try all backends (even potentially broken ones that wouldn't be
527               tried with "EVFLAG_AUTO"). Since this is a mask, you can do
528               stuff such as "EVBACKEND_ALL & ~EVBACKEND_KQUEUE".
529
530               It is definitely not recommended to use this flag.
531
532           If one or more of the backend flags are or'ed into the flags value,
533           then only these backends will be tried (in the reverse order as
534           listed here). If none are specified, all backends in
535           "ev_recommended_backends ()" will be tried.
536
537           Example: This is the most typical usage.
538
539              if (!ev_default_loop (0))
540                fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?");
541
542           Example: Restrict libev to the select and poll backends, and do not
543           allow environment settings to be taken into account:
544
545              ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV);
546
547           Example: Use whatever libev has to offer, but make sure that kqueue
548           is used if available (warning, breaks stuff, best use only with
549           your own private event loop and only if you know the OS supports
550           your types of fds):
551
552              ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE);
553
554       struct ev_loop *ev_loop_new (unsigned int flags)
555           Similar to "ev_default_loop", but always creates a new event loop
556           that is always distinct from the default loop. Unlike the default
557           loop, it cannot handle signal and child watchers, and attempts to
558           do so will be greeted by undefined behaviour (or a failed assertion
559           if assertions are enabled).
560
561           Note that this function is thread-safe, and the recommended way to
562           use libev with threads is indeed to create one loop per thread, and
563           using the default loop in the "main" or "initial" thread.
564
565           Example: Try to create a event loop that uses epoll and nothing
566           else.
567
568              struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV);
569              if (!epoller)
570                fatal ("no epoll found here, maybe it hides under your chair");
571
572       ev_default_destroy ()
573           Destroys the default loop again (frees all memory and kernel state
574           etc.). None of the active event watchers will be stopped in the
575           normal sense, so e.g. "ev_is_active" might still return true. It is
576           your responsibility to either stop all watchers cleanly yourself
577           before calling this function, or cope with the fact afterwards
578           (which is usually the easiest thing, you can just ignore the
579           watchers and/or "free ()" them for example).
580
581           Note that certain global state, such as signal state (and installed
582           signal handlers), will not be freed by this function, and related
583           watchers (such as signal and child watchers) would need to be
584           stopped manually.
585
586           In general it is not advisable to call this function except in the
587           rare occasion where you really need to free e.g. the signal
588           handling pipe fds. If you need dynamically allocated loops it is
589           better to use "ev_loop_new" and "ev_loop_destroy".
590
591       ev_loop_destroy (loop)
592           Like "ev_default_destroy", but destroys an event loop created by an
593           earlier call to "ev_loop_new".
594
595       ev_default_fork ()
596           This function sets a flag that causes subsequent "ev_loop"
597           iterations to reinitialise the kernel state for backends that have
598           one. Despite the name, you can call it anytime, but it makes most
599           sense after forking, in the child process (or both child and
600           parent, but that again makes little sense). You must call it in the
601           child before using any of the libev functions, and it will only
602           take effect at the next "ev_loop" iteration.
603
604           On the other hand, you only need to call this function in the child
605           process if and only if you want to use the event library in the
606           child. If you just fork+exec, you don't have to call it at all.
607
608           The function itself is quite fast and it's usually not a problem to
609           call it just in case after a fork. To make this easy, the function
610           will fit in quite nicely into a call to "pthread_atfork":
611
612               pthread_atfork (0, 0, ev_default_fork);
613
614       ev_loop_fork (loop)
615           Like "ev_default_fork", but acts on an event loop created by
616           "ev_loop_new". Yes, you have to call this on every allocated event
617           loop after fork that you want to re-use in the child, and how you
618           do this is entirely your own problem.
619
620       int ev_is_default_loop (loop)
621           Returns true when the given loop is, in fact, the default loop, and
622           false otherwise.
623
624       unsigned int ev_loop_count (loop)
625           Returns the count of loop iterations for the loop, which is
626           identical to the number of times libev did poll for new events. It
627           starts at 0 and happily wraps around with enough iterations.
628
629           This value can sometimes be useful as a generation counter of sorts
630           (it "ticks" the number of loop iterations), as it roughly
631           corresponds with "ev_prepare" and "ev_check" calls.
632
633       unsigned int ev_loop_depth (loop)
634           Returns the number of times "ev_loop" was entered minus the number
635           of times "ev_loop" was exited, in other words, the recursion depth.
636
637           Outside "ev_loop", this number is zero. In a callback, this number
638           is 1, unless "ev_loop" was invoked recursively (or from another
639           thread), in which case it is higher.
640
641           Leaving "ev_loop" abnormally (setjmp/longjmp, cancelling the thread
642           etc.), doesn't count as exit.
643
644       unsigned int ev_backend (loop)
645           Returns one of the "EVBACKEND_*" flags indicating the event backend
646           in use.
647
648       ev_tstamp ev_now (loop)
649           Returns the current "event loop time", which is the time the event
650           loop received events and started processing them. This timestamp
651           does not change as long as callbacks are being processed, and this
652           is also the base time used for relative timers. You can treat it as
653           the timestamp of the event occurring (or more correctly, libev
654           finding out about it).
655
656       ev_now_update (loop)
657           Establishes the current time by querying the kernel, updating the
658           time returned by "ev_now ()" in the progress. This is a costly
659           operation and is usually done automatically within "ev_loop ()".
660
661           This function is rarely useful, but when some event callback runs
662           for a very long time without entering the event loop, updating
663           libev's idea of the current time is a good idea.
664
665           See also "The special problem of time updates" in the "ev_timer"
666           section.
667
668       ev_suspend (loop)
669       ev_resume (loop)
670           These two functions suspend and resume a loop, for use when the
671           loop is not used for a while and timeouts should not be processed.
672
673           A typical use case would be an interactive program such as a game:
674           When the user presses "^Z" to suspend the game and resumes it an
675           hour later it would be best to handle timeouts as if no time had
676           actually passed while the program was suspended. This can be
677           achieved by calling "ev_suspend" in your "SIGTSTP" handler, sending
678           yourself a "SIGSTOP" and calling "ev_resume" directly afterwards to
679           resume timer processing.
680
681           Effectively, all "ev_timer" watchers will be delayed by the time
682           spend between "ev_suspend" and "ev_resume", and all "ev_periodic"
683           watchers will be rescheduled (that is, they will lose any events
684           that would have occured while suspended).
685
686           After calling "ev_suspend" you must not call any function on the
687           given loop other than "ev_resume", and you must not call
688           "ev_resume" without a previous call to "ev_suspend".
689
690           Calling "ev_suspend"/"ev_resume" has the side effect of updating
691           the event loop time (see "ev_now_update").
692
693       ev_loop (loop, int flags)
694           Finally, this is it, the event handler. This function usually is
695           called after you have initialised all your watchers and you want to
696           start handling events.
697
698           If the flags argument is specified as 0, it will not return until
699           either no event watchers are active anymore or "ev_unloop" was
700           called.
701
702           Please note that an explicit "ev_unloop" is usually better than
703           relying on all watchers to be stopped when deciding when a program
704           has finished (especially in interactive programs), but having a
705           program that automatically loops as long as it has to and no longer
706           by virtue of relying on its watchers stopping correctly, that is
707           truly a thing of beauty.
708
709           A flags value of "EVLOOP_NONBLOCK" will look for new events, will
710           handle those events and any already outstanding ones, but will not
711           block your process in case there are no events and will return
712           after one iteration of the loop.
713
714           A flags value of "EVLOOP_ONESHOT" will look for new events (waiting
715           if necessary) and will handle those and any already outstanding
716           ones. It will block your process until at least one new event
717           arrives (which could be an event internal to libev itself, so there
718           is no guarantee that a user-registered callback will be called),
719           and will return after one iteration of the loop.
720
721           This is useful if you are waiting for some external event in
722           conjunction with something not expressible using other libev
723           watchers (i.e. "roll your own "ev_loop""). However, a pair of
724           "ev_prepare"/"ev_check" watchers is usually a better approach for
725           this kind of thing.
726
727           Here are the gory details of what "ev_loop" does:
728
729              - Before the first iteration, call any pending watchers.
730              * If EVFLAG_FORKCHECK was used, check for a fork.
731              - If a fork was detected (by any means), queue and call all fork watchers.
732              - Queue and call all prepare watchers.
733              - If we have been forked, detach and recreate the kernel state
734                as to not disturb the other process.
735              - Update the kernel state with all outstanding changes.
736              - Update the "event loop time" (ev_now ()).
737              - Calculate for how long to sleep or block, if at all
738                (active idle watchers, EVLOOP_NONBLOCK or not having
739                any active watchers at all will result in not sleeping).
740              - Sleep if the I/O and timer collect interval say so.
741              - Block the process, waiting for any events.
742              - Queue all outstanding I/O (fd) events.
743              - Update the "event loop time" (ev_now ()), and do time jump adjustments.
744              - Queue all expired timers.
745              - Queue all expired periodics.
746              - Unless any events are pending now, queue all idle watchers.
747              - Queue all check watchers.
748              - Call all queued watchers in reverse order (i.e. check watchers first).
749                Signals and child watchers are implemented as I/O watchers, and will
750                be handled here by queueing them when their watcher gets executed.
751              - If ev_unloop has been called, or EVLOOP_ONESHOT or EVLOOP_NONBLOCK
752                were used, or there are no active watchers, return, otherwise
753                continue with step *.
754
755           Example: Queue some jobs and then loop until no events are
756           outstanding anymore.
757
758              ... queue jobs here, make sure they register event watchers as long
759              ... as they still have work to do (even an idle watcher will do..)
760              ev_loop (my_loop, 0);
761              ... jobs done or somebody called unloop. yeah!
762
763       ev_unloop (loop, how)
764           Can be used to make a call to "ev_loop" return early (but only
765           after it has processed all outstanding events). The "how" argument
766           must be either "EVUNLOOP_ONE", which will make the innermost
767           "ev_loop" call return, or "EVUNLOOP_ALL", which will make all
768           nested "ev_loop" calls return.
769
770           This "unloop state" will be cleared when entering "ev_loop" again.
771
772           It is safe to call "ev_unloop" from otuside any "ev_loop" calls.
773
774       ev_ref (loop)
775       ev_unref (loop)
776           Ref/unref can be used to add or remove a reference count on the
777           event loop: Every watcher keeps one reference, and as long as the
778           reference count is nonzero, "ev_loop" will not return on its own.
779
780           This is useful when you have a watcher that you never intend to
781           unregister, but that nevertheless should not keep "ev_loop" from
782           returning. In such a case, call "ev_unref" after starting, and
783           "ev_ref" before stopping it.
784
785           As an example, libev itself uses this for its internal signal pipe:
786           It is not visible to the libev user and should not keep "ev_loop"
787           from exiting if no event watchers registered by it are active. It
788           is also an excellent way to do this for generic recurring timers or
789           from within third-party libraries. Just remember to unref after
790           start and ref before stop (but only if the watcher wasn't active
791           before, or was active before, respectively. Note also that libev
792           might stop watchers itself (e.g. non-repeating timers) in which
793           case you have to "ev_ref" in the callback).
794
795           Example: Create a signal watcher, but keep it from keeping
796           "ev_loop" running when nothing else is active.
797
798              ev_signal exitsig;
799              ev_signal_init (&exitsig, sig_cb, SIGINT);
800              ev_signal_start (loop, &exitsig);
801              evf_unref (loop);
802
803           Example: For some weird reason, unregister the above signal handler
804           again.
805
806              ev_ref (loop);
807              ev_signal_stop (loop, &exitsig);
808
809       ev_set_io_collect_interval (loop, ev_tstamp interval)
810       ev_set_timeout_collect_interval (loop, ev_tstamp interval)
811           These advanced functions influence the time that libev will spend
812           waiting for events. Both time intervals are by default 0, meaning
813           that libev will try to invoke timer/periodic callbacks and I/O
814           callbacks with minimum latency.
815
816           Setting these to a higher value (the "interval" must be >= 0)
817           allows libev to delay invocation of I/O and timer/periodic
818           callbacks to increase efficiency of loop iterations (or to increase
819           power-saving opportunities).
820
821           The idea is that sometimes your program runs just fast enough to
822           handle one (or very few) event(s) per loop iteration. While this
823           makes the program responsive, it also wastes a lot of CPU time to
824           poll for new events, especially with backends like "select ()"
825           which have a high overhead for the actual polling but can deliver
826           many events at once.
827
828           By setting a higher io collect interval you allow libev to spend
829           more time collecting I/O events, so you can handle more events per
830           iteration, at the cost of increasing latency. Timeouts (both
831           "ev_periodic" and "ev_timer") will be not affected. Setting this to
832           a non-null value will introduce an additional "ev_sleep ()" call
833           into most loop iterations. The sleep time ensures that libev will
834           not poll for I/O events more often then once per this interval, on
835           average.
836
837           Likewise, by setting a higher timeout collect interval you allow
838           libev to spend more time collecting timeouts, at the expense of
839           increased latency/jitter/inexactness (the watcher callback will be
840           called later). "ev_io" watchers will not be affected. Setting this
841           to a non-null value will not introduce any overhead in libev.
842
843           Many (busy) programs can usually benefit by setting the I/O collect
844           interval to a value near 0.1 or so, which is often enough for
845           interactive servers (of course not for games), likewise for
846           timeouts. It usually doesn't make much sense to set it to a lower
847           value than 0.01, as this approaches the timing granularity of most
848           systems. Note that if you do transactions with the outside world
849           and you can't increase the parallelity, then this setting will
850           limit your transaction rate (if you need to poll once per
851           transaction and the I/O collect interval is 0.01, then you can't do
852           more than 100 transations per second).
853
854           Setting the timeout collect interval can improve the opportunity
855           for saving power, as the program will "bundle" timer callback
856           invocations that are "near" in time together, by delaying some,
857           thus reducing the number of times the process sleeps and wakes up
858           again. Another useful technique to reduce iterations/wake-ups is to
859           use "ev_periodic" watchers and make sure they fire on, say, one-
860           second boundaries only.
861
862           Example: we only need 0.1s timeout granularity, and we wish not to
863           poll more often than 100 times per second:
864
865              ev_set_timeout_collect_interval (EV_DEFAULT_UC_ 0.1);
866              ev_set_io_collect_interval (EV_DEFAULT_UC_ 0.01);
867
868       ev_invoke_pending (loop)
869           This call will simply invoke all pending watchers while resetting
870           their pending state. Normally, "ev_loop" does this automatically
871           when required, but when overriding the invoke callback this call
872           comes handy.
873
874       int ev_pending_count (loop)
875           Returns the number of pending watchers - zero indicates that no
876           watchers are pending.
877
878       ev_set_invoke_pending_cb (loop, void (*invoke_pending_cb)(EV_P))
879           This overrides the invoke pending functionality of the loop:
880           Instead of invoking all pending watchers when there are any,
881           "ev_loop" will call this callback instead. This is useful, for
882           example, when you want to invoke the actual watchers inside another
883           context (another thread etc.).
884
885           If you want to reset the callback, use "ev_invoke_pending" as new
886           callback.
887
888       ev_set_loop_release_cb (loop, void (*release)(EV_P), void
889       (*acquire)(EV_P))
890           Sometimes you want to share the same loop between multiple threads.
891           This can be done relatively simply by putting mutex_lock/unlock
892           calls around each call to a libev function.
893
894           However, "ev_loop" can run an indefinite time, so it is not
895           feasible to wait for it to return. One way around this is to wake
896           up the loop via "ev_unloop" and "av_async_send", another way is to
897           set these release and acquire callbacks on the loop.
898
899           When set, then "release" will be called just before the thread is
900           suspended waiting for new events, and "acquire" is called just
901           afterwards.
902
903           Ideally, "release" will just call your mutex_unlock function, and
904           "acquire" will just call the mutex_lock function again.
905
906           While event loop modifications are allowed between invocations of
907           "release" and "acquire" (that's their only purpose after all), no
908           modifications done will affect the event loop, i.e. adding watchers
909           will have no effect on the set of file descriptors being watched,
910           or the time waited. Use an "ev_async" watcher to wake up "ev_loop"
911           when you want it to take note of any changes you made.
912
913           In theory, threads executing "ev_loop" will be async-cancel safe
914           between invocations of "release" and "acquire".
915
916           See also the locking example in the "THREADS" section later in this
917           document.
918
919       ev_set_userdata (loop, void *data)
920       ev_userdata (loop)
921           Set and retrieve a single "void *" associated with a loop. When
922           "ev_set_userdata" has never been called, then "ev_userdata" returns
923           0.
924
925           These two functions can be used to associate arbitrary data with a
926           loop, and are intended solely for the "invoke_pending_cb",
927           "release" and "acquire" callbacks described above, but of course
928           can be (ab-)used for any other purpose as well.
929
930       ev_loop_verify (loop)
931           This function only does something when "EV_VERIFY" support has been
932           compiled in, which is the default for non-minimal builds. It tries
933           to go through all internal structures and checks them for validity.
934           If anything is found to be inconsistent, it will print an error
935           message to standard error and call "abort ()".
936
937           This can be used to catch bugs inside libev itself: under normal
938           circumstances, this function will never abort as of course libev
939           keeps its data structures consistent.
940

ANATOMY OF A WATCHER

942       In the following description, uppercase "TYPE" in names stands for the
943       watcher type, e.g. "ev_TYPE_start" can mean "ev_timer_start" for timer
944       watchers and "ev_io_start" for I/O watchers.
945
946       A watcher is a structure that you create and register to record your
947       interest in some event. For instance, if you want to wait for STDIN to
948       become readable, you would create an "ev_io" watcher for that:
949
950          static void my_cb (struct ev_loop *loop, ev_io *w, int revents)
951          {
952            ev_io_stop (w);
953            ev_unloop (loop, EVUNLOOP_ALL);
954          }
955
956          struct ev_loop *loop = ev_default_loop (0);
957
958          ev_io stdin_watcher;
959
960          ev_init (&stdin_watcher, my_cb);
961          ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ);
962          ev_io_start (loop, &stdin_watcher);
963
964          ev_loop (loop, 0);
965
966       As you can see, you are responsible for allocating the memory for your
967       watcher structures (and it is usually a bad idea to do this on the
968       stack).
969
970       Each watcher has an associated watcher structure (called "struct
971       ev_TYPE" or simply "ev_TYPE", as typedefs are provided for all watcher
972       structs).
973
974       Each watcher structure must be initialised by a call to "ev_init
975       (watcher *, callback)", which expects a callback to be provided. This
976       callback gets invoked each time the event occurs (or, in the case of
977       I/O watchers, each time the event loop detects that the file descriptor
978       given is readable and/or writable).
979
980       Each watcher type further has its own "ev_TYPE_set (watcher *, ...)"
981       macro to configure it, with arguments specific to the watcher type.
982       There is also a macro to combine initialisation and setting in one
983       call: "ev_TYPE_init (watcher *, callback, ...)".
984
985       To make the watcher actually watch out for events, you have to start it
986       with a watcher-specific start function ("ev_TYPE_start (loop, watcher
987       *)"), and you can stop watching for events at any time by calling the
988       corresponding stop function ("ev_TYPE_stop (loop, watcher *)".
989
990       As long as your watcher is active (has been started but not stopped)
991       you must not touch the values stored in it. Most specifically you must
992       never reinitialise it or call its "ev_TYPE_set" macro.
993
994       Each and every callback receives the event loop pointer as first, the
995       registered watcher structure as second, and a bitset of received events
996       as third argument.
997
998       The received events usually include a single bit per event type
999       received (you can receive multiple events at the same time). The
1000       possible bit masks are:
1001
1002       "EV_READ"
1003       "EV_WRITE"
1004           The file descriptor in the "ev_io" watcher has become readable
1005           and/or writable.
1006
1007       "EV_TIMEOUT"
1008           The "ev_timer" watcher has timed out.
1009
1010       "EV_PERIODIC"
1011           The "ev_periodic" watcher has timed out.
1012
1013       "EV_SIGNAL"
1014           The signal specified in the "ev_signal" watcher has been received
1015           by a thread.
1016
1017       "EV_CHILD"
1018           The pid specified in the "ev_child" watcher has received a status
1019           change.
1020
1021       "EV_STAT"
1022           The path specified in the "ev_stat" watcher changed its attributes
1023           somehow.
1024
1025       "EV_IDLE"
1026           The "ev_idle" watcher has determined that you have nothing better
1027           to do.
1028
1029       "EV_PREPARE"
1030       "EV_CHECK"
1031           All "ev_prepare" watchers are invoked just before "ev_loop" starts
1032           to gather new events, and all "ev_check" watchers are invoked just
1033           after "ev_loop" has gathered them, but before it invokes any
1034           callbacks for any received events. Callbacks of both watcher types
1035           can start and stop as many watchers as they want, and all of them
1036           will be taken into account (for example, a "ev_prepare" watcher
1037           might start an idle watcher to keep "ev_loop" from blocking).
1038
1039       "EV_EMBED"
1040           The embedded event loop specified in the "ev_embed" watcher needs
1041           attention.
1042
1043       "EV_FORK"
1044           The event loop has been resumed in the child process after fork
1045           (see "ev_fork").
1046
1047       "EV_ASYNC"
1048           The given async watcher has been asynchronously notified (see
1049           "ev_async").
1050
1051       "EV_CUSTOM"
1052           Not ever sent (or otherwise used) by libev itself, but can be
1053           freely used by libev users to signal watchers (e.g. via
1054           "ev_feed_event").
1055
1056       "EV_ERROR"
1057           An unspecified error has occurred, the watcher has been stopped.
1058           This might happen because the watcher could not be properly started
1059           because libev ran out of memory, a file descriptor was found to be
1060           closed or any other problem. Libev considers these application
1061           bugs.
1062
1063           You best act on it by reporting the problem and somehow coping with
1064           the watcher being stopped. Note that well-written programs should
1065           not receive an error ever, so when your watcher receives it, this
1066           usually indicates a bug in your program.
1067
1068           Libev will usually signal a few "dummy" events together with an
1069           error, for example it might indicate that a fd is readable or
1070           writable, and if your callbacks is well-written it can just attempt
1071           the operation and cope with the error from read() or write(). This
1072           will not work in multi-threaded programs, though, as the fd could
1073           already be closed and reused for another thing, so beware.
1074
1075   GENERIC WATCHER FUNCTIONS
1076       "ev_init" (ev_TYPE *watcher, callback)
1077           This macro initialises the generic portion of a watcher. The
1078           contents of the watcher object can be arbitrary (so "malloc" will
1079           do). Only the generic parts of the watcher are initialised, you
1080           need to call the type-specific "ev_TYPE_set" macro afterwards to
1081           initialise the type-specific parts. For each type there is also a
1082           "ev_TYPE_init" macro which rolls both calls into one.
1083
1084           You can reinitialise a watcher at any time as long as it has been
1085           stopped (or never started) and there are no pending events
1086           outstanding.
1087
1088           The callback is always of type "void (*)(struct ev_loop *loop,
1089           ev_TYPE *watcher, int revents)".
1090
1091           Example: Initialise an "ev_io" watcher in two steps.
1092
1093              ev_io w;
1094              ev_init (&w, my_cb);
1095              ev_io_set (&w, STDIN_FILENO, EV_READ);
1096
1097       "ev_TYPE_set" (ev_TYPE *watcher, [args])
1098           This macro initialises the type-specific parts of a watcher. You
1099           need to call "ev_init" at least once before you call this macro,
1100           but you can call "ev_TYPE_set" any number of times. You must not,
1101           however, call this macro on a watcher that is active (it can be
1102           pending, however, which is a difference to the "ev_init" macro).
1103
1104           Although some watcher types do not have type-specific arguments
1105           (e.g. "ev_prepare") you still need to call its "set" macro.
1106
1107           See "ev_init", above, for an example.
1108
1109       "ev_TYPE_init" (ev_TYPE *watcher, callback, [args])
1110           This convenience macro rolls both "ev_init" and "ev_TYPE_set" macro
1111           calls into a single call. This is the most convenient method to
1112           initialise a watcher. The same limitations apply, of course.
1113
1114           Example: Initialise and set an "ev_io" watcher in one step.
1115
1116              ev_io_init (&w, my_cb, STDIN_FILENO, EV_READ);
1117
1118       "ev_TYPE_start" (loop, ev_TYPE *watcher)
1119           Starts (activates) the given watcher. Only active watchers will
1120           receive events. If the watcher is already active nothing will
1121           happen.
1122
1123           Example: Start the "ev_io" watcher that is being abused as example
1124           in this whole section.
1125
1126              ev_io_start (EV_DEFAULT_UC, &w);
1127
1128       "ev_TYPE_stop" (loop, ev_TYPE *watcher)
1129           Stops the given watcher if active, and clears the pending status
1130           (whether the watcher was active or not).
1131
1132           It is possible that stopped watchers are pending - for example,
1133           non-repeating timers are being stopped when they become pending -
1134           but calling "ev_TYPE_stop" ensures that the watcher is neither
1135           active nor pending. If you want to free or reuse the memory used by
1136           the watcher it is therefore a good idea to always call its
1137           "ev_TYPE_stop" function.
1138
1139       bool ev_is_active (ev_TYPE *watcher)
1140           Returns a true value iff the watcher is active (i.e. it has been
1141           started and not yet been stopped). As long as a watcher is active
1142           you must not modify it.
1143
1144       bool ev_is_pending (ev_TYPE *watcher)
1145           Returns a true value iff the watcher is pending, (i.e. it has
1146           outstanding events but its callback has not yet been invoked). As
1147           long as a watcher is pending (but not active) you must not call an
1148           init function on it (but "ev_TYPE_set" is safe), you must not
1149           change its priority, and you must make sure the watcher is
1150           available to libev (e.g. you cannot "free ()" it).
1151
1152       callback ev_cb (ev_TYPE *watcher)
1153           Returns the callback currently set on the watcher.
1154
1155       ev_cb_set (ev_TYPE *watcher, callback)
1156           Change the callback. You can change the callback at virtually any
1157           time (modulo threads).
1158
1159       ev_set_priority (ev_TYPE *watcher, int priority)
1160       int ev_priority (ev_TYPE *watcher)
1161           Set and query the priority of the watcher. The priority is a small
1162           integer between "EV_MAXPRI" (default: 2) and "EV_MINPRI" (default:
1163           "-2"). Pending watchers with higher priority will be invoked before
1164           watchers with lower priority, but priority will not keep watchers
1165           from being executed (except for "ev_idle" watchers).
1166
1167           If you need to suppress invocation when higher priority events are
1168           pending you need to look at "ev_idle" watchers, which provide this
1169           functionality.
1170
1171           You must not change the priority of a watcher as long as it is
1172           active or pending.
1173
1174           Setting a priority outside the range of "EV_MINPRI" to "EV_MAXPRI"
1175           is fine, as long as you do not mind that the priority value you
1176           query might or might not have been clamped to the valid range.
1177
1178           The default priority used by watchers when no priority has been set
1179           is always 0, which is supposed to not be too high and not be too
1180           low :).
1181
1182           See "WATCHER PRIORITY MODELS", below, for a more thorough treatment
1183           of priorities.
1184
1185       ev_invoke (loop, ev_TYPE *watcher, int revents)
1186           Invoke the "watcher" with the given "loop" and "revents". Neither
1187           "loop" nor "revents" need to be valid as long as the watcher
1188           callback can deal with that fact, as both are simply passed through
1189           to the callback.
1190
1191       int ev_clear_pending (loop, ev_TYPE *watcher)
1192           If the watcher is pending, this function clears its pending status
1193           and returns its "revents" bitset (as if its callback was invoked).
1194           If the watcher isn't pending it does nothing and returns 0.
1195
1196           Sometimes it can be useful to "poll" a watcher instead of waiting
1197           for its callback to be invoked, which can be accomplished with this
1198           function.
1199
1200       ev_feed_event (loop, ev_TYPE *watcher, int revents)
1201           Feeds the given event set into the event loop, as if the specified
1202           event had happened for the specified watcher (which must be a
1203           pointer to an initialised but not necessarily started event
1204           watcher). Obviously you must not free the watcher as long as it has
1205           pending events.
1206
1207           Stopping the watcher, letting libev invoke it, or calling
1208           "ev_clear_pending" will clear the pending event, even if the
1209           watcher was not started in the first place.
1210
1211           See also "ev_feed_fd_event" and "ev_feed_signal_event" for related
1212           functions that do not need a watcher.
1213
1214   ASSOCIATING CUSTOM DATA WITH A WATCHER
1215       Each watcher has, by default, a member "void *data" that you can change
1216       and read at any time: libev will completely ignore it. This can be used
1217       to associate arbitrary data with your watcher. If you need more data
1218       and don't want to allocate memory and store a pointer to it in that
1219       data member, you can also "subclass" the watcher type and provide your
1220       own data:
1221
1222          struct my_io
1223          {
1224            ev_io io;
1225            int otherfd;
1226            void *somedata;
1227            struct whatever *mostinteresting;
1228          };
1229
1230          ...
1231          struct my_io w;
1232          ev_io_init (&w.io, my_cb, fd, EV_READ);
1233
1234       And since your callback will be called with a pointer to the watcher,
1235       you can cast it back to your own type:
1236
1237          static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
1238          {
1239            struct my_io *w = (struct my_io *)w_;
1240            ...
1241          }
1242
1243       More interesting and less C-conformant ways of casting your callback
1244       type instead have been omitted.
1245
1246       Another common scenario is to use some data structure with multiple
1247       embedded watchers:
1248
1249          struct my_biggy
1250          {
1251            int some_data;
1252            ev_timer t1;
1253            ev_timer t2;
1254          }
1255
1256       In this case getting the pointer to "my_biggy" is a bit more
1257       complicated: Either you store the address of your "my_biggy" struct in
1258       the "data" member of the watcher (for woozies), or you need to use some
1259       pointer arithmetic using "offsetof" inside your watchers (for real
1260       programmers):
1261
1262          #include <stddef.h>
1263
1264          static void
1265          t1_cb (EV_P_ ev_timer *w, int revents)
1266          {
1267            struct my_biggy big = (struct my_biggy *)
1268              (((char *)w) - offsetof (struct my_biggy, t1));
1269          }
1270
1271          static void
1272          t2_cb (EV_P_ ev_timer *w, int revents)
1273          {
1274            struct my_biggy big = (struct my_biggy *)
1275              (((char *)w) - offsetof (struct my_biggy, t2));
1276          }
1277
1278   WATCHER PRIORITY MODELS
1279       Many event loops support watcher priorities, which are usually small
1280       integers that influence the ordering of event callback invocation
1281       between watchers in some way, all else being equal.
1282
1283       In libev, Watcher priorities can be set using "ev_set_priority". See
1284       its description for the more technical details such as the actual
1285       priority range.
1286
1287       There are two common ways how these these priorities are being
1288       interpreted by event loops:
1289
1290       In the more common lock-out model, higher priorities "lock out"
1291       invocation of lower priority watchers, which means as long as higher
1292       priority watchers receive events, lower priority watchers are not being
1293       invoked.
1294
1295       The less common only-for-ordering model uses priorities solely to order
1296       callback invocation within a single event loop iteration: Higher
1297       priority watchers are invoked before lower priority ones, but they all
1298       get invoked before polling for new events.
1299
1300       Libev uses the second (only-for-ordering) model for all its watchers
1301       except for idle watchers (which use the lock-out model).
1302
1303       The rationale behind this is that implementing the lock-out model for
1304       watchers is not well supported by most kernel interfaces, and most
1305       event libraries will just poll for the same events again and again as
1306       long as their callbacks have not been executed, which is very
1307       inefficient in the common case of one high-priority watcher locking out
1308       a mass of lower priority ones.
1309
1310       Static (ordering) priorities are most useful when you have two or more
1311       watchers handling the same resource: a typical usage example is having
1312       an "ev_io" watcher to receive data, and an associated "ev_timer" to
1313       handle timeouts. Under load, data might be received while the program
1314       handles other jobs, but since timers normally get invoked first, the
1315       timeout handler will be executed before checking for data. In that
1316       case, giving the timer a lower priority than the I/O watcher ensures
1317       that I/O will be handled first even under adverse conditions (which is
1318       usually, but not always, what you want).
1319
1320       Since idle watchers use the "lock-out" model, meaning that idle
1321       watchers will only be executed when no same or higher priority watchers
1322       have received events, they can be used to implement the "lock-out"
1323       model when required.
1324
1325       For example, to emulate how many other event libraries handle
1326       priorities, you can associate an "ev_idle" watcher to each such
1327       watcher, and in the normal watcher callback, you just start the idle
1328       watcher. The real processing is done in the idle watcher callback. This
1329       causes libev to continously poll and process kernel event data for the
1330       watcher, but when the lock-out case is known to be rare (which in turn
1331       is rare :), this is workable.
1332
1333       Usually, however, the lock-out model implemented that way will perform
1334       miserably under the type of load it was designed to handle. In that
1335       case, it might be preferable to stop the real watcher before starting
1336       the idle watcher, so the kernel will not have to process the event in
1337       case the actual processing will be delayed for considerable time.
1338
1339       Here is an example of an I/O watcher that should run at a strictly
1340       lower priority than the default, and which should only process data
1341       when no other events are pending:
1342
1343          ev_idle idle; // actual processing watcher
1344          ev_io io;     // actual event watcher
1345
1346          static void
1347          io_cb (EV_P_ ev_io *w, int revents)
1348          {
1349            // stop the I/O watcher, we received the event, but
1350            // are not yet ready to handle it.
1351            ev_io_stop (EV_A_ w);
1352
1353            // start the idle watcher to ahndle the actual event.
1354            // it will not be executed as long as other watchers
1355            // with the default priority are receiving events.
1356            ev_idle_start (EV_A_ &idle);
1357          }
1358
1359          static void
1360          idle_cb (EV_P_ ev_idle *w, int revents)
1361          {
1362            // actual processing
1363            read (STDIN_FILENO, ...);
1364
1365            // have to start the I/O watcher again, as
1366            // we have handled the event
1367            ev_io_start (EV_P_ &io);
1368          }
1369
1370          // initialisation
1371          ev_idle_init (&idle, idle_cb);
1372          ev_io_init (&io, io_cb, STDIN_FILENO, EV_READ);
1373          ev_io_start (EV_DEFAULT_ &io);
1374
1375       In the "real" world, it might also be beneficial to start a timer, so
1376       that low-priority connections can not be locked out forever under load.
1377       This enables your program to keep a lower latency for important
1378       connections during short periods of high load, while not completely
1379       locking out less important ones.
1380

WATCHER TYPES

1382       This section describes each watcher in detail, but will not repeat
1383       information given in the last section. Any initialisation/set macros,
1384       functions and members specific to the watcher type are explained.
1385
1386       Members are additionally marked with either [read-only], meaning that,
1387       while the watcher is active, you can look at the member and expect some
1388       sensible content, but you must not modify it (you can modify it while
1389       the watcher is stopped to your hearts content), or [read-write], which
1390       means you can expect it to have some sensible content while the watcher
1391       is active, but you can also modify it. Modifying it may not do
1392       something sensible or take immediate effect (or do anything at all),
1393       but libev will not crash or malfunction in any way.
1394
1395   "ev_io" - is this file descriptor readable or writable?
1396       I/O watchers check whether a file descriptor is readable or writable in
1397       each iteration of the event loop, or, more precisely, when reading
1398       would not block the process and writing would at least be able to write
1399       some data. This behaviour is called level-triggering because you keep
1400       receiving events as long as the condition persists. Remember you can
1401       stop the watcher if you don't want to act on the event and neither want
1402       to receive future events.
1403
1404       In general you can register as many read and/or write event watchers
1405       per fd as you want (as long as you don't confuse yourself). Setting all
1406       file descriptors to non-blocking mode is also usually a good idea (but
1407       not required if you know what you are doing).
1408
1409       If you cannot use non-blocking mode, then force the use of a known-to-
1410       be-good backend (at the time of this writing, this includes only
1411       "EVBACKEND_SELECT" and "EVBACKEND_POLL"). The same applies to file
1412       descriptors for which non-blocking operation makes no sense (such as
1413       files) - libev doesn't guarentee any specific behaviour in that case.
1414
1415       Another thing you have to watch out for is that it is quite easy to
1416       receive "spurious" readiness notifications, that is your callback might
1417       be called with "EV_READ" but a subsequent "read"(2) will actually block
1418       because there is no data. Not only are some backends known to create a
1419       lot of those (for example Solaris ports), it is very easy to get into
1420       this situation even with a relatively standard program structure. Thus
1421       it is best to always use non-blocking I/O: An extra "read"(2) returning
1422       "EAGAIN" is far preferable to a program hanging until some data
1423       arrives.
1424
1425       If you cannot run the fd in non-blocking mode (for example you should
1426       not play around with an Xlib connection), then you have to separately
1427       re-test whether a file descriptor is really ready with a known-to-be
1428       good interface such as poll (fortunately in our Xlib example, Xlib
1429       already does this on its own, so its quite safe to use). Some people
1430       additionally use "SIGALRM" and an interval timer, just to be sure you
1431       won't block indefinitely.
1432
1433       But really, best use non-blocking mode.
1434
1435       The special problem of disappearing file descriptors
1436
1437       Some backends (e.g. kqueue, epoll) need to be told about closing a file
1438       descriptor (either due to calling "close" explicitly or any other
1439       means, such as "dup2"). The reason is that you register interest in
1440       some file descriptor, but when it goes away, the operating system will
1441       silently drop this interest. If another file descriptor with the same
1442       number then is registered with libev, there is no efficient way to see
1443       that this is, in fact, a different file descriptor.
1444
1445       To avoid having to explicitly tell libev about such cases, libev
1446       follows the following policy:  Each time "ev_io_set" is being called,
1447       libev will assume that this is potentially a new file descriptor,
1448       otherwise it is assumed that the file descriptor stays the same. That
1449       means that you have to call "ev_io_set" (or "ev_io_init") when you
1450       change the descriptor even if the file descriptor number itself did not
1451       change.
1452
1453       This is how one would do it normally anyway, the important point is
1454       that the libev application should not optimise around libev but should
1455       leave optimisations to libev.
1456
1457       The special problem of dup'ed file descriptors
1458
1459       Some backends (e.g. epoll), cannot register events for file
1460       descriptors, but only events for the underlying file descriptions. That
1461       means when you have "dup ()"'ed file descriptors or weirder
1462       constellations, and register events for them, only one file descriptor
1463       might actually receive events.
1464
1465       There is no workaround possible except not registering events for
1466       potentially "dup ()"'ed file descriptors, or to resort to
1467       "EVBACKEND_SELECT" or "EVBACKEND_POLL".
1468
1469       The special problem of fork
1470
1471       Some backends (epoll, kqueue) do not support "fork ()" at all or
1472       exhibit useless behaviour. Libev fully supports fork, but needs to be
1473       told about it in the child.
1474
1475       To support fork in your programs, you either have to call
1476       "ev_default_fork ()" or "ev_loop_fork ()" after a fork in the child,
1477       enable "EVFLAG_FORKCHECK", or resort to "EVBACKEND_SELECT" or
1478       "EVBACKEND_POLL".
1479
1480       The special problem of SIGPIPE
1481
1482       While not really specific to libev, it is easy to forget about
1483       "SIGPIPE": when writing to a pipe whose other end has been closed, your
1484       program gets sent a SIGPIPE, which, by default, aborts your program.
1485       For most programs this is sensible behaviour, for daemons, this is
1486       usually undesirable.
1487
1488       So when you encounter spurious, unexplained daemon exits, make sure you
1489       ignore SIGPIPE (and maybe make sure you log the exit status of your
1490       daemon somewhere, as that would have given you a big clue).
1491
1492       Watcher-Specific Functions
1493
1494       ev_io_init (ev_io *, callback, int fd, int events)
1495       ev_io_set (ev_io *, int fd, int events)
1496           Configures an "ev_io" watcher. The "fd" is the file descriptor to
1497           receive events for and "events" is either "EV_READ", "EV_WRITE" or
1498           "EV_READ | EV_WRITE", to express the desire to receive the given
1499           events.
1500
1501       int fd [read-only]
1502           The file descriptor being watched.
1503
1504       int events [read-only]
1505           The events being watched.
1506
1507       Examples
1508
1509       Example: Call "stdin_readable_cb" when STDIN_FILENO has become, well
1510       readable, but only once. Since it is likely line-buffered, you could
1511       attempt to read a whole line in the callback.
1512
1513          static void
1514          stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents)
1515          {
1516             ev_io_stop (loop, w);
1517            .. read from stdin here (or from w->fd) and handle any I/O errors
1518          }
1519
1520          ...
1521          struct ev_loop *loop = ev_default_init (0);
1522          ev_io stdin_readable;
1523          ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ);
1524          ev_io_start (loop, &stdin_readable);
1525          ev_loop (loop, 0);
1526
1527   "ev_timer" - relative and optionally repeating timeouts
1528       Timer watchers are simple relative timers that generate an event after
1529       a given time, and optionally repeating in regular intervals after that.
1530
1531       The timers are based on real time, that is, if you register an event
1532       that times out after an hour and you reset your system clock to January
1533       last year, it will still time out after (roughly) one hour. "Roughly"
1534       because detecting time jumps is hard, and some inaccuracies are
1535       unavoidable (the monotonic clock option helps a lot here).
1536
1537       The callback is guaranteed to be invoked only after its timeout has
1538       passed (not at, so on systems with very low-resolution clocks this
1539       might introduce a small delay). If multiple timers become ready during
1540       the same loop iteration then the ones with earlier time-out values are
1541       invoked before ones of the same priority with later time-out values
1542       (but this is no longer true when a callback calls "ev_loop"
1543       recursively).
1544
1545       Be smart about timeouts
1546
1547       Many real-world problems involve some kind of timeout, usually for
1548       error recovery. A typical example is an HTTP request - if the other
1549       side hangs, you want to raise some error after a while.
1550
1551       What follows are some ways to handle this problem, from obvious and
1552       inefficient to smart and efficient.
1553
1554       In the following, a 60 second activity timeout is assumed - a timeout
1555       that gets reset to 60 seconds each time there is activity (e.g. each
1556       time some data or other life sign was received).
1557
1558       1. Use a timer and stop, reinitialise and start it on activity.
1559           This is the most obvious, but not the most simple way: In the
1560           beginning, start the watcher:
1561
1562              ev_timer_init (timer, callback, 60., 0.);
1563              ev_timer_start (loop, timer);
1564
1565           Then, each time there is some activity, "ev_timer_stop" it,
1566           initialise it and start it again:
1567
1568              ev_timer_stop (loop, timer);
1569              ev_timer_set (timer, 60., 0.);
1570              ev_timer_start (loop, timer);
1571
1572           This is relatively simple to implement, but means that each time
1573           there is some activity, libev will first have to remove the timer
1574           from its internal data structure and then add it again. Libev tries
1575           to be fast, but it's still not a constant-time operation.
1576
1577       2. Use a timer and re-start it with "ev_timer_again" inactivity.
1578           This is the easiest way, and involves using "ev_timer_again"
1579           instead of "ev_timer_start".
1580
1581           To implement this, configure an "ev_timer" with a "repeat" value of
1582           60 and then call "ev_timer_again" at start and each time you
1583           successfully read or write some data. If you go into an idle state
1584           where you do not expect data to travel on the socket, you can
1585           "ev_timer_stop" the timer, and "ev_timer_again" will automatically
1586           restart it if need be.
1587
1588           That means you can ignore both the "ev_timer_start" function and
1589           the "after" argument to "ev_timer_set", and only ever use the
1590           "repeat" member and "ev_timer_again".
1591
1592           At start:
1593
1594              ev_init (timer, callback);
1595              timer->repeat = 60.;
1596              ev_timer_again (loop, timer);
1597
1598           Each time there is some activity:
1599
1600              ev_timer_again (loop, timer);
1601
1602           It is even possible to change the time-out on the fly, regardless
1603           of whether the watcher is active or not:
1604
1605              timer->repeat = 30.;
1606              ev_timer_again (loop, timer);
1607
1608           This is slightly more efficient then stopping/starting the timer
1609           each time you want to modify its timeout value, as libev does not
1610           have to completely remove and re-insert the timer from/into its
1611           internal data structure.
1612
1613           It is, however, even simpler than the "obvious" way to do it.
1614
1615       3. Let the timer time out, but then re-arm it as required.
1616           This method is more tricky, but usually most efficient: Most
1617           timeouts are relatively long compared to the intervals between
1618           other activity - in our example, within 60 seconds, there are
1619           usually many I/O events with associated activity resets.
1620
1621           In this case, it would be more efficient to leave the "ev_timer"
1622           alone, but remember the time of last activity, and check for a real
1623           timeout only within the callback:
1624
1625              ev_tstamp last_activity; // time of last activity
1626
1627              static void
1628              callback (EV_P_ ev_timer *w, int revents)
1629              {
1630                ev_tstamp now     = ev_now (EV_A);
1631                ev_tstamp timeout = last_activity + 60.;
1632
1633                // if last_activity + 60. is older than now, we did time out
1634                if (timeout < now)
1635                  {
1636                    // timeout occured, take action
1637                  }
1638                else
1639                  {
1640                    // callback was invoked, but there was some activity, re-arm
1641                    // the watcher to fire in last_activity + 60, which is
1642                    // guaranteed to be in the future, so "again" is positive:
1643                    w->repeat = timeout - now;
1644                    ev_timer_again (EV_A_ w);
1645                  }
1646              }
1647
1648           To summarise the callback: first calculate the real timeout
1649           (defined as "60 seconds after the last activity"), then check if
1650           that time has been reached, which means something did, in fact,
1651           time out. Otherwise the callback was invoked too early ("timeout"
1652           is in the future), so re-schedule the timer to fire at that future
1653           time, to see if maybe we have a timeout then.
1654
1655           Note how "ev_timer_again" is used, taking advantage of the
1656           "ev_timer_again" optimisation when the timer is already running.
1657
1658           This scheme causes more callback invocations (about one every 60
1659           seconds minus half the average time between activity), but
1660           virtually no calls to libev to change the timeout.
1661
1662           To start the timer, simply initialise the watcher and set
1663           "last_activity" to the current time (meaning we just have some
1664           activity :), then call the callback, which will "do the right
1665           thing" and start the timer:
1666
1667              ev_init (timer, callback);
1668              last_activity = ev_now (loop);
1669              callback (loop, timer, EV_TIMEOUT);
1670
1671           And when there is some activity, simply store the current time in
1672           "last_activity", no libev calls at all:
1673
1674              last_actiivty = ev_now (loop);
1675
1676           This technique is slightly more complex, but in most cases where
1677           the time-out is unlikely to be triggered, much more efficient.
1678
1679           Changing the timeout is trivial as well (if it isn't hard-coded in
1680           the callback :) - just change the timeout and invoke the callback,
1681           which will fix things for you.
1682
1683       4. Wee, just use a double-linked list for your timeouts.
1684           If there is not one request, but many thousands (millions...), all
1685           employing some kind of timeout with the same timeout value, then
1686           one can do even better:
1687
1688           When starting the timeout, calculate the timeout value and put the
1689           timeout at the end of the list.
1690
1691           Then use an "ev_timer" to fire when the timeout at the beginning of
1692           the list is expected to fire (for example, using the technique #3).
1693
1694           When there is some activity, remove the timer from the list,
1695           recalculate the timeout, append it to the end of the list again,
1696           and make sure to update the "ev_timer" if it was taken from the
1697           beginning of the list.
1698
1699           This way, one can manage an unlimited number of timeouts in O(1)
1700           time for starting, stopping and updating the timers, at the expense
1701           of a major complication, and having to use a constant timeout. The
1702           constant timeout ensures that the list stays sorted.
1703
1704       So which method the best?
1705
1706       Method #2 is a simple no-brain-required solution that is adequate in
1707       most situations. Method #3 requires a bit more thinking, but handles
1708       many cases better, and isn't very complicated either. In most case,
1709       choosing either one is fine, with #3 being better in typical
1710       situations.
1711
1712       Method #1 is almost always a bad idea, and buys you nothing. Method #4
1713       is rather complicated, but extremely efficient, something that really
1714       pays off after the first million or so of active timers, i.e. it's
1715       usually overkill :)
1716
1717       The special problem of time updates
1718
1719       Establishing the current time is a costly operation (it usually takes
1720       at least two system calls): EV therefore updates its idea of the
1721       current time only before and after "ev_loop" collects new events, which
1722       causes a growing difference between "ev_now ()" and "ev_time ()" when
1723       handling lots of events in one iteration.
1724
1725       The relative timeouts are calculated relative to the "ev_now ()" time.
1726       This is usually the right thing as this timestamp refers to the time of
1727       the event triggering whatever timeout you are modifying/starting. If
1728       you suspect event processing to be delayed and you need to base the
1729       timeout on the current time, use something like this to adjust for
1730       this:
1731
1732          ev_timer_set (&timer, after + ev_now () - ev_time (), 0.);
1733
1734       If the event loop is suspended for a long time, you can also force an
1735       update of the time returned by "ev_now ()" by calling "ev_now_update
1736       ()".
1737
1738       The special problems of suspended animation
1739
1740       When you leave the server world it is quite customary to hit machines
1741       that can suspend/hibernate - what happens to the clocks during such a
1742       suspend?
1743
1744       Some quick tests made with a Linux 2.6.28 indicate that a suspend
1745       freezes all processes, while the clocks ("times", "CLOCK_MONOTONIC")
1746       continue to run until the system is suspended, but they will not
1747       advance while the system is suspended. That means, on resume, it will
1748       be as if the program was frozen for a few seconds, but the suspend time
1749       will not be counted towards "ev_timer" when a monotonic clock source is
1750       used. The real time clock advanced as expected, but if it is used as
1751       sole clocksource, then a long suspend would be detected as a time jump
1752       by libev, and timers would be adjusted accordingly.
1753
1754       I would not be surprised to see different behaviour in different
1755       between operating systems, OS versions or even different hardware.
1756
1757       The other form of suspend (job control, or sending a SIGSTOP) will see
1758       a time jump in the monotonic clocks and the realtime clock. If the
1759       program is suspended for a very long time, and monotonic clock sources
1760       are in use, then you can expect "ev_timer"s to expire as the full
1761       suspension time will be counted towards the timers. When no monotonic
1762       clock source is in use, then libev will again assume a timejump and
1763       adjust accordingly.
1764
1765       It might be beneficial for this latter case to call "ev_suspend" and
1766       "ev_resume" in code that handles "SIGTSTP", to at least get
1767       deterministic behaviour in this case (you can do nothing against
1768       "SIGSTOP").
1769
1770       Watcher-Specific Functions and Data Members
1771
1772       ev_timer_init (ev_timer *, callback, ev_tstamp after, ev_tstamp repeat)
1773       ev_timer_set (ev_timer *, ev_tstamp after, ev_tstamp repeat)
1774           Configure the timer to trigger after "after" seconds. If "repeat"
1775           is 0., then it will automatically be stopped once the timeout is
1776           reached. If it is positive, then the timer will automatically be
1777           configured to trigger again "repeat" seconds later, again, and
1778           again, until stopped manually.
1779
1780           The timer itself will do a best-effort at avoiding drift, that is,
1781           if you configure a timer to trigger every 10 seconds, then it will
1782           normally trigger at exactly 10 second intervals. If, however, your
1783           program cannot keep up with the timer (because it takes longer than
1784           those 10 seconds to do stuff) the timer will not fire more than
1785           once per event loop iteration.
1786
1787       ev_timer_again (loop, ev_timer *)
1788           This will act as if the timer timed out and restart it again if it
1789           is repeating. The exact semantics are:
1790
1791           If the timer is pending, its pending status is cleared.
1792
1793           If the timer is started but non-repeating, stop it (as if it timed
1794           out).
1795
1796           If the timer is repeating, either start it if necessary (with the
1797           "repeat" value), or reset the running timer to the "repeat" value.
1798
1799           This sounds a bit complicated, see "Be smart about timeouts",
1800           above, for a usage example.
1801
1802       ev_tstamp ev_timer_remaining (loop, ev_timer *)
1803           Returns the remaining time until a timer fires. If the timer is
1804           active, then this time is relative to the current event loop time,
1805           otherwise it's the timeout value currently configured.
1806
1807           That is, after an "ev_timer_set (w, 5, 7)", "ev_timer_remaining"
1808           returns 5. When the timer is started and one second passes,
1809           "ev_timer_remain" will return 4. When the timer expires and is
1810           restarted, it will return roughly 7 (likely slightly less as
1811           callback invocation takes some time, too), and so on.
1812
1813       ev_tstamp repeat [read-write]
1814           The current "repeat" value. Will be used each time the watcher
1815           times out or "ev_timer_again" is called, and determines the next
1816           timeout (if any), which is also when any modifications are taken
1817           into account.
1818
1819       Examples
1820
1821       Example: Create a timer that fires after 60 seconds.
1822
1823          static void
1824          one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents)
1825          {
1826            .. one minute over, w is actually stopped right here
1827          }
1828
1829          ev_timer mytimer;
1830          ev_timer_init (&mytimer, one_minute_cb, 60., 0.);
1831          ev_timer_start (loop, &mytimer);
1832
1833       Example: Create a timeout timer that times out after 10 seconds of
1834       inactivity.
1835
1836          static void
1837          timeout_cb (struct ev_loop *loop, ev_timer *w, int revents)
1838          {
1839            .. ten seconds without any activity
1840          }
1841
1842          ev_timer mytimer;
1843          ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */
1844          ev_timer_again (&mytimer); /* start timer */
1845          ev_loop (loop, 0);
1846
1847          // and in some piece of code that gets executed on any "activity":
1848          // reset the timeout to start ticking again at 10 seconds
1849          ev_timer_again (&mytimer);
1850
1851   "ev_periodic" - to cron or not to cron?
1852       Periodic watchers are also timers of a kind, but they are very
1853       versatile (and unfortunately a bit complex).
1854
1855       Unlike "ev_timer", periodic watchers are not based on real time (or
1856       relative time, the physical time that passes) but on wall clock time
1857       (absolute time, the thing you can read on your calender or clock). The
1858       difference is that wall clock time can run faster or slower than real
1859       time, and time jumps are not uncommon (e.g. when you adjust your wrist-
1860       watch).
1861
1862       You can tell a periodic watcher to trigger after some specific point in
1863       time: for example, if you tell a periodic watcher to trigger "in 10
1864       seconds" (by specifying e.g. "ev_now () + 10.", that is, an absolute
1865       time not a delay) and then reset your system clock to January of the
1866       previous year, then it will take a year or more to trigger the event
1867       (unlike an "ev_timer", which would still trigger roughly 10 seconds
1868       after starting it, as it uses a relative timeout).
1869
1870       "ev_periodic" watchers can also be used to implement vastly more
1871       complex timers, such as triggering an event on each "midnight, local
1872       time", or other complicated rules. This cannot be done with "ev_timer"
1873       watchers, as those cannot react to time jumps.
1874
1875       As with timers, the callback is guaranteed to be invoked only when the
1876       point in time where it is supposed to trigger has passed. If multiple
1877       timers become ready during the same loop iteration then the ones with
1878       earlier time-out values are invoked before ones with later time-out
1879       values (but this is no longer true when a callback calls "ev_loop"
1880       recursively).
1881
1882       Watcher-Specific Functions and Data Members
1883
1884       ev_periodic_init (ev_periodic *, callback, ev_tstamp offset, ev_tstamp
1885       interval, reschedule_cb)
1886       ev_periodic_set (ev_periodic *, ev_tstamp offset, ev_tstamp interval,
1887       reschedule_cb)
1888           Lots of arguments, let's sort it out... There are basically three
1889           modes of operation, and we will explain them from simplest to most
1890           complex:
1891
1892           ·   absolute timer (offset = absolute time, interval = 0,
1893               reschedule_cb = 0)
1894
1895               In this configuration the watcher triggers an event after the
1896               wall clock time "offset" has passed. It will not repeat and
1897               will not adjust when a time jump occurs, that is, if it is to
1898               be run at January 1st 2011 then it will be stopped and invoked
1899               when the system clock reaches or surpasses this point in time.
1900
1901           ·   repeating interval timer (offset = offset within interval,
1902               interval > 0, reschedule_cb = 0)
1903
1904               In this mode the watcher will always be scheduled to time out
1905               at the next "offset + N * interval" time (for some integer N,
1906               which can also be negative) and then repeat, regardless of any
1907               time jumps. The "offset" argument is merely an offset into the
1908               "interval" periods.
1909
1910               This can be used to create timers that do not drift with
1911               respect to the system clock, for example, here is an
1912               "ev_periodic" that triggers each hour, on the hour (with
1913               respect to UTC):
1914
1915                  ev_periodic_set (&periodic, 0., 3600., 0);
1916
1917               This doesn't mean there will always be 3600 seconds in between
1918               triggers, but only that the callback will be called when the
1919               system time shows a full hour (UTC), or more correctly, when
1920               the system time is evenly divisible by 3600.
1921
1922               Another way to think about it (for the mathematically inclined)
1923               is that "ev_periodic" will try to run the callback in this mode
1924               at the next possible time where "time = offset (mod interval)",
1925               regardless of any time jumps.
1926
1927               For numerical stability it is preferable that the "offset"
1928               value is near "ev_now ()" (the current time), but there is no
1929               range requirement for this value, and in fact is often
1930               specified as zero.
1931
1932               Note also that there is an upper limit to how often a timer can
1933               fire (CPU speed for example), so if "interval" is very small
1934               then timing stability will of course deteriorate. Libev itself
1935               tries to be exact to be about one millisecond (if the OS
1936               supports it and the machine is fast enough).
1937
1938           ·   manual reschedule mode (offset ignored, interval ignored,
1939               reschedule_cb = callback)
1940
1941               In this mode the values for "interval" and "offset" are both
1942               being ignored. Instead, each time the periodic watcher gets
1943               scheduled, the reschedule callback will be called with the
1944               watcher as first, and the current time as second argument.
1945
1946               NOTE: This callback MUST NOT stop or destroy any periodic
1947               watcher, ever, or make ANY other event loop modifications
1948               whatsoever, unless explicitly allowed by documentation here.
1949
1950               If you need to stop it, return "now + 1e30" (or so, fudge
1951               fudge) and stop it afterwards (e.g. by starting an "ev_prepare"
1952               watcher, which is the only event loop modification you are
1953               allowed to do).
1954
1955               The callback prototype is "ev_tstamp
1956               (*reschedule_cb)(ev_periodic *w, ev_tstamp now)", e.g.:
1957
1958                  static ev_tstamp
1959                  my_rescheduler (ev_periodic *w, ev_tstamp now)
1960                  {
1961                    return now + 60.;
1962                  }
1963
1964               It must return the next time to trigger, based on the passed
1965               time value (that is, the lowest time value larger than to the
1966               second argument). It will usually be called just before the
1967               callback will be triggered, but might be called at other times,
1968               too.
1969
1970               NOTE: This callback must always return a time that is higher
1971               than or equal to the passed "now" value.
1972
1973               This can be used to create very complex timers, such as a timer
1974               that triggers on "next midnight, local time". To do this, you
1975               would calculate the next midnight after "now" and return the
1976               timestamp value for this. How you do this is, again, up to you
1977               (but it is not trivial, which is the main reason I omitted it
1978               as an example).
1979
1980       ev_periodic_again (loop, ev_periodic *)
1981           Simply stops and restarts the periodic watcher again. This is only
1982           useful when you changed some parameters or the reschedule callback
1983           would return a different time than the last time it was called
1984           (e.g. in a crond like program when the crontabs have changed).
1985
1986       ev_tstamp ev_periodic_at (ev_periodic *)
1987           When active, returns the absolute time that the watcher is supposed
1988           to trigger next. This is not the same as the "offset" argument to
1989           "ev_periodic_set", but indeed works even in interval and manual
1990           rescheduling modes.
1991
1992       ev_tstamp offset [read-write]
1993           When repeating, this contains the offset value, otherwise this is
1994           the absolute point in time (the "offset" value passed to
1995           "ev_periodic_set", although libev might modify this value for
1996           better numerical stability).
1997
1998           Can be modified any time, but changes only take effect when the
1999           periodic timer fires or "ev_periodic_again" is being called.
2000
2001       ev_tstamp interval [read-write]
2002           The current interval value. Can be modified any time, but changes
2003           only take effect when the periodic timer fires or
2004           "ev_periodic_again" is being called.
2005
2006       ev_tstamp (*reschedule_cb)(ev_periodic *w, ev_tstamp now) [read-write]
2007           The current reschedule callback, or 0, if this functionality is
2008           switched off. Can be changed any time, but changes only take effect
2009           when the periodic timer fires or "ev_periodic_again" is being
2010           called.
2011
2012       Examples
2013
2014       Example: Call a callback every hour, or, more precisely, whenever the
2015       system time is divisible by 3600. The callback invocation times have
2016       potentially a lot of jitter, but good long-term stability.
2017
2018          static void
2019          clock_cb (struct ev_loop *loop, ev_io *w, int revents)
2020          {
2021            ... its now a full hour (UTC, or TAI or whatever your clock follows)
2022          }
2023
2024          ev_periodic hourly_tick;
2025          ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0);
2026          ev_periodic_start (loop, &hourly_tick);
2027
2028       Example: The same as above, but use a reschedule callback to do it:
2029
2030          #include <math.h>
2031
2032          static ev_tstamp
2033          my_scheduler_cb (ev_periodic *w, ev_tstamp now)
2034          {
2035            return now + (3600. - fmod (now, 3600.));
2036          }
2037
2038          ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb);
2039
2040       Example: Call a callback every hour, starting now:
2041
2042          ev_periodic hourly_tick;
2043          ev_periodic_init (&hourly_tick, clock_cb,
2044                            fmod (ev_now (loop), 3600.), 3600., 0);
2045          ev_periodic_start (loop, &hourly_tick);
2046
2047   "ev_signal" - signal me when a signal gets signalled!
2048       Signal watchers will trigger an event when the process receives a
2049       specific signal one or more times. Even though signals are very
2050       asynchronous, libev will try it's best to deliver signals
2051       synchronously, i.e. as part of the normal event processing, like any
2052       other event.
2053
2054       If you want signals to be delivered truly asynchronously, just use
2055       "sigaction" as you would do without libev and forget about sharing the
2056       signal. You can even use "ev_async" from a signal handler to
2057       synchronously wake up an event loop.
2058
2059       You can configure as many watchers as you like for the same signal, but
2060       only within the same loop, i.e. you can watch for "SIGINT" in your
2061       default loop and for "SIGIO" in another loop, but you cannot watch for
2062       "SIGINT" in both the default loop and another loop at the same time. At
2063       the moment, "SIGCHLD" is permanently tied to the default loop.
2064
2065       When the first watcher gets started will libev actually register
2066       something with the kernel (thus it coexists with your own signal
2067       handlers as long as you don't register any with libev for the same
2068       signal).
2069
2070       If possible and supported, libev will install its handlers with
2071       "SA_RESTART" (or equivalent) behaviour enabled, so system calls should
2072       not be unduly interrupted. If you have a problem with system calls
2073       getting interrupted by signals you can block all signals in an
2074       "ev_check" watcher and unblock them in an "ev_prepare" watcher.
2075
2076       The special problem of inheritance over fork/execve/pthread_create
2077
2078       Both the signal mask ("sigprocmask") and the signal disposition
2079       ("sigaction") are unspecified after starting a signal watcher (and
2080       after stopping it again), that is, libev might or might not block the
2081       signal, and might or might not set or restore the installed signal
2082       handler.
2083
2084       While this does not matter for the signal disposition (libev never sets
2085       signals to "SIG_IGN", so handlers will be reset to "SIG_DFL" on
2086       "execve"), this matters for the signal mask: many programs do not
2087       expect certain signals to be blocked.
2088
2089       This means that before calling "exec" (from the child) you should reset
2090       the signal mask to whatever "default" you expect (all clear is a good
2091       choice usually).
2092
2093       The simplest way to ensure that the signal mask is reset in the child
2094       is to install a fork handler with "pthread_atfork" that resets it. That
2095       will catch fork calls done by libraries (such as the libc) as well.
2096
2097       In current versions of libev, the signal will not be blocked
2098       indefinitely unless you use the "signalfd" API ("EV_SIGNALFD"). While
2099       this reduces the window of opportunity for problems, it will not go
2100       away, as libev has to modify the signal mask, at least temporarily.
2101
2102       So I can't stress this enough: If you do not reset your signal mask
2103       when you expect it to be empty, you have a race condition in your code.
2104       This is not a libev-specific thing, this is true for most event
2105       libraries.
2106
2107       Watcher-Specific Functions and Data Members
2108
2109       ev_signal_init (ev_signal *, callback, int signum)
2110       ev_signal_set (ev_signal *, int signum)
2111           Configures the watcher to trigger on the given signal number
2112           (usually one of the "SIGxxx" constants).
2113
2114       int signum [read-only]
2115           The signal the watcher watches out for.
2116
2117       Examples
2118
2119       Example: Try to exit cleanly on SIGINT.
2120
2121          static void
2122          sigint_cb (struct ev_loop *loop, ev_signal *w, int revents)
2123          {
2124            ev_unloop (loop, EVUNLOOP_ALL);
2125          }
2126
2127          ev_signal signal_watcher;
2128          ev_signal_init (&signal_watcher, sigint_cb, SIGINT);
2129          ev_signal_start (loop, &signal_watcher);
2130
2131   "ev_child" - watch out for process status changes
2132       Child watchers trigger when your process receives a SIGCHLD in response
2133       to some child status changes (most typically when a child of yours dies
2134       or exits). It is permissible to install a child watcher after the child
2135       has been forked (which implies it might have already exited), as long
2136       as the event loop isn't entered (or is continued from a watcher), i.e.,
2137       forking and then immediately registering a watcher for the child is
2138       fine, but forking and registering a watcher a few event loop iterations
2139       later or in the next callback invocation is not.
2140
2141       Only the default event loop is capable of handling signals, and
2142       therefore you can only register child watchers in the default event
2143       loop.
2144
2145       Due to some design glitches inside libev, child watchers will always be
2146       handled at maximum priority (their priority is set to "EV_MAXPRI" by
2147       libev)
2148
2149       Process Interaction
2150
2151       Libev grabs "SIGCHLD" as soon as the default event loop is initialised.
2152       This is necessary to guarantee proper behaviour even if the first child
2153       watcher is started after the child exits. The occurrence of "SIGCHLD"
2154       is recorded asynchronously, but child reaping is done synchronously as
2155       part of the event loop processing. Libev always reaps all children,
2156       even ones not watched.
2157
2158       Overriding the Built-In Processing
2159
2160       Libev offers no special support for overriding the built-in child
2161       processing, but if your application collides with libev's default child
2162       handler, you can override it easily by installing your own handler for
2163       "SIGCHLD" after initialising the default loop, and making sure the
2164       default loop never gets destroyed. You are encouraged, however, to use
2165       an event-based approach to child reaping and thus use libev's support
2166       for that, so other libev users can use "ev_child" watchers freely.
2167
2168       Stopping the Child Watcher
2169
2170       Currently, the child watcher never gets stopped, even when the child
2171       terminates, so normally one needs to stop the watcher in the callback.
2172       Future versions of libev might stop the watcher automatically when a
2173       child exit is detected (calling "ev_child_stop" twice is not a
2174       problem).
2175
2176       Watcher-Specific Functions and Data Members
2177
2178       ev_child_init (ev_child *, callback, int pid, int trace)
2179       ev_child_set (ev_child *, int pid, int trace)
2180           Configures the watcher to wait for status changes of process "pid"
2181           (or any process if "pid" is specified as 0). The callback can look
2182           at the "rstatus" member of the "ev_child" watcher structure to see
2183           the status word (use the macros from "sys/wait.h" and see your
2184           systems "waitpid" documentation). The "rpid" member contains the
2185           pid of the process causing the status change. "trace" must be
2186           either 0 (only activate the watcher when the process terminates) or
2187           1 (additionally activate the watcher when the process is stopped or
2188           continued).
2189
2190       int pid [read-only]
2191           The process id this watcher watches out for, or 0, meaning any
2192           process id.
2193
2194       int rpid [read-write]
2195           The process id that detected a status change.
2196
2197       int rstatus [read-write]
2198           The process exit/trace status caused by "rpid" (see your systems
2199           "waitpid" and "sys/wait.h" documentation for details).
2200
2201       Examples
2202
2203       Example: "fork()" a new process and install a child handler to wait for
2204       its completion.
2205
2206          ev_child cw;
2207
2208          static void
2209          child_cb (EV_P_ ev_child *w, int revents)
2210          {
2211            ev_child_stop (EV_A_ w);
2212            printf ("process %d exited with status %x\n", w->rpid, w->rstatus);
2213          }
2214
2215          pid_t pid = fork ();
2216
2217          if (pid < 0)
2218            // error
2219          else if (pid == 0)
2220            {
2221              // the forked child executes here
2222              exit (1);
2223            }
2224          else
2225            {
2226              ev_child_init (&cw, child_cb, pid, 0);
2227              ev_child_start (EV_DEFAULT_ &cw);
2228            }
2229
2230   "ev_stat" - did the file attributes just change?
2231       This watches a file system path for attribute changes. That is, it
2232       calls "stat" on that path in regular intervals (or when the OS says it
2233       changed) and sees if it changed compared to the last time, invoking the
2234       callback if it did.
2235
2236       The path does not need to exist: changing from "path exists" to "path
2237       does not exist" is a status change like any other. The condition "path
2238       does not exist" (or more correctly "path cannot be stat'ed") is
2239       signified by the "st_nlink" field being zero (which is otherwise always
2240       forced to be at least one) and all the other fields of the stat buffer
2241       having unspecified contents.
2242
2243       The path must not end in a slash or contain special components such as
2244       "." or "..". The path should be absolute: If it is relative and your
2245       working directory changes, then the behaviour is undefined.
2246
2247       Since there is no portable change notification interface available, the
2248       portable implementation simply calls stat(2) regularly on the path to
2249       see if it changed somehow. You can specify a recommended polling
2250       interval for this case. If you specify a polling interval of 0 (highly
2251       recommended!) then a suitable, unspecified default value will be used
2252       (which you can expect to be around five seconds, although this might
2253       change dynamically). Libev will also impose a minimum interval which is
2254       currently around 0.1, but that's usually overkill.
2255
2256       This watcher type is not meant for massive numbers of stat watchers, as
2257       even with OS-supported change notifications, this can be resource-
2258       intensive.
2259
2260       At the time of this writing, the only OS-specific interface implemented
2261       is the Linux inotify interface (implementing kqueue support is left as
2262       an exercise for the reader. Note, however, that the author sees no way
2263       of implementing "ev_stat" semantics with kqueue, except as a hint).
2264
2265       ABI Issues (Largefile Support)
2266
2267       Libev by default (unless the user overrides this) uses the default
2268       compilation environment, which means that on systems with large file
2269       support disabled by default, you get the 32 bit version of the stat
2270       structure. When using the library from programs that change the ABI to
2271       use 64 bit file offsets the programs will fail. In that case you have
2272       to compile libev with the same flags to get binary compatibility. This
2273       is obviously the case with any flags that change the ABI, but the
2274       problem is most noticeably displayed with ev_stat and large file
2275       support.
2276
2277       The solution for this is to lobby your distribution maker to make large
2278       file interfaces available by default (as e.g. FreeBSD does) and not
2279       optional. Libev cannot simply switch on large file support because it
2280       has to exchange stat structures with application programs compiled
2281       using the default compilation environment.
2282
2283       Inotify and Kqueue
2284
2285       When "inotify (7)" support has been compiled into libev and present at
2286       runtime, it will be used to speed up change detection where possible.
2287       The inotify descriptor will be created lazily when the first "ev_stat"
2288       watcher is being started.
2289
2290       Inotify presence does not change the semantics of "ev_stat" watchers
2291       except that changes might be detected earlier, and in some cases, to
2292       avoid making regular "stat" calls. Even in the presence of inotify
2293       support there are many cases where libev has to resort to regular
2294       "stat" polling, but as long as kernel 2.6.25 or newer is used (2.6.24
2295       and older have too many bugs), the path exists (i.e. stat succeeds),
2296       and the path resides on a local filesystem (libev currently assumes
2297       only ext2/3, jfs, reiserfs and xfs are fully working) libev usually
2298       gets away without polling.
2299
2300       There is no support for kqueue, as apparently it cannot be used to
2301       implement this functionality, due to the requirement of having a file
2302       descriptor open on the object at all times, and detecting renames,
2303       unlinks etc. is difficult.
2304
2305       "stat ()" is a synchronous operation
2306
2307       Libev doesn't normally do any kind of I/O itself, and so is not
2308       blocking the process. The exception are "ev_stat" watchers - those call
2309       "stat ()", which is a synchronous operation.
2310
2311       For local paths, this usually doesn't matter: unless the system is very
2312       busy or the intervals between stat's are large, a stat call will be
2313       fast, as the path data is usually in memory already (except when
2314       starting the watcher).
2315
2316       For networked file systems, calling "stat ()" can block an indefinite
2317       time due to network issues, and even under good conditions, a stat call
2318       often takes multiple milliseconds.
2319
2320       Therefore, it is best to avoid using "ev_stat" watchers on networked
2321       paths, although this is fully supported by libev.
2322
2323       The special problem of stat time resolution
2324
2325       The "stat ()" system call only supports full-second resolution
2326       portably, and even on systems where the resolution is higher, most file
2327       systems still only support whole seconds.
2328
2329       That means that, if the time is the only thing that changes, you can
2330       easily miss updates: on the first update, "ev_stat" detects a change
2331       and calls your callback, which does something. When there is another
2332       update within the same second, "ev_stat" will be unable to detect
2333       unless the stat data does change in other ways (e.g. file size).
2334
2335       The solution to this is to delay acting on a change for slightly more
2336       than a second (or till slightly after the next full second boundary),
2337       using a roughly one-second-delay "ev_timer" (e.g. "ev_timer_set (w, 0.,
2338       1.02); ev_timer_again (loop, w)").
2339
2340       The .02 offset is added to work around small timing inconsistencies of
2341       some operating systems (where the second counter of the current time
2342       might be be delayed. One such system is the Linux kernel, where a call
2343       to "gettimeofday" might return a timestamp with a full second later
2344       than a subsequent "time" call - if the equivalent of "time ()" is used
2345       to update file times then there will be a small window where the kernel
2346       uses the previous second to update file times but libev might already
2347       execute the timer callback).
2348
2349       Watcher-Specific Functions and Data Members
2350
2351       ev_stat_init (ev_stat *, callback, const char *path, ev_tstamp
2352       interval)
2353       ev_stat_set (ev_stat *, const char *path, ev_tstamp interval)
2354           Configures the watcher to wait for status changes of the given
2355           "path". The "interval" is a hint on how quickly a change is
2356           expected to be detected and should normally be specified as 0 to
2357           let libev choose a suitable value. The memory pointed to by "path"
2358           must point to the same path for as long as the watcher is active.
2359
2360           The callback will receive an "EV_STAT" event when a change was
2361           detected, relative to the attributes at the time the watcher was
2362           started (or the last change was detected).
2363
2364       ev_stat_stat (loop, ev_stat *)
2365           Updates the stat buffer immediately with new values. If you change
2366           the watched path in your callback, you could call this function to
2367           avoid detecting this change (while introducing a race condition if
2368           you are not the only one changing the path). Can also be useful
2369           simply to find out the new values.
2370
2371       ev_statdata attr [read-only]
2372           The most-recently detected attributes of the file. Although the
2373           type is "ev_statdata", this is usually the (or one of the) "struct
2374           stat" types suitable for your system, but you can only rely on the
2375           POSIX-standardised members to be present. If the "st_nlink" member
2376           is 0, then there was some error while "stat"ing the file.
2377
2378       ev_statdata prev [read-only]
2379           The previous attributes of the file. The callback gets invoked
2380           whenever "prev" != "attr", or, more precisely, one or more of these
2381           members differ: "st_dev", "st_ino", "st_mode", "st_nlink",
2382           "st_uid", "st_gid", "st_rdev", "st_size", "st_atime", "st_mtime",
2383           "st_ctime".
2384
2385       ev_tstamp interval [read-only]
2386           The specified interval.
2387
2388       const char *path [read-only]
2389           The file system path that is being watched.
2390
2391       Examples
2392
2393       Example: Watch "/etc/passwd" for attribute changes.
2394
2395          static void
2396          passwd_cb (struct ev_loop *loop, ev_stat *w, int revents)
2397          {
2398            /* /etc/passwd changed in some way */
2399            if (w->attr.st_nlink)
2400              {
2401                printf ("passwd current size  %ld\n", (long)w->attr.st_size);
2402                printf ("passwd current atime %ld\n", (long)w->attr.st_mtime);
2403                printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime);
2404              }
2405            else
2406              /* you shalt not abuse printf for puts */
2407              puts ("wow, /etc/passwd is not there, expect problems. "
2408                    "if this is windows, they already arrived\n");
2409          }
2410
2411          ...
2412          ev_stat passwd;
2413
2414          ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.);
2415          ev_stat_start (loop, &passwd);
2416
2417       Example: Like above, but additionally use a one-second delay so we do
2418       not miss updates (however, frequent updates will delay processing, too,
2419       so one might do the work both on "ev_stat" callback invocation and on
2420       "ev_timer" callback invocation).
2421
2422          static ev_stat passwd;
2423          static ev_timer timer;
2424
2425          static void
2426          timer_cb (EV_P_ ev_timer *w, int revents)
2427          {
2428            ev_timer_stop (EV_A_ w);
2429
2430            /* now it's one second after the most recent passwd change */
2431          }
2432
2433          static void
2434          stat_cb (EV_P_ ev_stat *w, int revents)
2435          {
2436            /* reset the one-second timer */
2437            ev_timer_again (EV_A_ &timer);
2438          }
2439
2440          ...
2441          ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.);
2442          ev_stat_start (loop, &passwd);
2443          ev_timer_init (&timer, timer_cb, 0., 1.02);
2444
2445   "ev_idle" - when you've got nothing better to do...
2446       Idle watchers trigger events when no other events of the same or higher
2447       priority are pending (prepare, check and other idle watchers do not
2448       count as receiving "events").
2449
2450       That is, as long as your process is busy handling sockets or timeouts
2451       (or even signals, imagine) of the same or higher priority it will not
2452       be triggered. But when your process is idle (or only lower-priority
2453       watchers are pending), the idle watchers are being called once per
2454       event loop iteration - until stopped, that is, or your process receives
2455       more events and becomes busy again with higher priority stuff.
2456
2457       The most noteworthy effect is that as long as any idle watchers are
2458       active, the process will not block when waiting for new events.
2459
2460       Apart from keeping your process non-blocking (which is a useful effect
2461       on its own sometimes), idle watchers are a good place to do "pseudo-
2462       background processing", or delay processing stuff to after the event
2463       loop has handled all outstanding events.
2464
2465       Watcher-Specific Functions and Data Members
2466
2467       ev_idle_init (ev_idle *, callback)
2468           Initialises and configures the idle watcher - it has no parameters
2469           of any kind. There is a "ev_idle_set" macro, but using it is
2470           utterly pointless, believe me.
2471
2472       Examples
2473
2474       Example: Dynamically allocate an "ev_idle" watcher, start it, and in
2475       the callback, free it. Also, use no error checking, as usual.
2476
2477          static void
2478          idle_cb (struct ev_loop *loop, ev_idle *w, int revents)
2479          {
2480            free (w);
2481            // now do something you wanted to do when the program has
2482            // no longer anything immediate to do.
2483          }
2484
2485          ev_idle *idle_watcher = malloc (sizeof (ev_idle));
2486          ev_idle_init (idle_watcher, idle_cb);
2487          ev_idle_start (loop, idle_watcher);
2488
2489   "ev_prepare" and "ev_check" - customise your event loop!
2490       Prepare and check watchers are usually (but not always) used in pairs:
2491       prepare watchers get invoked before the process blocks and check
2492       watchers afterwards.
2493
2494       You must not call "ev_loop" or similar functions that enter the current
2495       event loop from either "ev_prepare" or "ev_check" watchers. Other loops
2496       than the current one are fine, however. The rationale behind this is
2497       that you do not need to check for recursion in those watchers, i.e. the
2498       sequence will always be "ev_prepare", blocking, "ev_check" so if you
2499       have one watcher of each kind they will always be called in pairs
2500       bracketing the blocking call.
2501
2502       Their main purpose is to integrate other event mechanisms into libev
2503       and their use is somewhat advanced. They could be used, for example, to
2504       track variable changes, implement your own watchers, integrate net-snmp
2505       or a coroutine library and lots more. They are also occasionally useful
2506       if you cache some data and want to flush it before blocking (for
2507       example, in X programs you might want to do an "XFlush ()" in an
2508       "ev_prepare" watcher).
2509
2510       This is done by examining in each prepare call which file descriptors
2511       need to be watched by the other library, registering "ev_io" watchers
2512       for them and starting an "ev_timer" watcher for any timeouts (many
2513       libraries provide exactly this functionality). Then, in the check
2514       watcher, you check for any events that occurred (by checking the
2515       pending status of all watchers and stopping them) and call back into
2516       the library. The I/O and timer callbacks will never actually be called
2517       (but must be valid nevertheless, because you never know, you know?).
2518
2519       As another example, the Perl Coro module uses these hooks to integrate
2520       coroutines into libev programs, by yielding to other active coroutines
2521       during each prepare and only letting the process block if no coroutines
2522       are ready to run (it's actually more complicated: it only runs
2523       coroutines with priority higher than or equal to the event loop and one
2524       coroutine of lower priority, but only once, using idle watchers to keep
2525       the event loop from blocking if lower-priority coroutines are active,
2526       thus mapping low-priority coroutines to idle/background tasks).
2527
2528       It is recommended to give "ev_check" watchers highest ("EV_MAXPRI")
2529       priority, to ensure that they are being run before any other watchers
2530       after the poll (this doesn't matter for "ev_prepare" watchers).
2531
2532       Also, "ev_check" watchers (and "ev_prepare" watchers, too) should not
2533       activate ("feed") events into libev. While libev fully supports this,
2534       they might get executed before other "ev_check" watchers did their job.
2535       As "ev_check" watchers are often used to embed other (non-libev) event
2536       loops those other event loops might be in an unusable state until their
2537       "ev_check" watcher ran (always remind yourself to coexist peacefully
2538       with others).
2539
2540       Watcher-Specific Functions and Data Members
2541
2542       ev_prepare_init (ev_prepare *, callback)
2543       ev_check_init (ev_check *, callback)
2544           Initialises and configures the prepare or check watcher - they have
2545           no parameters of any kind. There are "ev_prepare_set" and
2546           "ev_check_set" macros, but using them is utterly, utterly, utterly
2547           and completely pointless.
2548
2549       Examples
2550
2551       There are a number of principal ways to embed other event loops or
2552       modules into libev. Here are some ideas on how to include libadns into
2553       libev (there is a Perl module named "EV::ADNS" that does this, which
2554       you could use as a working example. Another Perl module named
2555       "EV::Glib" embeds a Glib main context into libev, and finally,
2556       "Glib::EV" embeds EV into the Glib event loop).
2557
2558       Method 1: Add IO watchers and a timeout watcher in a prepare handler,
2559       and in a check watcher, destroy them and call into libadns. What
2560       follows is pseudo-code only of course. This requires you to either use
2561       a low priority for the check watcher or use "ev_clear_pending"
2562       explicitly, as the callbacks for the IO/timeout watchers might not have
2563       been called yet.
2564
2565          static ev_io iow [nfd];
2566          static ev_timer tw;
2567
2568          static void
2569          io_cb (struct ev_loop *loop, ev_io *w, int revents)
2570          {
2571          }
2572
2573          // create io watchers for each fd and a timer before blocking
2574          static void
2575          adns_prepare_cb (struct ev_loop *loop, ev_prepare *w, int revents)
2576          {
2577            int timeout = 3600000;
2578            struct pollfd fds [nfd];
2579            // actual code will need to loop here and realloc etc.
2580            adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ()));
2581
2582            /* the callback is illegal, but won't be called as we stop during check */
2583            ev_timer_init (&tw, 0, timeout * 1e-3, 0.);
2584            ev_timer_start (loop, &tw);
2585
2586            // create one ev_io per pollfd
2587            for (int i = 0; i < nfd; ++i)
2588              {
2589                ev_io_init (iow + i, io_cb, fds [i].fd,
2590                  ((fds [i].events & POLLIN ? EV_READ : 0)
2591                   | (fds [i].events & POLLOUT ? EV_WRITE : 0)));
2592
2593                fds [i].revents = 0;
2594                ev_io_start (loop, iow + i);
2595              }
2596          }
2597
2598          // stop all watchers after blocking
2599          static void
2600          adns_check_cb (struct ev_loop *loop, ev_check *w, int revents)
2601          {
2602            ev_timer_stop (loop, &tw);
2603
2604            for (int i = 0; i < nfd; ++i)
2605              {
2606                // set the relevant poll flags
2607                // could also call adns_processreadable etc. here
2608                struct pollfd *fd = fds + i;
2609                int revents = ev_clear_pending (iow + i);
2610                if (revents & EV_READ ) fd->revents |= fd->events & POLLIN;
2611                if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT;
2612
2613                // now stop the watcher
2614                ev_io_stop (loop, iow + i);
2615              }
2616
2617            adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop));
2618          }
2619
2620       Method 2: This would be just like method 1, but you run
2621       "adns_afterpoll" in the prepare watcher and would dispose of the check
2622       watcher.
2623
2624       Method 3: If the module to be embedded supports explicit event
2625       notification (libadns does), you can also make use of the actual
2626       watcher callbacks, and only destroy/create the watchers in the prepare
2627       watcher.
2628
2629          static void
2630          timer_cb (EV_P_ ev_timer *w, int revents)
2631          {
2632            adns_state ads = (adns_state)w->data;
2633            update_now (EV_A);
2634
2635            adns_processtimeouts (ads, &tv_now);
2636          }
2637
2638          static void
2639          io_cb (EV_P_ ev_io *w, int revents)
2640          {
2641            adns_state ads = (adns_state)w->data;
2642            update_now (EV_A);
2643
2644            if (revents & EV_READ ) adns_processreadable  (ads, w->fd, &tv_now);
2645            if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now);
2646          }
2647
2648          // do not ever call adns_afterpoll
2649
2650       Method 4: Do not use a prepare or check watcher because the module you
2651       want to embed is not flexible enough to support it. Instead, you can
2652       override their poll function. The drawback with this solution is that
2653       the main loop is now no longer controllable by EV. The "Glib::EV"
2654       module uses this approach, effectively embedding EV as a client into
2655       the horrible libglib event loop.
2656
2657          static gint
2658          event_poll_func (GPollFD *fds, guint nfds, gint timeout)
2659          {
2660            int got_events = 0;
2661
2662            for (n = 0; n < nfds; ++n)
2663              // create/start io watcher that sets the relevant bits in fds[n] and increment got_events
2664
2665            if (timeout >= 0)
2666              // create/start timer
2667
2668            // poll
2669            ev_loop (EV_A_ 0);
2670
2671            // stop timer again
2672            if (timeout >= 0)
2673              ev_timer_stop (EV_A_ &to);
2674
2675            // stop io watchers again - their callbacks should have set
2676            for (n = 0; n < nfds; ++n)
2677              ev_io_stop (EV_A_ iow [n]);
2678
2679            return got_events;
2680          }
2681
2682   "ev_embed" - when one backend isn't enough...
2683       This is a rather advanced watcher type that lets you embed one event
2684       loop into another (currently only "ev_io" events are supported in the
2685       embedded loop, other types of watchers might be handled in a delayed or
2686       incorrect fashion and must not be used).
2687
2688       There are primarily two reasons you would want that: work around bugs
2689       and prioritise I/O.
2690
2691       As an example for a bug workaround, the kqueue backend might only
2692       support sockets on some platform, so it is unusable as generic backend,
2693       but you still want to make use of it because you have many sockets and
2694       it scales so nicely. In this case, you would create a kqueue-based loop
2695       and embed it into your default loop (which might use e.g. poll).
2696       Overall operation will be a bit slower because first libev has to call
2697       "poll" and then "kevent", but at least you can use both mechanisms for
2698       what they are best: "kqueue" for scalable sockets and "poll" if you
2699       want it to work :)
2700
2701       As for prioritising I/O: under rare circumstances you have the case
2702       where some fds have to be watched and handled very quickly (with low
2703       latency), and even priorities and idle watchers might have too much
2704       overhead. In this case you would put all the high priority stuff in one
2705       loop and all the rest in a second one, and embed the second one in the
2706       first.
2707
2708       As long as the watcher is active, the callback will be invoked every
2709       time there might be events pending in the embedded loop. The callback
2710       must then call "ev_embed_sweep (mainloop, watcher)" to make a single
2711       sweep and invoke their callbacks (the callback doesn't need to invoke
2712       the "ev_embed_sweep" function directly, it could also start an idle
2713       watcher to give the embedded loop strictly lower priority for example).
2714
2715       You can also set the callback to 0, in which case the embed watcher
2716       will automatically execute the embedded loop sweep whenever necessary.
2717
2718       Fork detection will be handled transparently while the "ev_embed"
2719       watcher is active, i.e., the embedded loop will automatically be forked
2720       when the embedding loop forks. In other cases, the user is responsible
2721       for calling "ev_loop_fork" on the embedded loop.
2722
2723       Unfortunately, not all backends are embeddable: only the ones returned
2724       by "ev_embeddable_backends" are, which, unfortunately, does not include
2725       any portable one.
2726
2727       So when you want to use this feature you will always have to be
2728       prepared that you cannot get an embeddable loop. The recommended way to
2729       get around this is to have a separate variables for your embeddable
2730       loop, try to create it, and if that fails, use the normal loop for
2731       everything.
2732
2733       "ev_embed" and fork
2734
2735       While the "ev_embed" watcher is running, forks in the embedding loop
2736       will automatically be applied to the embedded loop as well, so no
2737       special fork handling is required in that case. When the watcher is not
2738       running, however, it is still the task of the libev user to call
2739       "ev_loop_fork ()" as applicable.
2740
2741       Watcher-Specific Functions and Data Members
2742
2743       ev_embed_init (ev_embed *, callback, struct ev_loop *embedded_loop)
2744       ev_embed_set (ev_embed *, callback, struct ev_loop *embedded_loop)
2745           Configures the watcher to embed the given loop, which must be
2746           embeddable. If the callback is 0, then "ev_embed_sweep" will be
2747           invoked automatically, otherwise it is the responsibility of the
2748           callback to invoke it (it will continue to be called until the
2749           sweep has been done, if you do not want that, you need to
2750           temporarily stop the embed watcher).
2751
2752       ev_embed_sweep (loop, ev_embed *)
2753           Make a single, non-blocking sweep over the embedded loop. This
2754           works similarly to "ev_loop (embedded_loop, EVLOOP_NONBLOCK)", but
2755           in the most appropriate way for embedded loops.
2756
2757       struct ev_loop *other [read-only]
2758           The embedded event loop.
2759
2760       Examples
2761
2762       Example: Try to get an embeddable event loop and embed it into the
2763       default event loop. If that is not possible, use the default loop. The
2764       default loop is stored in "loop_hi", while the embeddable loop is
2765       stored in "loop_lo" (which is "loop_hi" in the case no embeddable loop
2766       can be used).
2767
2768          struct ev_loop *loop_hi = ev_default_init (0);
2769          struct ev_loop *loop_lo = 0;
2770          ev_embed embed;
2771
2772          // see if there is a chance of getting one that works
2773          // (remember that a flags value of 0 means autodetection)
2774          loop_lo = ev_embeddable_backends () & ev_recommended_backends ()
2775            ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ())
2776            : 0;
2777
2778          // if we got one, then embed it, otherwise default to loop_hi
2779          if (loop_lo)
2780            {
2781              ev_embed_init (&embed, 0, loop_lo);
2782              ev_embed_start (loop_hi, &embed);
2783            }
2784          else
2785            loop_lo = loop_hi;
2786
2787       Example: Check if kqueue is available but not recommended and create a
2788       kqueue backend for use with sockets (which usually work with any kqueue
2789       implementation). Store the kqueue/socket-only event loop in
2790       "loop_socket". (One might optionally use "EVFLAG_NOENV", too).
2791
2792          struct ev_loop *loop = ev_default_init (0);
2793          struct ev_loop *loop_socket = 0;
2794          ev_embed embed;
2795
2796          if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE)
2797            if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE))
2798              {
2799                ev_embed_init (&embed, 0, loop_socket);
2800                ev_embed_start (loop, &embed);
2801              }
2802
2803          if (!loop_socket)
2804            loop_socket = loop;
2805
2806          // now use loop_socket for all sockets, and loop for everything else
2807
2808   "ev_fork" - the audacity to resume the event loop after a fork
2809       Fork watchers are called when a "fork ()" was detected (usually because
2810       whoever is a good citizen cared to tell libev about it by calling
2811       "ev_default_fork" or "ev_loop_fork"). The invocation is done before the
2812       event loop blocks next and before "ev_check" watchers are being called,
2813       and only in the child after the fork. If whoever good citizen calling
2814       "ev_default_fork" cheats and calls it in the wrong process, the fork
2815       handlers will be invoked, too, of course.
2816
2817       The special problem of life after fork - how is it possible?
2818
2819       Most uses of "fork()" consist of forking, then some simple calls to ste
2820       up/change the process environment, followed by a call to "exec()". This
2821       sequence should be handled by libev without any problems.
2822
2823       This changes when the application actually wants to do event handling
2824       in the child, or both parent in child, in effect "continuing" after the
2825       fork.
2826
2827       The default mode of operation (for libev, with application help to
2828       detect forks) is to duplicate all the state in the child, as would be
2829       expected when either the parent or the child process continues.
2830
2831       When both processes want to continue using libev, then this is usually
2832       the wrong result. In that case, usually one process (typically the
2833       parent) is supposed to continue with all watchers in place as before,
2834       while the other process typically wants to start fresh, i.e. without
2835       any active watchers.
2836
2837       The cleanest and most efficient way to achieve that with libev is to
2838       simply create a new event loop, which of course will be "empty", and
2839       use that for new watchers. This has the advantage of not touching more
2840       memory than necessary, and thus avoiding the copy-on-write, and the
2841       disadvantage of having to use multiple event loops (which do not
2842       support signal watchers).
2843
2844       When this is not possible, or you want to use the default loop for
2845       other reasons, then in the process that wants to start "fresh", call
2846       "ev_default_destroy ()" followed by "ev_default_loop (...)". Destroying
2847       the default loop will "orphan" (not stop) all registered watchers, so
2848       you have to be careful not to execute code that modifies those
2849       watchers. Note also that in that case, you have to re-register any
2850       signal watchers.
2851
2852       Watcher-Specific Functions and Data Members
2853
2854       ev_fork_init (ev_signal *, callback)
2855           Initialises and configures the fork watcher - it has no parameters
2856           of any kind. There is a "ev_fork_set" macro, but using it is
2857           utterly pointless, believe me.
2858
2859   "ev_async" - how to wake up another event loop
2860       In general, you cannot use an "ev_loop" from multiple threads or other
2861       asynchronous sources such as signal handlers (as opposed to multiple
2862       event loops - those are of course safe to use in different threads).
2863
2864       Sometimes, however, you need to wake up another event loop you do not
2865       control, for example because it belongs to another thread. This is what
2866       "ev_async" watchers do: as long as the "ev_async" watcher is active,
2867       you can signal it by calling "ev_async_send", which is thread- and
2868       signal safe.
2869
2870       This functionality is very similar to "ev_signal" watchers, as signals,
2871       too, are asynchronous in nature, and signals, too, will be compressed
2872       (i.e. the number of callback invocations may be less than the number of
2873       "ev_async_sent" calls).
2874
2875       Unlike "ev_signal" watchers, "ev_async" works with any event loop, not
2876       just the default loop.
2877
2878       Queueing
2879
2880       "ev_async" does not support queueing of data in any way. The reason is
2881       that the author does not know of a simple (or any) algorithm for a
2882       multiple-writer-single-reader queue that works in all cases and doesn't
2883       need elaborate support such as pthreads or unportable memory access
2884       semantics.
2885
2886       That means that if you want to queue data, you have to provide your own
2887       queue. But at least I can tell you how to implement locking around your
2888       queue:
2889
2890       queueing from a signal handler context
2891           To implement race-free queueing, you simply add to the queue in the
2892           signal handler but you block the signal handler in the watcher
2893           callback. Here is an example that does that for some fictitious
2894           SIGUSR1 handler:
2895
2896              static ev_async mysig;
2897
2898              static void
2899              sigusr1_handler (void)
2900              {
2901                sometype data;
2902
2903                // no locking etc.
2904                queue_put (data);
2905                ev_async_send (EV_DEFAULT_ &mysig);
2906              }
2907
2908              static void
2909              mysig_cb (EV_P_ ev_async *w, int revents)
2910              {
2911                sometype data;
2912                sigset_t block, prev;
2913
2914                sigemptyset (&block);
2915                sigaddset (&block, SIGUSR1);
2916                sigprocmask (SIG_BLOCK, &block, &prev);
2917
2918                while (queue_get (&data))
2919                  process (data);
2920
2921                if (sigismember (&prev, SIGUSR1)
2922                  sigprocmask (SIG_UNBLOCK, &block, 0);
2923              }
2924
2925           (Note: pthreads in theory requires you to use "pthread_setmask"
2926           instead of "sigprocmask" when you use threads, but libev doesn't do
2927           it either...).
2928
2929       queueing from a thread context
2930           The strategy for threads is different, as you cannot (easily) block
2931           threads but you can easily preempt them, so to queue safely you
2932           need to employ a traditional mutex lock, such as in this pthread
2933           example:
2934
2935              static ev_async mysig;
2936              static pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
2937
2938              static void
2939              otherthread (void)
2940              {
2941                // only need to lock the actual queueing operation
2942                pthread_mutex_lock (&mymutex);
2943                queue_put (data);
2944                pthread_mutex_unlock (&mymutex);
2945
2946                ev_async_send (EV_DEFAULT_ &mysig);
2947              }
2948
2949              static void
2950              mysig_cb (EV_P_ ev_async *w, int revents)
2951              {
2952                pthread_mutex_lock (&mymutex);
2953
2954                while (queue_get (&data))
2955                  process (data);
2956
2957                pthread_mutex_unlock (&mymutex);
2958              }
2959
2960       Watcher-Specific Functions and Data Members
2961
2962       ev_async_init (ev_async *, callback)
2963           Initialises and configures the async watcher - it has no parameters
2964           of any kind. There is a "ev_async_set" macro, but using it is
2965           utterly pointless, trust me.
2966
2967       ev_async_send (loop, ev_async *)
2968           Sends/signals/activates the given "ev_async" watcher, that is,
2969           feeds an "EV_ASYNC" event on the watcher into the event loop.
2970           Unlike "ev_feed_event", this call is safe to do from other threads,
2971           signal or similar contexts (see the discussion of "EV_ATOMIC_T" in
2972           the embedding section below on what exactly this means).
2973
2974           Note that, as with other watchers in libev, multiple events might
2975           get compressed into a single callback invocation (another way to
2976           look at this is that "ev_async" watchers are level-triggered, set
2977           on "ev_async_send", reset when the event loop detects that).
2978
2979           This call incurs the overhead of a system call only once per event
2980           loop iteration, so while the overhead might be noticeable, it
2981           doesn't apply to repeated calls to "ev_async_send" for the same
2982           event loop.
2983
2984       bool = ev_async_pending (ev_async *)
2985           Returns a non-zero value when "ev_async_send" has been called on
2986           the watcher but the event has not yet been processed (or even
2987           noted) by the event loop.
2988
2989           "ev_async_send" sets a flag in the watcher and wakes up the loop.
2990           When the loop iterates next and checks for the watcher to have
2991           become active, it will reset the flag again. "ev_async_pending" can
2992           be used to very quickly check whether invoking the loop might be a
2993           good idea.
2994
2995           Not that this does not check whether the watcher itself is pending,
2996           only whether it has been requested to make this watcher pending:
2997           there is a time window between the event loop checking and
2998           resetting the async notification, and the callback being invoked.
2999

OTHER FUNCTIONS

3001       There are some other functions of possible interest. Described. Here.
3002       Now.
3003
3004       ev_once (loop, int fd, int events, ev_tstamp timeout, callback)
3005           This function combines a simple timer and an I/O watcher, calls
3006           your callback on whichever event happens first and automatically
3007           stops both watchers. This is useful if you want to wait for a
3008           single event on an fd or timeout without having to
3009           allocate/configure/start/stop/free one or more watchers yourself.
3010
3011           If "fd" is less than 0, then no I/O watcher will be started and the
3012           "events" argument is being ignored. Otherwise, an "ev_io" watcher
3013           for the given "fd" and "events" set will be created and started.
3014
3015           If "timeout" is less than 0, then no timeout watcher will be
3016           started. Otherwise an "ev_timer" watcher with after = "timeout"
3017           (and repeat = 0) will be started. 0 is a valid timeout.
3018
3019           The callback has the type "void (*cb)(int revents, void *arg)" and
3020           gets passed an "revents" set like normal event callbacks (a
3021           combination of "EV_ERROR", "EV_READ", "EV_WRITE" or "EV_TIMEOUT")
3022           and the "arg" value passed to "ev_once". Note that it is possible
3023           to receive both a timeout and an io event at the same time - you
3024           probably should give io events precedence.
3025
3026           Example: wait up to ten seconds for data to appear on STDIN_FILENO.
3027
3028              static void stdin_ready (int revents, void *arg)
3029              {
3030                if (revents & EV_READ)
3031                  /* stdin might have data for us, joy! */;
3032                else if (revents & EV_TIMEOUT)
3033                  /* doh, nothing entered */;
3034              }
3035
3036              ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);
3037
3038       ev_feed_fd_event (loop, int fd, int revents)
3039           Feed an event on the given fd, as if a file descriptor backend
3040           detected the given events it.
3041
3042       ev_feed_signal_event (loop, int signum)
3043           Feed an event as if the given signal occurred ("loop" must be the
3044           default loop!).
3045

LIBEVENT EMULATION

3047       Libev offers a compatibility emulation layer for libevent. It cannot
3048       emulate the internals of libevent, so here are some usage hints:
3049
3050       ·   Use it by including <event.h>, as usual.
3051
3052       ·   The following members are fully supported: ev_base, ev_callback,
3053           ev_arg, ev_fd, ev_res, ev_events.
3054
3055       ·   Avoid using ev_flags and the EVLIST_*-macros, while it is
3056           maintained by libev, it does not work exactly the same way as in
3057           libevent (consider it a private API).
3058
3059       ·   Priorities are not currently supported. Initialising priorities
3060           will fail and all watchers will have the same priority, even though
3061           there is an ev_pri field.
3062
3063       ·   In libevent, the last base created gets the signals, in libev, the
3064           first base created (== the default loop) gets the signals.
3065
3066       ·   Other members are not supported.
3067
3068       ·   The libev emulation is not ABI compatible to libevent, you need to
3069           use the libev header file and library.
3070

C++ SUPPORT

3072       Libev comes with some simplistic wrapper classes for C++ that mainly
3073       allow you to use some convenience methods to start/stop watchers and
3074       also change the callback model to a model using method callbacks on
3075       objects.
3076
3077       To use it,
3078
3079          #include <ev++.h>
3080
3081       This automatically includes ev.h and puts all of its definitions (many
3082       of them macros) into the global namespace. All C++ specific things are
3083       put into the "ev" namespace. It should support all the same embedding
3084       options as ev.h, most notably "EV_MULTIPLICITY".
3085
3086       Care has been taken to keep the overhead low. The only data member the
3087       C++ classes add (compared to plain C-style watchers) is the event loop
3088       pointer that the watcher is associated with (or no additional members
3089       at all if you disable "EV_MULTIPLICITY" when embedding libev).
3090
3091       Currently, functions, and static and non-static member functions can be
3092       used as callbacks. Other types should be easy to add as long as they
3093       only need one additional pointer for context. If you need support for
3094       other types of functors please contact the author (preferably after
3095       implementing it).
3096
3097       Here is a list of things available in the "ev" namespace:
3098
3099       "ev::READ", "ev::WRITE" etc.
3100           These are just enum values with the same values as the "EV_READ"
3101           etc.  macros from ev.h.
3102
3103       "ev::tstamp", "ev::now"
3104           Aliases to the same types/functions as with the "ev_" prefix.
3105
3106       "ev::io", "ev::timer", "ev::periodic", "ev::idle", "ev::sig" etc.
3107           For each "ev_TYPE" watcher in ev.h there is a corresponding class
3108           of the same name in the "ev" namespace, with the exception of
3109           "ev_signal" which is called "ev::sig" to avoid clashes with the
3110           "signal" macro defines by many implementations.
3111
3112           All of those classes have these methods:
3113
3114           ev::TYPE::TYPE ()
3115           ev::TYPE::TYPE (loop)
3116           ev::TYPE::~TYPE
3117               The constructor (optionally) takes an event loop to associate
3118               the watcher with. If it is omitted, it will use "EV_DEFAULT".
3119
3120               The constructor calls "ev_init" for you, which means you have
3121               to call the "set" method before starting it.
3122
3123               It will not set a callback, however: You have to call the
3124               templated "set" method to set a callback before you can start
3125               the watcher.
3126
3127               (The reason why you have to use a method is a limitation in C++
3128               which does not allow explicit template arguments for
3129               constructors).
3130
3131               The destructor automatically stops the watcher if it is active.
3132
3133           w->set<class, &class::method> (object *)
3134               This method sets the callback method to call. The method has to
3135               have a signature of "void (*)(ev_TYPE &, int)", it receives the
3136               watcher as first argument and the "revents" as second. The
3137               object must be given as parameter and is stored in the "data"
3138               member of the watcher.
3139
3140               This method synthesizes efficient thunking code to call your
3141               method from the C callback that libev requires. If your
3142               compiler can inline your callback (i.e. it is visible to it at
3143               the place of the "set" call and your compiler is good :), then
3144               the method will be fully inlined into the thunking function,
3145               making it as fast as a direct C callback.
3146
3147               Example: simple class declaration and watcher initialisation
3148
3149                  struct myclass
3150                  {
3151                    void io_cb (ev::io &w, int revents) { }
3152                  }
3153
3154                  myclass obj;
3155                  ev::io iow;
3156                  iow.set <myclass, &myclass::io_cb> (&obj);
3157
3158           w->set (object *)
3159               This is an experimental feature that might go away in a future
3160               version.
3161
3162               This is a variation of a method callback - leaving out the
3163               method to call will default the method to "operator ()", which
3164               makes it possible to use functor objects without having to
3165               manually specify the "operator ()" all the time. Incidentally,
3166               you can then also leave out the template argument list.
3167
3168               The "operator ()" method prototype must be "void operator
3169               ()(watcher &w, int revents)".
3170
3171               See the method-"set" above for more details.
3172
3173               Example: use a functor object as callback.
3174
3175                  struct myfunctor
3176                  {
3177                    void operator() (ev::io &w, int revents)
3178                    {
3179                      ...
3180                    }
3181                  }
3182
3183                  myfunctor f;
3184
3185                  ev::io w;
3186                  w.set (&f);
3187
3188           w->set<function> (void *data = 0)
3189               Also sets a callback, but uses a static method or plain
3190               function as callback. The optional "data" argument will be
3191               stored in the watcher's "data" member and is free for you to
3192               use.
3193
3194               The prototype of the "function" must be "void (*)(ev::TYPE &w,
3195               int)".
3196
3197               See the method-"set" above for more details.
3198
3199               Example: Use a plain function as callback.
3200
3201                  static void io_cb (ev::io &w, int revents) { }
3202                  iow.set <io_cb> ();
3203
3204           w->set (loop)
3205               Associates a different "struct ev_loop" with this watcher. You
3206               can only do this when the watcher is inactive (and not pending
3207               either).
3208
3209           w->set ([arguments])
3210               Basically the same as "ev_TYPE_set", with the same arguments.
3211               Must be called at least once. Unlike the C counterpart, an
3212               active watcher gets automatically stopped and restarted when
3213               reconfiguring it with this method.
3214
3215           w->start ()
3216               Starts the watcher. Note that there is no "loop" argument, as
3217               the constructor already stores the event loop.
3218
3219           w->stop ()
3220               Stops the watcher if it is active. Again, no "loop" argument.
3221
3222           w->again () ("ev::timer", "ev::periodic" only)
3223               For "ev::timer" and "ev::periodic", this invokes the
3224               corresponding "ev_TYPE_again" function.
3225
3226           w->sweep () ("ev::embed" only)
3227               Invokes "ev_embed_sweep".
3228
3229           w->update () ("ev::stat" only)
3230               Invokes "ev_stat_stat".
3231
3232       Example: Define a class with an IO and idle watcher, start one of them
3233       in the constructor.
3234
3235          class myclass
3236          {
3237            ev::io   io  ; void io_cb   (ev::io   &w, int revents);
3238            ev::idle idle; void idle_cb (ev::idle &w, int revents);
3239
3240            myclass (int fd)
3241            {
3242              io  .set <myclass, &myclass::io_cb  > (this);
3243              idle.set <myclass, &myclass::idle_cb> (this);
3244
3245              io.start (fd, ev::READ);
3246            }
3247          };
3248

OTHER LANGUAGE BINDINGS

3250       Libev does not offer other language bindings itself, but bindings for a
3251       number of languages exist in the form of third-party packages. If you
3252       know any interesting language binding in addition to the ones listed
3253       here, drop me a note.
3254
3255       Perl
3256           The EV module implements the full libev API and is actually used to
3257           test libev. EV is developed together with libev. Apart from the EV
3258           core module, there are additional modules that implement libev-
3259           compatible interfaces to "libadns" ("EV::ADNS", but "AnyEvent::DNS"
3260           is preferred nowadays), "Net::SNMP" ("Net::SNMP::EV") and the
3261           "libglib" event core ("Glib::EV" and "EV::Glib").
3262
3263           It can be found and installed via CPAN, its homepage is at
3264           <http://software.schmorp.de/pkg/EV>.
3265
3266       Python
3267           Python bindings can be found at <http://code.google.com/p/pyev/>.
3268           It seems to be quite complete and well-documented.
3269
3270       Ruby
3271           Tony Arcieri has written a ruby extension that offers access to a
3272           subset of the libev API and adds file handle abstractions,
3273           asynchronous DNS and more on top of it. It can be found via gem
3274           servers. Its homepage is at <http://rev.rubyforge.org/>.
3275
3276           Roger Pack reports that using the link order "-lws2_32
3277           -lmsvcrt-ruby-190" makes rev work even on mingw.
3278
3279       Haskell
3280           A haskell binding to libev is available at
3281           <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hlibev>.
3282
3283       D   Leandro Lucarella has written a D language binding (ev.d) for
3284           libev, to be found at <http://proj.llucax.com.ar/wiki/evd>.
3285
3286       Ocaml
3287           Erkki Seppala has written Ocaml bindings for libev, to be found at
3288           <http://modeemi.cs.tut.fi/~flux/software/ocaml-ev/>.
3289
3290       Lua Brian Maher has written a partial interface to libev for lua (only
3291           "ev_io" and "ev_timer"), to be found at
3292           <http://github.com/brimworks/lua-ev>.
3293

MACRO MAGIC

3295       Libev can be compiled with a variety of options, the most fundamental
3296       of which is "EV_MULTIPLICITY". This option determines whether (most)
3297       functions and callbacks have an initial "struct ev_loop *" argument.
3298
3299       To make it easier to write programs that cope with either variant, the
3300       following macros are defined:
3301
3302       "EV_A", "EV_A_"
3303           This provides the loop argument for functions, if one is required
3304           ("ev loop argument"). The "EV_A" form is used when this is the sole
3305           argument, "EV_A_" is used when other arguments are following.
3306           Example:
3307
3308              ev_unref (EV_A);
3309              ev_timer_add (EV_A_ watcher);
3310              ev_loop (EV_A_ 0);
3311
3312           It assumes the variable "loop" of type "struct ev_loop *" is in
3313           scope, which is often provided by the following macro.
3314
3315       "EV_P", "EV_P_"
3316           This provides the loop parameter for functions, if one is required
3317           ("ev loop parameter"). The "EV_P" form is used when this is the
3318           sole parameter, "EV_P_" is used when other parameters are
3319           following. Example:
3320
3321              // this is how ev_unref is being declared
3322              static void ev_unref (EV_P);
3323
3324              // this is how you can declare your typical callback
3325              static void cb (EV_P_ ev_timer *w, int revents)
3326
3327           It declares a parameter "loop" of type "struct ev_loop *", quite
3328           suitable for use with "EV_A".
3329
3330       "EV_DEFAULT", "EV_DEFAULT_"
3331           Similar to the other two macros, this gives you the value of the
3332           default loop, if multiple loops are supported ("ev loop default").
3333
3334       "EV_DEFAULT_UC", "EV_DEFAULT_UC_"
3335           Usage identical to "EV_DEFAULT" and "EV_DEFAULT_", but requires
3336           that the default loop has been initialised ("UC" == unchecked).
3337           Their behaviour is undefined when the default loop has not been
3338           initialised by a previous execution of "EV_DEFAULT", "EV_DEFAULT_"
3339           or "ev_default_init (...)".
3340
3341           It is often prudent to use "EV_DEFAULT" when initialising the first
3342           watcher in a function but use "EV_DEFAULT_UC" afterwards.
3343
3344       Example: Declare and initialise a check watcher, utilising the above
3345       macros so it will work regardless of whether multiple loops are
3346       supported or not.
3347
3348          static void
3349          check_cb (EV_P_ ev_timer *w, int revents)
3350          {
3351            ev_check_stop (EV_A_ w);
3352          }
3353
3354          ev_check check;
3355          ev_check_init (&check, check_cb);
3356          ev_check_start (EV_DEFAULT_ &check);
3357          ev_loop (EV_DEFAULT_ 0);
3358

EMBEDDING

3360       Libev can (and often is) directly embedded into host applications.
3361       Examples of applications that embed it include the Deliantra Game
3362       Server, the EV perl module, the GNU Virtual Private Ethernet (gvpe) and
3363       rxvt-unicode.
3364
3365       The goal is to enable you to just copy the necessary files into your
3366       source directory without having to change even a single line in them,
3367       so you can easily upgrade by simply copying (or having a checked-out
3368       copy of libev somewhere in your source tree).
3369
3370   FILESETS
3371       Depending on what features you need you need to include one or more
3372       sets of files in your application.
3373
3374       CORE EVENT LOOP
3375
3376       To include only the libev core (all the "ev_*" functions), with manual
3377       configuration (no autoconf):
3378
3379          #define EV_STANDALONE 1
3380          #include "ev.c"
3381
3382       This will automatically include ev.h, too, and should be done in a
3383       single C source file only to provide the function implementations. To
3384       use it, do the same for ev.h in all files wishing to use this API (best
3385       done by writing a wrapper around ev.h that you can include instead and
3386       where you can put other configuration options):
3387
3388          #define EV_STANDALONE 1
3389          #include "ev.h"
3390
3391       Both header files and implementation files can be compiled with a C++
3392       compiler (at least, that's a stated goal, and breakage will be treated
3393       as a bug).
3394
3395       You need the following files in your source tree, or in a directory in
3396       your include path (e.g. in libev/ when using -Ilibev):
3397
3398          ev.h
3399          ev.c
3400          ev_vars.h
3401          ev_wrap.h
3402
3403          ev_win32.c      required on win32 platforms only
3404
3405          ev_select.c     only when select backend is enabled (which is enabled by default)
3406          ev_poll.c       only when poll backend is enabled (disabled by default)
3407          ev_epoll.c      only when the epoll backend is enabled (disabled by default)
3408          ev_kqueue.c     only when the kqueue backend is enabled (disabled by default)
3409          ev_port.c       only when the solaris port backend is enabled (disabled by default)
3410
3411       ev.c includes the backend files directly when enabled, so you only need
3412       to compile this single file.
3413
3414       LIBEVENT COMPATIBILITY API
3415
3416       To include the libevent compatibility API, also include:
3417
3418          #include "event.c"
3419
3420       in the file including ev.c, and:
3421
3422          #include "event.h"
3423
3424       in the files that want to use the libevent API. This also includes
3425       ev.h.
3426
3427       You need the following additional files for this:
3428
3429          event.h
3430          event.c
3431
3432       AUTOCONF SUPPORT
3433
3434       Instead of using "EV_STANDALONE=1" and providing your configuration in
3435       whatever way you want, you can also "m4_include([libev.m4])" in your
3436       configure.ac and leave "EV_STANDALONE" undefined. ev.c will then
3437       include config.h and configure itself accordingly.
3438
3439       For this of course you need the m4 file:
3440
3441          libev.m4
3442
3443   PREPROCESSOR SYMBOLS/MACROS
3444       Libev can be configured via a variety of preprocessor symbols you have
3445       to define before including any of its files. The default in the absence
3446       of autoconf is documented for every option.
3447
3448       EV_STANDALONE
3449           Must always be 1 if you do not use autoconf configuration, which
3450           keeps libev from including config.h, and it also defines dummy
3451           implementations for some libevent functions (such as logging, which
3452           is not supported). It will also not define any of the structs
3453           usually found in event.h that are not directly supported by the
3454           libev core alone.
3455
3456           In standalone mode, libev will still try to automatically deduce
3457           the configuration, but has to be more conservative.
3458
3459       EV_USE_MONOTONIC
3460           If defined to be 1, libev will try to detect the availability of
3461           the monotonic clock option at both compile time and runtime.
3462           Otherwise no use of the monotonic clock option will be attempted.
3463           If you enable this, you usually have to link against librt or
3464           something similar. Enabling it when the functionality isn't
3465           available is safe, though, although you have to make sure you link
3466           against any libraries where the "clock_gettime" function is hiding
3467           in (often -lrt). See also "EV_USE_CLOCK_SYSCALL".
3468
3469       EV_USE_REALTIME
3470           If defined to be 1, libev will try to detect the availability of
3471           the real-time clock option at compile time (and assume its
3472           availability at runtime if successful). Otherwise no use of the
3473           real-time clock option will be attempted. This effectively replaces
3474           "gettimeofday" by "clock_get (CLOCK_REALTIME, ...)" and will not
3475           normally affect correctness. See the note about libraries in the
3476           description of "EV_USE_MONOTONIC", though. Defaults to the opposite
3477           value of "EV_USE_CLOCK_SYSCALL".
3478
3479       EV_USE_CLOCK_SYSCALL
3480           If defined to be 1, libev will try to use a direct syscall instead
3481           of calling the system-provided "clock_gettime" function. This
3482           option exists because on GNU/Linux, "clock_gettime" is in "librt",
3483           but "librt" unconditionally pulls in "libpthread", slowing down
3484           single-threaded programs needlessly. Using a direct syscall is
3485           slightly slower (in theory), because no optimised vdso
3486           implementation can be used, but avoids the pthread dependency.
3487           Defaults to 1 on GNU/Linux with glibc 2.x or higher, as it
3488           simplifies linking (no need for "-lrt").
3489
3490       EV_USE_NANOSLEEP
3491           If defined to be 1, libev will assume that "nanosleep ()" is
3492           available and will use it for delays. Otherwise it will use "select
3493           ()".
3494
3495       EV_USE_EVENTFD
3496           If defined to be 1, then libev will assume that "eventfd ()" is
3497           available and will probe for kernel support at runtime. This will
3498           improve "ev_signal" and "ev_async" performance and reduce resource
3499           consumption.  If undefined, it will be enabled if the headers
3500           indicate GNU/Linux + Glibc 2.7 or newer, otherwise disabled.
3501
3502       EV_USE_SELECT
3503           If undefined or defined to be 1, libev will compile in support for
3504           the "select"(2) backend. No attempt at auto-detection will be done:
3505           if no other method takes over, select will be it. Otherwise the
3506           select backend will not be compiled in.
3507
3508       EV_SELECT_USE_FD_SET
3509           If defined to 1, then the select backend will use the system
3510           "fd_set" structure. This is useful if libev doesn't compile due to
3511           a missing "NFDBITS" or "fd_mask" definition or it mis-guesses the
3512           bitset layout on exotic systems. This usually limits the range of
3513           file descriptors to some low limit such as 1024 or might have other
3514           limitations (winsocket only allows 64 sockets). The "FD_SETSIZE"
3515           macro, set before compilation, configures the maximum size of the
3516           "fd_set".
3517
3518       EV_SELECT_IS_WINSOCKET
3519           When defined to 1, the select backend will assume that
3520           select/socket/connect etc. don't understand file descriptors but
3521           wants osf handles on win32 (this is the case when the select to be
3522           used is the winsock select). This means that it will call
3523           "_get_osfhandle" on the fd to convert it to an OS handle.
3524           Otherwise, it is assumed that all these functions actually work on
3525           fds, even on win32. Should not be defined on non-win32 platforms.
3526
3527       EV_FD_TO_WIN32_HANDLE(fd)
3528           If "EV_SELECT_IS_WINSOCKET" is enabled, then libev needs a way to
3529           map file descriptors to socket handles. When not defining this
3530           symbol (the default), then libev will call "_get_osfhandle", which
3531           is usually correct. In some cases, programs use their own file
3532           descriptor management, in which case they can provide this function
3533           to map fds to socket handles.
3534
3535       EV_WIN32_HANDLE_TO_FD(handle)
3536           If "EV_SELECT_IS_WINSOCKET" then libev maps handles to file
3537           descriptors using the standard "_open_osfhandle" function. For
3538           programs implementing their own fd to handle mapping, overwriting
3539           this function makes it easier to do so. This can be done by
3540           defining this macro to an appropriate value.
3541
3542       EV_WIN32_CLOSE_FD(fd)
3543           If programs implement their own fd to handle mapping on win32, then
3544           this macro can be used to override the "close" function, useful to
3545           unregister file descriptors again. Note that the replacement
3546           function has to close the underlying OS handle.
3547
3548       EV_USE_POLL
3549           If defined to be 1, libev will compile in support for the "poll"(2)
3550           backend. Otherwise it will be enabled on non-win32 platforms. It
3551           takes precedence over select.
3552
3553       EV_USE_EPOLL
3554           If defined to be 1, libev will compile in support for the Linux
3555           "epoll"(7) backend. Its availability will be detected at runtime,
3556           otherwise another method will be used as fallback. This is the
3557           preferred backend for GNU/Linux systems. If undefined, it will be
3558           enabled if the headers indicate GNU/Linux + Glibc 2.4 or newer,
3559           otherwise disabled.
3560
3561       EV_USE_KQUEUE
3562           If defined to be 1, libev will compile in support for the BSD style
3563           "kqueue"(2) backend. Its actual availability will be detected at
3564           runtime, otherwise another method will be used as fallback. This is
3565           the preferred backend for BSD and BSD-like systems, although on
3566           most BSDs kqueue only supports some types of fds correctly (the
3567           only platform we found that supports ptys for example was NetBSD),
3568           so kqueue might be compiled in, but not be used unless explicitly
3569           requested. The best way to use it is to find out whether kqueue
3570           supports your type of fd properly and use an embedded kqueue loop.
3571
3572       EV_USE_PORT
3573           If defined to be 1, libev will compile in support for the Solaris
3574           10 port style backend. Its availability will be detected at
3575           runtime, otherwise another method will be used as fallback. This is
3576           the preferred backend for Solaris 10 systems.
3577
3578       EV_USE_DEVPOLL
3579           Reserved for future expansion, works like the USE symbols above.
3580
3581       EV_USE_INOTIFY
3582           If defined to be 1, libev will compile in support for the Linux
3583           inotify interface to speed up "ev_stat" watchers. Its actual
3584           availability will be detected at runtime. If undefined, it will be
3585           enabled if the headers indicate GNU/Linux + Glibc 2.4 or newer,
3586           otherwise disabled.
3587
3588       EV_ATOMIC_T
3589           Libev requires an integer type (suitable for storing 0 or 1) whose
3590           access is atomic with respect to other threads or signal contexts.
3591           No such type is easily found in the C language, so you can provide
3592           your own type that you know is safe for your purposes. It is used
3593           both for signal handler "locking" as well as for signal and thread
3594           safety in "ev_async" watchers.
3595
3596           In the absence of this define, libev will use "sig_atomic_t
3597           volatile" (from signal.h), which is usually good enough on most
3598           platforms.
3599
3600       EV_H
3601           The name of the ev.h header file used to include it. The default if
3602           undefined is "ev.h" in event.h, ev.c and ev++.h. This can be used
3603           to virtually rename the ev.h header file in case of conflicts.
3604
3605       EV_CONFIG_H
3606           If "EV_STANDALONE" isn't 1, this variable can be used to override
3607           ev.c's idea of where to find the config.h file, similarly to
3608           "EV_H", above.
3609
3610       EV_EVENT_H
3611           Similarly to "EV_H", this macro can be used to override event.c's
3612           idea of how the event.h header can be found, the default is
3613           "event.h".
3614
3615       EV_PROTOTYPES
3616           If defined to be 0, then ev.h will not define any function
3617           prototypes, but still define all the structs and other symbols.
3618           This is occasionally useful if you want to provide your own wrapper
3619           functions around libev functions.
3620
3621       EV_MULTIPLICITY
3622           If undefined or defined to 1, then all event-loop-specific
3623           functions will have the "struct ev_loop *" as first argument, and
3624           you can create additional independent event loops. Otherwise there
3625           will be no support for multiple event loops and there is no first
3626           event loop pointer argument. Instead, all functions act on the
3627           single default loop.
3628
3629       EV_MINPRI
3630       EV_MAXPRI
3631           The range of allowed priorities. "EV_MINPRI" must be smaller or
3632           equal to "EV_MAXPRI", but otherwise there are no non-obvious
3633           limitations. You can provide for more priorities by overriding
3634           those symbols (usually defined to be "-2" and 2, respectively).
3635
3636           When doing priority-based operations, libev usually has to linearly
3637           search all the priorities, so having many of them (hundreds) uses a
3638           lot of space and time, so using the defaults of five priorities (-2
3639           .. +2) is usually fine.
3640
3641           If your embedding application does not need any priorities,
3642           defining these both to 0 will save some memory and CPU.
3643
3644       EV_PERIODIC_ENABLE
3645           If undefined or defined to be 1, then periodic timers are
3646           supported. If defined to be 0, then they are not. Disabling them
3647           saves a few kB of code.
3648
3649       EV_IDLE_ENABLE
3650           If undefined or defined to be 1, then idle watchers are supported.
3651           If defined to be 0, then they are not. Disabling them saves a few
3652           kB of code.
3653
3654       EV_EMBED_ENABLE
3655           If undefined or defined to be 1, then embed watchers are supported.
3656           If defined to be 0, then they are not. Embed watchers rely on most
3657           other watcher types, which therefore must not be disabled.
3658
3659       EV_STAT_ENABLE
3660           If undefined or defined to be 1, then stat watchers are supported.
3661           If defined to be 0, then they are not.
3662
3663       EV_FORK_ENABLE
3664           If undefined or defined to be 1, then fork watchers are supported.
3665           If defined to be 0, then they are not.
3666
3667       EV_ASYNC_ENABLE
3668           If undefined or defined to be 1, then async watchers are supported.
3669           If defined to be 0, then they are not.
3670
3671       EV_MINIMAL
3672           If you need to shave off some kilobytes of code at the expense of
3673           some speed (but with the full API), define this symbol to 1.
3674           Currently this is used to override some inlining decisions, saves
3675           roughly 30% code size on amd64. It also selects a much smaller
3676           2-heap for timer management over the default 4-heap.
3677
3678           You can save even more by disabling watcher types you do not need
3679           and setting "EV_MAXPRI" == "EV_MINPRI". Also, disabling "assert"
3680           ("-DNDEBUG") will usually reduce code size a lot.
3681
3682           Defining "EV_MINIMAL" to 2 will additionally reduce the core API to
3683           provide a bare-bones event library. See "ev.h" for details on what
3684           parts of the API are still available, and do not complain if this
3685           subset changes over time.
3686
3687       EV_NSIG
3688           The highest supported signal number, +1 (or, the number of
3689           signals): Normally, libev tries to deduce the maximum number of
3690           signals automatically, but sometimes this fails, in which case it
3691           can be specified. Also, using a lower number than detected (32
3692           should be good for about any system in existance) can save some
3693           memory, as libev statically allocates some 12-24 bytes per signal
3694           number.
3695
3696       EV_PID_HASHSIZE
3697           "ev_child" watchers use a small hash table to distribute workload
3698           by pid. The default size is 16 (or 1 with "EV_MINIMAL"), usually
3699           more than enough. If you need to manage thousands of children you
3700           might want to increase this value (must be a power of two).
3701
3702       EV_INOTIFY_HASHSIZE
3703           "ev_stat" watchers use a small hash table to distribute workload by
3704           inotify watch id. The default size is 16 (or 1 with "EV_MINIMAL"),
3705           usually more than enough. If you need to manage thousands of
3706           "ev_stat" watchers you might want to increase this value (must be a
3707           power of two).
3708
3709       EV_USE_4HEAP
3710           Heaps are not very cache-efficient. To improve the cache-efficiency
3711           of the timer and periodics heaps, libev uses a 4-heap when this
3712           symbol is defined to 1. The 4-heap uses more complicated (longer)
3713           code but has noticeably faster performance with many (thousands) of
3714           watchers.
3715
3716           The default is 1 unless "EV_MINIMAL" is set in which case it is 0
3717           (disabled).
3718
3719       EV_HEAP_CACHE_AT
3720           Heaps are not very cache-efficient. To improve the cache-efficiency
3721           of the timer and periodics heaps, libev can cache the timestamp
3722           (at) within the heap structure (selected by defining
3723           "EV_HEAP_CACHE_AT" to 1), which uses 8-12 bytes more per watcher
3724           and a few hundred bytes more code, but avoids random read accesses
3725           on heap changes. This improves performance noticeably with many
3726           (hundreds) of watchers.
3727
3728           The default is 1 unless "EV_MINIMAL" is set in which case it is 0
3729           (disabled).
3730
3731       EV_VERIFY
3732           Controls how much internal verification (see "ev_loop_verify ()")
3733           will be done: If set to 0, no internal verification code will be
3734           compiled in. If set to 1, then verification code will be compiled
3735           in, but not called. If set to 2, then the internal verification
3736           code will be called once per loop, which can slow down libev. If
3737           set to 3, then the verification code will be called very
3738           frequently, which will slow down libev considerably.
3739
3740           The default is 1, unless "EV_MINIMAL" is set, in which case it will
3741           be 0.
3742
3743       EV_COMMON
3744           By default, all watchers have a "void *data" member. By redefining
3745           this macro to a something else you can include more and other types
3746           of members. You have to define it each time you include one of the
3747           files, though, and it must be identical each time.
3748
3749           For example, the perl EV module uses something like this:
3750
3751              #define EV_COMMON                       \
3752                SV *self; /* contains this struct */  \
3753                SV *cb_sv, *fh /* note no trailing ";" */
3754
3755       EV_CB_DECLARE (type)
3756       EV_CB_INVOKE (watcher, revents)
3757       ev_set_cb (ev, cb)
3758           Can be used to change the callback member declaration in each
3759           watcher, and the way callbacks are invoked and set. Must expand to
3760           a struct member definition and a statement, respectively. See the
3761           ev.h header file for their default definitions. One possible use
3762           for overriding these is to avoid the "struct ev_loop *" as first
3763           argument in all cases, or to use method calls instead of plain
3764           function calls in C++.
3765
3766   EXPORTED API SYMBOLS
3767       If you need to re-export the API (e.g. via a DLL) and you need a list
3768       of exported symbols, you can use the provided Symbol.* files which list
3769       all public symbols, one per line:
3770
3771          Symbols.ev      for libev proper
3772          Symbols.event   for the libevent emulation
3773
3774       This can also be used to rename all public symbols to avoid clashes
3775       with multiple versions of libev linked together (which is obviously bad
3776       in itself, but sometimes it is inconvenient to avoid this).
3777
3778       A sed command like this will create wrapper "#define"'s that you need
3779       to include before including ev.h:
3780
3781          <Symbols.ev sed -e "s/.*/#define & myprefix_&/" >wrap.h
3782
3783       This would create a file wrap.h which essentially looks like this:
3784
3785          #define ev_backend     myprefix_ev_backend
3786          #define ev_check_start myprefix_ev_check_start
3787          #define ev_check_stop  myprefix_ev_check_stop
3788          ...
3789
3790   EXAMPLES
3791       For a real-world example of a program the includes libev verbatim, you
3792       can have a look at the EV perl module
3793       (<http://software.schmorp.de/pkg/EV.html>). It has the libev files in
3794       the libev/ subdirectory and includes them in the EV/EVAPI.h (public
3795       interface) and EV.xs (implementation) files. Only the EV.xs file will
3796       be compiled. It is pretty complex because it provides its own header
3797       file.
3798
3799       The usage in rxvt-unicode is simpler. It has a ev_cpp.h header file
3800       that everybody includes and which overrides some configure choices:
3801
3802          #define EV_MINIMAL 1
3803          #define EV_USE_POLL 0
3804          #define EV_MULTIPLICITY 0
3805          #define EV_PERIODIC_ENABLE 0
3806          #define EV_STAT_ENABLE 0
3807          #define EV_FORK_ENABLE 0
3808          #define EV_CONFIG_H <config.h>
3809          #define EV_MINPRI 0
3810          #define EV_MAXPRI 0
3811
3812          #include "ev++.h"
3813
3814       And a ev_cpp.C implementation file that contains libev proper and is
3815       compiled:
3816
3817          #include "ev_cpp.h"
3818          #include "ev.c"
3819

INTERACTION WITH OTHER PROGRAMS OR LIBRARIES

3821   THREADS AND COROUTINES
3822       THREADS
3823
3824       All libev functions are reentrant and thread-safe unless explicitly
3825       documented otherwise, but libev implements no locking itself. This
3826       means that you can use as many loops as you want in parallel, as long
3827       as there are no concurrent calls into any libev function with the same
3828       loop parameter ("ev_default_*" calls have an implicit default loop
3829       parameter, of course): libev guarantees that different event loops
3830       share no data structures that need any locking.
3831
3832       Or to put it differently: calls with different loop parameters can be
3833       done concurrently from multiple threads, calls with the same loop
3834       parameter must be done serially (but can be done from different
3835       threads, as long as only one thread ever is inside a call at any point
3836       in time, e.g. by using a mutex per loop).
3837
3838       Specifically to support threads (and signal handlers), libev implements
3839       so-called "ev_async" watchers, which allow some limited form of
3840       concurrency on the same event loop, namely waking it up "from the
3841       outside".
3842
3843       If you want to know which design (one loop, locking, or multiple loops
3844       without or something else still) is best for your problem, then I
3845       cannot help you, but here is some generic advice:
3846
3847       ·   most applications have a main thread: use the default libev loop in
3848           that thread, or create a separate thread running only the default
3849           loop.
3850
3851           This helps integrating other libraries or software modules that use
3852           libev themselves and don't care/know about threading.
3853
3854       ·   one loop per thread is usually a good model.
3855
3856           Doing this is almost never wrong, sometimes a better-performance
3857           model exists, but it is always a good start.
3858
3859       ·   other models exist, such as the leader/follower pattern, where one
3860           loop is handed through multiple threads in a kind of round-robin
3861           fashion.
3862
3863           Choosing a model is hard - look around, learn, know that usually
3864           you can do better than you currently do :-)
3865
3866       ·   often you need to talk to some other thread which blocks in the
3867           event loop.
3868
3869           "ev_async" watchers can be used to wake them up from other threads
3870           safely (or from signal contexts...).
3871
3872           An example use would be to communicate signals or other events that
3873           only work in the default loop by registering the signal watcher
3874           with the default loop and triggering an "ev_async" watcher from the
3875           default loop watcher callback into the event loop interested in the
3876           signal.
3877
3878       THREAD LOCKING EXAMPLE
3879
3880       Here is a fictitious example of how to run an event loop in a different
3881       thread than where callbacks are being invoked and watchers are
3882       created/added/removed.
3883
3884       For a real-world example, see the "EV::Loop::Async" perl module, which
3885       uses exactly this technique (which is suited for many high-level
3886       languages).
3887
3888       The example uses a pthread mutex to protect the loop data, a condition
3889       variable to wait for callback invocations, an async watcher to notify
3890       the event loop thread and an unspecified mechanism to wake up the main
3891       thread.
3892
3893       First, you need to associate some data with the event loop:
3894
3895          typedef struct {
3896            mutex_t lock; /* global loop lock */
3897            ev_async async_w;
3898            thread_t tid;
3899            cond_t invoke_cv;
3900          } userdata;
3901
3902          void prepare_loop (EV_P)
3903          {
3904             // for simplicity, we use a static userdata struct.
3905             static userdata u;
3906
3907             ev_async_init (&u->async_w, async_cb);
3908             ev_async_start (EV_A_ &u->async_w);
3909
3910             pthread_mutex_init (&u->lock, 0);
3911             pthread_cond_init (&u->invoke_cv, 0);
3912
3913             // now associate this with the loop
3914             ev_set_userdata (EV_A_ u);
3915             ev_set_invoke_pending_cb (EV_A_ l_invoke);
3916             ev_set_loop_release_cb (EV_A_ l_release, l_acquire);
3917
3918             // then create the thread running ev_loop
3919             pthread_create (&u->tid, 0, l_run, EV_A);
3920          }
3921
3922       The callback for the "ev_async" watcher does nothing: the watcher is
3923       used solely to wake up the event loop so it takes notice of any new
3924       watchers that might have been added:
3925
3926          static void
3927          async_cb (EV_P_ ev_async *w, int revents)
3928          {
3929             // just used for the side effects
3930          }
3931
3932       The "l_release" and "l_acquire" callbacks simply unlock/lock the mutex
3933       protecting the loop data, respectively.
3934
3935          static void
3936          l_release (EV_P)
3937          {
3938            userdata *u = ev_userdata (EV_A);
3939            pthread_mutex_unlock (&u->lock);
3940          }
3941
3942          static void
3943          l_acquire (EV_P)
3944          {
3945            userdata *u = ev_userdata (EV_A);
3946            pthread_mutex_lock (&u->lock);
3947          }
3948
3949       The event loop thread first acquires the mutex, and then jumps straight
3950       into "ev_loop":
3951
3952          void *
3953          l_run (void *thr_arg)
3954          {
3955            struct ev_loop *loop = (struct ev_loop *)thr_arg;
3956
3957            l_acquire (EV_A);
3958            pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
3959            ev_loop (EV_A_ 0);
3960            l_release (EV_A);
3961
3962            return 0;
3963          }
3964
3965       Instead of invoking all pending watchers, the "l_invoke" callback will
3966       signal the main thread via some unspecified mechanism (signals? pipe
3967       writes? "Async::Interrupt"?) and then waits until all pending watchers
3968       have been called (in a while loop because a) spurious wakeups are
3969       possible and b) skipping inter-thread-communication when there are no
3970       pending watchers is very beneficial):
3971
3972          static void
3973          l_invoke (EV_P)
3974          {
3975            userdata *u = ev_userdata (EV_A);
3976
3977            while (ev_pending_count (EV_A))
3978              {
3979                wake_up_other_thread_in_some_magic_or_not_so_magic_way ();
3980                pthread_cond_wait (&u->invoke_cv, &u->lock);
3981              }
3982          }
3983
3984       Now, whenever the main thread gets told to invoke pending watchers, it
3985       will grab the lock, call "ev_invoke_pending" and then signal the loop
3986       thread to continue:
3987
3988          static void
3989          real_invoke_pending (EV_P)
3990          {
3991            userdata *u = ev_userdata (EV_A);
3992
3993            pthread_mutex_lock (&u->lock);
3994            ev_invoke_pending (EV_A);
3995            pthread_cond_signal (&u->invoke_cv);
3996            pthread_mutex_unlock (&u->lock);
3997          }
3998
3999       Whenever you want to start/stop a watcher or do other modifications to
4000       an event loop, you will now have to lock:
4001
4002          ev_timer timeout_watcher;
4003          userdata *u = ev_userdata (EV_A);
4004
4005          ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
4006
4007          pthread_mutex_lock (&u->lock);
4008          ev_timer_start (EV_A_ &timeout_watcher);
4009          ev_async_send (EV_A_ &u->async_w);
4010          pthread_mutex_unlock (&u->lock);
4011
4012       Note that sending the "ev_async" watcher is required because otherwise
4013       an event loop currently blocking in the kernel will have no knowledge
4014       about the newly added timer. By waking up the loop it will pick up any
4015       new watchers in the next event loop iteration.
4016
4017       COROUTINES
4018
4019       Libev is very accommodating to coroutines ("cooperative threads"):
4020       libev fully supports nesting calls to its functions from different
4021       coroutines (e.g. you can call "ev_loop" on the same loop from two
4022       different coroutines, and switch freely between both coroutines running
4023       the loop, as long as you don't confuse yourself). The only exception is
4024       that you must not do this from "ev_periodic" reschedule callbacks.
4025
4026       Care has been taken to ensure that libev does not keep local state
4027       inside "ev_loop", and other calls do not usually allow for coroutine
4028       switches as they do not call any callbacks.
4029
4030   COMPILER WARNINGS
4031       Depending on your compiler and compiler settings, you might get no or a
4032       lot of warnings when compiling libev code. Some people are apparently
4033       scared by this.
4034
4035       However, these are unavoidable for many reasons. For one, each compiler
4036       has different warnings, and each user has different tastes regarding
4037       warning options. "Warn-free" code therefore cannot be a goal except
4038       when targeting a specific compiler and compiler-version.
4039
4040       Another reason is that some compiler warnings require elaborate
4041       workarounds, or other changes to the code that make it less clear and
4042       less maintainable.
4043
4044       And of course, some compiler warnings are just plain stupid, or simply
4045       wrong (because they don't actually warn about the condition their
4046       message seems to warn about). For example, certain older gcc versions
4047       had some warnings that resulted an extreme number of false positives.
4048       These have been fixed, but some people still insist on making code
4049       warn-free with such buggy versions.
4050
4051       While libev is written to generate as few warnings as possible, "warn-
4052       free" code is not a goal, and it is recommended not to build libev with
4053       any compiler warnings enabled unless you are prepared to cope with them
4054       (e.g. by ignoring them). Remember that warnings are just that:
4055       warnings, not errors, or proof of bugs.
4056
4057   VALGRIND
4058       Valgrind has a special section here because it is a popular tool that
4059       is highly useful. Unfortunately, valgrind reports are very hard to
4060       interpret.
4061
4062       If you think you found a bug (memory leak, uninitialised data access
4063       etc.)  in libev, then check twice: If valgrind reports something like:
4064
4065          ==2274==    definitely lost: 0 bytes in 0 blocks.
4066          ==2274==      possibly lost: 0 bytes in 0 blocks.
4067          ==2274==    still reachable: 256 bytes in 1 blocks.
4068
4069       Then there is no memory leak, just as memory accounted to global
4070       variables is not a memleak - the memory is still being referenced, and
4071       didn't leak.
4072
4073       Similarly, under some circumstances, valgrind might report kernel bugs
4074       as if it were a bug in libev (e.g. in realloc or in the poll backend,
4075       although an acceptable workaround has been found here), or it might be
4076       confused.
4077
4078       Keep in mind that valgrind is a very good tool, but only a tool. Don't
4079       make it into some kind of religion.
4080
4081       If you are unsure about something, feel free to contact the mailing
4082       list with the full valgrind report and an explanation on why you think
4083       this is a bug in libev (best check the archives, too :). However, don't
4084       be annoyed when you get a brisk "this is no bug" answer and take the
4085       chance of learning how to interpret valgrind properly.
4086
4087       If you need, for some reason, empty reports from valgrind for your
4088       project I suggest using suppression lists.
4089

PORTABILITY NOTES

4091   WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS
4092       Win32 doesn't support any of the standards (e.g. POSIX) that libev
4093       requires, and its I/O model is fundamentally incompatible with the
4094       POSIX model. Libev still offers limited functionality on this platform
4095       in the form of the "EVBACKEND_SELECT" backend, and only supports socket
4096       descriptors. This only applies when using Win32 natively, not when
4097       using e.g. cygwin.
4098
4099       Lifting these limitations would basically require the full re-
4100       implementation of the I/O system. If you are into these kinds of
4101       things, then note that glib does exactly that for you in a very
4102       portable way (note also that glib is the slowest event library known to
4103       man).
4104
4105       There is no supported compilation method available on windows except
4106       embedding it into other applications.
4107
4108       Sensible signal handling is officially unsupported by Microsoft - libev
4109       tries its best, but under most conditions, signals will simply not
4110       work.
4111
4112       Not a libev limitation but worth mentioning: windows apparently doesn't
4113       accept large writes: instead of resulting in a partial write, windows
4114       will either accept everything or return "ENOBUFS" if the buffer is too
4115       large, so make sure you only write small amounts into your sockets
4116       (less than a megabyte seems safe, but this apparently depends on the
4117       amount of memory available).
4118
4119       Due to the many, low, and arbitrary limits on the win32 platform and
4120       the abysmal performance of winsockets, using a large number of sockets
4121       is not recommended (and not reasonable). If your program needs to use
4122       more than a hundred or so sockets, then likely it needs to use a
4123       totally different implementation for windows, as libev offers the POSIX
4124       readiness notification model, which cannot be implemented efficiently
4125       on windows (due to Microsoft monopoly games).
4126
4127       A typical way to use libev under windows is to embed it (see the
4128       embedding section for details) and use the following evwrap.h header
4129       file instead of ev.h:
4130
4131          #define EV_STANDALONE              /* keeps ev from requiring config.h */
4132          #define EV_SELECT_IS_WINSOCKET 1   /* configure libev for windows select */
4133
4134          #include "ev.h"
4135
4136       And compile the following evwrap.c file into your project (make sure
4137       you do not compile the ev.c or any other embedded source files!):
4138
4139          #include "evwrap.h"
4140          #include "ev.c"
4141
4142       The winsocket select function
4143           The winsocket "select" function doesn't follow POSIX in that it
4144           requires socket handles and not socket file descriptors (it is also
4145           extremely buggy). This makes select very inefficient, and also
4146           requires a mapping from file descriptors to socket handles (the
4147           Microsoft C runtime provides the function "_open_osfhandle" for
4148           this). See the discussion of the "EV_SELECT_USE_FD_SET",
4149           "EV_SELECT_IS_WINSOCKET" and "EV_FD_TO_WIN32_HANDLE" preprocessor
4150           symbols for more info.
4151
4152           The configuration for a "naked" win32 using the Microsoft runtime
4153           libraries and raw winsocket select is:
4154
4155              #define EV_USE_SELECT 1
4156              #define EV_SELECT_IS_WINSOCKET 1   /* forces EV_SELECT_USE_FD_SET, too */
4157
4158           Note that winsockets handling of fd sets is O(n), so you can easily
4159           get a complexity in the O(nAX) range when using win32.
4160
4161       Limited number of file descriptors
4162           Windows has numerous arbitrary (and low) limits on things.
4163
4164           Early versions of winsocket's select only supported waiting for a
4165           maximum of 64 handles (probably owning to the fact that all windows
4166           kernels can only wait for 64 things at the same time internally;
4167           Microsoft recommends spawning a chain of threads and wait for 63
4168           handles and the previous thread in each. Sounds great!).
4169
4170           Newer versions support more handles, but you need to define
4171           "FD_SETSIZE" to some high number (e.g. 2048) before compiling the
4172           winsocket select call (which might be in libev or elsewhere, for
4173           example, perl and many other interpreters do their own select
4174           emulation on windows).
4175
4176           Another limit is the number of file descriptors in the Microsoft
4177           runtime libraries, which by default is 64 (there must be a hidden
4178           64 fetish or something like this inside Microsoft). You can
4179           increase this by calling "_setmaxstdio", which can increase this
4180           limit to 2048 (another arbitrary limit), but is broken in many
4181           versions of the Microsoft runtime libraries. This might get you to
4182           about 512 or 2048 sockets (depending on windows version and/or the
4183           phase of the moon). To get more, you need to wrap all I/O functions
4184           and provide your own fd management, but the cost of calling select
4185           (O(nAX)) will likely make this unworkable.
4186
4187   PORTABILITY REQUIREMENTS
4188       In addition to a working ISO-C implementation and of course the
4189       backend-specific APIs, libev relies on a few additional extensions:
4190
4191       "void (*)(ev_watcher_type *, int revents)" must have compatible calling
4192       conventions regardless of "ev_watcher_type *".
4193           Libev assumes not only that all watcher pointers have the same
4194           internal structure (guaranteed by POSIX but not by ISO C for
4195           example), but it also assumes that the same (machine) code can be
4196           used to call any watcher callback: The watcher callbacks have
4197           different type signatures, but libev calls them using an
4198           "ev_watcher *" internally.
4199
4200       "sig_atomic_t volatile" must be thread-atomic as well
4201           The type "sig_atomic_t volatile" (or whatever is defined as
4202           "EV_ATOMIC_T") must be atomic with respect to accesses from
4203           different threads. This is not part of the specification for
4204           "sig_atomic_t", but is believed to be sufficiently portable.
4205
4206       "sigprocmask" must work in a threaded environment
4207           Libev uses "sigprocmask" to temporarily block signals. This is not
4208           allowed in a threaded program ("pthread_sigmask" has to be used).
4209           Typical pthread implementations will either allow "sigprocmask" in
4210           the "main thread" or will block signals process-wide, both
4211           behaviours would be compatible with libev. Interaction between
4212           "sigprocmask" and "pthread_sigmask" could complicate things,
4213           however.
4214
4215           The most portable way to handle signals is to block signals in all
4216           threads except the initial one, and run the default loop in the
4217           initial thread as well.
4218
4219       "long" must be large enough for common memory allocation sizes
4220           To improve portability and simplify its API, libev uses "long"
4221           internally instead of "size_t" when allocating its data structures.
4222           On non-POSIX systems (Microsoft...) this might be unexpectedly low,
4223           but is still at least 31 bits everywhere, which is enough for
4224           hundreds of millions of watchers.
4225
4226       "double" must hold a time value in seconds with enough accuracy
4227           The type "double" is used to represent timestamps. It is required
4228           to have at least 51 bits of mantissa (and 9 bits of exponent),
4229           which is good enough for at least into the year 4000. This
4230           requirement is fulfilled by implementations implementing IEEE 754,
4231           which is basically all existing ones. With IEEE 754 doubles, you
4232           get microsecond accuracy until at least 2200.
4233
4234       If you know of other additional requirements drop me a note.
4235

ALGORITHMIC COMPLEXITIES

4237       In this section the complexities of (many of) the algorithms used
4238       inside libev will be documented. For complexity discussions about
4239       backends see the documentation for "ev_default_init".
4240
4241       All of the following are about amortised time: If an array needs to be
4242       extended, libev needs to realloc and move the whole array, but this
4243       happens asymptotically rarer with higher number of elements, so O(1)
4244       might mean that libev does a lengthy realloc operation in rare cases,
4245       but on average it is much faster and asymptotically approaches constant
4246       time.
4247
4248       Starting and stopping timer/periodic watchers: O(log
4249       skipped_other_timers)
4250           This means that, when you have a watcher that triggers in one hour
4251           and there are 100 watchers that would trigger before that, then
4252           inserting will have to skip roughly seven ("ld 100") of these
4253           watchers.
4254
4255       Changing timer/periodic watchers (by autorepeat or calling again):
4256       O(log skipped_other_timers)
4257           That means that changing a timer costs less than removing/adding
4258           them, as only the relative motion in the event queue has to be paid
4259           for.
4260
4261       Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1)
4262           These just add the watcher into an array or at the head of a list.
4263
4264       Stopping check/prepare/idle/fork/async watchers: O(1)
4265       Stopping an io/signal/child watcher:
4266       O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE))
4267           These watchers are stored in lists, so they need to be walked to
4268           find the correct watcher to remove. The lists are usually short
4269           (you don't usually have many watchers waiting for the same fd or
4270           signal: one is typical, two is rare).
4271
4272       Finding the next timer in each loop iteration: O(1)
4273           By virtue of using a binary or 4-heap, the next timer is always
4274           found at a fixed position in the storage array.
4275
4276       Each change on a file descriptor per loop iteration:
4277       O(number_of_watchers_for_this_fd)
4278           A change means an I/O watcher gets started or stopped, which
4279           requires libev to recalculate its status (and possibly tell the
4280           kernel, depending on backend and whether "ev_io_set" was used).
4281
4282       Activating one watcher (putting it into the pending state): O(1)
4283       Priority handling: O(number_of_priorities)
4284           Priorities are implemented by allocating some space for each
4285           priority. When doing priority-based operations, libev usually has
4286           to linearly search all the priorities, but starting/stopping and
4287           activating watchers becomes O(1) with respect to priority handling.
4288
4289       Sending an ev_async: O(1)
4290       Processing ev_async_send: O(number_of_async_watchers)
4291       Processing signals: O(max_signal_number)
4292           Sending involves a system call iff there were no other
4293           "ev_async_send" calls in the current loop iteration. Checking for
4294           async and signal events involves iterating over all running async
4295           watchers or all signal numbers.
4296

GLOSSARY

4298       active
4299           A watcher is active as long as it has been started (has been
4300           attached to an event loop) but not yet stopped (disassociated from
4301           the event loop).
4302
4303       application
4304           In this document, an application is whatever is using libev.
4305
4306       callback
4307           The address of a function that is called when some event has been
4308           detected. Callbacks are being passed the event loop, the watcher
4309           that received the event, and the actual event bitset.
4310
4311       callback invocation
4312           The act of calling the callback associated with a watcher.
4313
4314       event
4315           A change of state of some external event, such as data now being
4316           available for reading on a file descriptor, time having passed or
4317           simply not having any other events happening anymore.
4318
4319           In libev, events are represented as single bits (such as "EV_READ"
4320           or "EV_TIMEOUT").
4321
4322       event library
4323           A software package implementing an event model and loop.
4324
4325       event loop
4326           An entity that handles and processes external events and converts
4327           them into callback invocations.
4328
4329       event model
4330           The model used to describe how an event loop handles and processes
4331           watchers and events.
4332
4333       pending
4334           A watcher is pending as soon as the corresponding event has been
4335           detected, and stops being pending as soon as the watcher will be
4336           invoked or its pending status is explicitly cleared by the
4337           application.
4338
4339           A watcher can be pending, but not active. Stopping a watcher also
4340           clears its pending status.
4341
4342       real time
4343           The physical time that is observed. It is apparently strictly
4344           monotonic :)
4345
4346       wall-clock time
4347           The time and date as shown on clocks. Unlike real time, it can
4348           actually be wrong and jump forwards and backwards, e.g. when the
4349           you adjust your clock.
4350
4351       watcher
4352           A data structure that describes interest in certain events.
4353           Watchers need to be started (attached to an event loop) before they
4354           can receive events.
4355
4356       watcher invocation
4357           The act of calling the callback associated with a watcher.
4358

AUTHOR

4360       Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael
4361       Magnusson.
4362
4363
4364
4365libev-3.9                         2009-12-31                          LIBEV(3)
Impressum