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

NAME

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

SYNOPSIS

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

ABOUT THIS DOCUMENT

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

WHAT TO READ WHEN IN A HURRY

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

ABOUT LIBEV

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

ERROR HANDLING

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

GLOBAL FUNCTIONS

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

FUNCTIONS CONTROLLING EVENT LOOPS

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

ANATOMY OF A WATCHER

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

WATCHER TYPES

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

OTHER FUNCTIONS

3389       There are some other functions of possible interest. Described. Here.
3390       Now.
3391
3392       ev_once (loop, int fd, int events, ev_tstamp timeout, callback)
3393           This function combines a simple timer and an I/O watcher, calls
3394           your callback on whichever event happens first and automatically
3395           stops both watchers. This is useful if you want to wait for a
3396           single event on an fd or timeout without having to
3397           allocate/configure/start/stop/free one or more watchers yourself.
3398
3399           If "fd" is less than 0, then no I/O watcher will be started and the
3400           "events" argument is being ignored. Otherwise, an "ev_io" watcher
3401           for the given "fd" and "events" set will be created and started.
3402
3403           If "timeout" is less than 0, then no timeout watcher will be
3404           started. Otherwise an "ev_timer" watcher with after = "timeout"
3405           (and repeat = 0) will be started. 0 is a valid timeout.
3406
3407           The callback has the type "void (*cb)(int revents, void *arg)" and
3408           is passed an "revents" set like normal event callbacks (a
3409           combination of "EV_ERROR", "EV_READ", "EV_WRITE" or "EV_TIMER") and
3410           the "arg" value passed to "ev_once". Note that it is possible to
3411           receive both a timeout and an io event at the same time - you
3412           probably should give io events precedence.
3413
3414           Example: wait up to ten seconds for data to appear on STDIN_FILENO.
3415
3416              static void stdin_ready (int revents, void *arg)
3417              {
3418                if (revents & EV_READ)
3419                  /* stdin might have data for us, joy! */;
3420                else if (revents & EV_TIMER)
3421                  /* doh, nothing entered */;
3422              }
3423
3424              ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);
3425
3426       ev_feed_fd_event (loop, int fd, int revents)
3427           Feed an event on the given fd, as if a file descriptor backend
3428           detected the given events.
3429
3430       ev_feed_signal_event (loop, int signum)
3431           Feed an event as if the given signal occurred. See also
3432           "ev_feed_signal", which is async-safe.
3433

COMMON OR USEFUL IDIOMS (OR BOTH)

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

LIBEVENT EMULATION

3780       Libev offers a compatibility emulation layer for libevent. It cannot
3781       emulate the internals of libevent, so here are some usage hints:
3782
3783       ·   Only the libevent-1.4.1-beta API is being emulated.
3784
3785           This was the newest libevent version available when libev was
3786           implemented, and is still mostly unchanged in 2010.
3787
3788       ·   Use it by including <event.h>, as usual.
3789
3790       ·   The following members are fully supported: ev_base, ev_callback,
3791           ev_arg, ev_fd, ev_res, ev_events.
3792
3793       ·   Avoid using ev_flags and the EVLIST_*-macros, while it is
3794           maintained by libev, it does not work exactly the same way as in
3795           libevent (consider it a private API).
3796
3797       ·   Priorities are not currently supported. Initialising priorities
3798           will fail and all watchers will have the same priority, even though
3799           there is an ev_pri field.
3800
3801       ·   In libevent, the last base created gets the signals, in libev, the
3802           base that registered the signal gets the signals.
3803
3804       ·   Other members are not supported.
3805
3806       ·   The libev emulation is not ABI compatible to libevent, you need to
3807           use the libev header file and library.
3808

C++ SUPPORT

3810   C API
3811       The normal C API should work fine when used from C++: both ev.h and the
3812       libev sources can be compiled as C++. Therefore, code that uses the C
3813       API will work fine.
3814
3815       Proper exception specifications might have to be added to callbacks
3816       passed to libev: exceptions may be thrown only from watcher callbacks,
3817       all other callbacks (allocator, syserr, loop acquire/release and
3818       periodic reschedule callbacks) must not throw exceptions, and might
3819       need a "throw ()" specification. If you have code that needs to be
3820       compiled as both C and C++ you can use the "EV_THROW" macro for this:
3821
3822          static void
3823          fatal_error (const char *msg) EV_THROW
3824          {
3825            perror (msg);
3826            abort ();
3827          }
3828
3829          ...
3830          ev_set_syserr_cb (fatal_error);
3831
3832       The only API functions that can currently throw exceptions are
3833       "ev_run", "ev_invoke", "ev_invoke_pending" and "ev_loop_destroy" (the
3834       latter because it runs cleanup watchers).
3835
3836       Throwing exceptions in watcher callbacks is only supported if libev
3837       itself is compiled with a C++ compiler or your C and C++ environments
3838       allow throwing exceptions through C libraries (most do).
3839
3840   C++ API
3841       Libev comes with some simplistic wrapper classes for C++ that mainly
3842       allow you to use some convenience methods to start/stop watchers and
3843       also change the callback model to a model using method callbacks on
3844       objects.
3845
3846       To use it,
3847
3848          #include <ev++.h>
3849
3850       This automatically includes ev.h and puts all of its definitions (many
3851       of them macros) into the global namespace. All C++ specific things are
3852       put into the "ev" namespace. It should support all the same embedding
3853       options as ev.h, most notably "EV_MULTIPLICITY".
3854
3855       Care has been taken to keep the overhead low. The only data member the
3856       C++ classes add (compared to plain C-style watchers) is the event loop
3857       pointer that the watcher is associated with (or no additional members
3858       at all if you disable "EV_MULTIPLICITY" when embedding libev).
3859
3860       Currently, functions, static and non-static member functions and
3861       classes with "operator ()" can be used as callbacks. Other types should
3862       be easy to add as long as they only need one additional pointer for
3863       context. If you need support for other types of functors please contact
3864       the author (preferably after implementing it).
3865
3866       For all this to work, your C++ compiler either has to use the same
3867       calling conventions as your C compiler (for static member functions),
3868       or you have to embed libev and compile libev itself as C++.
3869
3870       Here is a list of things available in the "ev" namespace:
3871
3872       "ev::READ", "ev::WRITE" etc.
3873           These are just enum values with the same values as the "EV_READ"
3874           etc.  macros from ev.h.
3875
3876       "ev::tstamp", "ev::now"
3877           Aliases to the same types/functions as with the "ev_" prefix.
3878
3879       "ev::io", "ev::timer", "ev::periodic", "ev::idle", "ev::sig" etc.
3880           For each "ev_TYPE" watcher in ev.h there is a corresponding class
3881           of the same name in the "ev" namespace, with the exception of
3882           "ev_signal" which is called "ev::sig" to avoid clashes with the
3883           "signal" macro defined by many implementations.
3884
3885           All of those classes have these methods:
3886
3887           ev::TYPE::TYPE ()
3888           ev::TYPE::TYPE (loop)
3889           ev::TYPE::~TYPE
3890               The constructor (optionally) takes an event loop to associate
3891               the watcher with. If it is omitted, it will use "EV_DEFAULT".
3892
3893               The constructor calls "ev_init" for you, which means you have
3894               to call the "set" method before starting it.
3895
3896               It will not set a callback, however: You have to call the
3897               templated "set" method to set a callback before you can start
3898               the watcher.
3899
3900               (The reason why you have to use a method is a limitation in C++
3901               which does not allow explicit template arguments for
3902               constructors).
3903
3904               The destructor automatically stops the watcher if it is active.
3905
3906           w->set<class, &class::method> (object *)
3907               This method sets the callback method to call. The method has to
3908               have a signature of "void (*)(ev_TYPE &, int)", it receives the
3909               watcher as first argument and the "revents" as second. The
3910               object must be given as parameter and is stored in the "data"
3911               member of the watcher.
3912
3913               This method synthesizes efficient thunking code to call your
3914               method from the C callback that libev requires. If your
3915               compiler can inline your callback (i.e. it is visible to it at
3916               the place of the "set" call and your compiler is good :), then
3917               the method will be fully inlined into the thunking function,
3918               making it as fast as a direct C callback.
3919
3920               Example: simple class declaration and watcher initialisation
3921
3922                  struct myclass
3923                  {
3924                    void io_cb (ev::io &w, int revents) { }
3925                  }
3926
3927                  myclass obj;
3928                  ev::io iow;
3929                  iow.set <myclass, &myclass::io_cb> (&obj);
3930
3931           w->set (object *)
3932               This is a variation of a method callback - leaving out the
3933               method to call will default the method to "operator ()", which
3934               makes it possible to use functor objects without having to
3935               manually specify the "operator ()" all the time. Incidentally,
3936               you can then also leave out the template argument list.
3937
3938               The "operator ()" method prototype must be "void operator
3939               ()(watcher &w, int revents)".
3940
3941               See the method-"set" above for more details.
3942
3943               Example: use a functor object as callback.
3944
3945                  struct myfunctor
3946                  {
3947                    void operator() (ev::io &w, int revents)
3948                    {
3949                      ...
3950                    }
3951                  }
3952
3953                  myfunctor f;
3954
3955                  ev::io w;
3956                  w.set (&f);
3957
3958           w->set<function> (void *data = 0)
3959               Also sets a callback, but uses a static method or plain
3960               function as callback. The optional "data" argument will be
3961               stored in the watcher's "data" member and is free for you to
3962               use.
3963
3964               The prototype of the "function" must be "void (*)(ev::TYPE &w,
3965               int)".
3966
3967               See the method-"set" above for more details.
3968
3969               Example: Use a plain function as callback.
3970
3971                  static void io_cb (ev::io &w, int revents) { }
3972                  iow.set <io_cb> ();
3973
3974           w->set (loop)
3975               Associates a different "struct ev_loop" with this watcher. You
3976               can only do this when the watcher is inactive (and not pending
3977               either).
3978
3979           w->set ([arguments])
3980               Basically the same as "ev_TYPE_set" (except for "ev::embed"
3981               watchers>), with the same arguments. Either this method or a
3982               suitable start method must be called at least once. Unlike the
3983               C counterpart, an active watcher gets automatically stopped and
3984               restarted when reconfiguring it with this method.
3985
3986               For "ev::embed" watchers this method is called "set_embed", to
3987               avoid clashing with the "set (loop)" method.
3988
3989           w->start ()
3990               Starts the watcher. Note that there is no "loop" argument, as
3991               the constructor already stores the event loop.
3992
3993           w->start ([arguments])
3994               Instead of calling "set" and "start" methods separately, it is
3995               often convenient to wrap them in one call. Uses the same type
3996               of arguments as the configure "set" method of the watcher.
3997
3998           w->stop ()
3999               Stops the watcher if it is active. Again, no "loop" argument.
4000
4001           w->again () ("ev::timer", "ev::periodic" only)
4002               For "ev::timer" and "ev::periodic", this invokes the
4003               corresponding "ev_TYPE_again" function.
4004
4005           w->sweep () ("ev::embed" only)
4006               Invokes "ev_embed_sweep".
4007
4008           w->update () ("ev::stat" only)
4009               Invokes "ev_stat_stat".
4010
4011       Example: Define a class with two I/O and idle watchers, start the I/O
4012       watchers in the constructor.
4013
4014          class myclass
4015          {
4016            ev::io   io  ; void io_cb   (ev::io   &w, int revents);
4017            ev::io   io2 ; void io2_cb  (ev::io   &w, int revents);
4018            ev::idle idle; void idle_cb (ev::idle &w, int revents);
4019
4020            myclass (int fd)
4021            {
4022              io  .set <myclass, &myclass::io_cb  > (this);
4023              io2 .set <myclass, &myclass::io2_cb > (this);
4024              idle.set <myclass, &myclass::idle_cb> (this);
4025
4026              io.set (fd, ev::WRITE); // configure the watcher
4027              io.start ();            // start it whenever convenient
4028
4029              io2.start (fd, ev::READ); // set + start in one call
4030            }
4031          };
4032

OTHER LANGUAGE BINDINGS

4034       Libev does not offer other language bindings itself, but bindings for a
4035       number of languages exist in the form of third-party packages. If you
4036       know any interesting language binding in addition to the ones listed
4037       here, drop me a note.
4038
4039       Perl
4040           The EV module implements the full libev API and is actually used to
4041           test libev. EV is developed together with libev. Apart from the EV
4042           core module, there are additional modules that implement libev-
4043           compatible interfaces to "libadns" ("EV::ADNS", but "AnyEvent::DNS"
4044           is preferred nowadays), "Net::SNMP" ("Net::SNMP::EV") and the
4045           "libglib" event core ("Glib::EV" and "EV::Glib").
4046
4047           It can be found and installed via CPAN, its homepage is at
4048           <http://software.schmorp.de/pkg/EV>.
4049
4050       Python
4051           Python bindings can be found at <http://code.google.com/p/pyev/>.
4052           It seems to be quite complete and well-documented.
4053
4054       Ruby
4055           Tony Arcieri has written a ruby extension that offers access to a
4056           subset of the libev API and adds file handle abstractions,
4057           asynchronous DNS and more on top of it. It can be found via gem
4058           servers. Its homepage is at <http://rev.rubyforge.org/>.
4059
4060           Roger Pack reports that using the link order "-lws2_32
4061           -lmsvcrt-ruby-190" makes rev work even on mingw.
4062
4063       Haskell
4064           A haskell binding to libev is available at
4065           <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hlibev>.
4066
4067       D   Leandro Lucarella has written a D language binding (ev.d) for
4068           libev, to be found at
4069           <http://www.llucax.com.ar/proj/ev.d/index.html>.
4070
4071       Ocaml
4072           Erkki Seppala has written Ocaml bindings for libev, to be found at
4073           <http://modeemi.cs.tut.fi/~flux/software/ocaml-ev/>.
4074
4075       Lua Brian Maher has written a partial interface to libev for lua (at
4076           the time of this writing, only "ev_io" and "ev_timer"), to be found
4077           at <http://github.com/brimworks/lua-ev>.
4078
4079       Javascript
4080           Node.js (<http://nodejs.org>) uses libev as the underlying event
4081           library.
4082
4083       Others
4084           There are others, and I stopped counting.
4085

MACRO MAGIC

4087       Libev can be compiled with a variety of options, the most fundamental
4088       of which is "EV_MULTIPLICITY". This option determines whether (most)
4089       functions and callbacks have an initial "struct ev_loop *" argument.
4090
4091       To make it easier to write programs that cope with either variant, the
4092       following macros are defined:
4093
4094       "EV_A", "EV_A_"
4095           This provides the loop argument for functions, if one is required
4096           ("ev loop argument"). The "EV_A" form is used when this is the sole
4097           argument, "EV_A_" is used when other arguments are following.
4098           Example:
4099
4100              ev_unref (EV_A);
4101              ev_timer_add (EV_A_ watcher);
4102              ev_run (EV_A_ 0);
4103
4104           It assumes the variable "loop" of type "struct ev_loop *" is in
4105           scope, which is often provided by the following macro.
4106
4107       "EV_P", "EV_P_"
4108           This provides the loop parameter for functions, if one is required
4109           ("ev loop parameter"). The "EV_P" form is used when this is the
4110           sole parameter, "EV_P_" is used when other parameters are
4111           following. Example:
4112
4113              // this is how ev_unref is being declared
4114              static void ev_unref (EV_P);
4115
4116              // this is how you can declare your typical callback
4117              static void cb (EV_P_ ev_timer *w, int revents)
4118
4119           It declares a parameter "loop" of type "struct ev_loop *", quite
4120           suitable for use with "EV_A".
4121
4122       "EV_DEFAULT", "EV_DEFAULT_"
4123           Similar to the other two macros, this gives you the value of the
4124           default loop, if multiple loops are supported ("ev loop default").
4125           The default loop will be initialised if it isn't already
4126           initialised.
4127
4128           For non-multiplicity builds, these macros do nothing, so you always
4129           have to initialise the loop somewhere.
4130
4131       "EV_DEFAULT_UC", "EV_DEFAULT_UC_"
4132           Usage identical to "EV_DEFAULT" and "EV_DEFAULT_", but requires
4133           that the default loop has been initialised ("UC" == unchecked).
4134           Their behaviour is undefined when the default loop has not been
4135           initialised by a previous execution of "EV_DEFAULT", "EV_DEFAULT_"
4136           or "ev_default_init (...)".
4137
4138           It is often prudent to use "EV_DEFAULT" when initialising the first
4139           watcher in a function but use "EV_DEFAULT_UC" afterwards.
4140
4141       Example: Declare and initialise a check watcher, utilising the above
4142       macros so it will work regardless of whether multiple loops are
4143       supported or not.
4144
4145          static void
4146          check_cb (EV_P_ ev_timer *w, int revents)
4147          {
4148            ev_check_stop (EV_A_ w);
4149          }
4150
4151          ev_check check;
4152          ev_check_init (&check, check_cb);
4153          ev_check_start (EV_DEFAULT_ &check);
4154          ev_run (EV_DEFAULT_ 0);
4155

EMBEDDING

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

INTERACTION WITH OTHER PROGRAMS, LIBRARIES OR THE ENVIRONMENT

4739   THREADS AND COROUTINES
4740       THREADS
4741
4742       All libev functions are reentrant and thread-safe unless explicitly
4743       documented otherwise, but libev implements no locking itself. This
4744       means that you can use as many loops as you want in parallel, as long
4745       as there are no concurrent calls into any libev function with the same
4746       loop parameter ("ev_default_*" calls have an implicit default loop
4747       parameter, of course): libev guarantees that different event loops
4748       share no data structures that need any locking.
4749
4750       Or to put it differently: calls with different loop parameters can be
4751       done concurrently from multiple threads, calls with the same loop
4752       parameter must be done serially (but can be done from different
4753       threads, as long as only one thread ever is inside a call at any point
4754       in time, e.g. by using a mutex per loop).
4755
4756       Specifically to support threads (and signal handlers), libev implements
4757       so-called "ev_async" watchers, which allow some limited form of
4758       concurrency on the same event loop, namely waking it up "from the
4759       outside".
4760
4761       If you want to know which design (one loop, locking, or multiple loops
4762       without or something else still) is best for your problem, then I
4763       cannot help you, but here is some generic advice:
4764
4765       ·   most applications have a main thread: use the default libev loop in
4766           that thread, or create a separate thread running only the default
4767           loop.
4768
4769           This helps integrating other libraries or software modules that use
4770           libev themselves and don't care/know about threading.
4771
4772       ·   one loop per thread is usually a good model.
4773
4774           Doing this is almost never wrong, sometimes a better-performance
4775           model exists, but it is always a good start.
4776
4777       ·   other models exist, such as the leader/follower pattern, where one
4778           loop is handed through multiple threads in a kind of round-robin
4779           fashion.
4780
4781           Choosing a model is hard - look around, learn, know that usually
4782           you can do better than you currently do :-)
4783
4784       ·   often you need to talk to some other thread which blocks in the
4785           event loop.
4786
4787           "ev_async" watchers can be used to wake them up from other threads
4788           safely (or from signal contexts...).
4789
4790           An example use would be to communicate signals or other events that
4791           only work in the default loop by registering the signal watcher
4792           with the default loop and triggering an "ev_async" watcher from the
4793           default loop watcher callback into the event loop interested in the
4794           signal.
4795
4796       See also "THREAD LOCKING EXAMPLE".
4797
4798       COROUTINES
4799
4800       Libev is very accommodating to coroutines ("cooperative threads"):
4801       libev fully supports nesting calls to its functions from different
4802       coroutines (e.g. you can call "ev_run" on the same loop from two
4803       different coroutines, and switch freely between both coroutines running
4804       the loop, as long as you don't confuse yourself). The only exception is
4805       that you must not do this from "ev_periodic" reschedule callbacks.
4806
4807       Care has been taken to ensure that libev does not keep local state
4808       inside "ev_run", and other calls do not usually allow for coroutine
4809       switches as they do not call any callbacks.
4810
4811   COMPILER WARNINGS
4812       Depending on your compiler and compiler settings, you might get no or a
4813       lot of warnings when compiling libev code. Some people are apparently
4814       scared by this.
4815
4816       However, these are unavoidable for many reasons. For one, each compiler
4817       has different warnings, and each user has different tastes regarding
4818       warning options. "Warn-free" code therefore cannot be a goal except
4819       when targeting a specific compiler and compiler-version.
4820
4821       Another reason is that some compiler warnings require elaborate
4822       workarounds, or other changes to the code that make it less clear and
4823       less maintainable.
4824
4825       And of course, some compiler warnings are just plain stupid, or simply
4826       wrong (because they don't actually warn about the condition their
4827       message seems to warn about). For example, certain older gcc versions
4828       had some warnings that resulted in an extreme number of false
4829       positives. These have been fixed, but some people still insist on
4830       making code warn-free with such buggy versions.
4831
4832       While libev is written to generate as few warnings as possible, "warn-
4833       free" code is not a goal, and it is recommended not to build libev with
4834       any compiler warnings enabled unless you are prepared to cope with them
4835       (e.g. by ignoring them). Remember that warnings are just that:
4836       warnings, not errors, or proof of bugs.
4837
4838   VALGRIND
4839       Valgrind has a special section here because it is a popular tool that
4840       is highly useful. Unfortunately, valgrind reports are very hard to
4841       interpret.
4842
4843       If you think you found a bug (memory leak, uninitialised data access
4844       etc.)  in libev, then check twice: If valgrind reports something like:
4845
4846          ==2274==    definitely lost: 0 bytes in 0 blocks.
4847          ==2274==      possibly lost: 0 bytes in 0 blocks.
4848          ==2274==    still reachable: 256 bytes in 1 blocks.
4849
4850       Then there is no memory leak, just as memory accounted to global
4851       variables is not a memleak - the memory is still being referenced, and
4852       didn't leak.
4853
4854       Similarly, under some circumstances, valgrind might report kernel bugs
4855       as if it were a bug in libev (e.g. in realloc or in the poll backend,
4856       although an acceptable workaround has been found here), or it might be
4857       confused.
4858
4859       Keep in mind that valgrind is a very good tool, but only a tool. Don't
4860       make it into some kind of religion.
4861
4862       If you are unsure about something, feel free to contact the mailing
4863       list with the full valgrind report and an explanation on why you think
4864       this is a bug in libev (best check the archives, too :). However, don't
4865       be annoyed when you get a brisk "this is no bug" answer and take the
4866       chance of learning how to interpret valgrind properly.
4867
4868       If you need, for some reason, empty reports from valgrind for your
4869       project I suggest using suppression lists.
4870

PORTABILITY NOTES

4872   GNU/LINUX 32 BIT LIMITATIONS
4873       GNU/Linux is the only common platform that supports 64 bit file/large
4874       file interfaces but disables them by default.
4875
4876       That means that libev compiled in the default environment doesn't
4877       support files larger than 2GiB or so, which mainly affects "ev_stat"
4878       watchers.
4879
4880       Unfortunately, many programs try to work around this GNU/Linux issue by
4881       enabling the large file API, which makes them incompatible with the
4882       standard libev compiled for their system.
4883
4884       Likewise, libev cannot enable the large file API itself as this would
4885       suddenly make it incompatible to the default compile time environment,
4886       i.e. all programs not using special compile switches.
4887
4888   OS/X AND DARWIN BUGS
4889       The whole thing is a bug if you ask me - basically any system interface
4890       you touch is broken, whether it is locales, poll, kqueue or even the
4891       OpenGL drivers.
4892
4893       "kqueue" is buggy
4894
4895       The kqueue syscall is broken in all known versions - most versions
4896       support only sockets, many support pipes.
4897
4898       Libev tries to work around this by not using "kqueue" by default on
4899       this rotten platform, but of course you can still ask for it when
4900       creating a loop - embedding a socket-only kqueue loop into a select-
4901       based one is probably going to work well.
4902
4903       "poll" is buggy
4904
4905       Instead of fixing "kqueue", Apple replaced their (working) "poll"
4906       implementation by something calling "kqueue" internally around the
4907       10.5.6 release, so now "kqueue" and "poll" are broken.
4908
4909       Libev tries to work around this by not using "poll" by default on this
4910       rotten platform, but of course you can still ask for it when creating a
4911       loop.
4912
4913       "select" is buggy
4914
4915       All that's left is "select", and of course Apple found a way to fuck
4916       this one up as well: On OS/X, "select" actively limits the number of
4917       file descriptors you can pass in to 1024 - your program suddenly
4918       crashes when you use more.
4919
4920       There is an undocumented "workaround" for this - defining
4921       "_DARWIN_UNLIMITED_SELECT", which libev tries to use, so select should
4922       work on OS/X.
4923
4924   SOLARIS PROBLEMS AND WORKAROUNDS
4925       "errno" reentrancy
4926
4927       The default compile environment on Solaris is unfortunately so thread-
4928       unsafe that you can't even use components/libraries compiled without
4929       "-D_REENTRANT" in a threaded program, which, of course, isn't defined
4930       by default. A valid, if stupid, implementation choice.
4931
4932       If you want to use libev in threaded environments you have to make sure
4933       it's compiled with "_REENTRANT" defined.
4934
4935       Event port backend
4936
4937       The scalable event interface for Solaris is called "event ports".
4938       Unfortunately, this mechanism is very buggy in all major releases. If
4939       you run into high CPU usage, your program freezes or you get a large
4940       number of spurious wakeups, make sure you have all the relevant and
4941       latest kernel patches applied. No, I don't know which ones, but there
4942       are multiple ones to apply, and afterwards, event ports actually work
4943       great.
4944
4945       If you can't get it to work, you can try running the program by setting
4946       the environment variable "LIBEV_FLAGS=3" to only allow "poll" and
4947       "select" backends.
4948
4949   AIX POLL BUG
4950       AIX unfortunately has a broken "poll.h" header. Libev works around this
4951       by trying to avoid the poll backend altogether (i.e. it's not even
4952       compiled in), which normally isn't a big problem as "select" works fine
4953       with large bitsets on AIX, and AIX is dead anyway.
4954
4955   WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS
4956       General issues
4957
4958       Win32 doesn't support any of the standards (e.g. POSIX) that libev
4959       requires, and its I/O model is fundamentally incompatible with the
4960       POSIX model. Libev still offers limited functionality on this platform
4961       in the form of the "EVBACKEND_SELECT" backend, and only supports socket
4962       descriptors. This only applies when using Win32 natively, not when
4963       using e.g. cygwin. Actually, it only applies to the microsofts own
4964       compilers, as every compiler comes with a slightly differently
4965       broken/incompatible environment.
4966
4967       Lifting these limitations would basically require the full re-
4968       implementation of the I/O system. If you are into this kind of thing,
4969       then note that glib does exactly that for you in a very portable way
4970       (note also that glib is the slowest event library known to man).
4971
4972       There is no supported compilation method available on windows except
4973       embedding it into other applications.
4974
4975       Sensible signal handling is officially unsupported by Microsoft - libev
4976       tries its best, but under most conditions, signals will simply not
4977       work.
4978
4979       Not a libev limitation but worth mentioning: windows apparently doesn't
4980       accept large writes: instead of resulting in a partial write, windows
4981       will either accept everything or return "ENOBUFS" if the buffer is too
4982       large, so make sure you only write small amounts into your sockets
4983       (less than a megabyte seems safe, but this apparently depends on the
4984       amount of memory available).
4985
4986       Due to the many, low, and arbitrary limits on the win32 platform and
4987       the abysmal performance of winsockets, using a large number of sockets
4988       is not recommended (and not reasonable). If your program needs to use
4989       more than a hundred or so sockets, then likely it needs to use a
4990       totally different implementation for windows, as libev offers the POSIX
4991       readiness notification model, which cannot be implemented efficiently
4992       on windows (due to Microsoft monopoly games).
4993
4994       A typical way to use libev under windows is to embed it (see the
4995       embedding section for details) and use the following evwrap.h header
4996       file instead of ev.h:
4997
4998          #define EV_STANDALONE              /* keeps ev from requiring config.h */
4999          #define EV_SELECT_IS_WINSOCKET 1   /* configure libev for windows select */
5000
5001          #include "ev.h"
5002
5003       And compile the following evwrap.c file into your project (make sure
5004       you do not compile the ev.c or any other embedded source files!):
5005
5006          #include "evwrap.h"
5007          #include "ev.c"
5008
5009       The winsocket "select" function
5010
5011       The winsocket "select" function doesn't follow POSIX in that it
5012       requires socket handles and not socket file descriptors (it is also
5013       extremely buggy). This makes select very inefficient, and also requires
5014       a mapping from file descriptors to socket handles (the Microsoft C
5015       runtime provides the function "_open_osfhandle" for this). See the
5016       discussion of the "EV_SELECT_USE_FD_SET", "EV_SELECT_IS_WINSOCKET" and
5017       "EV_FD_TO_WIN32_HANDLE" preprocessor symbols for more info.
5018
5019       The configuration for a "naked" win32 using the Microsoft runtime
5020       libraries and raw winsocket select is:
5021
5022          #define EV_USE_SELECT 1
5023          #define EV_SELECT_IS_WINSOCKET 1   /* forces EV_SELECT_USE_FD_SET, too */
5024
5025       Note that winsockets handling of fd sets is O(n), so you can easily get
5026       a complexity in the O(n²) range when using win32.
5027
5028       Limited number of file descriptors
5029
5030       Windows has numerous arbitrary (and low) limits on things.
5031
5032       Early versions of winsocket's select only supported waiting for a
5033       maximum of 64 handles (probably owning to the fact that all windows
5034       kernels can only wait for 64 things at the same time internally;
5035       Microsoft recommends spawning a chain of threads and wait for 63
5036       handles and the previous thread in each. Sounds great!).
5037
5038       Newer versions support more handles, but you need to define
5039       "FD_SETSIZE" to some high number (e.g. 2048) before compiling the
5040       winsocket select call (which might be in libev or elsewhere, for
5041       example, perl and many other interpreters do their own select emulation
5042       on windows).
5043
5044       Another limit is the number of file descriptors in the Microsoft
5045       runtime libraries, which by default is 64 (there must be a hidden 64
5046       fetish or something like this inside Microsoft). You can increase this
5047       by calling "_setmaxstdio", which can increase this limit to 2048
5048       (another arbitrary limit), but is broken in many versions of the
5049       Microsoft runtime libraries. This might get you to about 512 or 2048
5050       sockets (depending on windows version and/or the phase of the moon). To
5051       get more, you need to wrap all I/O functions and provide your own fd
5052       management, but the cost of calling select (O(n²)) will likely make
5053       this unworkable.
5054
5055   PORTABILITY REQUIREMENTS
5056       In addition to a working ISO-C implementation and of course the
5057       backend-specific APIs, libev relies on a few additional extensions:
5058
5059       "void (*)(ev_watcher_type *, int revents)" must have compatible calling
5060       conventions regardless of "ev_watcher_type *".
5061           Libev assumes not only that all watcher pointers have the same
5062           internal structure (guaranteed by POSIX but not by ISO C for
5063           example), but it also assumes that the same (machine) code can be
5064           used to call any watcher callback: The watcher callbacks have
5065           different type signatures, but libev calls them using an
5066           "ev_watcher *" internally.
5067
5068       null pointers and integer zero are represented by 0 bytes
5069           Libev uses "memset" to initialise structs and arrays to 0 bytes,
5070           and relies on this setting pointers and integers to null.
5071
5072       pointer accesses must be thread-atomic
5073           Accessing a pointer value must be atomic, it must both be readable
5074           and writable in one piece - this is the case on all current
5075           architectures.
5076
5077       "sig_atomic_t volatile" must be thread-atomic as well
5078           The type "sig_atomic_t volatile" (or whatever is defined as
5079           "EV_ATOMIC_T") must be atomic with respect to accesses from
5080           different threads. This is not part of the specification for
5081           "sig_atomic_t", but is believed to be sufficiently portable.
5082
5083       "sigprocmask" must work in a threaded environment
5084           Libev uses "sigprocmask" to temporarily block signals. This is not
5085           allowed in a threaded program ("pthread_sigmask" has to be used).
5086           Typical pthread implementations will either allow "sigprocmask" in
5087           the "main thread" or will block signals process-wide, both
5088           behaviours would be compatible with libev. Interaction between
5089           "sigprocmask" and "pthread_sigmask" could complicate things,
5090           however.
5091
5092           The most portable way to handle signals is to block signals in all
5093           threads except the initial one, and run the signal handling loop in
5094           the initial thread as well.
5095
5096       "long" must be large enough for common memory allocation sizes
5097           To improve portability and simplify its API, libev uses "long"
5098           internally instead of "size_t" when allocating its data structures.
5099           On non-POSIX systems (Microsoft...) this might be unexpectedly low,
5100           but is still at least 31 bits everywhere, which is enough for
5101           hundreds of millions of watchers.
5102
5103       "double" must hold a time value in seconds with enough accuracy
5104           The type "double" is used to represent timestamps. It is required
5105           to have at least 51 bits of mantissa (and 9 bits of exponent),
5106           which is good enough for at least into the year 4000 with
5107           millisecond accuracy (the design goal for libev). This requirement
5108           is overfulfilled by implementations using IEEE 754, which is
5109           basically all existing ones.
5110
5111           With IEEE 754 doubles, you get microsecond accuracy until at least
5112           the year 2255 (and millisecond accuracy till the year 287396 - by
5113           then, libev is either obsolete or somebody patched it to use "long
5114           double" or something like that, just kidding).
5115
5116       If you know of other additional requirements drop me a note.
5117

ALGORITHMIC COMPLEXITIES

5119       In this section the complexities of (many of) the algorithms used
5120       inside libev will be documented. For complexity discussions about
5121       backends see the documentation for "ev_default_init".
5122
5123       All of the following are about amortised time: If an array needs to be
5124       extended, libev needs to realloc and move the whole array, but this
5125       happens asymptotically rarer with higher number of elements, so O(1)
5126       might mean that libev does a lengthy realloc operation in rare cases,
5127       but on average it is much faster and asymptotically approaches constant
5128       time.
5129
5130       Starting and stopping timer/periodic watchers: O(log
5131       skipped_other_timers)
5132           This means that, when you have a watcher that triggers in one hour
5133           and there are 100 watchers that would trigger before that, then
5134           inserting will have to skip roughly seven ("ld 100") of these
5135           watchers.
5136
5137       Changing timer/periodic watchers (by autorepeat or calling again):
5138       O(log skipped_other_timers)
5139           That means that changing a timer costs less than removing/adding
5140           them, as only the relative motion in the event queue has to be paid
5141           for.
5142
5143       Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1)
5144           These just add the watcher into an array or at the head of a list.
5145
5146       Stopping check/prepare/idle/fork/async watchers: O(1)
5147       Stopping an io/signal/child watcher:
5148       O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE))
5149           These watchers are stored in lists, so they need to be walked to
5150           find the correct watcher to remove. The lists are usually short
5151           (you don't usually have many watchers waiting for the same fd or
5152           signal: one is typical, two is rare).
5153
5154       Finding the next timer in each loop iteration: O(1)
5155           By virtue of using a binary or 4-heap, the next timer is always
5156           found at a fixed position in the storage array.
5157
5158       Each change on a file descriptor per loop iteration:
5159       O(number_of_watchers_for_this_fd)
5160           A change means an I/O watcher gets started or stopped, which
5161           requires libev to recalculate its status (and possibly tell the
5162           kernel, depending on backend and whether "ev_io_set" was used).
5163
5164       Activating one watcher (putting it into the pending state): O(1)
5165       Priority handling: O(number_of_priorities)
5166           Priorities are implemented by allocating some space for each
5167           priority. When doing priority-based operations, libev usually has
5168           to linearly search all the priorities, but starting/stopping and
5169           activating watchers becomes O(1) with respect to priority handling.
5170
5171       Sending an ev_async: O(1)
5172       Processing ev_async_send: O(number_of_async_watchers)
5173       Processing signals: O(max_signal_number)
5174           Sending involves a system call iff there were no other
5175           "ev_async_send" calls in the current loop iteration and the loop is
5176           currently blocked. Checking for async and signal events involves
5177           iterating over all running async watchers or all signal numbers.
5178

PORTING FROM LIBEV 3.X TO 4.X

5180       The major version 4 introduced some incompatible changes to the API.
5181
5182       At the moment, the "ev.h" header file provides compatibility
5183       definitions for all changes, so most programs should still compile. The
5184       compatibility layer might be removed in later versions of libev, so
5185       better update to the new API early than late.
5186
5187       "EV_COMPAT3" backwards compatibility mechanism
5188           The backward compatibility mechanism can be controlled by
5189           "EV_COMPAT3". See "PREPROCESSOR SYMBOLS/MACROS" in the "EMBEDDING"
5190           section.
5191
5192       "ev_default_destroy" and "ev_default_fork" have been removed
5193           These calls can be replaced easily by their "ev_loop_xxx"
5194           counterparts:
5195
5196              ev_loop_destroy (EV_DEFAULT_UC);
5197              ev_loop_fork (EV_DEFAULT);
5198
5199       function/symbol renames
5200           A number of functions and symbols have been renamed:
5201
5202             ev_loop         => ev_run
5203             EVLOOP_NONBLOCK => EVRUN_NOWAIT
5204             EVLOOP_ONESHOT  => EVRUN_ONCE
5205
5206             ev_unloop       => ev_break
5207             EVUNLOOP_CANCEL => EVBREAK_CANCEL
5208             EVUNLOOP_ONE    => EVBREAK_ONE
5209             EVUNLOOP_ALL    => EVBREAK_ALL
5210
5211             EV_TIMEOUT      => EV_TIMER
5212
5213             ev_loop_count   => ev_iteration
5214             ev_loop_depth   => ev_depth
5215             ev_loop_verify  => ev_verify
5216
5217           Most functions working on "struct ev_loop" objects don't have an
5218           "ev_loop_" prefix, so it was removed; "ev_loop", "ev_unloop" and
5219           associated constants have been renamed to not collide with the
5220           "struct ev_loop" anymore and "EV_TIMER" now follows the same naming
5221           scheme as all other watcher types. Note that "ev_loop_fork" is
5222           still called "ev_loop_fork" because it would otherwise clash with
5223           the "ev_fork" typedef.
5224
5225       "EV_MINIMAL" mechanism replaced by "EV_FEATURES"
5226           The preprocessor symbol "EV_MINIMAL" has been replaced by a
5227           different mechanism, "EV_FEATURES". Programs using "EV_MINIMAL"
5228           usually compile and work, but the library code will of course be
5229           larger.
5230

GLOSSARY

5232       active
5233           A watcher is active as long as it has been started and not yet
5234           stopped.  See "WATCHER STATES" for details.
5235
5236       application
5237           In this document, an application is whatever is using libev.
5238
5239       backend
5240           The part of the code dealing with the operating system interfaces.
5241
5242       callback
5243           The address of a function that is called when some event has been
5244           detected. Callbacks are being passed the event loop, the watcher
5245           that received the event, and the actual event bitset.
5246
5247       callback/watcher invocation
5248           The act of calling the callback associated with a watcher.
5249
5250       event
5251           A change of state of some external event, such as data now being
5252           available for reading on a file descriptor, time having passed or
5253           simply not having any other events happening anymore.
5254
5255           In libev, events are represented as single bits (such as "EV_READ"
5256           or "EV_TIMER").
5257
5258       event library
5259           A software package implementing an event model and loop.
5260
5261       event loop
5262           An entity that handles and processes external events and converts
5263           them into callback invocations.
5264
5265       event model
5266           The model used to describe how an event loop handles and processes
5267           watchers and events.
5268
5269       pending
5270           A watcher is pending as soon as the corresponding event has been
5271           detected. See "WATCHER STATES" for details.
5272
5273       real time
5274           The physical time that is observed. It is apparently strictly
5275           monotonic :)
5276
5277       wall-clock time
5278           The time and date as shown on clocks. Unlike real time, it can
5279           actually be wrong and jump forwards and backwards, e.g. when you
5280           adjust your clock.
5281
5282       watcher
5283           A data structure that describes interest in certain events.
5284           Watchers need to be started (attached to an event loop) before they
5285           can receive events.
5286

AUTHOR

5288       Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael
5289       Magnusson and Emanuele Giaquinta, and minor corrections by many others.
5290
5291
5292
5293perl v5.28.0                      2018-07-14                      libev::ev(3)
Impressum