1libev::ev(3) User Contributed Perl Documentation libev::ev(3)
2
3
4
6 libev - a high performance full-featured event loop written in C
7
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
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
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
92 Libev is an event loop: you register interest in certain events (such
93 as a file descriptor being readable or a timeout occurring), and it
94 will manage these event sources and provide your program with events.
95
96 To do this, it must take more or less complete control over your
97 process (or thread) by executing the event loop handler, and will then
98 communicate events via a callback mechanism.
99
100 You register interest in certain events by registering so-called event
101 watchers, which are relatively small C structures you initialise with
102 the details of the event, and then hand it over to libev by starting
103 the watcher.
104
105 FEATURES
106 Libev supports "select", "poll", the Linux-specific aio and "epoll"
107 interfaces, the BSD-specific "kqueue" and the Solaris-specific event
108 port mechanisms for file descriptor events ("ev_io"), the Linux
109 "inotify" interface (for "ev_stat"), Linux eventfd/signalfd (for faster
110 and cleaner inter-thread wakeup ("ev_async")/signal handling
111 ("ev_signal")) relative timers ("ev_timer"), absolute timers with
112 customised rescheduling ("ev_periodic"), synchronous signals
113 ("ev_signal"), process status change events ("ev_child"), and event
114 watchers dealing with the event loop mechanism itself ("ev_idle",
115 "ev_embed", "ev_prepare" and "ev_check" watchers) as well as file
116 watchers ("ev_stat") and even limited support for fork events
117 ("ev_fork").
118
119 It also is quite fast (see this benchmark
120 <http://libev.schmorp.de/bench.html> comparing it to libevent for
121 example).
122
123 CONVENTIONS
124 Libev is very configurable. In this manual the default (and most
125 common) configuration will be described, which supports multiple event
126 loops. For more info about various configuration options please have a
127 look at EMBED section in this manual. If libev was configured without
128 support for multiple event loops, then all functions taking an initial
129 argument of name "loop" (which is always of type "struct ev_loop *")
130 will not have this argument.
131
132 TIME REPRESENTATION
133 Libev represents time as a single floating point number, representing
134 the (fractional) number of seconds since the (POSIX) epoch (in practice
135 somewhere near the beginning of 1970, details are complicated, don't
136 ask). This type is called "ev_tstamp", which is what you should use
137 too. It usually aliases to the "double" type in C. When you need to do
138 any calculations on it, you should treat it as some floating point
139 value.
140
141 Unlike the name component "stamp" might indicate, it is also used for
142 time differences (e.g. delays) throughout libev.
143
145 Libev knows three classes of errors: operating system errors, usage
146 errors and internal errors (bugs).
147
148 When libev catches an operating system error it cannot handle (for
149 example a system call indicating a condition libev cannot fix), it
150 calls the callback set via "ev_set_syserr_cb", which is supposed to fix
151 the problem or abort. The default is to print a diagnostic message and
152 to call "abort ()".
153
154 When libev detects a usage error such as a negative timer interval,
155 then it will print a diagnostic message and abort (via the "assert"
156 mechanism, so "NDEBUG" will disable this checking): these are
157 programming errors in the libev caller and need to be fixed there.
158
159 Via the "EV_FREQUENT" macro you can compile in and/or enable extensive
160 consistency checking code inside libev that can be used to check for
161 internal inconsistencies, suually caused by application bugs.
162
163 Libev also has a few internal error-checking "assert"ions. These do not
164 trigger under normal circumstances, as they indicate either a bug in
165 libev or worse.
166
168 These functions can be called anytime, even before initialising the
169 library in any way.
170
171 ev_tstamp ev_time ()
172 Returns the current time as libev would use it. Please note that
173 the "ev_now" function is usually faster and also often returns the
174 timestamp you actually want to know. Also interesting is the
175 combination of "ev_now_update" and "ev_now".
176
177 ev_sleep (ev_tstamp interval)
178 Sleep for the given interval: The current thread will be blocked
179 until either it is interrupted or the given time interval has
180 passed (approximately - it might return a bit earlier even if not
181 interrupted). Returns immediately if "interval <= 0".
182
183 Basically this is a sub-second-resolution "sleep ()".
184
185 The range of the "interval" is limited - libev only guarantees to
186 work with sleep times of up to one day ("interval <= 86400").
187
188 int ev_version_major ()
189 int ev_version_minor ()
190 You can find out the major and minor ABI version numbers of the
191 library you linked against by calling the functions
192 "ev_version_major" and "ev_version_minor". If you want, you can
193 compare against the global symbols "EV_VERSION_MAJOR" and
194 "EV_VERSION_MINOR", which specify the version of the library your
195 program was compiled against.
196
197 These version numbers refer to the ABI version of the library, not
198 the release version.
199
200 Usually, it's a good idea to terminate if the major versions
201 mismatch, as this indicates an incompatible change. Minor versions
202 are usually compatible to older versions, so a larger minor version
203 alone is usually not a problem.
204
205 Example: Make sure we haven't accidentally been linked against the
206 wrong version (note, however, that this will not detect other ABI
207 mismatches, such as LFS or reentrancy).
208
209 assert (("libev version mismatch",
210 ev_version_major () == EV_VERSION_MAJOR
211 && ev_version_minor () >= EV_VERSION_MINOR));
212
213 unsigned int ev_supported_backends ()
214 Return the set of all backends (i.e. their corresponding
215 "EV_BACKEND_*" value) compiled into this binary of libev
216 (independent of their availability on the system you are running
217 on). See "ev_default_loop" for a description of the set values.
218
219 Example: make sure we have the epoll method, because yeah this is
220 cool and a must have and can we have a torrent of it please!!!11
221
222 assert (("sorry, no epoll, no sex",
223 ev_supported_backends () & EVBACKEND_EPOLL));
224
225 unsigned int ev_recommended_backends ()
226 Return the set of all backends compiled into this binary of libev
227 and also recommended for this platform, meaning it will work for
228 most file descriptor types. This set is often smaller than the one
229 returned by "ev_supported_backends", as for example kqueue is
230 broken on most BSDs and will not be auto-detected unless you
231 explicitly request it (assuming you know what you are doing). This
232 is the set of backends that libev will probe for if you specify no
233 backends explicitly.
234
235 unsigned int ev_embeddable_backends ()
236 Returns the set of backends that are embeddable in other event
237 loops. This value is platform-specific but can include backends not
238 available on the current system. To find which embeddable backends
239 might be supported on the current system, you would need to look at
240 "ev_embeddable_backends () & ev_supported_backends ()", likewise
241 for recommended ones.
242
243 See the description of "ev_embed" watchers for more info.
244
245 ev_set_allocator (void *(*cb)(void *ptr, long size) throw ())
246 Sets the allocation function to use (the prototype is similar - the
247 semantics are identical to the "realloc" C89/SuS/POSIX function).
248 It is used to allocate and free memory (no surprises here). If it
249 returns zero when memory needs to be allocated ("size != 0"), the
250 library might abort or take some potentially destructive action.
251
252 Since some systems (at least OpenBSD and Darwin) fail to implement
253 correct "realloc" semantics, libev will use a wrapper around the
254 system "realloc" and "free" functions by default.
255
256 You could override this function in high-availability programs to,
257 say, free some memory if it cannot allocate memory, to use a
258 special allocator, or even to sleep a while and retry until some
259 memory is available.
260
261 Example: The following is the "realloc" function that libev itself
262 uses which should work with "realloc" and "free" functions of all
263 kinds and is probably a good basis for your own implementation.
264
265 static void *
266 ev_realloc_emul (void *ptr, long size) EV_NOEXCEPT
267 {
268 if (size)
269 return realloc (ptr, size);
270
271 free (ptr);
272 return 0;
273 }
274
275 Example: Replace the libev allocator with one that waits a bit and
276 then retries.
277
278 static void *
279 persistent_realloc (void *ptr, size_t size)
280 {
281 if (!size)
282 {
283 free (ptr);
284 return 0;
285 }
286
287 for (;;)
288 {
289 void *newptr = realloc (ptr, size);
290
291 if (newptr)
292 return newptr;
293
294 sleep (60);
295 }
296 }
297
298 ...
299 ev_set_allocator (persistent_realloc);
300
301 ev_set_syserr_cb (void (*cb)(const char *msg) throw ())
302 Set the callback function to call on a retryable system call error
303 (such as failed select, poll, epoll_wait). The message is a
304 printable string indicating the system call or subsystem causing
305 the problem. If this callback is set, then libev will expect it to
306 remedy the situation, no matter what, when it returns. That is,
307 libev will generally retry the requested operation, or, if the
308 condition doesn't go away, do bad stuff (such as abort).
309
310 Example: This is basically the same thing that libev does
311 internally, too.
312
313 static void
314 fatal_error (const char *msg)
315 {
316 perror (msg);
317 abort ();
318 }
319
320 ...
321 ev_set_syserr_cb (fatal_error);
322
323 ev_feed_signal (int signum)
324 This function can be used to "simulate" a signal receive. It is
325 completely safe to call this function at any time, from any
326 context, including signal handlers or random threads.
327
328 Its main use is to customise signal handling in your process,
329 especially in the presence of threads. For example, you could block
330 signals by default in all threads (and specifying
331 "EVFLAG_NOSIGMASK" when creating any loops), and in one thread, use
332 "sigwait" or any other mechanism to wait for signals, then
333 "deliver" them to libev by calling "ev_feed_signal".
334
336 An event loop is described by a "struct ev_loop *" (the "struct" is not
337 optional in this case unless libev 3 compatibility is disabled, as
338 libev 3 had an "ev_loop" function colliding with the struct name).
339
340 The library knows two types of such loops, the default loop, which
341 supports child process events, and dynamically created event loops
342 which do not.
343
344 struct ev_loop *ev_default_loop (unsigned int flags)
345 This returns the "default" event loop object, which is what you
346 should normally use when you just need "the event loop". Event loop
347 objects and the "flags" parameter are described in more detail in
348 the entry for "ev_loop_new".
349
350 If the default loop is already initialised then this function
351 simply returns it (and ignores the flags. If that is troubling you,
352 check "ev_backend ()" afterwards). Otherwise it will create it with
353 the given flags, which should almost always be 0, unless the caller
354 is also the one calling "ev_run" or otherwise qualifies as "the
355 main program".
356
357 If you don't know what event loop to use, use the one returned from
358 this function (or via the "EV_DEFAULT" macro).
359
360 Note that this function is not thread-safe, so if you want to use
361 it from multiple threads, you have to employ some kind of mutex
362 (note also that this case is unlikely, as loops cannot be shared
363 easily between threads anyway).
364
365 The default loop is the only loop that can handle "ev_child"
366 watchers, and to do this, it always registers a handler for
367 "SIGCHLD". If this is a problem for your application you can either
368 create a dynamic loop with "ev_loop_new" which doesn't do that, or
369 you can simply overwrite the "SIGCHLD" signal handler after calling
370 "ev_default_init".
371
372 Example: This is the most typical usage.
373
374 if (!ev_default_loop (0))
375 fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?");
376
377 Example: Restrict libev to the select and poll backends, and do not
378 allow environment settings to be taken into account:
379
380 ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV);
381
382 struct ev_loop *ev_loop_new (unsigned int flags)
383 This will create and initialise a new event loop object. If the
384 loop could not be initialised, returns false.
385
386 This function is thread-safe, and one common way to use libev with
387 threads is indeed to create one loop per thread, and using the
388 default loop in the "main" or "initial" thread.
389
390 The flags argument can be used to specify special behaviour or
391 specific backends to use, and is usually specified as 0 (or
392 "EVFLAG_AUTO").
393
394 The following flags are supported:
395
396 "EVFLAG_AUTO"
397 The default flags value. Use this if you have no clue (it's the
398 right thing, believe me).
399
400 "EVFLAG_NOENV"
401 If this flag bit is or'ed into the flag value (or the program
402 runs setuid or setgid) then libev will not look at the
403 environment variable "LIBEV_FLAGS". Otherwise (the default),
404 this environment variable will override the flags completely if
405 it is found in the environment. This is useful to try out
406 specific backends to test their performance, to work around
407 bugs, or to make libev threadsafe (accessing environment
408 variables cannot be done in a threadsafe way, but usually it
409 works if no other thread modifies them).
410
411 "EVFLAG_FORKCHECK"
412 Instead of calling "ev_loop_fork" manually after a fork, you
413 can also make libev check for a fork in each iteration by
414 enabling this flag.
415
416 This works by calling "getpid ()" on every iteration of the
417 loop, and thus this might slow down your event loop if you do a
418 lot of loop iterations and little real work, but is usually not
419 noticeable (on my GNU/Linux system for example, "getpid" is
420 actually a simple 5-insn sequence without a system call and
421 thus very fast, but my GNU/Linux system also has
422 "pthread_atfork" which is even faster). (Update: glibc versions
423 2.25 apparently removed the "getpid" optimisation again).
424
425 The big advantage of this flag is that you can forget about
426 fork (and forget about forgetting to tell libev about forking,
427 although you still have to ignore "SIGPIPE") when you use this
428 flag.
429
430 This flag setting cannot be overridden or specified in the
431 "LIBEV_FLAGS" environment variable.
432
433 "EVFLAG_NOINOTIFY"
434 When this flag is specified, then libev will not attempt to use
435 the inotify API for its "ev_stat" watchers. Apart from
436 debugging and testing, this flag can be useful to conserve
437 inotify file descriptors, as otherwise each loop using
438 "ev_stat" watchers consumes one inotify handle.
439
440 "EVFLAG_SIGNALFD"
441 When this flag is specified, then libev will attempt to use the
442 signalfd API for its "ev_signal" (and "ev_child") watchers.
443 This API delivers signals synchronously, which makes it both
444 faster and might make it possible to get the queued signal
445 data. It can also simplify signal handling with threads, as
446 long as you properly block signals in your threads that are not
447 interested in handling them.
448
449 Signalfd will not be used by default as this changes your
450 signal mask, and there are a lot of shoddy libraries and
451 programs (glib's threadpool for example) that can't properly
452 initialise their signal masks.
453
454 "EVFLAG_NOSIGMASK"
455 When this flag is specified, then libev will avoid to modify
456 the signal mask. Specifically, this means you have to make sure
457 signals are unblocked when you want to receive them.
458
459 This behaviour is useful when you want to do your own signal
460 handling, or want to handle signals only in specific threads
461 and want to avoid libev unblocking the signals.
462
463 It's also required by POSIX in a threaded program, as libev
464 calls "sigprocmask", whose behaviour is officially unspecified.
465
466 "EVFLAG_NOTIMERFD"
467 When this flag is specified, the libev will avoid using a
468 "timerfd" to detect time jumps. It will still be able to detect
469 time jumps, but takes longer and has a lower accuracy in doing
470 so, but saves a file descriptor per loop.
471
472 The current implementation only tries to use a "timerfd" when
473 the first "ev_periodic" watcher is started and falls back on
474 other methods if it cannot be created, but this behaviour might
475 change in the future.
476
477 "EVBACKEND_SELECT" (value 1, portable select backend)
478 This is your standard select(2) backend. Not completely
479 standard, as libev tries to roll its own fd_set with no limits
480 on the number of fds, but if that fails, expect a fairly low
481 limit on the number of fds when using this backend. It doesn't
482 scale too well (O(highest_fd)), but its usually the fastest
483 backend for a low number of (low-numbered :) fds.
484
485 To get good performance out of this backend you need a high
486 amount of parallelism (most of the file descriptors should be
487 busy). If you are writing a server, you should "accept ()" in a
488 loop to accept as many connections as possible during one
489 iteration. You might also want to have a look at
490 "ev_set_io_collect_interval ()" to increase the amount of
491 readiness notifications you get per iteration.
492
493 This backend maps "EV_READ" to the "readfds" set and "EV_WRITE"
494 to the "writefds" set (and to work around Microsoft Windows
495 bugs, also onto the "exceptfds" set on that platform).
496
497 "EVBACKEND_POLL" (value 2, poll backend, available everywhere
498 except on windows)
499 And this is your standard poll(2) backend. It's more
500 complicated than select, but handles sparse fds better and has
501 no artificial limit on the number of fds you can use (except it
502 will slow down considerably with a lot of inactive fds). It
503 scales similarly to select, i.e. O(total_fds). See the entry
504 for "EVBACKEND_SELECT", above, for performance tips.
505
506 This backend maps "EV_READ" to "POLLIN | POLLERR | POLLHUP",
507 and "EV_WRITE" to "POLLOUT | POLLERR | POLLHUP".
508
509 "EVBACKEND_EPOLL" (value 4, Linux)
510 Use the Linux-specific epoll(7) interface (for both pre- and
511 post-2.6.9 kernels).
512
513 For few fds, this backend is a bit little slower than poll and
514 select, but it scales phenomenally better. While poll and
515 select usually scale like O(total_fds) where total_fds is the
516 total number of fds (or the highest fd), epoll scales either
517 O(1) or O(active_fds).
518
519 The epoll mechanism deserves honorable mention as the most
520 misdesigned of the more advanced event mechanisms: mere
521 annoyances include silently dropping file descriptors,
522 requiring a system call per change per file descriptor (and
523 unnecessary guessing of parameters), problems with dup,
524 returning before the timeout value, resulting in additional
525 iterations (and only giving 5ms accuracy while select on the
526 same platform gives 0.1ms) and so on. The biggest issue is fork
527 races, however - if a program forks then both parent and child
528 process have to recreate the epoll set, which can take
529 considerable time (one syscall per file descriptor) and is of
530 course hard to detect.
531
532 Epoll is also notoriously buggy - embedding epoll fds should
533 work, but of course doesn't, and epoll just loves to report
534 events for totally different file descriptors (even already
535 closed ones, so one cannot even remove them from the set) than
536 registered in the set (especially on SMP systems). Libev tries
537 to counter these spurious notifications by employing an
538 additional generation counter and comparing that against the
539 events to filter out spurious ones, recreating the set when
540 required. Epoll also erroneously rounds down timeouts, but
541 gives you no way to know when and by how much, so sometimes you
542 have to busy-wait because epoll returns immediately despite a
543 nonzero timeout. And last not least, it also refuses to work
544 with some file descriptors which work perfectly fine with
545 "select" (files, many character devices...).
546
547 Epoll is truly the train wreck among event poll mechanisms, a
548 frankenpoll, cobbled together in a hurry, no thought to design
549 or interaction with others. Oh, the pain, will it ever stop...
550
551 While stopping, setting and starting an I/O watcher in the same
552 iteration will result in some caching, there is still a system
553 call per such incident (because the same file descriptor could
554 point to a different file description now), so its best to
555 avoid that. Also, "dup ()"'ed file descriptors might not work
556 very well if you register events for both file descriptors.
557
558 Best performance from this backend is achieved by not
559 unregistering all watchers for a file descriptor until it has
560 been closed, if possible, i.e. keep at least one watcher active
561 per fd at all times. Stopping and starting a watcher (without
562 re-setting it) also usually doesn't cause extra overhead. A
563 fork can both result in spurious notifications as well as in
564 libev having to destroy and recreate the epoll object, which
565 can take considerable time and thus should be avoided.
566
567 All this means that, in practice, "EVBACKEND_SELECT" can be as
568 fast or faster than epoll for maybe up to a hundred file
569 descriptors, depending on the usage. So sad.
570
571 While nominally embeddable in other event loops, this feature
572 is broken in a lot of kernel revisions, but probably(!) works
573 in current versions.
574
575 This backend maps "EV_READ" and "EV_WRITE" in the same way as
576 "EVBACKEND_POLL".
577
578 "EVBACKEND_LINUXAIO" (value 64, Linux)
579 Use the Linux-specific Linux AIO (not aio(7) but io_submit(2))
580 event interface available in post-4.18 kernels (but libev only
581 tries to use it in 4.19+).
582
583 This is another Linux train wreck of an event interface.
584
585 If this backend works for you (as of this writing, it was very
586 experimental), it is the best event interface available on
587 Linux and might be well worth enabling it - if it isn't
588 available in your kernel this will be detected and this backend
589 will be skipped.
590
591 This backend can batch oneshot requests and supports a user-
592 space ring buffer to receive events. It also doesn't suffer
593 from most of the design problems of epoll (such as not being
594 able to remove event sources from the epoll set), and generally
595 sounds too good to be true. Because, this being the Linux
596 kernel, of course it suffers from a whole new set of
597 limitations, forcing you to fall back to epoll, inheriting all
598 its design issues.
599
600 For one, it is not easily embeddable (but probably could be
601 done using an event fd at some extra overhead). It also is
602 subject to a system wide limit that can be configured in
603 /proc/sys/fs/aio-max-nr. If no AIO requests are left, this
604 backend will be skipped during initialisation, and will switch
605 to epoll when the loop is active.
606
607 Most problematic in practice, however, is that not all file
608 descriptors work with it. For example, in Linux 5.1, TCP
609 sockets, pipes, event fds, files, /dev/null and many others are
610 supported, but ttys do not work properly (a known bug that the
611 kernel developers don't care about, see
612 <https://lore.kernel.org/patchwork/patch/1047453/>), so this is
613 not (yet?) a generic event polling interface.
614
615 Overall, it seems the Linux developers just don't want it to
616 have a generic event handling mechanism other than "select" or
617 "poll".
618
619 To work around all these problem, the current version of libev
620 uses its epoll backend as a fallback for file descriptor types
621 that do not work. Or falls back completely to epoll if the
622 kernel acts up.
623
624 This backend maps "EV_READ" and "EV_WRITE" in the same way as
625 "EVBACKEND_POLL".
626
627 "EVBACKEND_KQUEUE" (value 8, most BSD clones)
628 Kqueue deserves special mention, as at the time this backend
629 was implemented, it was broken on all BSDs except NetBSD
630 (usually it doesn't work reliably with anything but sockets and
631 pipes, except on Darwin, where of course it's completely
632 useless). Unlike epoll, however, whose brokenness is by design,
633 these kqueue bugs can be (and mostly have been) fixed without
634 API changes to existing programs. For this reason it's not
635 being "auto-detected" on all platforms unless you explicitly
636 specify it in the flags (i.e. using "EVBACKEND_KQUEUE") or
637 libev was compiled on a known-to-be-good (-enough) system like
638 NetBSD.
639
640 You still can embed kqueue into a normal poll or select backend
641 and use it only for sockets (after having made sure that
642 sockets work with kqueue on the target platform). See
643 "ev_embed" watchers for more info.
644
645 It scales in the same way as the epoll backend, but the
646 interface to the kernel is more efficient (which says nothing
647 about its actual speed, of course). While stopping, setting and
648 starting an I/O watcher does never cause an extra system call
649 as with "EVBACKEND_EPOLL", it still adds up to two event
650 changes per incident. Support for "fork ()" is very bad (you
651 might have to leak fds on fork, but it's more sane than epoll)
652 and it drops fds silently in similarly hard-to-detect cases.
653
654 This backend usually performs well under most conditions.
655
656 While nominally embeddable in other event loops, this doesn't
657 work everywhere, so you might need to test for this. And since
658 it is broken almost everywhere, you should only use it when you
659 have a lot of sockets (for which it usually works), by
660 embedding it into another event loop (e.g. "EVBACKEND_SELECT"
661 or "EVBACKEND_POLL" (but "poll" is of course also broken on OS
662 X)) and, did I mention it, using it only for sockets.
663
664 This backend maps "EV_READ" into an "EVFILT_READ" kevent with
665 "NOTE_EOF", and "EV_WRITE" into an "EVFILT_WRITE" kevent with
666 "NOTE_EOF".
667
668 "EVBACKEND_DEVPOLL" (value 16, Solaris 8)
669 This is not implemented yet (and might never be, unless you
670 send me an implementation). According to reports, "/dev/poll"
671 only supports sockets and is not embeddable, which would limit
672 the usefulness of this backend immensely.
673
674 "EVBACKEND_PORT" (value 32, Solaris 10)
675 This uses the Solaris 10 event port mechanism. As with
676 everything on Solaris, it's really slow, but it still scales
677 very well (O(active_fds)).
678
679 While this backend scales well, it requires one system call per
680 active file descriptor per loop iteration. For small and medium
681 numbers of file descriptors a "slow" "EVBACKEND_SELECT" or
682 "EVBACKEND_POLL" backend might perform better.
683
684 On the positive side, this backend actually performed fully to
685 specification in all tests and is fully embeddable, which is a
686 rare feat among the OS-specific backends (I vastly prefer
687 correctness over speed hacks).
688
689 On the negative side, the interface is bizarre - so bizarre
690 that even sun itself gets it wrong in their code examples: The
691 event polling function sometimes returns events to the caller
692 even though an error occurred, but with no indication whether
693 it has done so or not (yes, it's even documented that way) -
694 deadly for edge-triggered interfaces where you absolutely have
695 to know whether an event occurred or not because you have to
696 re-arm the watcher.
697
698 Fortunately libev seems to be able to work around these
699 idiocies.
700
701 This backend maps "EV_READ" and "EV_WRITE" in the same way as
702 "EVBACKEND_POLL".
703
704 "EVBACKEND_ALL"
705 Try all backends (even potentially broken ones that wouldn't be
706 tried with "EVFLAG_AUTO"). Since this is a mask, you can do
707 stuff such as "EVBACKEND_ALL & ~EVBACKEND_KQUEUE".
708
709 It is definitely not recommended to use this flag, use whatever
710 "ev_recommended_backends ()" returns, or simply do not specify
711 a backend at all.
712
713 "EVBACKEND_MASK"
714 Not a backend at all, but a mask to select all backend bits
715 from a "flags" value, in case you want to mask out any backends
716 from a flags value (e.g. when modifying the "LIBEV_FLAGS"
717 environment variable).
718
719 If one or more of the backend flags are or'ed into the flags value,
720 then only these backends will be tried (in the reverse order as
721 listed here). If none are specified, all backends in
722 "ev_recommended_backends ()" will be tried.
723
724 Example: Try to create a event loop that uses epoll and nothing
725 else.
726
727 struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV);
728 if (!epoller)
729 fatal ("no epoll found here, maybe it hides under your chair");
730
731 Example: Use whatever libev has to offer, but make sure that kqueue
732 is used if available.
733
734 struct ev_loop *loop = ev_loop_new (ev_recommended_backends () | EVBACKEND_KQUEUE);
735
736 Example: Similarly, on linux, you mgiht want to take advantage of
737 the linux aio backend if possible, but fall back to something else
738 if that isn't available.
739
740 struct ev_loop *loop = ev_loop_new (ev_recommended_backends () | EVBACKEND_LINUXAIO);
741
742 ev_loop_destroy (loop)
743 Destroys an event loop object (frees all memory and kernel state
744 etc.). None of the active event watchers will be stopped in the
745 normal sense, so e.g. "ev_is_active" might still return true. It is
746 your responsibility to either stop all watchers cleanly yourself
747 before calling this function, or cope with the fact afterwards
748 (which is usually the easiest thing, you can just ignore the
749 watchers and/or "free ()" them for example).
750
751 Note that certain global state, such as signal state (and installed
752 signal handlers), will not be freed by this function, and related
753 watchers (such as signal and child watchers) would need to be
754 stopped manually.
755
756 This function is normally used on loop objects allocated by
757 "ev_loop_new", but it can also be used on the default loop returned
758 by "ev_default_loop", in which case it is not thread-safe.
759
760 Note that it is not advisable to call this function on the default
761 loop except in the rare occasion where you really need to free its
762 resources. If you need dynamically allocated loops it is better to
763 use "ev_loop_new" and "ev_loop_destroy".
764
765 ev_loop_fork (loop)
766 This function sets a flag that causes subsequent "ev_run"
767 iterations to reinitialise the kernel state for backends that have
768 one. Despite the name, you can call it anytime you are allowed to
769 start or stop watchers (except inside an "ev_prepare" callback),
770 but it makes most sense after forking, in the child process. You
771 must call it (or use "EVFLAG_FORKCHECK") in the child before
772 resuming or calling "ev_run".
773
774 In addition, if you want to reuse a loop (via this function or
775 "EVFLAG_FORKCHECK"), you also have to ignore "SIGPIPE".
776
777 Again, you have to call it on any loop that you want to re-use
778 after a fork, even if you do not plan to use the loop in the
779 parent. This is because some kernel interfaces *cough* kqueue
780 *cough* do funny things during fork.
781
782 On the other hand, you only need to call this function in the child
783 process if and only if you want to use the event loop in the child.
784 If you just fork+exec or create a new loop in the child, you don't
785 have to call it at all (in fact, "epoll" is so badly broken that it
786 makes a difference, but libev will usually detect this case on its
787 own and do a costly reset of the backend).
788
789 The function itself is quite fast and it's usually not a problem to
790 call it just in case after a fork.
791
792 Example: Automate calling "ev_loop_fork" on the default loop when
793 using pthreads.
794
795 static void
796 post_fork_child (void)
797 {
798 ev_loop_fork (EV_DEFAULT);
799 }
800
801 ...
802 pthread_atfork (0, 0, post_fork_child);
803
804 int ev_is_default_loop (loop)
805 Returns true when the given loop is, in fact, the default loop, and
806 false otherwise.
807
808 unsigned int ev_iteration (loop)
809 Returns the current iteration count for the event loop, which is
810 identical to the number of times libev did poll for new events. It
811 starts at 0 and happily wraps around with enough iterations.
812
813 This value can sometimes be useful as a generation counter of sorts
814 (it "ticks" the number of loop iterations), as it roughly
815 corresponds with "ev_prepare" and "ev_check" calls - and is
816 incremented between the prepare and check phases.
817
818 unsigned int ev_depth (loop)
819 Returns the number of times "ev_run" was entered minus the number
820 of times "ev_run" was exited normally, in other words, the
821 recursion depth.
822
823 Outside "ev_run", this number is zero. In a callback, this number
824 is 1, unless "ev_run" was invoked recursively (or from another
825 thread), in which case it is higher.
826
827 Leaving "ev_run" abnormally (setjmp/longjmp, cancelling the thread,
828 throwing an exception etc.), doesn't count as "exit" - consider
829 this as a hint to avoid such ungentleman-like behaviour unless it's
830 really convenient, in which case it is fully supported.
831
832 unsigned int ev_backend (loop)
833 Returns one of the "EVBACKEND_*" flags indicating the event backend
834 in use.
835
836 ev_tstamp ev_now (loop)
837 Returns the current "event loop time", which is the time the event
838 loop received events and started processing them. This timestamp
839 does not change as long as callbacks are being processed, and this
840 is also the base time used for relative timers. You can treat it as
841 the timestamp of the event occurring (or more correctly, libev
842 finding out about it).
843
844 ev_now_update (loop)
845 Establishes the current time by querying the kernel, updating the
846 time returned by "ev_now ()" in the progress. This is a costly
847 operation and is usually done automatically within "ev_run ()".
848
849 This function is rarely useful, but when some event callback runs
850 for a very long time without entering the event loop, updating
851 libev's idea of the current time is a good idea.
852
853 See also "The special problem of time updates" in the "ev_timer"
854 section.
855
856 ev_suspend (loop)
857 ev_resume (loop)
858 These two functions suspend and resume an event loop, for use when
859 the loop is not used for a while and timeouts should not be
860 processed.
861
862 A typical use case would be an interactive program such as a game:
863 When the user presses "^Z" to suspend the game and resumes it an
864 hour later it would be best to handle timeouts as if no time had
865 actually passed while the program was suspended. This can be
866 achieved by calling "ev_suspend" in your "SIGTSTP" handler, sending
867 yourself a "SIGSTOP" and calling "ev_resume" directly afterwards to
868 resume timer processing.
869
870 Effectively, all "ev_timer" watchers will be delayed by the time
871 spend between "ev_suspend" and "ev_resume", and all "ev_periodic"
872 watchers will be rescheduled (that is, they will lose any events
873 that would have occurred while suspended).
874
875 After calling "ev_suspend" you must not call any function on the
876 given loop other than "ev_resume", and you must not call
877 "ev_resume" without a previous call to "ev_suspend".
878
879 Calling "ev_suspend"/"ev_resume" has the side effect of updating
880 the event loop time (see "ev_now_update").
881
882 bool ev_run (loop, int flags)
883 Finally, this is it, the event handler. This function usually is
884 called after you have initialised all your watchers and you want to
885 start handling events. It will ask the operating system for any new
886 events, call the watcher callbacks, and then repeat the whole
887 process indefinitely: This is why event loops are called loops.
888
889 If the flags argument is specified as 0, it will keep handling
890 events until either no event watchers are active anymore or
891 "ev_break" was called.
892
893 The return value is false if there are no more active watchers
894 (which usually means "all jobs done" or "deadlock"), and true in
895 all other cases (which usually means " you should call "ev_run"
896 again").
897
898 Please note that an explicit "ev_break" is usually better than
899 relying on all watchers to be stopped when deciding when a program
900 has finished (especially in interactive programs), but having a
901 program that automatically loops as long as it has to and no longer
902 by virtue of relying on its watchers stopping correctly, that is
903 truly a thing of beauty.
904
905 This function is mostly exception-safe - you can break out of a
906 "ev_run" call by calling "longjmp" in a callback, throwing a C++
907 exception and so on. This does not decrement the "ev_depth" value,
908 nor will it clear any outstanding "EVBREAK_ONE" breaks.
909
910 A flags value of "EVRUN_NOWAIT" will look for new events, will
911 handle those events and any already outstanding ones, but will not
912 wait and block your process in case there are no events and will
913 return after one iteration of the loop. This is sometimes useful to
914 poll and handle new events while doing lengthy calculations, to
915 keep the program responsive.
916
917 A flags value of "EVRUN_ONCE" will look for new events (waiting if
918 necessary) and will handle those and any already outstanding ones.
919 It will block your process until at least one new event arrives
920 (which could be an event internal to libev itself, so there is no
921 guarantee that a user-registered callback will be called), and will
922 return after one iteration of the loop.
923
924 This is useful if you are waiting for some external event in
925 conjunction with something not expressible using other libev
926 watchers (i.e. "roll your own "ev_run""). However, a pair of
927 "ev_prepare"/"ev_check" watchers is usually a better approach for
928 this kind of thing.
929
930 Here are the gory details of what "ev_run" does (this is for your
931 understanding, not a guarantee that things will work exactly like
932 this in future versions):
933
934 - Increment loop depth.
935 - Reset the ev_break status.
936 - Before the first iteration, call any pending watchers.
937 LOOP:
938 - If EVFLAG_FORKCHECK was used, check for a fork.
939 - If a fork was detected (by any means), queue and call all fork watchers.
940 - Queue and call all prepare watchers.
941 - If ev_break was called, goto FINISH.
942 - If we have been forked, detach and recreate the kernel state
943 as to not disturb the other process.
944 - Update the kernel state with all outstanding changes.
945 - Update the "event loop time" (ev_now ()).
946 - Calculate for how long to sleep or block, if at all
947 (active idle watchers, EVRUN_NOWAIT or not having
948 any active watchers at all will result in not sleeping).
949 - Sleep if the I/O and timer collect interval say so.
950 - Increment loop iteration counter.
951 - Block the process, waiting for any events.
952 - Queue all outstanding I/O (fd) events.
953 - Update the "event loop time" (ev_now ()), and do time jump adjustments.
954 - Queue all expired timers.
955 - Queue all expired periodics.
956 - Queue all idle watchers with priority higher than that of pending events.
957 - Queue all check watchers.
958 - Call all queued watchers in reverse order (i.e. check watchers first).
959 Signals and child watchers are implemented as I/O watchers, and will
960 be handled here by queueing them when their watcher gets executed.
961 - If ev_break has been called, or EVRUN_ONCE or EVRUN_NOWAIT
962 were used, or there are no active watchers, goto FINISH, otherwise
963 continue with step LOOP.
964 FINISH:
965 - Reset the ev_break status iff it was EVBREAK_ONE.
966 - Decrement the loop depth.
967 - Return.
968
969 Example: Queue some jobs and then loop until no events are
970 outstanding anymore.
971
972 ... queue jobs here, make sure they register event watchers as long
973 ... as they still have work to do (even an idle watcher will do..)
974 ev_run (my_loop, 0);
975 ... jobs done or somebody called break. yeah!
976
977 ev_break (loop, how)
978 Can be used to make a call to "ev_run" return early (but only after
979 it has processed all outstanding events). The "how" argument must
980 be either "EVBREAK_ONE", which will make the innermost "ev_run"
981 call return, or "EVBREAK_ALL", which will make all nested "ev_run"
982 calls return.
983
984 This "break state" will be cleared on the next call to "ev_run".
985
986 It is safe to call "ev_break" from outside any "ev_run" calls, too,
987 in which case it will have no effect.
988
989 ev_ref (loop)
990 ev_unref (loop)
991 Ref/unref can be used to add or remove a reference count on the
992 event loop: Every watcher keeps one reference, and as long as the
993 reference count is nonzero, "ev_run" will not return on its own.
994
995 This is useful when you have a watcher that you never intend to
996 unregister, but that nevertheless should not keep "ev_run" from
997 returning. In such a case, call "ev_unref" after starting, and
998 "ev_ref" before stopping it.
999
1000 As an example, libev itself uses this for its internal signal pipe:
1001 It is not visible to the libev user and should not keep "ev_run"
1002 from exiting if no event watchers registered by it are active. It
1003 is also an excellent way to do this for generic recurring timers or
1004 from within third-party libraries. Just remember to unref after
1005 start and ref before stop (but only if the watcher wasn't active
1006 before, or was active before, respectively. Note also that libev
1007 might stop watchers itself (e.g. non-repeating timers) in which
1008 case you have to "ev_ref" in the callback).
1009
1010 Example: Create a signal watcher, but keep it from keeping "ev_run"
1011 running when nothing else is active.
1012
1013 ev_signal exitsig;
1014 ev_signal_init (&exitsig, sig_cb, SIGINT);
1015 ev_signal_start (loop, &exitsig);
1016 ev_unref (loop);
1017
1018 Example: For some weird reason, unregister the above signal handler
1019 again.
1020
1021 ev_ref (loop);
1022 ev_signal_stop (loop, &exitsig);
1023
1024 ev_set_io_collect_interval (loop, ev_tstamp interval)
1025 ev_set_timeout_collect_interval (loop, ev_tstamp interval)
1026 These advanced functions influence the time that libev will spend
1027 waiting for events. Both time intervals are by default 0, meaning
1028 that libev will try to invoke timer/periodic callbacks and I/O
1029 callbacks with minimum latency.
1030
1031 Setting these to a higher value (the "interval" must be >= 0)
1032 allows libev to delay invocation of I/O and timer/periodic
1033 callbacks to increase efficiency of loop iterations (or to increase
1034 power-saving opportunities).
1035
1036 The idea is that sometimes your program runs just fast enough to
1037 handle one (or very few) event(s) per loop iteration. While this
1038 makes the program responsive, it also wastes a lot of CPU time to
1039 poll for new events, especially with backends like "select ()"
1040 which have a high overhead for the actual polling but can deliver
1041 many events at once.
1042
1043 By setting a higher io collect interval you allow libev to spend
1044 more time collecting I/O events, so you can handle more events per
1045 iteration, at the cost of increasing latency. Timeouts (both
1046 "ev_periodic" and "ev_timer") will not be affected. Setting this to
1047 a non-null value will introduce an additional "ev_sleep ()" call
1048 into most loop iterations. The sleep time ensures that libev will
1049 not poll for I/O events more often then once per this interval, on
1050 average (as long as the host time resolution is good enough).
1051
1052 Likewise, by setting a higher timeout collect interval you allow
1053 libev to spend more time collecting timeouts, at the expense of
1054 increased latency/jitter/inexactness (the watcher callback will be
1055 called later). "ev_io" watchers will not be affected. Setting this
1056 to a non-null value will not introduce any overhead in libev.
1057
1058 Many (busy) programs can usually benefit by setting the I/O collect
1059 interval to a value near 0.1 or so, which is often enough for
1060 interactive servers (of course not for games), likewise for
1061 timeouts. It usually doesn't make much sense to set it to a lower
1062 value than 0.01, as this approaches the timing granularity of most
1063 systems. Note that if you do transactions with the outside world
1064 and you can't increase the parallelity, then this setting will
1065 limit your transaction rate (if you need to poll once per
1066 transaction and the I/O collect interval is 0.01, then you can't do
1067 more than 100 transactions per second).
1068
1069 Setting the timeout collect interval can improve the opportunity
1070 for saving power, as the program will "bundle" timer callback
1071 invocations that are "near" in time together, by delaying some,
1072 thus reducing the number of times the process sleeps and wakes up
1073 again. Another useful technique to reduce iterations/wake-ups is to
1074 use "ev_periodic" watchers and make sure they fire on, say, one-
1075 second boundaries only.
1076
1077 Example: we only need 0.1s timeout granularity, and we wish not to
1078 poll more often than 100 times per second:
1079
1080 ev_set_timeout_collect_interval (EV_DEFAULT_UC_ 0.1);
1081 ev_set_io_collect_interval (EV_DEFAULT_UC_ 0.01);
1082
1083 ev_invoke_pending (loop)
1084 This call will simply invoke all pending watchers while resetting
1085 their pending state. Normally, "ev_run" does this automatically
1086 when required, but when overriding the invoke callback this call
1087 comes handy. This function can be invoked from a watcher - this can
1088 be useful for example when you want to do some lengthy calculation
1089 and want to pass further event handling to another thread (you
1090 still have to make sure only one thread executes within
1091 "ev_invoke_pending" or "ev_run" of course).
1092
1093 int ev_pending_count (loop)
1094 Returns the number of pending watchers - zero indicates that no
1095 watchers are pending.
1096
1097 ev_set_invoke_pending_cb (loop, void (*invoke_pending_cb)(EV_P))
1098 This overrides the invoke pending functionality of the loop:
1099 Instead of invoking all pending watchers when there are any,
1100 "ev_run" will call this callback instead. This is useful, for
1101 example, when you want to invoke the actual watchers inside another
1102 context (another thread etc.).
1103
1104 If you want to reset the callback, use "ev_invoke_pending" as new
1105 callback.
1106
1107 ev_set_loop_release_cb (loop, void (*release)(EV_P) throw (), void
1108 (*acquire)(EV_P) throw ())
1109 Sometimes you want to share the same loop between multiple threads.
1110 This can be done relatively simply by putting mutex_lock/unlock
1111 calls around each call to a libev function.
1112
1113 However, "ev_run" can run an indefinite time, so it is not feasible
1114 to wait for it to return. One way around this is to wake up the
1115 event loop via "ev_break" and "ev_async_send", another way is to
1116 set these release and acquire callbacks on the loop.
1117
1118 When set, then "release" will be called just before the thread is
1119 suspended waiting for new events, and "acquire" is called just
1120 afterwards.
1121
1122 Ideally, "release" will just call your mutex_unlock function, and
1123 "acquire" will just call the mutex_lock function again.
1124
1125 While event loop modifications are allowed between invocations of
1126 "release" and "acquire" (that's their only purpose after all), no
1127 modifications done will affect the event loop, i.e. adding watchers
1128 will have no effect on the set of file descriptors being watched,
1129 or the time waited. Use an "ev_async" watcher to wake up "ev_run"
1130 when you want it to take note of any changes you made.
1131
1132 In theory, threads executing "ev_run" will be async-cancel safe
1133 between invocations of "release" and "acquire".
1134
1135 See also the locking example in the "THREADS" section later in this
1136 document.
1137
1138 ev_set_userdata (loop, void *data)
1139 void *ev_userdata (loop)
1140 Set and retrieve a single "void *" associated with a loop. When
1141 "ev_set_userdata" has never been called, then "ev_userdata" returns
1142 0.
1143
1144 These two functions can be used to associate arbitrary data with a
1145 loop, and are intended solely for the "invoke_pending_cb",
1146 "release" and "acquire" callbacks described above, but of course
1147 can be (ab-)used for any other purpose as well.
1148
1149 ev_verify (loop)
1150 This function only does something when "EV_VERIFY" support has been
1151 compiled in, which is the default for non-minimal builds. It tries
1152 to go through all internal structures and checks them for validity.
1153 If anything is found to be inconsistent, it will print an error
1154 message to standard error and call "abort ()".
1155
1156 This can be used to catch bugs inside libev itself: under normal
1157 circumstances, this function will never abort as of course libev
1158 keeps its data structures consistent.
1159
1161 In the following description, uppercase "TYPE" in names stands for the
1162 watcher type, e.g. "ev_TYPE_start" can mean "ev_timer_start" for timer
1163 watchers and "ev_io_start" for I/O watchers.
1164
1165 A watcher is an opaque structure that you allocate and register to
1166 record your interest in some event. To make a concrete example, imagine
1167 you want to wait for STDIN to become readable, you would create an
1168 "ev_io" watcher for that:
1169
1170 static void my_cb (struct ev_loop *loop, ev_io *w, int revents)
1171 {
1172 ev_io_stop (w);
1173 ev_break (loop, EVBREAK_ALL);
1174 }
1175
1176 struct ev_loop *loop = ev_default_loop (0);
1177
1178 ev_io stdin_watcher;
1179
1180 ev_init (&stdin_watcher, my_cb);
1181 ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ);
1182 ev_io_start (loop, &stdin_watcher);
1183
1184 ev_run (loop, 0);
1185
1186 As you can see, you are responsible for allocating the memory for your
1187 watcher structures (and it is usually a bad idea to do this on the
1188 stack).
1189
1190 Each watcher has an associated watcher structure (called "struct
1191 ev_TYPE" or simply "ev_TYPE", as typedefs are provided for all watcher
1192 structs).
1193
1194 Each watcher structure must be initialised by a call to "ev_init
1195 (watcher *, callback)", which expects a callback to be provided. This
1196 callback is invoked each time the event occurs (or, in the case of I/O
1197 watchers, each time the event loop detects that the file descriptor
1198 given is readable and/or writable).
1199
1200 Each watcher type further has its own "ev_TYPE_set (watcher *, ...)"
1201 macro to configure it, with arguments specific to the watcher type.
1202 There is also a macro to combine initialisation and setting in one
1203 call: "ev_TYPE_init (watcher *, callback, ...)".
1204
1205 To make the watcher actually watch out for events, you have to start it
1206 with a watcher-specific start function ("ev_TYPE_start (loop, watcher
1207 *)"), and you can stop watching for events at any time by calling the
1208 corresponding stop function ("ev_TYPE_stop (loop, watcher *)".
1209
1210 As long as your watcher is active (has been started but not stopped)
1211 you must not touch the values stored in it. Most specifically you must
1212 never reinitialise it or call its "ev_TYPE_set" macro.
1213
1214 Each and every callback receives the event loop pointer as first, the
1215 registered watcher structure as second, and a bitset of received events
1216 as third argument.
1217
1218 The received events usually include a single bit per event type
1219 received (you can receive multiple events at the same time). The
1220 possible bit masks are:
1221
1222 "EV_READ"
1223 "EV_WRITE"
1224 The file descriptor in the "ev_io" watcher has become readable
1225 and/or writable.
1226
1227 "EV_TIMER"
1228 The "ev_timer" watcher has timed out.
1229
1230 "EV_PERIODIC"
1231 The "ev_periodic" watcher has timed out.
1232
1233 "EV_SIGNAL"
1234 The signal specified in the "ev_signal" watcher has been received
1235 by a thread.
1236
1237 "EV_CHILD"
1238 The pid specified in the "ev_child" watcher has received a status
1239 change.
1240
1241 "EV_STAT"
1242 The path specified in the "ev_stat" watcher changed its attributes
1243 somehow.
1244
1245 "EV_IDLE"
1246 The "ev_idle" watcher has determined that you have nothing better
1247 to do.
1248
1249 "EV_PREPARE"
1250 "EV_CHECK"
1251 All "ev_prepare" watchers are invoked just before "ev_run" starts
1252 to gather new events, and all "ev_check" watchers are queued (not
1253 invoked) just after "ev_run" has gathered them, but before it
1254 queues any callbacks for any received events. That means
1255 "ev_prepare" watchers are the last watchers invoked before the
1256 event loop sleeps or polls for new events, and "ev_check" watchers
1257 will be invoked before any other watchers of the same or lower
1258 priority within an event loop iteration.
1259
1260 Callbacks of both watcher types can start and stop as many watchers
1261 as they want, and all of them will be taken into account (for
1262 example, a "ev_prepare" watcher might start an idle watcher to keep
1263 "ev_run" from blocking).
1264
1265 "EV_EMBED"
1266 The embedded event loop specified in the "ev_embed" watcher needs
1267 attention.
1268
1269 "EV_FORK"
1270 The event loop has been resumed in the child process after fork
1271 (see "ev_fork").
1272
1273 "EV_CLEANUP"
1274 The event loop is about to be destroyed (see "ev_cleanup").
1275
1276 "EV_ASYNC"
1277 The given async watcher has been asynchronously notified (see
1278 "ev_async").
1279
1280 "EV_CUSTOM"
1281 Not ever sent (or otherwise used) by libev itself, but can be
1282 freely used by libev users to signal watchers (e.g. via
1283 "ev_feed_event").
1284
1285 "EV_ERROR"
1286 An unspecified error has occurred, the watcher has been stopped.
1287 This might happen because the watcher could not be properly started
1288 because libev ran out of memory, a file descriptor was found to be
1289 closed or any other problem. Libev considers these application
1290 bugs.
1291
1292 You best act on it by reporting the problem and somehow coping with
1293 the watcher being stopped. Note that well-written programs should
1294 not receive an error ever, so when your watcher receives it, this
1295 usually indicates a bug in your program.
1296
1297 Libev will usually signal a few "dummy" events together with an
1298 error, for example it might indicate that a fd is readable or
1299 writable, and if your callbacks is well-written it can just attempt
1300 the operation and cope with the error from read() or write(). This
1301 will not work in multi-threaded programs, though, as the fd could
1302 already be closed and reused for another thing, so beware.
1303
1304 GENERIC WATCHER FUNCTIONS
1305 "ev_init" (ev_TYPE *watcher, callback)
1306 This macro initialises the generic portion of a watcher. The
1307 contents of the watcher object can be arbitrary (so "malloc" will
1308 do). Only the generic parts of the watcher are initialised, you
1309 need to call the type-specific "ev_TYPE_set" macro afterwards to
1310 initialise the type-specific parts. For each type there is also a
1311 "ev_TYPE_init" macro which rolls both calls into one.
1312
1313 You can reinitialise a watcher at any time as long as it has been
1314 stopped (or never started) and there are no pending events
1315 outstanding.
1316
1317 The callback is always of type "void (*)(struct ev_loop *loop,
1318 ev_TYPE *watcher, int revents)".
1319
1320 Example: Initialise an "ev_io" watcher in two steps.
1321
1322 ev_io w;
1323 ev_init (&w, my_cb);
1324 ev_io_set (&w, STDIN_FILENO, EV_READ);
1325
1326 "ev_TYPE_set" (ev_TYPE *watcher, [args])
1327 This macro initialises the type-specific parts of a watcher. You
1328 need to call "ev_init" at least once before you call this macro,
1329 but you can call "ev_TYPE_set" any number of times. You must not,
1330 however, call this macro on a watcher that is active (it can be
1331 pending, however, which is a difference to the "ev_init" macro).
1332
1333 Although some watcher types do not have type-specific arguments
1334 (e.g. "ev_prepare") you still need to call its "set" macro.
1335
1336 See "ev_init", above, for an example.
1337
1338 "ev_TYPE_init" (ev_TYPE *watcher, callback, [args])
1339 This convenience macro rolls both "ev_init" and "ev_TYPE_set" macro
1340 calls into a single call. This is the most convenient method to
1341 initialise a watcher. The same limitations apply, of course.
1342
1343 Example: Initialise and set an "ev_io" watcher in one step.
1344
1345 ev_io_init (&w, my_cb, STDIN_FILENO, EV_READ);
1346
1347 "ev_TYPE_start" (loop, ev_TYPE *watcher)
1348 Starts (activates) the given watcher. Only active watchers will
1349 receive events. If the watcher is already active nothing will
1350 happen.
1351
1352 Example: Start the "ev_io" watcher that is being abused as example
1353 in this whole section.
1354
1355 ev_io_start (EV_DEFAULT_UC, &w);
1356
1357 "ev_TYPE_stop" (loop, ev_TYPE *watcher)
1358 Stops the given watcher if active, and clears the pending status
1359 (whether the watcher was active or not).
1360
1361 It is possible that stopped watchers are pending - for example,
1362 non-repeating timers are being stopped when they become pending -
1363 but calling "ev_TYPE_stop" ensures that the watcher is neither
1364 active nor pending. If you want to free or reuse the memory used by
1365 the watcher it is therefore a good idea to always call its
1366 "ev_TYPE_stop" function.
1367
1368 bool ev_is_active (ev_TYPE *watcher)
1369 Returns a true value iff the watcher is active (i.e. it has been
1370 started and not yet been stopped). As long as a watcher is active
1371 you must not modify it.
1372
1373 bool ev_is_pending (ev_TYPE *watcher)
1374 Returns a true value iff the watcher is pending, (i.e. it has
1375 outstanding events but its callback has not yet been invoked). As
1376 long as a watcher is pending (but not active) you must not call an
1377 init function on it (but "ev_TYPE_set" is safe), you must not
1378 change its priority, and you must make sure the watcher is
1379 available to libev (e.g. you cannot "free ()" it).
1380
1381 callback ev_cb (ev_TYPE *watcher)
1382 Returns the callback currently set on the watcher.
1383
1384 ev_set_cb (ev_TYPE *watcher, callback)
1385 Change the callback. You can change the callback at virtually any
1386 time (modulo threads).
1387
1388 ev_set_priority (ev_TYPE *watcher, int priority)
1389 int ev_priority (ev_TYPE *watcher)
1390 Set and query the priority of the watcher. The priority is a small
1391 integer between "EV_MAXPRI" (default: 2) and "EV_MINPRI" (default:
1392 "-2"). Pending watchers with higher priority will be invoked before
1393 watchers with lower priority, but priority will not keep watchers
1394 from being executed (except for "ev_idle" watchers).
1395
1396 If you need to suppress invocation when higher priority events are
1397 pending you need to look at "ev_idle" watchers, which provide this
1398 functionality.
1399
1400 You must not change the priority of a watcher as long as it is
1401 active or pending.
1402
1403 Setting a priority outside the range of "EV_MINPRI" to "EV_MAXPRI"
1404 is fine, as long as you do not mind that the priority value you
1405 query might or might not have been clamped to the valid range.
1406
1407 The default priority used by watchers when no priority has been set
1408 is always 0, which is supposed to not be too high and not be too
1409 low :).
1410
1411 See "WATCHER PRIORITY MODELS", below, for a more thorough treatment
1412 of priorities.
1413
1414 ev_invoke (loop, ev_TYPE *watcher, int revents)
1415 Invoke the "watcher" with the given "loop" and "revents". Neither
1416 "loop" nor "revents" need to be valid as long as the watcher
1417 callback can deal with that fact, as both are simply passed through
1418 to the callback.
1419
1420 int ev_clear_pending (loop, ev_TYPE *watcher)
1421 If the watcher is pending, this function clears its pending status
1422 and returns its "revents" bitset (as if its callback was invoked).
1423 If the watcher isn't pending it does nothing and returns 0.
1424
1425 Sometimes it can be useful to "poll" a watcher instead of waiting
1426 for its callback to be invoked, which can be accomplished with this
1427 function.
1428
1429 ev_feed_event (loop, ev_TYPE *watcher, int revents)
1430 Feeds the given event set into the event loop, as if the specified
1431 event had happened for the specified watcher (which must be a
1432 pointer to an initialised but not necessarily started event
1433 watcher). Obviously you must not free the watcher as long as it has
1434 pending events.
1435
1436 Stopping the watcher, letting libev invoke it, or calling
1437 "ev_clear_pending" will clear the pending event, even if the
1438 watcher was not started in the first place.
1439
1440 See also "ev_feed_fd_event" and "ev_feed_signal_event" for related
1441 functions that do not need a watcher.
1442
1443 See also the "ASSOCIATING CUSTOM DATA WITH A WATCHER" and "BUILDING
1444 YOUR OWN COMPOSITE WATCHERS" idioms.
1445
1446 WATCHER STATES
1447 There are various watcher states mentioned throughout this manual -
1448 active, pending and so on. In this section these states and the rules
1449 to transition between them will be described in more detail - and while
1450 these rules might look complicated, they usually do "the right thing".
1451
1452 initialised
1453 Before a watcher can be registered with the event loop it has to be
1454 initialised. This can be done with a call to "ev_TYPE_init", or
1455 calls to "ev_init" followed by the watcher-specific "ev_TYPE_set"
1456 function.
1457
1458 In this state it is simply some block of memory that is suitable
1459 for use in an event loop. It can be moved around, freed, reused
1460 etc. at will - as long as you either keep the memory contents
1461 intact, or call "ev_TYPE_init" again.
1462
1463 started/running/active
1464 Once a watcher has been started with a call to "ev_TYPE_start" it
1465 becomes property of the event loop, and is actively waiting for
1466 events. While in this state it cannot be accessed (except in a few
1467 documented ways), moved, freed or anything else - the only legal
1468 thing is to keep a pointer to it, and call libev functions on it
1469 that are documented to work on active watchers.
1470
1471 pending
1472 If a watcher is active and libev determines that an event it is
1473 interested in has occurred (such as a timer expiring), it will
1474 become pending. It will stay in this pending state until either it
1475 is stopped or its callback is about to be invoked, so it is not
1476 normally pending inside the watcher callback.
1477
1478 The watcher might or might not be active while it is pending (for
1479 example, an expired non-repeating timer can be pending but no
1480 longer active). If it is stopped, it can be freely accessed (e.g.
1481 by calling "ev_TYPE_set"), but it is still property of the event
1482 loop at this time, so cannot be moved, freed or reused. And if it
1483 is active the rules described in the previous item still apply.
1484
1485 It is also possible to feed an event on a watcher that is not
1486 active (e.g. via "ev_feed_event"), in which case it becomes
1487 pending without being active.
1488
1489 stopped
1490 A watcher can be stopped implicitly by libev (in which case it
1491 might still be pending), or explicitly by calling its
1492 "ev_TYPE_stop" function. The latter will clear any pending state
1493 the watcher might be in, regardless of whether it was active or
1494 not, so stopping a watcher explicitly before freeing it is often a
1495 good idea.
1496
1497 While stopped (and not pending) the watcher is essentially in the
1498 initialised state, that is, it can be reused, moved, modified in
1499 any way you wish (but when you trash the memory block, you need to
1500 "ev_TYPE_init" it again).
1501
1502 WATCHER PRIORITY MODELS
1503 Many event loops support watcher priorities, which are usually small
1504 integers that influence the ordering of event callback invocation
1505 between watchers in some way, all else being equal.
1506
1507 In libev, watcher priorities can be set using "ev_set_priority". See
1508 its description for the more technical details such as the actual
1509 priority range.
1510
1511 There are two common ways how these these priorities are being
1512 interpreted by event loops:
1513
1514 In the more common lock-out model, higher priorities "lock out"
1515 invocation of lower priority watchers, which means as long as higher
1516 priority watchers receive events, lower priority watchers are not being
1517 invoked.
1518
1519 The less common only-for-ordering model uses priorities solely to order
1520 callback invocation within a single event loop iteration: Higher
1521 priority watchers are invoked before lower priority ones, but they all
1522 get invoked before polling for new events.
1523
1524 Libev uses the second (only-for-ordering) model for all its watchers
1525 except for idle watchers (which use the lock-out model).
1526
1527 The rationale behind this is that implementing the lock-out model for
1528 watchers is not well supported by most kernel interfaces, and most
1529 event libraries will just poll for the same events again and again as
1530 long as their callbacks have not been executed, which is very
1531 inefficient in the common case of one high-priority watcher locking out
1532 a mass of lower priority ones.
1533
1534 Static (ordering) priorities are most useful when you have two or more
1535 watchers handling the same resource: a typical usage example is having
1536 an "ev_io" watcher to receive data, and an associated "ev_timer" to
1537 handle timeouts. Under load, data might be received while the program
1538 handles other jobs, but since timers normally get invoked first, the
1539 timeout handler will be executed before checking for data. In that
1540 case, giving the timer a lower priority than the I/O watcher ensures
1541 that I/O will be handled first even under adverse conditions (which is
1542 usually, but not always, what you want).
1543
1544 Since idle watchers use the "lock-out" model, meaning that idle
1545 watchers will only be executed when no same or higher priority watchers
1546 have received events, they can be used to implement the "lock-out"
1547 model when required.
1548
1549 For example, to emulate how many other event libraries handle
1550 priorities, you can associate an "ev_idle" watcher to each such
1551 watcher, and in the normal watcher callback, you just start the idle
1552 watcher. The real processing is done in the idle watcher callback. This
1553 causes libev to continuously poll and process kernel event data for the
1554 watcher, but when the lock-out case is known to be rare (which in turn
1555 is rare :), this is workable.
1556
1557 Usually, however, the lock-out model implemented that way will perform
1558 miserably under the type of load it was designed to handle. In that
1559 case, it might be preferable to stop the real watcher before starting
1560 the idle watcher, so the kernel will not have to process the event in
1561 case the actual processing will be delayed for considerable time.
1562
1563 Here is an example of an I/O watcher that should run at a strictly
1564 lower priority than the default, and which should only process data
1565 when no other events are pending:
1566
1567 ev_idle idle; // actual processing watcher
1568 ev_io io; // actual event watcher
1569
1570 static void
1571 io_cb (EV_P_ ev_io *w, int revents)
1572 {
1573 // stop the I/O watcher, we received the event, but
1574 // are not yet ready to handle it.
1575 ev_io_stop (EV_A_ w);
1576
1577 // start the idle watcher to handle the actual event.
1578 // it will not be executed as long as other watchers
1579 // with the default priority are receiving events.
1580 ev_idle_start (EV_A_ &idle);
1581 }
1582
1583 static void
1584 idle_cb (EV_P_ ev_idle *w, int revents)
1585 {
1586 // actual processing
1587 read (STDIN_FILENO, ...);
1588
1589 // have to start the I/O watcher again, as
1590 // we have handled the event
1591 ev_io_start (EV_P_ &io);
1592 }
1593
1594 // initialisation
1595 ev_idle_init (&idle, idle_cb);
1596 ev_io_init (&io, io_cb, STDIN_FILENO, EV_READ);
1597 ev_io_start (EV_DEFAULT_ &io);
1598
1599 In the "real" world, it might also be beneficial to start a timer, so
1600 that low-priority connections can not be locked out forever under load.
1601 This enables your program to keep a lower latency for important
1602 connections during short periods of high load, while not completely
1603 locking out less important ones.
1604
1606 This section describes each watcher in detail, but will not repeat
1607 information given in the last section. Any initialisation/set macros,
1608 functions and members specific to the watcher type are explained.
1609
1610 Members are additionally marked with either [read-only], meaning that,
1611 while the watcher is active, you can look at the member and expect some
1612 sensible content, but you must not modify it (you can modify it while
1613 the watcher is stopped to your hearts content), or [read-write], which
1614 means you can expect it to have some sensible content while the watcher
1615 is active, but you can also modify it. Modifying it may not do
1616 something sensible or take immediate effect (or do anything at all),
1617 but libev will not crash or malfunction in any way.
1618
1619 "ev_io" - is this file descriptor readable or writable?
1620 I/O watchers check whether a file descriptor is readable or writable in
1621 each iteration of the event loop, or, more precisely, when reading
1622 would not block the process and writing would at least be able to write
1623 some data. This behaviour is called level-triggering because you keep
1624 receiving events as long as the condition persists. Remember you can
1625 stop the watcher if you don't want to act on the event and neither want
1626 to receive future events.
1627
1628 In general you can register as many read and/or write event watchers
1629 per fd as you want (as long as you don't confuse yourself). Setting all
1630 file descriptors to non-blocking mode is also usually a good idea (but
1631 not required if you know what you are doing).
1632
1633 Another thing you have to watch out for is that it is quite easy to
1634 receive "spurious" readiness notifications, that is, your callback
1635 might be called with "EV_READ" but a subsequent "read"(2) will actually
1636 block because there is no data. It is very easy to get into this
1637 situation even with a relatively standard program structure. Thus it is
1638 best to always use non-blocking I/O: An extra "read"(2) returning
1639 "EAGAIN" is far preferable to a program hanging until some data
1640 arrives.
1641
1642 If you cannot run the fd in non-blocking mode (for example you should
1643 not play around with an Xlib connection), then you have to separately
1644 re-test whether a file descriptor is really ready with a known-to-be
1645 good interface such as poll (fortunately in the case of Xlib, it
1646 already does this on its own, so its quite safe to use). Some people
1647 additionally use "SIGALRM" and an interval timer, just to be sure you
1648 won't block indefinitely.
1649
1650 But really, best use non-blocking mode.
1651
1652 The special problem of disappearing file descriptors
1653
1654 Some backends (e.g. kqueue, epoll, linuxaio) need to be told about
1655 closing a file descriptor (either due to calling "close" explicitly or
1656 any other means, such as "dup2"). The reason is that you register
1657 interest in some file descriptor, but when it goes away, the operating
1658 system will silently drop this interest. If another file descriptor
1659 with the same number then is registered with libev, there is no
1660 efficient way to see that this is, in fact, a different file
1661 descriptor.
1662
1663 To avoid having to explicitly tell libev about such cases, libev
1664 follows the following policy: Each time "ev_io_set" is being called,
1665 libev will assume that this is potentially a new file descriptor,
1666 otherwise it is assumed that the file descriptor stays the same. That
1667 means that you have to call "ev_io_set" (or "ev_io_init") when you
1668 change the descriptor even if the file descriptor number itself did not
1669 change.
1670
1671 This is how one would do it normally anyway, the important point is
1672 that the libev application should not optimise around libev but should
1673 leave optimisations to libev.
1674
1675 The special problem of dup'ed file descriptors
1676
1677 Some backends (e.g. epoll), cannot register events for file
1678 descriptors, but only events for the underlying file descriptions. That
1679 means when you have "dup ()"'ed file descriptors or weirder
1680 constellations, and register events for them, only one file descriptor
1681 might actually receive events.
1682
1683 There is no workaround possible except not registering events for
1684 potentially "dup ()"'ed file descriptors, or to resort to
1685 "EVBACKEND_SELECT" or "EVBACKEND_POLL".
1686
1687 The special problem of files
1688
1689 Many people try to use "select" (or libev) on file descriptors
1690 representing files, and expect it to become ready when their program
1691 doesn't block on disk accesses (which can take a long time on their
1692 own).
1693
1694 However, this cannot ever work in the "expected" way - you get a
1695 readiness notification as soon as the kernel knows whether and how much
1696 data is there, and in the case of open files, that's always the case,
1697 so you always get a readiness notification instantly, and your read (or
1698 possibly write) will still block on the disk I/O.
1699
1700 Another way to view it is that in the case of sockets, pipes, character
1701 devices and so on, there is another party (the sender) that delivers
1702 data on its own, but in the case of files, there is no such thing: the
1703 disk will not send data on its own, simply because it doesn't know what
1704 you wish to read - you would first have to request some data.
1705
1706 Since files are typically not-so-well supported by advanced
1707 notification mechanism, libev tries hard to emulate POSIX behaviour
1708 with respect to files, even though you should not use it. The reason
1709 for this is convenience: sometimes you want to watch STDIN or STDOUT,
1710 which is usually a tty, often a pipe, but also sometimes files or
1711 special devices (for example, "epoll" on Linux works with /dev/random
1712 but not with /dev/urandom), and even though the file might better be
1713 served with asynchronous I/O instead of with non-blocking I/O, it is
1714 still useful when it "just works" instead of freezing.
1715
1716 So avoid file descriptors pointing to files when you know it (e.g. use
1717 libeio), but use them when it is convenient, e.g. for STDIN/STDOUT, or
1718 when you rarely read from a file instead of from a socket, and want to
1719 reuse the same code path.
1720
1721 The special problem of fork
1722
1723 Some backends (epoll, kqueue, linuxaio, iouring) do not support "fork
1724 ()" at all or exhibit useless behaviour. Libev fully supports fork, but
1725 needs to be told about it in the child if you want to continue to use
1726 it in the child.
1727
1728 To support fork in your child processes, you have to call "ev_loop_fork
1729 ()" after a fork in the child, enable "EVFLAG_FORKCHECK", or resort to
1730 "EVBACKEND_SELECT" or "EVBACKEND_POLL".
1731
1732 The special problem of SIGPIPE
1733
1734 While not really specific to libev, it is easy to forget about
1735 "SIGPIPE": when writing to a pipe whose other end has been closed, your
1736 program gets sent a SIGPIPE, which, by default, aborts your program.
1737 For most programs this is sensible behaviour, for daemons, this is
1738 usually undesirable.
1739
1740 So when you encounter spurious, unexplained daemon exits, make sure you
1741 ignore SIGPIPE (and maybe make sure you log the exit status of your
1742 daemon somewhere, as that would have given you a big clue).
1743
1744 The special problem of accept()ing when you can't
1745
1746 Many implementations of the POSIX "accept" function (for example, found
1747 in post-2004 Linux) have the peculiar behaviour of not removing a
1748 connection from the pending queue in all error cases.
1749
1750 For example, larger servers often run out of file descriptors (because
1751 of resource limits), causing "accept" to fail with "ENFILE" but not
1752 rejecting the connection, leading to libev signalling readiness on the
1753 next iteration again (the connection still exists after all), and
1754 typically causing the program to loop at 100% CPU usage.
1755
1756 Unfortunately, the set of errors that cause this issue differs between
1757 operating systems, there is usually little the app can do to remedy the
1758 situation, and no known thread-safe method of removing the connection
1759 to cope with overload is known (to me).
1760
1761 One of the easiest ways to handle this situation is to just ignore it -
1762 when the program encounters an overload, it will just loop until the
1763 situation is over. While this is a form of busy waiting, no OS offers
1764 an event-based way to handle this situation, so it's the best one can
1765 do.
1766
1767 A better way to handle the situation is to log any errors other than
1768 "EAGAIN" and "EWOULDBLOCK", making sure not to flood the log with such
1769 messages, and continue as usual, which at least gives the user an idea
1770 of what could be wrong ("raise the ulimit!"). For extra points one
1771 could stop the "ev_io" watcher on the listening fd "for a while", which
1772 reduces CPU usage.
1773
1774 If your program is single-threaded, then you could also keep a dummy
1775 file descriptor for overload situations (e.g. by opening /dev/null),
1776 and when you run into "ENFILE" or "EMFILE", close it, run "accept",
1777 close that fd, and create a new dummy fd. This will gracefully refuse
1778 clients under typical overload conditions.
1779
1780 The last way to handle it is to simply log the error and "exit", as is
1781 often done with "malloc" failures, but this results in an easy
1782 opportunity for a DoS attack.
1783
1784 Watcher-Specific Functions
1785
1786 ev_io_init (ev_io *, callback, int fd, int events)
1787 ev_io_set (ev_io *, int fd, int events)
1788 Configures an "ev_io" watcher. The "fd" is the file descriptor to
1789 receive events for and "events" is either "EV_READ", "EV_WRITE" or
1790 "EV_READ | EV_WRITE", to express the desire to receive the given
1791 events.
1792
1793 int fd [read-only]
1794 The file descriptor being watched.
1795
1796 int events [read-only]
1797 The events being watched.
1798
1799 Examples
1800
1801 Example: Call "stdin_readable_cb" when STDIN_FILENO has become, well
1802 readable, but only once. Since it is likely line-buffered, you could
1803 attempt to read a whole line in the callback.
1804
1805 static void
1806 stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents)
1807 {
1808 ev_io_stop (loop, w);
1809 .. read from stdin here (or from w->fd) and handle any I/O errors
1810 }
1811
1812 ...
1813 struct ev_loop *loop = ev_default_init (0);
1814 ev_io stdin_readable;
1815 ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ);
1816 ev_io_start (loop, &stdin_readable);
1817 ev_run (loop, 0);
1818
1819 "ev_timer" - relative and optionally repeating timeouts
1820 Timer watchers are simple relative timers that generate an event after
1821 a given time, and optionally repeating in regular intervals after that.
1822
1823 The timers are based on real time, that is, if you register an event
1824 that times out after an hour and you reset your system clock to January
1825 last year, it will still time out after (roughly) one hour. "Roughly"
1826 because detecting time jumps is hard, and some inaccuracies are
1827 unavoidable (the monotonic clock option helps a lot here).
1828
1829 The callback is guaranteed to be invoked only after its timeout has
1830 passed (not at, so on systems with very low-resolution clocks this
1831 might introduce a small delay, see "the special problem of being too
1832 early", below). If multiple timers become ready during the same loop
1833 iteration then the ones with earlier time-out values are invoked before
1834 ones of the same priority with later time-out values (but this is no
1835 longer true when a callback calls "ev_run" recursively).
1836
1837 Be smart about timeouts
1838
1839 Many real-world problems involve some kind of timeout, usually for
1840 error recovery. A typical example is an HTTP request - if the other
1841 side hangs, you want to raise some error after a while.
1842
1843 What follows are some ways to handle this problem, from obvious and
1844 inefficient to smart and efficient.
1845
1846 In the following, a 60 second activity timeout is assumed - a timeout
1847 that gets reset to 60 seconds each time there is activity (e.g. each
1848 time some data or other life sign was received).
1849
1850 1. Use a timer and stop, reinitialise and start it on activity.
1851 This is the most obvious, but not the most simple way: In the
1852 beginning, start the watcher:
1853
1854 ev_timer_init (timer, callback, 60., 0.);
1855 ev_timer_start (loop, timer);
1856
1857 Then, each time there is some activity, "ev_timer_stop" it,
1858 initialise it and start it again:
1859
1860 ev_timer_stop (loop, timer);
1861 ev_timer_set (timer, 60., 0.);
1862 ev_timer_start (loop, timer);
1863
1864 This is relatively simple to implement, but means that each time
1865 there is some activity, libev will first have to remove the timer
1866 from its internal data structure and then add it again. Libev tries
1867 to be fast, but it's still not a constant-time operation.
1868
1869 2. Use a timer and re-start it with "ev_timer_again" inactivity.
1870 This is the easiest way, and involves using "ev_timer_again"
1871 instead of "ev_timer_start".
1872
1873 To implement this, configure an "ev_timer" with a "repeat" value of
1874 60 and then call "ev_timer_again" at start and each time you
1875 successfully read or write some data. If you go into an idle state
1876 where you do not expect data to travel on the socket, you can
1877 "ev_timer_stop" the timer, and "ev_timer_again" will automatically
1878 restart it if need be.
1879
1880 That means you can ignore both the "ev_timer_start" function and
1881 the "after" argument to "ev_timer_set", and only ever use the
1882 "repeat" member and "ev_timer_again".
1883
1884 At start:
1885
1886 ev_init (timer, callback);
1887 timer->repeat = 60.;
1888 ev_timer_again (loop, timer);
1889
1890 Each time there is some activity:
1891
1892 ev_timer_again (loop, timer);
1893
1894 It is even possible to change the time-out on the fly, regardless
1895 of whether the watcher is active or not:
1896
1897 timer->repeat = 30.;
1898 ev_timer_again (loop, timer);
1899
1900 This is slightly more efficient then stopping/starting the timer
1901 each time you want to modify its timeout value, as libev does not
1902 have to completely remove and re-insert the timer from/into its
1903 internal data structure.
1904
1905 It is, however, even simpler than the "obvious" way to do it.
1906
1907 3. Let the timer time out, but then re-arm it as required.
1908 This method is more tricky, but usually most efficient: Most
1909 timeouts are relatively long compared to the intervals between
1910 other activity - in our example, within 60 seconds, there are
1911 usually many I/O events with associated activity resets.
1912
1913 In this case, it would be more efficient to leave the "ev_timer"
1914 alone, but remember the time of last activity, and check for a real
1915 timeout only within the callback:
1916
1917 ev_tstamp timeout = 60.;
1918 ev_tstamp last_activity; // time of last activity
1919 ev_timer timer;
1920
1921 static void
1922 callback (EV_P_ ev_timer *w, int revents)
1923 {
1924 // calculate when the timeout would happen
1925 ev_tstamp after = last_activity - ev_now (EV_A) + timeout;
1926
1927 // if negative, it means we the timeout already occurred
1928 if (after < 0.)
1929 {
1930 // timeout occurred, take action
1931 }
1932 else
1933 {
1934 // callback was invoked, but there was some recent
1935 // activity. simply restart the timer to time out
1936 // after "after" seconds, which is the earliest time
1937 // the timeout can occur.
1938 ev_timer_set (w, after, 0.);
1939 ev_timer_start (EV_A_ w);
1940 }
1941 }
1942
1943 To summarise the callback: first calculate in how many seconds the
1944 timeout will occur (by calculating the absolute time when it would
1945 occur, "last_activity + timeout", and subtracting the current time,
1946 "ev_now (EV_A)" from that).
1947
1948 If this value is negative, then we are already past the timeout,
1949 i.e. we timed out, and need to do whatever is needed in this case.
1950
1951 Otherwise, we now the earliest time at which the timeout would
1952 trigger, and simply start the timer with this timeout value.
1953
1954 In other words, each time the callback is invoked it will check
1955 whether the timeout occurred. If not, it will simply reschedule
1956 itself to check again at the earliest time it could time out.
1957 Rinse. Repeat.
1958
1959 This scheme causes more callback invocations (about one every 60
1960 seconds minus half the average time between activity), but
1961 virtually no calls to libev to change the timeout.
1962
1963 To start the machinery, simply initialise the watcher and set
1964 "last_activity" to the current time (meaning there was some
1965 activity just now), then call the callback, which will "do the
1966 right thing" and start the timer:
1967
1968 last_activity = ev_now (EV_A);
1969 ev_init (&timer, callback);
1970 callback (EV_A_ &timer, 0);
1971
1972 When there is some activity, simply store the current time in
1973 "last_activity", no libev calls at all:
1974
1975 if (activity detected)
1976 last_activity = ev_now (EV_A);
1977
1978 When your timeout value changes, then the timeout can be changed by
1979 simply providing a new value, stopping the timer and calling the
1980 callback, which will again do the right thing (for example, time
1981 out immediately :).
1982
1983 timeout = new_value;
1984 ev_timer_stop (EV_A_ &timer);
1985 callback (EV_A_ &timer, 0);
1986
1987 This technique is slightly more complex, but in most cases where
1988 the time-out is unlikely to be triggered, much more efficient.
1989
1990 4. Wee, just use a double-linked list for your timeouts.
1991 If there is not one request, but many thousands (millions...), all
1992 employing some kind of timeout with the same timeout value, then
1993 one can do even better:
1994
1995 When starting the timeout, calculate the timeout value and put the
1996 timeout at the end of the list.
1997
1998 Then use an "ev_timer" to fire when the timeout at the beginning of
1999 the list is expected to fire (for example, using the technique #3).
2000
2001 When there is some activity, remove the timer from the list,
2002 recalculate the timeout, append it to the end of the list again,
2003 and make sure to update the "ev_timer" if it was taken from the
2004 beginning of the list.
2005
2006 This way, one can manage an unlimited number of timeouts in O(1)
2007 time for starting, stopping and updating the timers, at the expense
2008 of a major complication, and having to use a constant timeout. The
2009 constant timeout ensures that the list stays sorted.
2010
2011 So which method the best?
2012
2013 Method #2 is a simple no-brain-required solution that is adequate in
2014 most situations. Method #3 requires a bit more thinking, but handles
2015 many cases better, and isn't very complicated either. In most case,
2016 choosing either one is fine, with #3 being better in typical
2017 situations.
2018
2019 Method #1 is almost always a bad idea, and buys you nothing. Method #4
2020 is rather complicated, but extremely efficient, something that really
2021 pays off after the first million or so of active timers, i.e. it's
2022 usually overkill :)
2023
2024 The special problem of being too early
2025
2026 If you ask a timer to call your callback after three seconds, then you
2027 expect it to be invoked after three seconds - but of course, this
2028 cannot be guaranteed to infinite precision. Less obviously, it cannot
2029 be guaranteed to any precision by libev - imagine somebody suspending
2030 the process with a STOP signal for a few hours for example.
2031
2032 So, libev tries to invoke your callback as soon as possible after the
2033 delay has occurred, but cannot guarantee this.
2034
2035 A less obvious failure mode is calling your callback too early: many
2036 event loops compare timestamps with a "elapsed delay >= requested
2037 delay", but this can cause your callback to be invoked much earlier
2038 than you would expect.
2039
2040 To see why, imagine a system with a clock that only offers full second
2041 resolution (think windows if you can't come up with a broken enough OS
2042 yourself). If you schedule a one-second timer at the time 500.9, then
2043 the event loop will schedule your timeout to elapse at a system time of
2044 500 (500.9 truncated to the resolution) + 1, or 501.
2045
2046 If an event library looks at the timeout 0.1s later, it will see "501
2047 >= 501" and invoke the callback 0.1s after it was started, even though
2048 a one-second delay was requested - this is being "too early", despite
2049 best intentions.
2050
2051 This is the reason why libev will never invoke the callback if the
2052 elapsed delay equals the requested delay, but only when the elapsed
2053 delay is larger than the requested delay. In the example above, libev
2054 would only invoke the callback at system time 502, or 1.1s after the
2055 timer was started.
2056
2057 So, while libev cannot guarantee that your callback will be invoked
2058 exactly when requested, it can and does guarantee that the requested
2059 delay has actually elapsed, or in other words, it always errs on the
2060 "too late" side of things.
2061
2062 The special problem of time updates
2063
2064 Establishing the current time is a costly operation (it usually takes
2065 at least one system call): EV therefore updates its idea of the current
2066 time only before and after "ev_run" collects new events, which causes a
2067 growing difference between "ev_now ()" and "ev_time ()" when handling
2068 lots of events in one iteration.
2069
2070 The relative timeouts are calculated relative to the "ev_now ()" time.
2071 This is usually the right thing as this timestamp refers to the time of
2072 the event triggering whatever timeout you are modifying/starting. If
2073 you suspect event processing to be delayed and you need to base the
2074 timeout on the current time, use something like the following to adjust
2075 for it:
2076
2077 ev_timer_set (&timer, after + (ev_time () - ev_now ()), 0.);
2078
2079 If the event loop is suspended for a long time, you can also force an
2080 update of the time returned by "ev_now ()" by calling "ev_now_update
2081 ()", although that will push the event time of all outstanding events
2082 further into the future.
2083
2084 The special problem of unsynchronised clocks
2085
2086 Modern systems have a variety of clocks - libev itself uses the normal
2087 "wall clock" clock and, if available, the monotonic clock (to avoid
2088 time jumps).
2089
2090 Neither of these clocks is synchronised with each other or any other
2091 clock on the system, so "ev_time ()" might return a considerably
2092 different time than "gettimeofday ()" or "time ()". On a GNU/Linux
2093 system, for example, a call to "gettimeofday" might return a second
2094 count that is one higher than a directly following call to "time".
2095
2096 The moral of this is to only compare libev-related timestamps with
2097 "ev_time ()" and "ev_now ()", at least if you want better precision
2098 than a second or so.
2099
2100 One more problem arises due to this lack of synchronisation: if libev
2101 uses the system monotonic clock and you compare timestamps from
2102 "ev_time" or "ev_now" from when you started your timer and when your
2103 callback is invoked, you will find that sometimes the callback is a bit
2104 "early".
2105
2106 This is because "ev_timer"s work in real time, not wall clock time, so
2107 libev makes sure your callback is not invoked before the delay
2108 happened, measured according to the real time, not the system clock.
2109
2110 If your timeouts are based on a physical timescale (e.g. "time out this
2111 connection after 100 seconds") then this shouldn't bother you as it is
2112 exactly the right behaviour.
2113
2114 If you want to compare wall clock/system timestamps to your timers,
2115 then you need to use "ev_periodic"s, as these are based on the wall
2116 clock time, where your comparisons will always generate correct
2117 results.
2118
2119 The special problems of suspended animation
2120
2121 When you leave the server world it is quite customary to hit machines
2122 that can suspend/hibernate - what happens to the clocks during such a
2123 suspend?
2124
2125 Some quick tests made with a Linux 2.6.28 indicate that a suspend
2126 freezes all processes, while the clocks ("times", "CLOCK_MONOTONIC")
2127 continue to run until the system is suspended, but they will not
2128 advance while the system is suspended. That means, on resume, it will
2129 be as if the program was frozen for a few seconds, but the suspend time
2130 will not be counted towards "ev_timer" when a monotonic clock source is
2131 used. The real time clock advanced as expected, but if it is used as
2132 sole clocksource, then a long suspend would be detected as a time jump
2133 by libev, and timers would be adjusted accordingly.
2134
2135 I would not be surprised to see different behaviour in different
2136 between operating systems, OS versions or even different hardware.
2137
2138 The other form of suspend (job control, or sending a SIGSTOP) will see
2139 a time jump in the monotonic clocks and the realtime clock. If the
2140 program is suspended for a very long time, and monotonic clock sources
2141 are in use, then you can expect "ev_timer"s to expire as the full
2142 suspension time will be counted towards the timers. When no monotonic
2143 clock source is in use, then libev will again assume a timejump and
2144 adjust accordingly.
2145
2146 It might be beneficial for this latter case to call "ev_suspend" and
2147 "ev_resume" in code that handles "SIGTSTP", to at least get
2148 deterministic behaviour in this case (you can do nothing against
2149 "SIGSTOP").
2150
2151 Watcher-Specific Functions and Data Members
2152
2153 ev_timer_init (ev_timer *, callback, ev_tstamp after, ev_tstamp repeat)
2154 ev_timer_set (ev_timer *, ev_tstamp after, ev_tstamp repeat)
2155 Configure the timer to trigger after "after" seconds (fractional
2156 and negative values are supported). If "repeat" is 0., then it will
2157 automatically be stopped once the timeout is reached. If it is
2158 positive, then the timer will automatically be configured to
2159 trigger again "repeat" seconds later, again, and again, until
2160 stopped manually.
2161
2162 The timer itself will do a best-effort at avoiding drift, that is,
2163 if you configure a timer to trigger every 10 seconds, then it will
2164 normally trigger at exactly 10 second intervals. If, however, your
2165 program cannot keep up with the timer (because it takes longer than
2166 those 10 seconds to do stuff) the timer will not fire more than
2167 once per event loop iteration.
2168
2169 ev_timer_again (loop, ev_timer *)
2170 This will act as if the timer timed out, and restarts it again if
2171 it is repeating. It basically works like calling "ev_timer_stop",
2172 updating the timeout to the "repeat" value and calling
2173 "ev_timer_start".
2174
2175 The exact semantics are as in the following rules, all of which
2176 will be applied to the watcher:
2177
2178 If the timer is pending, the pending status is always cleared.
2179 If the timer is started but non-repeating, stop it (as if it timed
2180 out, without invoking it).
2181 If the timer is repeating, make the "repeat" value the new timeout
2182 and start the timer, if necessary.
2183
2184 This sounds a bit complicated, see "Be smart about timeouts",
2185 above, for a usage example.
2186
2187 ev_tstamp ev_timer_remaining (loop, ev_timer *)
2188 Returns the remaining time until a timer fires. If the timer is
2189 active, then this time is relative to the current event loop time,
2190 otherwise it's the timeout value currently configured.
2191
2192 That is, after an "ev_timer_set (w, 5, 7)", "ev_timer_remaining"
2193 returns 5. When the timer is started and one second passes,
2194 "ev_timer_remaining" will return 4. When the timer expires and is
2195 restarted, it will return roughly 7 (likely slightly less as
2196 callback invocation takes some time, too), and so on.
2197
2198 ev_tstamp repeat [read-write]
2199 The current "repeat" value. Will be used each time the watcher
2200 times out or "ev_timer_again" is called, and determines the next
2201 timeout (if any), which is also when any modifications are taken
2202 into account.
2203
2204 Examples
2205
2206 Example: Create a timer that fires after 60 seconds.
2207
2208 static void
2209 one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents)
2210 {
2211 .. one minute over, w is actually stopped right here
2212 }
2213
2214 ev_timer mytimer;
2215 ev_timer_init (&mytimer, one_minute_cb, 60., 0.);
2216 ev_timer_start (loop, &mytimer);
2217
2218 Example: Create a timeout timer that times out after 10 seconds of
2219 inactivity.
2220
2221 static void
2222 timeout_cb (struct ev_loop *loop, ev_timer *w, int revents)
2223 {
2224 .. ten seconds without any activity
2225 }
2226
2227 ev_timer mytimer;
2228 ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */
2229 ev_timer_again (&mytimer); /* start timer */
2230 ev_run (loop, 0);
2231
2232 // and in some piece of code that gets executed on any "activity":
2233 // reset the timeout to start ticking again at 10 seconds
2234 ev_timer_again (&mytimer);
2235
2236 "ev_periodic" - to cron or not to cron?
2237 Periodic watchers are also timers of a kind, but they are very
2238 versatile (and unfortunately a bit complex).
2239
2240 Unlike "ev_timer", periodic watchers are not based on real time (or
2241 relative time, the physical time that passes) but on wall clock time
2242 (absolute time, the thing you can read on your calendar or clock). The
2243 difference is that wall clock time can run faster or slower than real
2244 time, and time jumps are not uncommon (e.g. when you adjust your wrist-
2245 watch).
2246
2247 You can tell a periodic watcher to trigger after some specific point in
2248 time: for example, if you tell a periodic watcher to trigger "in 10
2249 seconds" (by specifying e.g. "ev_now () + 10.", that is, an absolute
2250 time not a delay) and then reset your system clock to January of the
2251 previous year, then it will take a year or more to trigger the event
2252 (unlike an "ev_timer", which would still trigger roughly 10 seconds
2253 after starting it, as it uses a relative timeout).
2254
2255 "ev_periodic" watchers can also be used to implement vastly more
2256 complex timers, such as triggering an event on each "midnight, local
2257 time", or other complicated rules. This cannot easily be done with
2258 "ev_timer" watchers, as those cannot react to time jumps.
2259
2260 As with timers, the callback is guaranteed to be invoked only when the
2261 point in time where it is supposed to trigger has passed. If multiple
2262 timers become ready during the same loop iteration then the ones with
2263 earlier time-out values are invoked before ones with later time-out
2264 values (but this is no longer true when a callback calls "ev_run"
2265 recursively).
2266
2267 Watcher-Specific Functions and Data Members
2268
2269 ev_periodic_init (ev_periodic *, callback, ev_tstamp offset, ev_tstamp
2270 interval, reschedule_cb)
2271 ev_periodic_set (ev_periodic *, ev_tstamp offset, ev_tstamp interval,
2272 reschedule_cb)
2273 Lots of arguments, let's sort it out... There are basically three
2274 modes of operation, and we will explain them from simplest to most
2275 complex:
2276
2277 · absolute timer (offset = absolute time, interval = 0,
2278 reschedule_cb = 0)
2279
2280 In this configuration the watcher triggers an event after the
2281 wall clock time "offset" has passed. It will not repeat and
2282 will not adjust when a time jump occurs, that is, if it is to
2283 be run at January 1st 2011 then it will be stopped and invoked
2284 when the system clock reaches or surpasses this point in time.
2285
2286 · repeating interval timer (offset = offset within interval,
2287 interval > 0, reschedule_cb = 0)
2288
2289 In this mode the watcher will always be scheduled to time out
2290 at the next "offset + N * interval" time (for some integer N,
2291 which can also be negative) and then repeat, regardless of any
2292 time jumps. The "offset" argument is merely an offset into the
2293 "interval" periods.
2294
2295 This can be used to create timers that do not drift with
2296 respect to the system clock, for example, here is an
2297 "ev_periodic" that triggers each hour, on the hour (with
2298 respect to UTC):
2299
2300 ev_periodic_set (&periodic, 0., 3600., 0);
2301
2302 This doesn't mean there will always be 3600 seconds in between
2303 triggers, but only that the callback will be called when the
2304 system time shows a full hour (UTC), or more correctly, when
2305 the system time is evenly divisible by 3600.
2306
2307 Another way to think about it (for the mathematically inclined)
2308 is that "ev_periodic" will try to run the callback in this mode
2309 at the next possible time where "time = offset (mod interval)",
2310 regardless of any time jumps.
2311
2312 The "interval" MUST be positive, and for numerical stability,
2313 the interval value should be higher than "1/8192" (which is
2314 around 100 microseconds) and "offset" should be higher than 0
2315 and should have at most a similar magnitude as the current time
2316 (say, within a factor of ten). Typical values for offset are,
2317 in fact, 0 or something between 0 and "interval", which is also
2318 the recommended range.
2319
2320 Note also that there is an upper limit to how often a timer can
2321 fire (CPU speed for example), so if "interval" is very small
2322 then timing stability will of course deteriorate. Libev itself
2323 tries to be exact to be about one millisecond (if the OS
2324 supports it and the machine is fast enough).
2325
2326 · manual reschedule mode (offset ignored, interval ignored,
2327 reschedule_cb = callback)
2328
2329 In this mode the values for "interval" and "offset" are both
2330 being ignored. Instead, each time the periodic watcher gets
2331 scheduled, the reschedule callback will be called with the
2332 watcher as first, and the current time as second argument.
2333
2334 NOTE: This callback MUST NOT stop or destroy any periodic
2335 watcher, ever, or make ANY other event loop modifications
2336 whatsoever, unless explicitly allowed by documentation here.
2337
2338 If you need to stop it, return "now + 1e30" (or so, fudge
2339 fudge) and stop it afterwards (e.g. by starting an "ev_prepare"
2340 watcher, which is the only event loop modification you are
2341 allowed to do).
2342
2343 The callback prototype is "ev_tstamp
2344 (*reschedule_cb)(ev_periodic *w, ev_tstamp now)", e.g.:
2345
2346 static ev_tstamp
2347 my_rescheduler (ev_periodic *w, ev_tstamp now)
2348 {
2349 return now + 60.;
2350 }
2351
2352 It must return the next time to trigger, based on the passed
2353 time value (that is, the lowest time value larger than to the
2354 second argument). It will usually be called just before the
2355 callback will be triggered, but might be called at other times,
2356 too.
2357
2358 NOTE: This callback must always return a time that is higher
2359 than or equal to the passed "now" value.
2360
2361 This can be used to create very complex timers, such as a timer
2362 that triggers on "next midnight, local time". To do this, you
2363 would calculate the next midnight after "now" and return the
2364 timestamp value for this. Here is a (completely untested, no
2365 error checking) example on how to do this:
2366
2367 #include <time.h>
2368
2369 static ev_tstamp
2370 my_rescheduler (ev_periodic *w, ev_tstamp now)
2371 {
2372 time_t tnow = (time_t)now;
2373 struct tm tm;
2374 localtime_r (&tnow, &tm);
2375
2376 tm.tm_sec = tm.tm_min = tm.tm_hour = 0; // midnight current day
2377 ++tm.tm_mday; // midnight next day
2378
2379 return mktime (&tm);
2380 }
2381
2382 Note: this code might run into trouble on days that have more
2383 then two midnights (beginning and end).
2384
2385 ev_periodic_again (loop, ev_periodic *)
2386 Simply stops and restarts the periodic watcher again. This is only
2387 useful when you changed some parameters or the reschedule callback
2388 would return a different time than the last time it was called
2389 (e.g. in a crond like program when the crontabs have changed).
2390
2391 ev_tstamp ev_periodic_at (ev_periodic *)
2392 When active, returns the absolute time that the watcher is supposed
2393 to trigger next. This is not the same as the "offset" argument to
2394 "ev_periodic_set", but indeed works even in interval and manual
2395 rescheduling modes.
2396
2397 ev_tstamp offset [read-write]
2398 When repeating, this contains the offset value, otherwise this is
2399 the absolute point in time (the "offset" value passed to
2400 "ev_periodic_set", although libev might modify this value for
2401 better numerical stability).
2402
2403 Can be modified any time, but changes only take effect when the
2404 periodic timer fires or "ev_periodic_again" is being called.
2405
2406 ev_tstamp interval [read-write]
2407 The current interval value. Can be modified any time, but changes
2408 only take effect when the periodic timer fires or
2409 "ev_periodic_again" is being called.
2410
2411 ev_tstamp (*reschedule_cb)(ev_periodic *w, ev_tstamp now) [read-write]
2412 The current reschedule callback, or 0, if this functionality is
2413 switched off. Can be changed any time, but changes only take effect
2414 when the periodic timer fires or "ev_periodic_again" is being
2415 called.
2416
2417 Examples
2418
2419 Example: Call a callback every hour, or, more precisely, whenever the
2420 system time is divisible by 3600. The callback invocation times have
2421 potentially a lot of jitter, but good long-term stability.
2422
2423 static void
2424 clock_cb (struct ev_loop *loop, ev_periodic *w, int revents)
2425 {
2426 ... its now a full hour (UTC, or TAI or whatever your clock follows)
2427 }
2428
2429 ev_periodic hourly_tick;
2430 ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0);
2431 ev_periodic_start (loop, &hourly_tick);
2432
2433 Example: The same as above, but use a reschedule callback to do it:
2434
2435 #include <math.h>
2436
2437 static ev_tstamp
2438 my_scheduler_cb (ev_periodic *w, ev_tstamp now)
2439 {
2440 return now + (3600. - fmod (now, 3600.));
2441 }
2442
2443 ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb);
2444
2445 Example: Call a callback every hour, starting now:
2446
2447 ev_periodic hourly_tick;
2448 ev_periodic_init (&hourly_tick, clock_cb,
2449 fmod (ev_now (loop), 3600.), 3600., 0);
2450 ev_periodic_start (loop, &hourly_tick);
2451
2452 "ev_signal" - signal me when a signal gets signalled!
2453 Signal watchers will trigger an event when the process receives a
2454 specific signal one or more times. Even though signals are very
2455 asynchronous, libev will try its best to deliver signals synchronously,
2456 i.e. as part of the normal event processing, like any other event.
2457
2458 If you want signals to be delivered truly asynchronously, just use
2459 "sigaction" as you would do without libev and forget about sharing the
2460 signal. You can even use "ev_async" from a signal handler to
2461 synchronously wake up an event loop.
2462
2463 You can configure as many watchers as you like for the same signal, but
2464 only within the same loop, i.e. you can watch for "SIGINT" in your
2465 default loop and for "SIGIO" in another loop, but you cannot watch for
2466 "SIGINT" in both the default loop and another loop at the same time. At
2467 the moment, "SIGCHLD" is permanently tied to the default loop.
2468
2469 Only after the first watcher for a signal is started will libev
2470 actually register something with the kernel. It thus coexists with your
2471 own signal handlers as long as you don't register any with libev for
2472 the same signal.
2473
2474 If possible and supported, libev will install its handlers with
2475 "SA_RESTART" (or equivalent) behaviour enabled, so system calls should
2476 not be unduly interrupted. If you have a problem with system calls
2477 getting interrupted by signals you can block all signals in an
2478 "ev_check" watcher and unblock them in an "ev_prepare" watcher.
2479
2480 The special problem of inheritance over fork/execve/pthread_create
2481
2482 Both the signal mask ("sigprocmask") and the signal disposition
2483 ("sigaction") are unspecified after starting a signal watcher (and
2484 after stopping it again), that is, libev might or might not block the
2485 signal, and might or might not set or restore the installed signal
2486 handler (but see "EVFLAG_NOSIGMASK").
2487
2488 While this does not matter for the signal disposition (libev never sets
2489 signals to "SIG_IGN", so handlers will be reset to "SIG_DFL" on
2490 "execve"), this matters for the signal mask: many programs do not
2491 expect certain signals to be blocked.
2492
2493 This means that before calling "exec" (from the child) you should reset
2494 the signal mask to whatever "default" you expect (all clear is a good
2495 choice usually).
2496
2497 The simplest way to ensure that the signal mask is reset in the child
2498 is to install a fork handler with "pthread_atfork" that resets it. That
2499 will catch fork calls done by libraries (such as the libc) as well.
2500
2501 In current versions of libev, the signal will not be blocked
2502 indefinitely unless you use the "signalfd" API ("EV_SIGNALFD"). While
2503 this reduces the window of opportunity for problems, it will not go
2504 away, as libev has to modify the signal mask, at least temporarily.
2505
2506 So I can't stress this enough: If you do not reset your signal mask
2507 when you expect it to be empty, you have a race condition in your code.
2508 This is not a libev-specific thing, this is true for most event
2509 libraries.
2510
2511 The special problem of threads signal handling
2512
2513 POSIX threads has problematic signal handling semantics, specifically,
2514 a lot of functionality (sigfd, sigwait etc.) only really works if all
2515 threads in a process block signals, which is hard to achieve.
2516
2517 When you want to use sigwait (or mix libev signal handling with your
2518 own for the same signals), you can tackle this problem by globally
2519 blocking all signals before creating any threads (or creating them with
2520 a fully set sigprocmask) and also specifying the "EVFLAG_NOSIGMASK"
2521 when creating loops. Then designate one thread as "signal receiver
2522 thread" which handles these signals. You can pass on any signals that
2523 libev might be interested in by calling "ev_feed_signal".
2524
2525 Watcher-Specific Functions and Data Members
2526
2527 ev_signal_init (ev_signal *, callback, int signum)
2528 ev_signal_set (ev_signal *, int signum)
2529 Configures the watcher to trigger on the given signal number
2530 (usually one of the "SIGxxx" constants).
2531
2532 int signum [read-only]
2533 The signal the watcher watches out for.
2534
2535 Examples
2536
2537 Example: Try to exit cleanly on SIGINT.
2538
2539 static void
2540 sigint_cb (struct ev_loop *loop, ev_signal *w, int revents)
2541 {
2542 ev_break (loop, EVBREAK_ALL);
2543 }
2544
2545 ev_signal signal_watcher;
2546 ev_signal_init (&signal_watcher, sigint_cb, SIGINT);
2547 ev_signal_start (loop, &signal_watcher);
2548
2549 "ev_child" - watch out for process status changes
2550 Child watchers trigger when your process receives a SIGCHLD in response
2551 to some child status changes (most typically when a child of yours dies
2552 or exits). It is permissible to install a child watcher after the child
2553 has been forked (which implies it might have already exited), as long
2554 as the event loop isn't entered (or is continued from a watcher), i.e.,
2555 forking and then immediately registering a watcher for the child is
2556 fine, but forking and registering a watcher a few event loop iterations
2557 later or in the next callback invocation is not.
2558
2559 Only the default event loop is capable of handling signals, and
2560 therefore you can only register child watchers in the default event
2561 loop.
2562
2563 Due to some design glitches inside libev, child watchers will always be
2564 handled at maximum priority (their priority is set to "EV_MAXPRI" by
2565 libev)
2566
2567 Process Interaction
2568
2569 Libev grabs "SIGCHLD" as soon as the default event loop is initialised.
2570 This is necessary to guarantee proper behaviour even if the first child
2571 watcher is started after the child exits. The occurrence of "SIGCHLD"
2572 is recorded asynchronously, but child reaping is done synchronously as
2573 part of the event loop processing. Libev always reaps all children,
2574 even ones not watched.
2575
2576 Overriding the Built-In Processing
2577
2578 Libev offers no special support for overriding the built-in child
2579 processing, but if your application collides with libev's default child
2580 handler, you can override it easily by installing your own handler for
2581 "SIGCHLD" after initialising the default loop, and making sure the
2582 default loop never gets destroyed. You are encouraged, however, to use
2583 an event-based approach to child reaping and thus use libev's support
2584 for that, so other libev users can use "ev_child" watchers freely.
2585
2586 Stopping the Child Watcher
2587
2588 Currently, the child watcher never gets stopped, even when the child
2589 terminates, so normally one needs to stop the watcher in the callback.
2590 Future versions of libev might stop the watcher automatically when a
2591 child exit is detected (calling "ev_child_stop" twice is not a
2592 problem).
2593
2594 Watcher-Specific Functions and Data Members
2595
2596 ev_child_init (ev_child *, callback, int pid, int trace)
2597 ev_child_set (ev_child *, int pid, int trace)
2598 Configures the watcher to wait for status changes of process "pid"
2599 (or any process if "pid" is specified as 0). The callback can look
2600 at the "rstatus" member of the "ev_child" watcher structure to see
2601 the status word (use the macros from "sys/wait.h" and see your
2602 systems "waitpid" documentation). The "rpid" member contains the
2603 pid of the process causing the status change. "trace" must be
2604 either 0 (only activate the watcher when the process terminates) or
2605 1 (additionally activate the watcher when the process is stopped or
2606 continued).
2607
2608 int pid [read-only]
2609 The process id this watcher watches out for, or 0, meaning any
2610 process id.
2611
2612 int rpid [read-write]
2613 The process id that detected a status change.
2614
2615 int rstatus [read-write]
2616 The process exit/trace status caused by "rpid" (see your systems
2617 "waitpid" and "sys/wait.h" documentation for details).
2618
2619 Examples
2620
2621 Example: "fork()" a new process and install a child handler to wait for
2622 its completion.
2623
2624 ev_child cw;
2625
2626 static void
2627 child_cb (EV_P_ ev_child *w, int revents)
2628 {
2629 ev_child_stop (EV_A_ w);
2630 printf ("process %d exited with status %x\n", w->rpid, w->rstatus);
2631 }
2632
2633 pid_t pid = fork ();
2634
2635 if (pid < 0)
2636 // error
2637 else if (pid == 0)
2638 {
2639 // the forked child executes here
2640 exit (1);
2641 }
2642 else
2643 {
2644 ev_child_init (&cw, child_cb, pid, 0);
2645 ev_child_start (EV_DEFAULT_ &cw);
2646 }
2647
2648 "ev_stat" - did the file attributes just change?
2649 This watches a file system path for attribute changes. That is, it
2650 calls "stat" on that path in regular intervals (or when the OS says it
2651 changed) and sees if it changed compared to the last time, invoking the
2652 callback if it did. Starting the watcher "stat"'s the file, so only
2653 changes that happen after the watcher has been started will be
2654 reported.
2655
2656 The path does not need to exist: changing from "path exists" to "path
2657 does not exist" is a status change like any other. The condition "path
2658 does not exist" (or more correctly "path cannot be stat'ed") is
2659 signified by the "st_nlink" field being zero (which is otherwise always
2660 forced to be at least one) and all the other fields of the stat buffer
2661 having unspecified contents.
2662
2663 The path must not end in a slash or contain special components such as
2664 "." or "..". The path should be absolute: If it is relative and your
2665 working directory changes, then the behaviour is undefined.
2666
2667 Since there is no portable change notification interface available, the
2668 portable implementation simply calls stat(2) regularly on the path to
2669 see if it changed somehow. You can specify a recommended polling
2670 interval for this case. If you specify a polling interval of 0 (highly
2671 recommended!) then a suitable, unspecified default value will be used
2672 (which you can expect to be around five seconds, although this might
2673 change dynamically). Libev will also impose a minimum interval which is
2674 currently around 0.1, but that's usually overkill.
2675
2676 This watcher type is not meant for massive numbers of stat watchers, as
2677 even with OS-supported change notifications, this can be resource-
2678 intensive.
2679
2680 At the time of this writing, the only OS-specific interface implemented
2681 is the Linux inotify interface (implementing kqueue support is left as
2682 an exercise for the reader. Note, however, that the author sees no way
2683 of implementing "ev_stat" semantics with kqueue, except as a hint).
2684
2685 ABI Issues (Largefile Support)
2686
2687 Libev by default (unless the user overrides this) uses the default
2688 compilation environment, which means that on systems with large file
2689 support disabled by default, you get the 32 bit version of the stat
2690 structure. When using the library from programs that change the ABI to
2691 use 64 bit file offsets the programs will fail. In that case you have
2692 to compile libev with the same flags to get binary compatibility. This
2693 is obviously the case with any flags that change the ABI, but the
2694 problem is most noticeably displayed with ev_stat and large file
2695 support.
2696
2697 The solution for this is to lobby your distribution maker to make large
2698 file interfaces available by default (as e.g. FreeBSD does) and not
2699 optional. Libev cannot simply switch on large file support because it
2700 has to exchange stat structures with application programs compiled
2701 using the default compilation environment.
2702
2703 Inotify and Kqueue
2704
2705 When "inotify (7)" support has been compiled into libev and present at
2706 runtime, it will be used to speed up change detection where possible.
2707 The inotify descriptor will be created lazily when the first "ev_stat"
2708 watcher is being started.
2709
2710 Inotify presence does not change the semantics of "ev_stat" watchers
2711 except that changes might be detected earlier, and in some cases, to
2712 avoid making regular "stat" calls. Even in the presence of inotify
2713 support there are many cases where libev has to resort to regular
2714 "stat" polling, but as long as kernel 2.6.25 or newer is used (2.6.24
2715 and older have too many bugs), the path exists (i.e. stat succeeds),
2716 and the path resides on a local filesystem (libev currently assumes
2717 only ext2/3, jfs, reiserfs and xfs are fully working) libev usually
2718 gets away without polling.
2719
2720 There is no support for kqueue, as apparently it cannot be used to
2721 implement this functionality, due to the requirement of having a file
2722 descriptor open on the object at all times, and detecting renames,
2723 unlinks etc. is difficult.
2724
2725 "stat ()" is a synchronous operation
2726
2727 Libev doesn't normally do any kind of I/O itself, and so is not
2728 blocking the process. The exception are "ev_stat" watchers - those call
2729 "stat ()", which is a synchronous operation.
2730
2731 For local paths, this usually doesn't matter: unless the system is very
2732 busy or the intervals between stat's are large, a stat call will be
2733 fast, as the path data is usually in memory already (except when
2734 starting the watcher).
2735
2736 For networked file systems, calling "stat ()" can block an indefinite
2737 time due to network issues, and even under good conditions, a stat call
2738 often takes multiple milliseconds.
2739
2740 Therefore, it is best to avoid using "ev_stat" watchers on networked
2741 paths, although this is fully supported by libev.
2742
2743 The special problem of stat time resolution
2744
2745 The "stat ()" system call only supports full-second resolution
2746 portably, and even on systems where the resolution is higher, most file
2747 systems still only support whole seconds.
2748
2749 That means that, if the time is the only thing that changes, you can
2750 easily miss updates: on the first update, "ev_stat" detects a change
2751 and calls your callback, which does something. When there is another
2752 update within the same second, "ev_stat" will be unable to detect
2753 unless the stat data does change in other ways (e.g. file size).
2754
2755 The solution to this is to delay acting on a change for slightly more
2756 than a second (or till slightly after the next full second boundary),
2757 using a roughly one-second-delay "ev_timer" (e.g. "ev_timer_set (w, 0.,
2758 1.02); ev_timer_again (loop, w)").
2759
2760 The .02 offset is added to work around small timing inconsistencies of
2761 some operating systems (where the second counter of the current time
2762 might be be delayed. One such system is the Linux kernel, where a call
2763 to "gettimeofday" might return a timestamp with a full second later
2764 than a subsequent "time" call - if the equivalent of "time ()" is used
2765 to update file times then there will be a small window where the kernel
2766 uses the previous second to update file times but libev might already
2767 execute the timer callback).
2768
2769 Watcher-Specific Functions and Data Members
2770
2771 ev_stat_init (ev_stat *, callback, const char *path, ev_tstamp
2772 interval)
2773 ev_stat_set (ev_stat *, const char *path, ev_tstamp interval)
2774 Configures the watcher to wait for status changes of the given
2775 "path". The "interval" is a hint on how quickly a change is
2776 expected to be detected and should normally be specified as 0 to
2777 let libev choose a suitable value. The memory pointed to by "path"
2778 must point to the same path for as long as the watcher is active.
2779
2780 The callback will receive an "EV_STAT" event when a change was
2781 detected, relative to the attributes at the time the watcher was
2782 started (or the last change was detected).
2783
2784 ev_stat_stat (loop, ev_stat *)
2785 Updates the stat buffer immediately with new values. If you change
2786 the watched path in your callback, you could call this function to
2787 avoid detecting this change (while introducing a race condition if
2788 you are not the only one changing the path). Can also be useful
2789 simply to find out the new values.
2790
2791 ev_statdata attr [read-only]
2792 The most-recently detected attributes of the file. Although the
2793 type is "ev_statdata", this is usually the (or one of the) "struct
2794 stat" types suitable for your system, but you can only rely on the
2795 POSIX-standardised members to be present. If the "st_nlink" member
2796 is 0, then there was some error while "stat"ing the file.
2797
2798 ev_statdata prev [read-only]
2799 The previous attributes of the file. The callback gets invoked
2800 whenever "prev" != "attr", or, more precisely, one or more of these
2801 members differ: "st_dev", "st_ino", "st_mode", "st_nlink",
2802 "st_uid", "st_gid", "st_rdev", "st_size", "st_atime", "st_mtime",
2803 "st_ctime".
2804
2805 ev_tstamp interval [read-only]
2806 The specified interval.
2807
2808 const char *path [read-only]
2809 The file system path that is being watched.
2810
2811 Examples
2812
2813 Example: Watch "/etc/passwd" for attribute changes.
2814
2815 static void
2816 passwd_cb (struct ev_loop *loop, ev_stat *w, int revents)
2817 {
2818 /* /etc/passwd changed in some way */
2819 if (w->attr.st_nlink)
2820 {
2821 printf ("passwd current size %ld\n", (long)w->attr.st_size);
2822 printf ("passwd current atime %ld\n", (long)w->attr.st_mtime);
2823 printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime);
2824 }
2825 else
2826 /* you shalt not abuse printf for puts */
2827 puts ("wow, /etc/passwd is not there, expect problems. "
2828 "if this is windows, they already arrived\n");
2829 }
2830
2831 ...
2832 ev_stat passwd;
2833
2834 ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.);
2835 ev_stat_start (loop, &passwd);
2836
2837 Example: Like above, but additionally use a one-second delay so we do
2838 not miss updates (however, frequent updates will delay processing, too,
2839 so one might do the work both on "ev_stat" callback invocation and on
2840 "ev_timer" callback invocation).
2841
2842 static ev_stat passwd;
2843 static ev_timer timer;
2844
2845 static void
2846 timer_cb (EV_P_ ev_timer *w, int revents)
2847 {
2848 ev_timer_stop (EV_A_ w);
2849
2850 /* now it's one second after the most recent passwd change */
2851 }
2852
2853 static void
2854 stat_cb (EV_P_ ev_stat *w, int revents)
2855 {
2856 /* reset the one-second timer */
2857 ev_timer_again (EV_A_ &timer);
2858 }
2859
2860 ...
2861 ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.);
2862 ev_stat_start (loop, &passwd);
2863 ev_timer_init (&timer, timer_cb, 0., 1.02);
2864
2865 "ev_idle" - when you've got nothing better to do...
2866 Idle watchers trigger events when no other events of the same or higher
2867 priority are pending (prepare, check and other idle watchers do not
2868 count as receiving "events").
2869
2870 That is, as long as your process is busy handling sockets or timeouts
2871 (or even signals, imagine) of the same or higher priority it will not
2872 be triggered. But when your process is idle (or only lower-priority
2873 watchers are pending), the idle watchers are being called once per
2874 event loop iteration - until stopped, that is, or your process receives
2875 more events and becomes busy again with higher priority stuff.
2876
2877 The most noteworthy effect is that as long as any idle watchers are
2878 active, the process will not block when waiting for new events.
2879
2880 Apart from keeping your process non-blocking (which is a useful effect
2881 on its own sometimes), idle watchers are a good place to do "pseudo-
2882 background processing", or delay processing stuff to after the event
2883 loop has handled all outstanding events.
2884
2885 Abusing an "ev_idle" watcher for its side-effect
2886
2887 As long as there is at least one active idle watcher, libev will never
2888 sleep unnecessarily. Or in other words, it will loop as fast as
2889 possible. For this to work, the idle watcher doesn't need to be
2890 invoked at all - the lowest priority will do.
2891
2892 This mode of operation can be useful together with an "ev_check"
2893 watcher, to do something on each event loop iteration - for example to
2894 balance load between different connections.
2895
2896 See "Abusing an ev_check watcher for its side-effect" for a longer
2897 example.
2898
2899 Watcher-Specific Functions and Data Members
2900
2901 ev_idle_init (ev_idle *, callback)
2902 Initialises and configures the idle watcher - it has no parameters
2903 of any kind. There is a "ev_idle_set" macro, but using it is
2904 utterly pointless, believe me.
2905
2906 Examples
2907
2908 Example: Dynamically allocate an "ev_idle" watcher, start it, and in
2909 the callback, free it. Also, use no error checking, as usual.
2910
2911 static void
2912 idle_cb (struct ev_loop *loop, ev_idle *w, int revents)
2913 {
2914 // stop the watcher
2915 ev_idle_stop (loop, w);
2916
2917 // now we can free it
2918 free (w);
2919
2920 // now do something you wanted to do when the program has
2921 // no longer anything immediate to do.
2922 }
2923
2924 ev_idle *idle_watcher = malloc (sizeof (ev_idle));
2925 ev_idle_init (idle_watcher, idle_cb);
2926 ev_idle_start (loop, idle_watcher);
2927
2928 "ev_prepare" and "ev_check" - customise your event loop!
2929 Prepare and check watchers are often (but not always) used in pairs:
2930 prepare watchers get invoked before the process blocks and check
2931 watchers afterwards.
2932
2933 You must not call "ev_run" (or similar functions that enter the current
2934 event loop) or "ev_loop_fork" from either "ev_prepare" or "ev_check"
2935 watchers. Other loops than the current one are fine, however. The
2936 rationale behind this is that you do not need to check for recursion in
2937 those watchers, i.e. the sequence will always be "ev_prepare",
2938 blocking, "ev_check" so if you have one watcher of each kind they will
2939 always be called in pairs bracketing the blocking call.
2940
2941 Their main purpose is to integrate other event mechanisms into libev
2942 and their use is somewhat advanced. They could be used, for example, to
2943 track variable changes, implement your own watchers, integrate net-snmp
2944 or a coroutine library and lots more. They are also occasionally useful
2945 if you cache some data and want to flush it before blocking (for
2946 example, in X programs you might want to do an "XFlush ()" in an
2947 "ev_prepare" watcher).
2948
2949 This is done by examining in each prepare call which file descriptors
2950 need to be watched by the other library, registering "ev_io" watchers
2951 for them and starting an "ev_timer" watcher for any timeouts (many
2952 libraries provide exactly this functionality). Then, in the check
2953 watcher, you check for any events that occurred (by checking the
2954 pending status of all watchers and stopping them) and call back into
2955 the library. The I/O and timer callbacks will never actually be called
2956 (but must be valid nevertheless, because you never know, you know?).
2957
2958 As another example, the Perl Coro module uses these hooks to integrate
2959 coroutines into libev programs, by yielding to other active coroutines
2960 during each prepare and only letting the process block if no coroutines
2961 are ready to run (it's actually more complicated: it only runs
2962 coroutines with priority higher than or equal to the event loop and one
2963 coroutine of lower priority, but only once, using idle watchers to keep
2964 the event loop from blocking if lower-priority coroutines are active,
2965 thus mapping low-priority coroutines to idle/background tasks).
2966
2967 When used for this purpose, it is recommended to give "ev_check"
2968 watchers highest ("EV_MAXPRI") priority, to ensure that they are being
2969 run before any other watchers after the poll (this doesn't matter for
2970 "ev_prepare" watchers).
2971
2972 Also, "ev_check" watchers (and "ev_prepare" watchers, too) should not
2973 activate ("feed") events into libev. While libev fully supports this,
2974 they might get executed before other "ev_check" watchers did their job.
2975 As "ev_check" watchers are often used to embed other (non-libev) event
2976 loops those other event loops might be in an unusable state until their
2977 "ev_check" watcher ran (always remind yourself to coexist peacefully
2978 with others).
2979
2980 Abusing an "ev_check" watcher for its side-effect
2981
2982 "ev_check" (and less often also "ev_prepare") watchers can also be
2983 useful because they are called once per event loop iteration. For
2984 example, if you want to handle a large number of connections fairly,
2985 you normally only do a bit of work for each active connection, and if
2986 there is more work to do, you wait for the next event loop iteration,
2987 so other connections have a chance of making progress.
2988
2989 Using an "ev_check" watcher is almost enough: it will be called on the
2990 next event loop iteration. However, that isn't as soon as possible -
2991 without external events, your "ev_check" watcher will not be invoked.
2992
2993 This is where "ev_idle" watchers come in handy - all you need is a
2994 single global idle watcher that is active as long as you have one
2995 active "ev_check" watcher. The "ev_idle" watcher makes sure the event
2996 loop will not sleep, and the "ev_check" watcher makes sure a callback
2997 gets invoked. Neither watcher alone can do that.
2998
2999 Watcher-Specific Functions and Data Members
3000
3001 ev_prepare_init (ev_prepare *, callback)
3002 ev_check_init (ev_check *, callback)
3003 Initialises and configures the prepare or check watcher - they have
3004 no parameters of any kind. There are "ev_prepare_set" and
3005 "ev_check_set" macros, but using them is utterly, utterly, utterly
3006 and completely pointless.
3007
3008 Examples
3009
3010 There are a number of principal ways to embed other event loops or
3011 modules into libev. Here are some ideas on how to include libadns into
3012 libev (there is a Perl module named "EV::ADNS" that does this, which
3013 you could use as a working example. Another Perl module named
3014 "EV::Glib" embeds a Glib main context into libev, and finally,
3015 "Glib::EV" embeds EV into the Glib event loop).
3016
3017 Method 1: Add IO watchers and a timeout watcher in a prepare handler,
3018 and in a check watcher, destroy them and call into libadns. What
3019 follows is pseudo-code only of course. This requires you to either use
3020 a low priority for the check watcher or use "ev_clear_pending"
3021 explicitly, as the callbacks for the IO/timeout watchers might not have
3022 been called yet.
3023
3024 static ev_io iow [nfd];
3025 static ev_timer tw;
3026
3027 static void
3028 io_cb (struct ev_loop *loop, ev_io *w, int revents)
3029 {
3030 }
3031
3032 // create io watchers for each fd and a timer before blocking
3033 static void
3034 adns_prepare_cb (struct ev_loop *loop, ev_prepare *w, int revents)
3035 {
3036 int timeout = 3600000;
3037 struct pollfd fds [nfd];
3038 // actual code will need to loop here and realloc etc.
3039 adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ()));
3040
3041 /* the callback is illegal, but won't be called as we stop during check */
3042 ev_timer_init (&tw, 0, timeout * 1e-3, 0.);
3043 ev_timer_start (loop, &tw);
3044
3045 // create one ev_io per pollfd
3046 for (int i = 0; i < nfd; ++i)
3047 {
3048 ev_io_init (iow + i, io_cb, fds [i].fd,
3049 ((fds [i].events & POLLIN ? EV_READ : 0)
3050 | (fds [i].events & POLLOUT ? EV_WRITE : 0)));
3051
3052 fds [i].revents = 0;
3053 ev_io_start (loop, iow + i);
3054 }
3055 }
3056
3057 // stop all watchers after blocking
3058 static void
3059 adns_check_cb (struct ev_loop *loop, ev_check *w, int revents)
3060 {
3061 ev_timer_stop (loop, &tw);
3062
3063 for (int i = 0; i < nfd; ++i)
3064 {
3065 // set the relevant poll flags
3066 // could also call adns_processreadable etc. here
3067 struct pollfd *fd = fds + i;
3068 int revents = ev_clear_pending (iow + i);
3069 if (revents & EV_READ ) fd->revents |= fd->events & POLLIN;
3070 if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT;
3071
3072 // now stop the watcher
3073 ev_io_stop (loop, iow + i);
3074 }
3075
3076 adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop));
3077 }
3078
3079 Method 2: This would be just like method 1, but you run
3080 "adns_afterpoll" in the prepare watcher and would dispose of the check
3081 watcher.
3082
3083 Method 3: If the module to be embedded supports explicit event
3084 notification (libadns does), you can also make use of the actual
3085 watcher callbacks, and only destroy/create the watchers in the prepare
3086 watcher.
3087
3088 static void
3089 timer_cb (EV_P_ ev_timer *w, int revents)
3090 {
3091 adns_state ads = (adns_state)w->data;
3092 update_now (EV_A);
3093
3094 adns_processtimeouts (ads, &tv_now);
3095 }
3096
3097 static void
3098 io_cb (EV_P_ ev_io *w, int revents)
3099 {
3100 adns_state ads = (adns_state)w->data;
3101 update_now (EV_A);
3102
3103 if (revents & EV_READ ) adns_processreadable (ads, w->fd, &tv_now);
3104 if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now);
3105 }
3106
3107 // do not ever call adns_afterpoll
3108
3109 Method 4: Do not use a prepare or check watcher because the module you
3110 want to embed is not flexible enough to support it. Instead, you can
3111 override their poll function. The drawback with this solution is that
3112 the main loop is now no longer controllable by EV. The "Glib::EV"
3113 module uses this approach, effectively embedding EV as a client into
3114 the horrible libglib event loop.
3115
3116 static gint
3117 event_poll_func (GPollFD *fds, guint nfds, gint timeout)
3118 {
3119 int got_events = 0;
3120
3121 for (n = 0; n < nfds; ++n)
3122 // create/start io watcher that sets the relevant bits in fds[n] and increment got_events
3123
3124 if (timeout >= 0)
3125 // create/start timer
3126
3127 // poll
3128 ev_run (EV_A_ 0);
3129
3130 // stop timer again
3131 if (timeout >= 0)
3132 ev_timer_stop (EV_A_ &to);
3133
3134 // stop io watchers again - their callbacks should have set
3135 for (n = 0; n < nfds; ++n)
3136 ev_io_stop (EV_A_ iow [n]);
3137
3138 return got_events;
3139 }
3140
3141 "ev_embed" - when one backend isn't enough...
3142 This is a rather advanced watcher type that lets you embed one event
3143 loop into another (currently only "ev_io" events are supported in the
3144 embedded loop, other types of watchers might be handled in a delayed or
3145 incorrect fashion and must not be used).
3146
3147 There are primarily two reasons you would want that: work around bugs
3148 and prioritise I/O.
3149
3150 As an example for a bug workaround, the kqueue backend might only
3151 support sockets on some platform, so it is unusable as generic backend,
3152 but you still want to make use of it because you have many sockets and
3153 it scales so nicely. In this case, you would create a kqueue-based loop
3154 and embed it into your default loop (which might use e.g. poll).
3155 Overall operation will be a bit slower because first libev has to call
3156 "poll" and then "kevent", but at least you can use both mechanisms for
3157 what they are best: "kqueue" for scalable sockets and "poll" if you
3158 want it to work :)
3159
3160 As for prioritising I/O: under rare circumstances you have the case
3161 where some fds have to be watched and handled very quickly (with low
3162 latency), and even priorities and idle watchers might have too much
3163 overhead. In this case you would put all the high priority stuff in one
3164 loop and all the rest in a second one, and embed the second one in the
3165 first.
3166
3167 As long as the watcher is active, the callback will be invoked every
3168 time there might be events pending in the embedded loop. The callback
3169 must then call "ev_embed_sweep (mainloop, watcher)" to make a single
3170 sweep and invoke their callbacks (the callback doesn't need to invoke
3171 the "ev_embed_sweep" function directly, it could also start an idle
3172 watcher to give the embedded loop strictly lower priority for example).
3173
3174 You can also set the callback to 0, in which case the embed watcher
3175 will automatically execute the embedded loop sweep whenever necessary.
3176
3177 Fork detection will be handled transparently while the "ev_embed"
3178 watcher is active, i.e., the embedded loop will automatically be forked
3179 when the embedding loop forks. In other cases, the user is responsible
3180 for calling "ev_loop_fork" on the embedded loop.
3181
3182 Unfortunately, not all backends are embeddable: only the ones returned
3183 by "ev_embeddable_backends" are, which, unfortunately, does not include
3184 any portable one.
3185
3186 So when you want to use this feature you will always have to be
3187 prepared that you cannot get an embeddable loop. The recommended way to
3188 get around this is to have a separate variables for your embeddable
3189 loop, try to create it, and if that fails, use the normal loop for
3190 everything.
3191
3192 "ev_embed" and fork
3193
3194 While the "ev_embed" watcher is running, forks in the embedding loop
3195 will automatically be applied to the embedded loop as well, so no
3196 special fork handling is required in that case. When the watcher is not
3197 running, however, it is still the task of the libev user to call
3198 "ev_loop_fork ()" as applicable.
3199
3200 Watcher-Specific Functions and Data Members
3201
3202 ev_embed_init (ev_embed *, callback, struct ev_loop *embedded_loop)
3203 ev_embed_set (ev_embed *, struct ev_loop *embedded_loop)
3204 Configures the watcher to embed the given loop, which must be
3205 embeddable. If the callback is 0, then "ev_embed_sweep" will be
3206 invoked automatically, otherwise it is the responsibility of the
3207 callback to invoke it (it will continue to be called until the
3208 sweep has been done, if you do not want that, you need to
3209 temporarily stop the embed watcher).
3210
3211 ev_embed_sweep (loop, ev_embed *)
3212 Make a single, non-blocking sweep over the embedded loop. This
3213 works similarly to "ev_run (embedded_loop, EVRUN_NOWAIT)", but in
3214 the most appropriate way for embedded loops.
3215
3216 struct ev_loop *other [read-only]
3217 The embedded event loop.
3218
3219 Examples
3220
3221 Example: Try to get an embeddable event loop and embed it into the
3222 default event loop. If that is not possible, use the default loop. The
3223 default loop is stored in "loop_hi", while the embeddable loop is
3224 stored in "loop_lo" (which is "loop_hi" in the case no embeddable loop
3225 can be used).
3226
3227 struct ev_loop *loop_hi = ev_default_init (0);
3228 struct ev_loop *loop_lo = 0;
3229 ev_embed embed;
3230
3231 // see if there is a chance of getting one that works
3232 // (remember that a flags value of 0 means autodetection)
3233 loop_lo = ev_embeddable_backends () & ev_recommended_backends ()
3234 ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ())
3235 : 0;
3236
3237 // if we got one, then embed it, otherwise default to loop_hi
3238 if (loop_lo)
3239 {
3240 ev_embed_init (&embed, 0, loop_lo);
3241 ev_embed_start (loop_hi, &embed);
3242 }
3243 else
3244 loop_lo = loop_hi;
3245
3246 Example: Check if kqueue is available but not recommended and create a
3247 kqueue backend for use with sockets (which usually work with any kqueue
3248 implementation). Store the kqueue/socket-only event loop in
3249 "loop_socket". (One might optionally use "EVFLAG_NOENV", too).
3250
3251 struct ev_loop *loop = ev_default_init (0);
3252 struct ev_loop *loop_socket = 0;
3253 ev_embed embed;
3254
3255 if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE)
3256 if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE))
3257 {
3258 ev_embed_init (&embed, 0, loop_socket);
3259 ev_embed_start (loop, &embed);
3260 }
3261
3262 if (!loop_socket)
3263 loop_socket = loop;
3264
3265 // now use loop_socket for all sockets, and loop for everything else
3266
3267 "ev_fork" - the audacity to resume the event loop after a fork
3268 Fork watchers are called when a "fork ()" was detected (usually because
3269 whoever is a good citizen cared to tell libev about it by calling
3270 "ev_loop_fork"). The invocation is done before the event loop blocks
3271 next and before "ev_check" watchers are being called, and only in the
3272 child after the fork. If whoever good citizen calling "ev_default_fork"
3273 cheats and calls it in the wrong process, the fork handlers will be
3274 invoked, too, of course.
3275
3276 The special problem of life after fork - how is it possible?
3277
3278 Most uses of "fork ()" consist of forking, then some simple calls to
3279 set up/change the process environment, followed by a call to "exec()".
3280 This sequence should be handled by libev without any problems.
3281
3282 This changes when the application actually wants to do event handling
3283 in the child, or both parent in child, in effect "continuing" after the
3284 fork.
3285
3286 The default mode of operation (for libev, with application help to
3287 detect forks) is to duplicate all the state in the child, as would be
3288 expected when either the parent or the child process continues.
3289
3290 When both processes want to continue using libev, then this is usually
3291 the wrong result. In that case, usually one process (typically the
3292 parent) is supposed to continue with all watchers in place as before,
3293 while the other process typically wants to start fresh, i.e. without
3294 any active watchers.
3295
3296 The cleanest and most efficient way to achieve that with libev is to
3297 simply create a new event loop, which of course will be "empty", and
3298 use that for new watchers. This has the advantage of not touching more
3299 memory than necessary, and thus avoiding the copy-on-write, and the
3300 disadvantage of having to use multiple event loops (which do not
3301 support signal watchers).
3302
3303 When this is not possible, or you want to use the default loop for
3304 other reasons, then in the process that wants to start "fresh", call
3305 "ev_loop_destroy (EV_DEFAULT)" followed by "ev_default_loop (...)".
3306 Destroying the default loop will "orphan" (not stop) all registered
3307 watchers, so you have to be careful not to execute code that modifies
3308 those watchers. Note also that in that case, you have to re-register
3309 any signal watchers.
3310
3311 Watcher-Specific Functions and Data Members
3312
3313 ev_fork_init (ev_fork *, callback)
3314 Initialises and configures the fork watcher - it has no parameters
3315 of any kind. There is a "ev_fork_set" macro, but using it is
3316 utterly pointless, really.
3317
3318 "ev_cleanup" - even the best things end
3319 Cleanup watchers are called just before the event loop is being
3320 destroyed by a call to "ev_loop_destroy".
3321
3322 While there is no guarantee that the event loop gets destroyed, cleanup
3323 watchers provide a convenient method to install cleanup hooks for your
3324 program, worker threads and so on - you just to make sure to destroy
3325 the loop when you want them to be invoked.
3326
3327 Cleanup watchers are invoked in the same way as any other watcher.
3328 Unlike all other watchers, they do not keep a reference to the event
3329 loop (which makes a lot of sense if you think about it). Like all other
3330 watchers, you can call libev functions in the callback, except
3331 "ev_cleanup_start".
3332
3333 Watcher-Specific Functions and Data Members
3334
3335 ev_cleanup_init (ev_cleanup *, callback)
3336 Initialises and configures the cleanup watcher - it has no
3337 parameters of any kind. There is a "ev_cleanup_set" macro, but
3338 using it is utterly pointless, I assure you.
3339
3340 Example: Register an atexit handler to destroy the default loop, so any
3341 cleanup functions are called.
3342
3343 static void
3344 program_exits (void)
3345 {
3346 ev_loop_destroy (EV_DEFAULT_UC);
3347 }
3348
3349 ...
3350 atexit (program_exits);
3351
3352 "ev_async" - how to wake up an event loop
3353 In general, you cannot use an "ev_loop" from multiple threads or other
3354 asynchronous sources such as signal handlers (as opposed to multiple
3355 event loops - those are of course safe to use in different threads).
3356
3357 Sometimes, however, you need to wake up an event loop you do not
3358 control, for example because it belongs to another thread. This is what
3359 "ev_async" watchers do: as long as the "ev_async" watcher is active,
3360 you can signal it by calling "ev_async_send", which is thread- and
3361 signal safe.
3362
3363 This functionality is very similar to "ev_signal" watchers, as signals,
3364 too, are asynchronous in nature, and signals, too, will be compressed
3365 (i.e. the number of callback invocations may be less than the number of
3366 "ev_async_send" calls). In fact, you could use signal watchers as a
3367 kind of "global async watchers" by using a watcher on an otherwise
3368 unused signal, and "ev_feed_signal" to signal this watcher from another
3369 thread, even without knowing which loop owns the signal.
3370
3371 Queueing
3372
3373 "ev_async" does not support queueing of data in any way. The reason is
3374 that the author does not know of a simple (or any) algorithm for a
3375 multiple-writer-single-reader queue that works in all cases and doesn't
3376 need elaborate support such as pthreads or unportable memory access
3377 semantics.
3378
3379 That means that if you want to queue data, you have to provide your own
3380 queue. But at least I can tell you how to implement locking around your
3381 queue:
3382
3383 queueing from a signal handler context
3384 To implement race-free queueing, you simply add to the queue in the
3385 signal handler but you block the signal handler in the watcher
3386 callback. Here is an example that does that for some fictitious
3387 SIGUSR1 handler:
3388
3389 static ev_async mysig;
3390
3391 static void
3392 sigusr1_handler (void)
3393 {
3394 sometype data;
3395
3396 // no locking etc.
3397 queue_put (data);
3398 ev_async_send (EV_DEFAULT_ &mysig);
3399 }
3400
3401 static void
3402 mysig_cb (EV_P_ ev_async *w, int revents)
3403 {
3404 sometype data;
3405 sigset_t block, prev;
3406
3407 sigemptyset (&block);
3408 sigaddset (&block, SIGUSR1);
3409 sigprocmask (SIG_BLOCK, &block, &prev);
3410
3411 while (queue_get (&data))
3412 process (data);
3413
3414 if (sigismember (&prev, SIGUSR1)
3415 sigprocmask (SIG_UNBLOCK, &block, 0);
3416 }
3417
3418 (Note: pthreads in theory requires you to use "pthread_setmask"
3419 instead of "sigprocmask" when you use threads, but libev doesn't do
3420 it either...).
3421
3422 queueing from a thread context
3423 The strategy for threads is different, as you cannot (easily) block
3424 threads but you can easily preempt them, so to queue safely you
3425 need to employ a traditional mutex lock, such as in this pthread
3426 example:
3427
3428 static ev_async mysig;
3429 static pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
3430
3431 static void
3432 otherthread (void)
3433 {
3434 // only need to lock the actual queueing operation
3435 pthread_mutex_lock (&mymutex);
3436 queue_put (data);
3437 pthread_mutex_unlock (&mymutex);
3438
3439 ev_async_send (EV_DEFAULT_ &mysig);
3440 }
3441
3442 static void
3443 mysig_cb (EV_P_ ev_async *w, int revents)
3444 {
3445 pthread_mutex_lock (&mymutex);
3446
3447 while (queue_get (&data))
3448 process (data);
3449
3450 pthread_mutex_unlock (&mymutex);
3451 }
3452
3453 Watcher-Specific Functions and Data Members
3454
3455 ev_async_init (ev_async *, callback)
3456 Initialises and configures the async watcher - it has no parameters
3457 of any kind. There is a "ev_async_set" macro, but using it is
3458 utterly pointless, trust me.
3459
3460 ev_async_send (loop, ev_async *)
3461 Sends/signals/activates the given "ev_async" watcher, that is,
3462 feeds an "EV_ASYNC" event on the watcher into the event loop, and
3463 instantly returns.
3464
3465 Unlike "ev_feed_event", this call is safe to do from other threads,
3466 signal or similar contexts (see the discussion of "EV_ATOMIC_T" in
3467 the embedding section below on what exactly this means).
3468
3469 Note that, as with other watchers in libev, multiple events might
3470 get compressed into a single callback invocation (another way to
3471 look at this is that "ev_async" watchers are level-triggered: they
3472 are set on "ev_async_send", reset when the event loop detects
3473 that).
3474
3475 This call incurs the overhead of at most one extra system call per
3476 event loop iteration, if the event loop is blocked, and no syscall
3477 at all if the event loop (or your program) is processing events.
3478 That means that repeated calls are basically free (there is no need
3479 to avoid calls for performance reasons) and that the overhead
3480 becomes smaller (typically zero) under load.
3481
3482 bool = ev_async_pending (ev_async *)
3483 Returns a non-zero value when "ev_async_send" has been called on
3484 the watcher but the event has not yet been processed (or even
3485 noted) by the event loop.
3486
3487 "ev_async_send" sets a flag in the watcher and wakes up the loop.
3488 When the loop iterates next and checks for the watcher to have
3489 become active, it will reset the flag again. "ev_async_pending" can
3490 be used to very quickly check whether invoking the loop might be a
3491 good idea.
3492
3493 Not that this does not check whether the watcher itself is pending,
3494 only whether it has been requested to make this watcher pending:
3495 there is a time window between the event loop checking and
3496 resetting the async notification, and the callback being invoked.
3497
3499 There are some other functions of possible interest. Described. Here.
3500 Now.
3501
3502 ev_once (loop, int fd, int events, ev_tstamp timeout, callback, arg)
3503 This function combines a simple timer and an I/O watcher, calls
3504 your callback on whichever event happens first and automatically
3505 stops both watchers. This is useful if you want to wait for a
3506 single event on an fd or timeout without having to
3507 allocate/configure/start/stop/free one or more watchers yourself.
3508
3509 If "fd" is less than 0, then no I/O watcher will be started and the
3510 "events" argument is being ignored. Otherwise, an "ev_io" watcher
3511 for the given "fd" and "events" set will be created and started.
3512
3513 If "timeout" is less than 0, then no timeout watcher will be
3514 started. Otherwise an "ev_timer" watcher with after = "timeout"
3515 (and repeat = 0) will be started. 0 is a valid timeout.
3516
3517 The callback has the type "void (*cb)(int revents, void *arg)" and
3518 is passed an "revents" set like normal event callbacks (a
3519 combination of "EV_ERROR", "EV_READ", "EV_WRITE" or "EV_TIMER") and
3520 the "arg" value passed to "ev_once". Note that it is possible to
3521 receive both a timeout and an io event at the same time - you
3522 probably should give io events precedence.
3523
3524 Example: wait up to ten seconds for data to appear on STDIN_FILENO.
3525
3526 static void stdin_ready (int revents, void *arg)
3527 {
3528 if (revents & EV_READ)
3529 /* stdin might have data for us, joy! */;
3530 else if (revents & EV_TIMER)
3531 /* doh, nothing entered */;
3532 }
3533
3534 ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);
3535
3536 ev_feed_fd_event (loop, int fd, int revents)
3537 Feed an event on the given fd, as if a file descriptor backend
3538 detected the given events.
3539
3540 ev_feed_signal_event (loop, int signum)
3541 Feed an event as if the given signal occurred. See also
3542 "ev_feed_signal", which is async-safe.
3543
3545 This section explains some common idioms that are not immediately
3546 obvious. Note that examples are sprinkled over the whole manual, and
3547 this section only contains stuff that wouldn't fit anywhere else.
3548
3549 ASSOCIATING CUSTOM DATA WITH A WATCHER
3550 Each watcher has, by default, a "void *data" member that you can read
3551 or modify at any time: libev will completely ignore it. This can be
3552 used to associate arbitrary data with your watcher. If you need more
3553 data and don't want to allocate memory separately and store a pointer
3554 to it in that data member, you can also "subclass" the watcher type and
3555 provide your own data:
3556
3557 struct my_io
3558 {
3559 ev_io io;
3560 int otherfd;
3561 void *somedata;
3562 struct whatever *mostinteresting;
3563 };
3564
3565 ...
3566 struct my_io w;
3567 ev_io_init (&w.io, my_cb, fd, EV_READ);
3568
3569 And since your callback will be called with a pointer to the watcher,
3570 you can cast it back to your own type:
3571
3572 static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
3573 {
3574 struct my_io *w = (struct my_io *)w_;
3575 ...
3576 }
3577
3578 More interesting and less C-conformant ways of casting your callback
3579 function type instead have been omitted.
3580
3581 BUILDING YOUR OWN COMPOSITE WATCHERS
3582 Another common scenario is to use some data structure with multiple
3583 embedded watchers, in effect creating your own watcher that combines
3584 multiple libev event sources into one "super-watcher":
3585
3586 struct my_biggy
3587 {
3588 int some_data;
3589 ev_timer t1;
3590 ev_timer t2;
3591 }
3592
3593 In this case getting the pointer to "my_biggy" is a bit more
3594 complicated: Either you store the address of your "my_biggy" struct in
3595 the "data" member of the watcher (for woozies or C++ coders), or you
3596 need to use some pointer arithmetic using "offsetof" inside your
3597 watchers (for real programmers):
3598
3599 #include <stddef.h>
3600
3601 static void
3602 t1_cb (EV_P_ ev_timer *w, int revents)
3603 {
3604 struct my_biggy big = (struct my_biggy *)
3605 (((char *)w) - offsetof (struct my_biggy, t1));
3606 }
3607
3608 static void
3609 t2_cb (EV_P_ ev_timer *w, int revents)
3610 {
3611 struct my_biggy big = (struct my_biggy *)
3612 (((char *)w) - offsetof (struct my_biggy, t2));
3613 }
3614
3615 AVOIDING FINISHING BEFORE RETURNING
3616 Often you have structures like this in event-based programs:
3617
3618 callback ()
3619 {
3620 free (request);
3621 }
3622
3623 request = start_new_request (..., callback);
3624
3625 The intent is to start some "lengthy" operation. The "request" could be
3626 used to cancel the operation, or do other things with it.
3627
3628 It's not uncommon to have code paths in "start_new_request" that
3629 immediately invoke the callback, for example, to report errors. Or you
3630 add some caching layer that finds that it can skip the lengthy aspects
3631 of the operation and simply invoke the callback with the result.
3632
3633 The problem here is that this will happen before "start_new_request"
3634 has returned, so "request" is not set.
3635
3636 Even if you pass the request by some safer means to the callback, you
3637 might want to do something to the request after starting it, such as
3638 canceling it, which probably isn't working so well when the callback
3639 has already been invoked.
3640
3641 A common way around all these issues is to make sure that
3642 "start_new_request" always returns before the callback is invoked. If
3643 "start_new_request" immediately knows the result, it can artificially
3644 delay invoking the callback by using a "prepare" or "idle" watcher for
3645 example, or more sneakily, by reusing an existing (stopped) watcher and
3646 pushing it into the pending queue:
3647
3648 ev_set_cb (watcher, callback);
3649 ev_feed_event (EV_A_ watcher, 0);
3650
3651 This way, "start_new_request" can safely return before the callback is
3652 invoked, while not delaying callback invocation too much.
3653
3654 MODEL/NESTED EVENT LOOP INVOCATIONS AND EXIT CONDITIONS
3655 Often (especially in GUI toolkits) there are places where you have
3656 modal interaction, which is most easily implemented by recursively
3657 invoking "ev_run".
3658
3659 This brings the problem of exiting - a callback might want to finish
3660 the main "ev_run" call, but not the nested one (e.g. user clicked
3661 "Quit", but a modal "Are you sure?" dialog is still waiting), or just
3662 the nested one and not the main one (e.g. user clocked "Ok" in a modal
3663 dialog), or some other combination: In these cases, a simple "ev_break"
3664 will not work.
3665
3666 The solution is to maintain "break this loop" variable for each
3667 "ev_run" invocation, and use a loop around "ev_run" until the condition
3668 is triggered, using "EVRUN_ONCE":
3669
3670 // main loop
3671 int exit_main_loop = 0;
3672
3673 while (!exit_main_loop)
3674 ev_run (EV_DEFAULT_ EVRUN_ONCE);
3675
3676 // in a modal watcher
3677 int exit_nested_loop = 0;
3678
3679 while (!exit_nested_loop)
3680 ev_run (EV_A_ EVRUN_ONCE);
3681
3682 To exit from any of these loops, just set the corresponding exit
3683 variable:
3684
3685 // exit modal loop
3686 exit_nested_loop = 1;
3687
3688 // exit main program, after modal loop is finished
3689 exit_main_loop = 1;
3690
3691 // exit both
3692 exit_main_loop = exit_nested_loop = 1;
3693
3694 THREAD LOCKING EXAMPLE
3695 Here is a fictitious example of how to run an event loop in a different
3696 thread from where callbacks are being invoked and watchers are
3697 created/added/removed.
3698
3699 For a real-world example, see the "EV::Loop::Async" perl module, which
3700 uses exactly this technique (which is suited for many high-level
3701 languages).
3702
3703 The example uses a pthread mutex to protect the loop data, a condition
3704 variable to wait for callback invocations, an async watcher to notify
3705 the event loop thread and an unspecified mechanism to wake up the main
3706 thread.
3707
3708 First, you need to associate some data with the event loop:
3709
3710 typedef struct {
3711 mutex_t lock; /* global loop lock */
3712 ev_async async_w;
3713 thread_t tid;
3714 cond_t invoke_cv;
3715 } userdata;
3716
3717 void prepare_loop (EV_P)
3718 {
3719 // for simplicity, we use a static userdata struct.
3720 static userdata u;
3721
3722 ev_async_init (&u->async_w, async_cb);
3723 ev_async_start (EV_A_ &u->async_w);
3724
3725 pthread_mutex_init (&u->lock, 0);
3726 pthread_cond_init (&u->invoke_cv, 0);
3727
3728 // now associate this with the loop
3729 ev_set_userdata (EV_A_ u);
3730 ev_set_invoke_pending_cb (EV_A_ l_invoke);
3731 ev_set_loop_release_cb (EV_A_ l_release, l_acquire);
3732
3733 // then create the thread running ev_run
3734 pthread_create (&u->tid, 0, l_run, EV_A);
3735 }
3736
3737 The callback for the "ev_async" watcher does nothing: the watcher is
3738 used solely to wake up the event loop so it takes notice of any new
3739 watchers that might have been added:
3740
3741 static void
3742 async_cb (EV_P_ ev_async *w, int revents)
3743 {
3744 // just used for the side effects
3745 }
3746
3747 The "l_release" and "l_acquire" callbacks simply unlock/lock the mutex
3748 protecting the loop data, respectively.
3749
3750 static void
3751 l_release (EV_P)
3752 {
3753 userdata *u = ev_userdata (EV_A);
3754 pthread_mutex_unlock (&u->lock);
3755 }
3756
3757 static void
3758 l_acquire (EV_P)
3759 {
3760 userdata *u = ev_userdata (EV_A);
3761 pthread_mutex_lock (&u->lock);
3762 }
3763
3764 The event loop thread first acquires the mutex, and then jumps straight
3765 into "ev_run":
3766
3767 void *
3768 l_run (void *thr_arg)
3769 {
3770 struct ev_loop *loop = (struct ev_loop *)thr_arg;
3771
3772 l_acquire (EV_A);
3773 pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
3774 ev_run (EV_A_ 0);
3775 l_release (EV_A);
3776
3777 return 0;
3778 }
3779
3780 Instead of invoking all pending watchers, the "l_invoke" callback will
3781 signal the main thread via some unspecified mechanism (signals? pipe
3782 writes? "Async::Interrupt"?) and then waits until all pending watchers
3783 have been called (in a while loop because a) spurious wakeups are
3784 possible and b) skipping inter-thread-communication when there are no
3785 pending watchers is very beneficial):
3786
3787 static void
3788 l_invoke (EV_P)
3789 {
3790 userdata *u = ev_userdata (EV_A);
3791
3792 while (ev_pending_count (EV_A))
3793 {
3794 wake_up_other_thread_in_some_magic_or_not_so_magic_way ();
3795 pthread_cond_wait (&u->invoke_cv, &u->lock);
3796 }
3797 }
3798
3799 Now, whenever the main thread gets told to invoke pending watchers, it
3800 will grab the lock, call "ev_invoke_pending" and then signal the loop
3801 thread to continue:
3802
3803 static void
3804 real_invoke_pending (EV_P)
3805 {
3806 userdata *u = ev_userdata (EV_A);
3807
3808 pthread_mutex_lock (&u->lock);
3809 ev_invoke_pending (EV_A);
3810 pthread_cond_signal (&u->invoke_cv);
3811 pthread_mutex_unlock (&u->lock);
3812 }
3813
3814 Whenever you want to start/stop a watcher or do other modifications to
3815 an event loop, you will now have to lock:
3816
3817 ev_timer timeout_watcher;
3818 userdata *u = ev_userdata (EV_A);
3819
3820 ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
3821
3822 pthread_mutex_lock (&u->lock);
3823 ev_timer_start (EV_A_ &timeout_watcher);
3824 ev_async_send (EV_A_ &u->async_w);
3825 pthread_mutex_unlock (&u->lock);
3826
3827 Note that sending the "ev_async" watcher is required because otherwise
3828 an event loop currently blocking in the kernel will have no knowledge
3829 about the newly added timer. By waking up the loop it will pick up any
3830 new watchers in the next event loop iteration.
3831
3832 THREADS, COROUTINES, CONTINUATIONS, QUEUES... INSTEAD OF CALLBACKS
3833 While the overhead of a callback that e.g. schedules a thread is small,
3834 it is still an overhead. If you embed libev, and your main usage is
3835 with some kind of threads or coroutines, you might want to customise
3836 libev so that doesn't need callbacks anymore.
3837
3838 Imagine you have coroutines that you can switch to using a function
3839 "switch_to (coro)", that libev runs in a coroutine called "libev_coro"
3840 and that due to some magic, the currently active coroutine is stored in
3841 a global called "current_coro". Then you can build your own "wait for
3842 libev event" primitive by changing "EV_CB_DECLARE" and "EV_CB_INVOKE"
3843 (note the differing ";" conventions):
3844
3845 #define EV_CB_DECLARE(type) struct my_coro *cb;
3846 #define EV_CB_INVOKE(watcher) switch_to ((watcher)->cb)
3847
3848 That means instead of having a C callback function, you store the
3849 coroutine to switch to in each watcher, and instead of having libev
3850 call your callback, you instead have it switch to that coroutine.
3851
3852 A coroutine might now wait for an event with a function called
3853 "wait_for_event". (the watcher needs to be started, as always, but it
3854 doesn't matter when, or whether the watcher is active or not when this
3855 function is called):
3856
3857 void
3858 wait_for_event (ev_watcher *w)
3859 {
3860 ev_set_cb (w, current_coro);
3861 switch_to (libev_coro);
3862 }
3863
3864 That basically suspends the coroutine inside "wait_for_event" and
3865 continues the libev coroutine, which, when appropriate, switches back
3866 to this or any other coroutine.
3867
3868 You can do similar tricks if you have, say, threads with an event queue
3869 - instead of storing a coroutine, you store the queue object and
3870 instead of switching to a coroutine, you push the watcher onto the
3871 queue and notify any waiters.
3872
3873 To embed libev, see "EMBEDDING", but in short, it's easiest to create
3874 two files, my_ev.h and my_ev.c that include the respective libev files:
3875
3876 // my_ev.h
3877 #define EV_CB_DECLARE(type) struct my_coro *cb;
3878 #define EV_CB_INVOKE(watcher) switch_to ((watcher)->cb)
3879 #include "../libev/ev.h"
3880
3881 // my_ev.c
3882 #define EV_H "my_ev.h"
3883 #include "../libev/ev.c"
3884
3885 And then use my_ev.h when you would normally use ev.h, and compile
3886 my_ev.c into your project. When properly specifying include paths, you
3887 can even use ev.h as header file name directly.
3888
3890 Libev offers a compatibility emulation layer for libevent. It cannot
3891 emulate the internals of libevent, so here are some usage hints:
3892
3893 · Only the libevent-1.4.1-beta API is being emulated.
3894
3895 This was the newest libevent version available when libev was
3896 implemented, and is still mostly unchanged in 2010.
3897
3898 · Use it by including <event.h>, as usual.
3899
3900 · The following members are fully supported: ev_base, ev_callback,
3901 ev_arg, ev_fd, ev_res, ev_events.
3902
3903 · Avoid using ev_flags and the EVLIST_*-macros, while it is
3904 maintained by libev, it does not work exactly the same way as in
3905 libevent (consider it a private API).
3906
3907 · Priorities are not currently supported. Initialising priorities
3908 will fail and all watchers will have the same priority, even though
3909 there is an ev_pri field.
3910
3911 · In libevent, the last base created gets the signals, in libev, the
3912 base that registered the signal gets the signals.
3913
3914 · Other members are not supported.
3915
3916 · The libev emulation is not ABI compatible to libevent, you need to
3917 use the libev header file and library.
3918
3920 C API
3921 The normal C API should work fine when used from C++: both ev.h and the
3922 libev sources can be compiled as C++. Therefore, code that uses the C
3923 API will work fine.
3924
3925 Proper exception specifications might have to be added to callbacks
3926 passed to libev: exceptions may be thrown only from watcher callbacks,
3927 all other callbacks (allocator, syserr, loop acquire/release and
3928 periodic reschedule callbacks) must not throw exceptions, and might
3929 need a "noexcept" specification. If you have code that needs to be
3930 compiled as both C and C++ you can use the "EV_NOEXCEPT" macro for
3931 this:
3932
3933 static void
3934 fatal_error (const char *msg) EV_NOEXCEPT
3935 {
3936 perror (msg);
3937 abort ();
3938 }
3939
3940 ...
3941 ev_set_syserr_cb (fatal_error);
3942
3943 The only API functions that can currently throw exceptions are
3944 "ev_run", "ev_invoke", "ev_invoke_pending" and "ev_loop_destroy" (the
3945 latter because it runs cleanup watchers).
3946
3947 Throwing exceptions in watcher callbacks is only supported if libev
3948 itself is compiled with a C++ compiler or your C and C++ environments
3949 allow throwing exceptions through C libraries (most do).
3950
3951 C++ API
3952 Libev comes with some simplistic wrapper classes for C++ that mainly
3953 allow you to use some convenience methods to start/stop watchers and
3954 also change the callback model to a model using method callbacks on
3955 objects.
3956
3957 To use it,
3958
3959 #include <ev++.h>
3960
3961 This automatically includes ev.h and puts all of its definitions (many
3962 of them macros) into the global namespace. All C++ specific things are
3963 put into the "ev" namespace. It should support all the same embedding
3964 options as ev.h, most notably "EV_MULTIPLICITY".
3965
3966 Care has been taken to keep the overhead low. The only data member the
3967 C++ classes add (compared to plain C-style watchers) is the event loop
3968 pointer that the watcher is associated with (or no additional members
3969 at all if you disable "EV_MULTIPLICITY" when embedding libev).
3970
3971 Currently, functions, static and non-static member functions and
3972 classes with "operator ()" can be used as callbacks. Other types should
3973 be easy to add as long as they only need one additional pointer for
3974 context. If you need support for other types of functors please contact
3975 the author (preferably after implementing it).
3976
3977 For all this to work, your C++ compiler either has to use the same
3978 calling conventions as your C compiler (for static member functions),
3979 or you have to embed libev and compile libev itself as C++.
3980
3981 Here is a list of things available in the "ev" namespace:
3982
3983 "ev::READ", "ev::WRITE" etc.
3984 These are just enum values with the same values as the "EV_READ"
3985 etc. macros from ev.h.
3986
3987 "ev::tstamp", "ev::now"
3988 Aliases to the same types/functions as with the "ev_" prefix.
3989
3990 "ev::io", "ev::timer", "ev::periodic", "ev::idle", "ev::sig" etc.
3991 For each "ev_TYPE" watcher in ev.h there is a corresponding class
3992 of the same name in the "ev" namespace, with the exception of
3993 "ev_signal" which is called "ev::sig" to avoid clashes with the
3994 "signal" macro defined by many implementations.
3995
3996 All of those classes have these methods:
3997
3998 ev::TYPE::TYPE ()
3999 ev::TYPE::TYPE (loop)
4000 ev::TYPE::~TYPE
4001 The constructor (optionally) takes an event loop to associate
4002 the watcher with. If it is omitted, it will use "EV_DEFAULT".
4003
4004 The constructor calls "ev_init" for you, which means you have
4005 to call the "set" method before starting it.
4006
4007 It will not set a callback, however: You have to call the
4008 templated "set" method to set a callback before you can start
4009 the watcher.
4010
4011 (The reason why you have to use a method is a limitation in C++
4012 which does not allow explicit template arguments for
4013 constructors).
4014
4015 The destructor automatically stops the watcher if it is active.
4016
4017 w->set<class, &class::method> (object *)
4018 This method sets the callback method to call. The method has to
4019 have a signature of "void (*)(ev_TYPE &, int)", it receives the
4020 watcher as first argument and the "revents" as second. The
4021 object must be given as parameter and is stored in the "data"
4022 member of the watcher.
4023
4024 This method synthesizes efficient thunking code to call your
4025 method from the C callback that libev requires. If your
4026 compiler can inline your callback (i.e. it is visible to it at
4027 the place of the "set" call and your compiler is good :), then
4028 the method will be fully inlined into the thunking function,
4029 making it as fast as a direct C callback.
4030
4031 Example: simple class declaration and watcher initialisation
4032
4033 struct myclass
4034 {
4035 void io_cb (ev::io &w, int revents) { }
4036 }
4037
4038 myclass obj;
4039 ev::io iow;
4040 iow.set <myclass, &myclass::io_cb> (&obj);
4041
4042 w->set (object *)
4043 This is a variation of a method callback - leaving out the
4044 method to call will default the method to "operator ()", which
4045 makes it possible to use functor objects without having to
4046 manually specify the "operator ()" all the time. Incidentally,
4047 you can then also leave out the template argument list.
4048
4049 The "operator ()" method prototype must be "void operator
4050 ()(watcher &w, int revents)".
4051
4052 See the method-"set" above for more details.
4053
4054 Example: use a functor object as callback.
4055
4056 struct myfunctor
4057 {
4058 void operator() (ev::io &w, int revents)
4059 {
4060 ...
4061 }
4062 }
4063
4064 myfunctor f;
4065
4066 ev::io w;
4067 w.set (&f);
4068
4069 w->set<function> (void *data = 0)
4070 Also sets a callback, but uses a static method or plain
4071 function as callback. The optional "data" argument will be
4072 stored in the watcher's "data" member and is free for you to
4073 use.
4074
4075 The prototype of the "function" must be "void (*)(ev::TYPE &w,
4076 int)".
4077
4078 See the method-"set" above for more details.
4079
4080 Example: Use a plain function as callback.
4081
4082 static void io_cb (ev::io &w, int revents) { }
4083 iow.set <io_cb> ();
4084
4085 w->set (loop)
4086 Associates a different "struct ev_loop" with this watcher. You
4087 can only do this when the watcher is inactive (and not pending
4088 either).
4089
4090 w->set ([arguments])
4091 Basically the same as "ev_TYPE_set" (except for "ev::embed"
4092 watchers>), with the same arguments. Either this method or a
4093 suitable start method must be called at least once. Unlike the
4094 C counterpart, an active watcher gets automatically stopped and
4095 restarted when reconfiguring it with this method.
4096
4097 For "ev::embed" watchers this method is called "set_embed", to
4098 avoid clashing with the "set (loop)" method.
4099
4100 w->start ()
4101 Starts the watcher. Note that there is no "loop" argument, as
4102 the constructor already stores the event loop.
4103
4104 w->start ([arguments])
4105 Instead of calling "set" and "start" methods separately, it is
4106 often convenient to wrap them in one call. Uses the same type
4107 of arguments as the configure "set" method of the watcher.
4108
4109 w->stop ()
4110 Stops the watcher if it is active. Again, no "loop" argument.
4111
4112 w->again () ("ev::timer", "ev::periodic" only)
4113 For "ev::timer" and "ev::periodic", this invokes the
4114 corresponding "ev_TYPE_again" function.
4115
4116 w->sweep () ("ev::embed" only)
4117 Invokes "ev_embed_sweep".
4118
4119 w->update () ("ev::stat" only)
4120 Invokes "ev_stat_stat".
4121
4122 Example: Define a class with two I/O and idle watchers, start the I/O
4123 watchers in the constructor.
4124
4125 class myclass
4126 {
4127 ev::io io ; void io_cb (ev::io &w, int revents);
4128 ev::io io2 ; void io2_cb (ev::io &w, int revents);
4129 ev::idle idle; void idle_cb (ev::idle &w, int revents);
4130
4131 myclass (int fd)
4132 {
4133 io .set <myclass, &myclass::io_cb > (this);
4134 io2 .set <myclass, &myclass::io2_cb > (this);
4135 idle.set <myclass, &myclass::idle_cb> (this);
4136
4137 io.set (fd, ev::WRITE); // configure the watcher
4138 io.start (); // start it whenever convenient
4139
4140 io2.start (fd, ev::READ); // set + start in one call
4141 }
4142 };
4143
4145 Libev does not offer other language bindings itself, but bindings for a
4146 number of languages exist in the form of third-party packages. If you
4147 know any interesting language binding in addition to the ones listed
4148 here, drop me a note.
4149
4150 Perl
4151 The EV module implements the full libev API and is actually used to
4152 test libev. EV is developed together with libev. Apart from the EV
4153 core module, there are additional modules that implement libev-
4154 compatible interfaces to "libadns" ("EV::ADNS", but "AnyEvent::DNS"
4155 is preferred nowadays), "Net::SNMP" ("Net::SNMP::EV") and the
4156 "libglib" event core ("Glib::EV" and "EV::Glib").
4157
4158 It can be found and installed via CPAN, its homepage is at
4159 <http://software.schmorp.de/pkg/EV>.
4160
4161 Python
4162 Python bindings can be found at <http://code.google.com/p/pyev/>.
4163 It seems to be quite complete and well-documented.
4164
4165 Ruby
4166 Tony Arcieri has written a ruby extension that offers access to a
4167 subset of the libev API and adds file handle abstractions,
4168 asynchronous DNS and more on top of it. It can be found via gem
4169 servers. Its homepage is at <http://rev.rubyforge.org/>.
4170
4171 Roger Pack reports that using the link order "-lws2_32
4172 -lmsvcrt-ruby-190" makes rev work even on mingw.
4173
4174 Haskell
4175 A haskell binding to libev is available at
4176 <http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hlibev>.
4177
4178 D Leandro Lucarella has written a D language binding (ev.d) for
4179 libev, to be found at
4180 <http://www.llucax.com.ar/proj/ev.d/index.html>.
4181
4182 Ocaml
4183 Erkki Seppala has written Ocaml bindings for libev, to be found at
4184 <http://modeemi.cs.tut.fi/~flux/software/ocaml-ev/>.
4185
4186 Lua Brian Maher has written a partial interface to libev for lua (at
4187 the time of this writing, only "ev_io" and "ev_timer"), to be found
4188 at <http://github.com/brimworks/lua-ev>.
4189
4190 Javascript
4191 Node.js (<http://nodejs.org>) uses libev as the underlying event
4192 library.
4193
4194 Others
4195 There are others, and I stopped counting.
4196
4198 Libev can be compiled with a variety of options, the most fundamental
4199 of which is "EV_MULTIPLICITY". This option determines whether (most)
4200 functions and callbacks have an initial "struct ev_loop *" argument.
4201
4202 To make it easier to write programs that cope with either variant, the
4203 following macros are defined:
4204
4205 "EV_A", "EV_A_"
4206 This provides the loop argument for functions, if one is required
4207 ("ev loop argument"). The "EV_A" form is used when this is the sole
4208 argument, "EV_A_" is used when other arguments are following.
4209 Example:
4210
4211 ev_unref (EV_A);
4212 ev_timer_add (EV_A_ watcher);
4213 ev_run (EV_A_ 0);
4214
4215 It assumes the variable "loop" of type "struct ev_loop *" is in
4216 scope, which is often provided by the following macro.
4217
4218 "EV_P", "EV_P_"
4219 This provides the loop parameter for functions, if one is required
4220 ("ev loop parameter"). The "EV_P" form is used when this is the
4221 sole parameter, "EV_P_" is used when other parameters are
4222 following. Example:
4223
4224 // this is how ev_unref is being declared
4225 static void ev_unref (EV_P);
4226
4227 // this is how you can declare your typical callback
4228 static void cb (EV_P_ ev_timer *w, int revents)
4229
4230 It declares a parameter "loop" of type "struct ev_loop *", quite
4231 suitable for use with "EV_A".
4232
4233 "EV_DEFAULT", "EV_DEFAULT_"
4234 Similar to the other two macros, this gives you the value of the
4235 default loop, if multiple loops are supported ("ev loop default").
4236 The default loop will be initialised if it isn't already
4237 initialised.
4238
4239 For non-multiplicity builds, these macros do nothing, so you always
4240 have to initialise the loop somewhere.
4241
4242 "EV_DEFAULT_UC", "EV_DEFAULT_UC_"
4243 Usage identical to "EV_DEFAULT" and "EV_DEFAULT_", but requires
4244 that the default loop has been initialised ("UC" == unchecked).
4245 Their behaviour is undefined when the default loop has not been
4246 initialised by a previous execution of "EV_DEFAULT", "EV_DEFAULT_"
4247 or "ev_default_init (...)".
4248
4249 It is often prudent to use "EV_DEFAULT" when initialising the first
4250 watcher in a function but use "EV_DEFAULT_UC" afterwards.
4251
4252 Example: Declare and initialise a check watcher, utilising the above
4253 macros so it will work regardless of whether multiple loops are
4254 supported or not.
4255
4256 static void
4257 check_cb (EV_P_ ev_timer *w, int revents)
4258 {
4259 ev_check_stop (EV_A_ w);
4260 }
4261
4262 ev_check check;
4263 ev_check_init (&check, check_cb);
4264 ev_check_start (EV_DEFAULT_ &check);
4265 ev_run (EV_DEFAULT_ 0);
4266
4268 Libev can (and often is) directly embedded into host applications.
4269 Examples of applications that embed it include the Deliantra Game
4270 Server, the EV perl module, the GNU Virtual Private Ethernet (gvpe) and
4271 rxvt-unicode.
4272
4273 The goal is to enable you to just copy the necessary files into your
4274 source directory without having to change even a single line in them,
4275 so you can easily upgrade by simply copying (or having a checked-out
4276 copy of libev somewhere in your source tree).
4277
4278 FILESETS
4279 Depending on what features you need you need to include one or more
4280 sets of files in your application.
4281
4282 CORE EVENT LOOP
4283
4284 To include only the libev core (all the "ev_*" functions), with manual
4285 configuration (no autoconf):
4286
4287 #define EV_STANDALONE 1
4288 #include "ev.c"
4289
4290 This will automatically include ev.h, too, and should be done in a
4291 single C source file only to provide the function implementations. To
4292 use it, do the same for ev.h in all files wishing to use this API (best
4293 done by writing a wrapper around ev.h that you can include instead and
4294 where you can put other configuration options):
4295
4296 #define EV_STANDALONE 1
4297 #include "ev.h"
4298
4299 Both header files and implementation files can be compiled with a C++
4300 compiler (at least, that's a stated goal, and breakage will be treated
4301 as a bug).
4302
4303 You need the following files in your source tree, or in a directory in
4304 your include path (e.g. in libev/ when using -Ilibev):
4305
4306 ev.h
4307 ev.c
4308 ev_vars.h
4309 ev_wrap.h
4310
4311 ev_win32.c required on win32 platforms only
4312
4313 ev_select.c only when select backend is enabled
4314 ev_poll.c only when poll backend is enabled
4315 ev_epoll.c only when the epoll backend is enabled
4316 ev_linuxaio.c only when the linux aio backend is enabled
4317 ev_iouring.c only when the linux io_uring backend is enabled
4318 ev_kqueue.c only when the kqueue backend is enabled
4319 ev_port.c only when the solaris port backend is enabled
4320
4321 ev.c includes the backend files directly when enabled, so you only need
4322 to compile this single file.
4323
4324 LIBEVENT COMPATIBILITY API
4325
4326 To include the libevent compatibility API, also include:
4327
4328 #include "event.c"
4329
4330 in the file including ev.c, and:
4331
4332 #include "event.h"
4333
4334 in the files that want to use the libevent API. This also includes
4335 ev.h.
4336
4337 You need the following additional files for this:
4338
4339 event.h
4340 event.c
4341
4342 AUTOCONF SUPPORT
4343
4344 Instead of using "EV_STANDALONE=1" and providing your configuration in
4345 whatever way you want, you can also "m4_include([libev.m4])" in your
4346 configure.ac and leave "EV_STANDALONE" undefined. ev.c will then
4347 include config.h and configure itself accordingly.
4348
4349 For this of course you need the m4 file:
4350
4351 libev.m4
4352
4353 PREPROCESSOR SYMBOLS/MACROS
4354 Libev can be configured via a variety of preprocessor symbols you have
4355 to define before including (or compiling) any of its files. The default
4356 in the absence of autoconf is documented for every option.
4357
4358 Symbols marked with "(h)" do not change the ABI, and can have different
4359 values when compiling libev vs. including ev.h, so it is permissible to
4360 redefine them before including ev.h without breaking compatibility to a
4361 compiled library. All other symbols change the ABI, which means all
4362 users of libev and the libev code itself must be compiled with
4363 compatible settings.
4364
4365 EV_COMPAT3 (h)
4366 Backwards compatibility is a major concern for libev. This is why
4367 this release of libev comes with wrappers for the functions and
4368 symbols that have been renamed between libev version 3 and 4.
4369
4370 You can disable these wrappers (to test compatibility with future
4371 versions) by defining "EV_COMPAT3" to 0 when compiling your
4372 sources. This has the additional advantage that you can drop the
4373 "struct" from "struct ev_loop" declarations, as libev will provide
4374 an "ev_loop" typedef in that case.
4375
4376 In some future version, the default for "EV_COMPAT3" will become 0,
4377 and in some even more future version the compatibility code will be
4378 removed completely.
4379
4380 EV_STANDALONE (h)
4381 Must always be 1 if you do not use autoconf configuration, which
4382 keeps libev from including config.h, and it also defines dummy
4383 implementations for some libevent functions (such as logging, which
4384 is not supported). It will also not define any of the structs
4385 usually found in event.h that are not directly supported by the
4386 libev core alone.
4387
4388 In standalone mode, libev will still try to automatically deduce
4389 the configuration, but has to be more conservative.
4390
4391 EV_USE_FLOOR
4392 If defined to be 1, libev will use the "floor ()" function for its
4393 periodic reschedule calculations, otherwise libev will fall back on
4394 a portable (slower) implementation. If you enable this, you usually
4395 have to link against libm or something equivalent. Enabling this
4396 when the "floor" function is not available will fail, so the safe
4397 default is to not enable this.
4398
4399 EV_USE_MONOTONIC
4400 If defined to be 1, libev will try to detect the availability of
4401 the monotonic clock option at both compile time and runtime.
4402 Otherwise no use of the monotonic clock option will be attempted.
4403 If you enable this, you usually have to link against librt or
4404 something similar. Enabling it when the functionality isn't
4405 available is safe, though, although you have to make sure you link
4406 against any libraries where the "clock_gettime" function is hiding
4407 in (often -lrt). See also "EV_USE_CLOCK_SYSCALL".
4408
4409 EV_USE_REALTIME
4410 If defined to be 1, libev will try to detect the availability of
4411 the real-time clock option at compile time (and assume its
4412 availability at runtime if successful). Otherwise no use of the
4413 real-time clock option will be attempted. This effectively replaces
4414 "gettimeofday" by "clock_get (CLOCK_REALTIME, ...)" and will not
4415 normally affect correctness. See the note about libraries in the
4416 description of "EV_USE_MONOTONIC", though. Defaults to the opposite
4417 value of "EV_USE_CLOCK_SYSCALL".
4418
4419 EV_USE_CLOCK_SYSCALL
4420 If defined to be 1, libev will try to use a direct syscall instead
4421 of calling the system-provided "clock_gettime" function. This
4422 option exists because on GNU/Linux, "clock_gettime" is in "librt",
4423 but "librt" unconditionally pulls in "libpthread", slowing down
4424 single-threaded programs needlessly. Using a direct syscall is
4425 slightly slower (in theory), because no optimised vdso
4426 implementation can be used, but avoids the pthread dependency.
4427 Defaults to 1 on GNU/Linux with glibc 2.x or higher, as it
4428 simplifies linking (no need for "-lrt").
4429
4430 EV_USE_NANOSLEEP
4431 If defined to be 1, libev will assume that "nanosleep ()" is
4432 available and will use it for delays. Otherwise it will use "select
4433 ()".
4434
4435 EV_USE_EVENTFD
4436 If defined to be 1, then libev will assume that "eventfd ()" is
4437 available and will probe for kernel support at runtime. This will
4438 improve "ev_signal" and "ev_async" performance and reduce resource
4439 consumption. If undefined, it will be enabled if the headers
4440 indicate GNU/Linux + Glibc 2.7 or newer, otherwise disabled.
4441
4442 EV_USE_SIGNALFD
4443 If defined to be 1, then libev will assume that "signalfd ()" is
4444 available and will probe for kernel support at runtime. This
4445 enables the use of EVFLAG_SIGNALFD for faster and simpler signal
4446 handling. If undefined, it will be enabled if the headers indicate
4447 GNU/Linux + Glibc 2.7 or newer, otherwise disabled.
4448
4449 EV_USE_TIMERFD
4450 If defined to be 1, then libev will assume that "timerfd ()" is
4451 available and will probe for kernel support at runtime. This allows
4452 libev to detect time jumps accurately. If undefined, it will be
4453 enabled if the headers indicate GNU/Linux + Glibc 2.8 or newer and
4454 define "TFD_TIMER_CANCEL_ON_SET", otherwise disabled.
4455
4456 EV_USE_EVENTFD
4457 If defined to be 1, then libev will assume that "eventfd ()" is
4458 available and will probe for kernel support at runtime. This will
4459 improve "ev_signal" and "ev_async" performance and reduce resource
4460 consumption. If undefined, it will be enabled if the headers
4461 indicate GNU/Linux + Glibc 2.7 or newer, otherwise disabled.
4462
4463 EV_USE_SELECT
4464 If undefined or defined to be 1, libev will compile in support for
4465 the "select"(2) backend. No attempt at auto-detection will be done:
4466 if no other method takes over, select will be it. Otherwise the
4467 select backend will not be compiled in.
4468
4469 EV_SELECT_USE_FD_SET
4470 If defined to 1, then the select backend will use the system
4471 "fd_set" structure. This is useful if libev doesn't compile due to
4472 a missing "NFDBITS" or "fd_mask" definition or it mis-guesses the
4473 bitset layout on exotic systems. This usually limits the range of
4474 file descriptors to some low limit such as 1024 or might have other
4475 limitations (winsocket only allows 64 sockets). The "FD_SETSIZE"
4476 macro, set before compilation, configures the maximum size of the
4477 "fd_set".
4478
4479 EV_SELECT_IS_WINSOCKET
4480 When defined to 1, the select backend will assume that
4481 select/socket/connect etc. don't understand file descriptors but
4482 wants osf handles on win32 (this is the case when the select to be
4483 used is the winsock select). This means that it will call
4484 "_get_osfhandle" on the fd to convert it to an OS handle.
4485 Otherwise, it is assumed that all these functions actually work on
4486 fds, even on win32. Should not be defined on non-win32 platforms.
4487
4488 EV_FD_TO_WIN32_HANDLE(fd)
4489 If "EV_SELECT_IS_WINSOCKET" is enabled, then libev needs a way to
4490 map file descriptors to socket handles. When not defining this
4491 symbol (the default), then libev will call "_get_osfhandle", which
4492 is usually correct. In some cases, programs use their own file
4493 descriptor management, in which case they can provide this function
4494 to map fds to socket handles.
4495
4496 EV_WIN32_HANDLE_TO_FD(handle)
4497 If "EV_SELECT_IS_WINSOCKET" then libev maps handles to file
4498 descriptors using the standard "_open_osfhandle" function. For
4499 programs implementing their own fd to handle mapping, overwriting
4500 this function makes it easier to do so. This can be done by
4501 defining this macro to an appropriate value.
4502
4503 EV_WIN32_CLOSE_FD(fd)
4504 If programs implement their own fd to handle mapping on win32, then
4505 this macro can be used to override the "close" function, useful to
4506 unregister file descriptors again. Note that the replacement
4507 function has to close the underlying OS handle.
4508
4509 EV_USE_WSASOCKET
4510 If defined to be 1, libev will use "WSASocket" to create its
4511 internal communication socket, which works better in some
4512 environments. Otherwise, the normal "socket" function will be used,
4513 which works better in other environments.
4514
4515 EV_USE_POLL
4516 If defined to be 1, libev will compile in support for the "poll"(2)
4517 backend. Otherwise it will be enabled on non-win32 platforms. It
4518 takes precedence over select.
4519
4520 EV_USE_EPOLL
4521 If defined to be 1, libev will compile in support for the Linux
4522 "epoll"(7) backend. Its availability will be detected at runtime,
4523 otherwise another method will be used as fallback. This is the
4524 preferred backend for GNU/Linux systems. If undefined, it will be
4525 enabled if the headers indicate GNU/Linux + Glibc 2.4 or newer,
4526 otherwise disabled.
4527
4528 EV_USE_LINUXAIO
4529 If defined to be 1, libev will compile in support for the Linux aio
4530 backend ("EV_USE_EPOLL" must also be enabled). If undefined, it
4531 will be enabled on linux, otherwise disabled.
4532
4533 EV_USE_IOURING
4534 If defined to be 1, libev will compile in support for the Linux
4535 io_uring backend ("EV_USE_EPOLL" must also be enabled). Due to it's
4536 current limitations it has to be requested explicitly. If
4537 undefined, it will be enabled on linux, otherwise disabled.
4538
4539 EV_USE_KQUEUE
4540 If defined to be 1, libev will compile in support for the BSD style
4541 "kqueue"(2) backend. Its actual availability will be detected at
4542 runtime, otherwise another method will be used as fallback. This is
4543 the preferred backend for BSD and BSD-like systems, although on
4544 most BSDs kqueue only supports some types of fds correctly (the
4545 only platform we found that supports ptys for example was NetBSD),
4546 so kqueue might be compiled in, but not be used unless explicitly
4547 requested. The best way to use it is to find out whether kqueue
4548 supports your type of fd properly and use an embedded kqueue loop.
4549
4550 EV_USE_PORT
4551 If defined to be 1, libev will compile in support for the Solaris
4552 10 port style backend. Its availability will be detected at
4553 runtime, otherwise another method will be used as fallback. This is
4554 the preferred backend for Solaris 10 systems.
4555
4556 EV_USE_DEVPOLL
4557 Reserved for future expansion, works like the USE symbols above.
4558
4559 EV_USE_INOTIFY
4560 If defined to be 1, libev will compile in support for the Linux
4561 inotify interface to speed up "ev_stat" watchers. Its actual
4562 availability will be detected at runtime. If undefined, it will be
4563 enabled if the headers indicate GNU/Linux + Glibc 2.4 or newer,
4564 otherwise disabled.
4565
4566 EV_NO_SMP
4567 If defined to be 1, libev will assume that memory is always
4568 coherent between threads, that is, threads can be used, but threads
4569 never run on different cpus (or different cpu cores). This reduces
4570 dependencies and makes libev faster.
4571
4572 EV_NO_THREADS
4573 If defined to be 1, libev will assume that it will never be called
4574 from different threads (that includes signal handlers), which is a
4575 stronger assumption than "EV_NO_SMP", above. This reduces
4576 dependencies and makes libev faster.
4577
4578 EV_ATOMIC_T
4579 Libev requires an integer type (suitable for storing 0 or 1) whose
4580 access is atomic with respect to other threads or signal contexts.
4581 No such type is easily found in the C language, so you can provide
4582 your own type that you know is safe for your purposes. It is used
4583 both for signal handler "locking" as well as for signal and thread
4584 safety in "ev_async" watchers.
4585
4586 In the absence of this define, libev will use "sig_atomic_t
4587 volatile" (from signal.h), which is usually good enough on most
4588 platforms.
4589
4590 EV_H (h)
4591 The name of the ev.h header file used to include it. The default if
4592 undefined is "ev.h" in event.h, ev.c and ev++.h. This can be used
4593 to virtually rename the ev.h header file in case of conflicts.
4594
4595 EV_CONFIG_H (h)
4596 If "EV_STANDALONE" isn't 1, this variable can be used to override
4597 ev.c's idea of where to find the config.h file, similarly to
4598 "EV_H", above.
4599
4600 EV_EVENT_H (h)
4601 Similarly to "EV_H", this macro can be used to override event.c's
4602 idea of how the event.h header can be found, the default is
4603 "event.h".
4604
4605 EV_PROTOTYPES (h)
4606 If defined to be 0, then ev.h will not define any function
4607 prototypes, but still define all the structs and other symbols.
4608 This is occasionally useful if you want to provide your own wrapper
4609 functions around libev functions.
4610
4611 EV_MULTIPLICITY
4612 If undefined or defined to 1, then all event-loop-specific
4613 functions will have the "struct ev_loop *" as first argument, and
4614 you can create additional independent event loops. Otherwise there
4615 will be no support for multiple event loops and there is no first
4616 event loop pointer argument. Instead, all functions act on the
4617 single default loop.
4618
4619 Note that "EV_DEFAULT" and "EV_DEFAULT_" will no longer provide a
4620 default loop when multiplicity is switched off - you always have to
4621 initialise the loop manually in this case.
4622
4623 EV_MINPRI
4624 EV_MAXPRI
4625 The range of allowed priorities. "EV_MINPRI" must be smaller or
4626 equal to "EV_MAXPRI", but otherwise there are no non-obvious
4627 limitations. You can provide for more priorities by overriding
4628 those symbols (usually defined to be "-2" and 2, respectively).
4629
4630 When doing priority-based operations, libev usually has to linearly
4631 search all the priorities, so having many of them (hundreds) uses a
4632 lot of space and time, so using the defaults of five priorities (-2
4633 .. +2) is usually fine.
4634
4635 If your embedding application does not need any priorities,
4636 defining these both to 0 will save some memory and CPU.
4637
4638 EV_PERIODIC_ENABLE, EV_IDLE_ENABLE, EV_EMBED_ENABLE, EV_STAT_ENABLE,
4639 EV_PREPARE_ENABLE, EV_CHECK_ENABLE, EV_FORK_ENABLE, EV_SIGNAL_ENABLE,
4640 EV_ASYNC_ENABLE, EV_CHILD_ENABLE.
4641 If undefined or defined to be 1 (and the platform supports it),
4642 then the respective watcher type is supported. If defined to be 0,
4643 then it is not. Disabling watcher types mainly saves code size.
4644
4645 EV_FEATURES
4646 If you need to shave off some kilobytes of code at the expense of
4647 some speed (but with the full API), you can define this symbol to
4648 request certain subsets of functionality. The default is to enable
4649 all features that can be enabled on the platform.
4650
4651 A typical way to use this symbol is to define it to 0 (or to a
4652 bitset with some broad features you want) and then selectively re-
4653 enable additional parts you want, for example if you want
4654 everything minimal, but multiple event loop support, async and
4655 child watchers and the poll backend, use this:
4656
4657 #define EV_FEATURES 0
4658 #define EV_MULTIPLICITY 1
4659 #define EV_USE_POLL 1
4660 #define EV_CHILD_ENABLE 1
4661 #define EV_ASYNC_ENABLE 1
4662
4663 The actual value is a bitset, it can be a combination of the
4664 following values (by default, all of these are enabled):
4665
4666 1 - faster/larger code
4667 Use larger code to speed up some operations.
4668
4669 Currently this is used to override some inlining decisions
4670 (enlarging the code size by roughly 30% on amd64).
4671
4672 When optimising for size, use of compiler flags such as "-Os"
4673 with gcc is recommended, as well as "-DNDEBUG", as libev
4674 contains a number of assertions.
4675
4676 The default is off when "__OPTIMIZE_SIZE__" is defined by your
4677 compiler (e.g. gcc with "-Os").
4678
4679 2 - faster/larger data structures
4680 Replaces the small 2-heap for timer management by a faster
4681 4-heap, larger hash table sizes and so on. This will usually
4682 further increase code size and can additionally have an effect
4683 on the size of data structures at runtime.
4684
4685 The default is off when "__OPTIMIZE_SIZE__" is defined by your
4686 compiler (e.g. gcc with "-Os").
4687
4688 4 - full API configuration
4689 This enables priorities (sets "EV_MAXPRI"=2 and
4690 "EV_MINPRI"=-2), and enables multiplicity
4691 ("EV_MULTIPLICITY"=1).
4692
4693 8 - full API
4694 This enables a lot of the "lesser used" API functions. See
4695 "ev.h" for details on which parts of the API are still
4696 available without this feature, and do not complain if this
4697 subset changes over time.
4698
4699 16 - enable all optional watcher types
4700 Enables all optional watcher types. If you want to selectively
4701 enable only some watcher types other than I/O and timers (e.g.
4702 prepare, embed, async, child...) you can enable them manually
4703 by defining "EV_watchertype_ENABLE" to 1 instead.
4704
4705 32 - enable all backends
4706 This enables all backends - without this feature, you need to
4707 enable at least one backend manually ("EV_USE_SELECT" is a good
4708 choice).
4709
4710 64 - enable OS-specific "helper" APIs
4711 Enable inotify, eventfd, signalfd and similar OS-specific
4712 helper APIs by default.
4713
4714 Compiling with "gcc -Os -DEV_STANDALONE -DEV_USE_EPOLL=1
4715 -DEV_FEATURES=0" reduces the compiled size of libev from 24.7Kb
4716 code/2.8Kb data to 6.5Kb code/0.3Kb data on my GNU/Linux amd64
4717 system, while still giving you I/O watchers, timers and monotonic
4718 clock support.
4719
4720 With an intelligent-enough linker (gcc+binutils are intelligent
4721 enough when you use "-Wl,--gc-sections -ffunction-sections")
4722 functions unused by your program might be left out as well - a
4723 binary starting a timer and an I/O watcher then might come out at
4724 only 5Kb.
4725
4726 EV_API_STATIC
4727 If this symbol is defined (by default it is not), then all
4728 identifiers will have static linkage. This means that libev will
4729 not export any identifiers, and you cannot link against libev
4730 anymore. This can be useful when you embed libev, only want to use
4731 libev functions in a single file, and do not want its identifiers
4732 to be visible.
4733
4734 To use this, define "EV_API_STATIC" and include ev.c in the file
4735 that wants to use libev.
4736
4737 This option only works when libev is compiled with a C compiler, as
4738 C++ doesn't support the required declaration syntax.
4739
4740 EV_AVOID_STDIO
4741 If this is set to 1 at compiletime, then libev will avoid using
4742 stdio functions (printf, scanf, perror etc.). This will increase
4743 the code size somewhat, but if your program doesn't otherwise
4744 depend on stdio and your libc allows it, this avoids linking in the
4745 stdio library which is quite big.
4746
4747 Note that error messages might become less precise when this option
4748 is enabled.
4749
4750 EV_NSIG
4751 The highest supported signal number, +1 (or, the number of
4752 signals): Normally, libev tries to deduce the maximum number of
4753 signals automatically, but sometimes this fails, in which case it
4754 can be specified. Also, using a lower number than detected (32
4755 should be good for about any system in existence) can save some
4756 memory, as libev statically allocates some 12-24 bytes per signal
4757 number.
4758
4759 EV_PID_HASHSIZE
4760 "ev_child" watchers use a small hash table to distribute workload
4761 by pid. The default size is 16 (or 1 with "EV_FEATURES" disabled),
4762 usually more than enough. If you need to manage thousands of
4763 children you might want to increase this value (must be a power of
4764 two).
4765
4766 EV_INOTIFY_HASHSIZE
4767 "ev_stat" watchers use a small hash table to distribute workload by
4768 inotify watch id. The default size is 16 (or 1 with "EV_FEATURES"
4769 disabled), usually more than enough. If you need to manage
4770 thousands of "ev_stat" watchers you might want to increase this
4771 value (must be a power of two).
4772
4773 EV_USE_4HEAP
4774 Heaps are not very cache-efficient. To improve the cache-efficiency
4775 of the timer and periodics heaps, libev uses a 4-heap when this
4776 symbol is defined to 1. The 4-heap uses more complicated (longer)
4777 code but has noticeably faster performance with many (thousands) of
4778 watchers.
4779
4780 The default is 1, unless "EV_FEATURES" overrides it, in which case
4781 it will be 0.
4782
4783 EV_HEAP_CACHE_AT
4784 Heaps are not very cache-efficient. To improve the cache-efficiency
4785 of the timer and periodics heaps, libev can cache the timestamp
4786 (at) within the heap structure (selected by defining
4787 "EV_HEAP_CACHE_AT" to 1), which uses 8-12 bytes more per watcher
4788 and a few hundred bytes more code, but avoids random read accesses
4789 on heap changes. This improves performance noticeably with many
4790 (hundreds) of watchers.
4791
4792 The default is 1, unless "EV_FEATURES" overrides it, in which case
4793 it will be 0.
4794
4795 EV_VERIFY
4796 Controls how much internal verification (see "ev_verify ()") will
4797 be done: If set to 0, no internal verification code will be
4798 compiled in. If set to 1, then verification code will be compiled
4799 in, but not called. If set to 2, then the internal verification
4800 code will be called once per loop, which can slow down libev. If
4801 set to 3, then the verification code will be called very
4802 frequently, which will slow down libev considerably.
4803
4804 Verification errors are reported via C's "assert" mechanism, so if
4805 you disable that (e.g. by defining "NDEBUG") then no errors will be
4806 reported.
4807
4808 The default is 1, unless "EV_FEATURES" overrides it, in which case
4809 it will be 0.
4810
4811 EV_COMMON
4812 By default, all watchers have a "void *data" member. By redefining
4813 this macro to something else you can include more and other types
4814 of members. You have to define it each time you include one of the
4815 files, though, and it must be identical each time.
4816
4817 For example, the perl EV module uses something like this:
4818
4819 #define EV_COMMON \
4820 SV *self; /* contains this struct */ \
4821 SV *cb_sv, *fh /* note no trailing ";" */
4822
4823 EV_CB_DECLARE (type)
4824 EV_CB_INVOKE (watcher, revents)
4825 ev_set_cb (ev, cb)
4826 Can be used to change the callback member declaration in each
4827 watcher, and the way callbacks are invoked and set. Must expand to
4828 a struct member definition and a statement, respectively. See the
4829 ev.h header file for their default definitions. One possible use
4830 for overriding these is to avoid the "struct ev_loop *" as first
4831 argument in all cases, or to use method calls instead of plain
4832 function calls in C++.
4833
4834 EXPORTED API SYMBOLS
4835 If you need to re-export the API (e.g. via a DLL) and you need a list
4836 of exported symbols, you can use the provided Symbol.* files which list
4837 all public symbols, one per line:
4838
4839 Symbols.ev for libev proper
4840 Symbols.event for the libevent emulation
4841
4842 This can also be used to rename all public symbols to avoid clashes
4843 with multiple versions of libev linked together (which is obviously bad
4844 in itself, but sometimes it is inconvenient to avoid this).
4845
4846 A sed command like this will create wrapper "#define"'s that you need
4847 to include before including ev.h:
4848
4849 <Symbols.ev sed -e "s/.*/#define & myprefix_&/" >wrap.h
4850
4851 This would create a file wrap.h which essentially looks like this:
4852
4853 #define ev_backend myprefix_ev_backend
4854 #define ev_check_start myprefix_ev_check_start
4855 #define ev_check_stop myprefix_ev_check_stop
4856 ...
4857
4858 EXAMPLES
4859 For a real-world example of a program the includes libev verbatim, you
4860 can have a look at the EV perl module
4861 (<http://software.schmorp.de/pkg/EV.html>). It has the libev files in
4862 the libev/ subdirectory and includes them in the EV/EVAPI.h (public
4863 interface) and EV.xs (implementation) files. Only the EV.xs file will
4864 be compiled. It is pretty complex because it provides its own header
4865 file.
4866
4867 The usage in rxvt-unicode is simpler. It has a ev_cpp.h header file
4868 that everybody includes and which overrides some configure choices:
4869
4870 #define EV_FEATURES 8
4871 #define EV_USE_SELECT 1
4872 #define EV_PREPARE_ENABLE 1
4873 #define EV_IDLE_ENABLE 1
4874 #define EV_SIGNAL_ENABLE 1
4875 #define EV_CHILD_ENABLE 1
4876 #define EV_USE_STDEXCEPT 0
4877 #define EV_CONFIG_H <config.h>
4878
4879 #include "ev++.h"
4880
4881 And a ev_cpp.C implementation file that contains libev proper and is
4882 compiled:
4883
4884 #include "ev_cpp.h"
4885 #include "ev.c"
4886
4888 THREADS AND COROUTINES
4889 THREADS
4890
4891 All libev functions are reentrant and thread-safe unless explicitly
4892 documented otherwise, but libev implements no locking itself. This
4893 means that you can use as many loops as you want in parallel, as long
4894 as there are no concurrent calls into any libev function with the same
4895 loop parameter ("ev_default_*" calls have an implicit default loop
4896 parameter, of course): libev guarantees that different event loops
4897 share no data structures that need any locking.
4898
4899 Or to put it differently: calls with different loop parameters can be
4900 done concurrently from multiple threads, calls with the same loop
4901 parameter must be done serially (but can be done from different
4902 threads, as long as only one thread ever is inside a call at any point
4903 in time, e.g. by using a mutex per loop).
4904
4905 Specifically to support threads (and signal handlers), libev implements
4906 so-called "ev_async" watchers, which allow some limited form of
4907 concurrency on the same event loop, namely waking it up "from the
4908 outside".
4909
4910 If you want to know which design (one loop, locking, or multiple loops
4911 without or something else still) is best for your problem, then I
4912 cannot help you, but here is some generic advice:
4913
4914 · most applications have a main thread: use the default libev loop in
4915 that thread, or create a separate thread running only the default
4916 loop.
4917
4918 This helps integrating other libraries or software modules that use
4919 libev themselves and don't care/know about threading.
4920
4921 · one loop per thread is usually a good model.
4922
4923 Doing this is almost never wrong, sometimes a better-performance
4924 model exists, but it is always a good start.
4925
4926 · other models exist, such as the leader/follower pattern, where one
4927 loop is handed through multiple threads in a kind of round-robin
4928 fashion.
4929
4930 Choosing a model is hard - look around, learn, know that usually
4931 you can do better than you currently do :-)
4932
4933 · often you need to talk to some other thread which blocks in the
4934 event loop.
4935
4936 "ev_async" watchers can be used to wake them up from other threads
4937 safely (or from signal contexts...).
4938
4939 An example use would be to communicate signals or other events that
4940 only work in the default loop by registering the signal watcher
4941 with the default loop and triggering an "ev_async" watcher from the
4942 default loop watcher callback into the event loop interested in the
4943 signal.
4944
4945 See also "THREAD LOCKING EXAMPLE".
4946
4947 COROUTINES
4948
4949 Libev is very accommodating to coroutines ("cooperative threads"):
4950 libev fully supports nesting calls to its functions from different
4951 coroutines (e.g. you can call "ev_run" on the same loop from two
4952 different coroutines, and switch freely between both coroutines running
4953 the loop, as long as you don't confuse yourself). The only exception is
4954 that you must not do this from "ev_periodic" reschedule callbacks.
4955
4956 Care has been taken to ensure that libev does not keep local state
4957 inside "ev_run", and other calls do not usually allow for coroutine
4958 switches as they do not call any callbacks.
4959
4960 COMPILER WARNINGS
4961 Depending on your compiler and compiler settings, you might get no or a
4962 lot of warnings when compiling libev code. Some people are apparently
4963 scared by this.
4964
4965 However, these are unavoidable for many reasons. For one, each compiler
4966 has different warnings, and each user has different tastes regarding
4967 warning options. "Warn-free" code therefore cannot be a goal except
4968 when targeting a specific compiler and compiler-version.
4969
4970 Another reason is that some compiler warnings require elaborate
4971 workarounds, or other changes to the code that make it less clear and
4972 less maintainable.
4973
4974 And of course, some compiler warnings are just plain stupid, or simply
4975 wrong (because they don't actually warn about the condition their
4976 message seems to warn about). For example, certain older gcc versions
4977 had some warnings that resulted in an extreme number of false
4978 positives. These have been fixed, but some people still insist on
4979 making code warn-free with such buggy versions.
4980
4981 While libev is written to generate as few warnings as possible, "warn-
4982 free" code is not a goal, and it is recommended not to build libev with
4983 any compiler warnings enabled unless you are prepared to cope with them
4984 (e.g. by ignoring them). Remember that warnings are just that:
4985 warnings, not errors, or proof of bugs.
4986
4987 VALGRIND
4988 Valgrind has a special section here because it is a popular tool that
4989 is highly useful. Unfortunately, valgrind reports are very hard to
4990 interpret.
4991
4992 If you think you found a bug (memory leak, uninitialised data access
4993 etc.) in libev, then check twice: If valgrind reports something like:
4994
4995 ==2274== definitely lost: 0 bytes in 0 blocks.
4996 ==2274== possibly lost: 0 bytes in 0 blocks.
4997 ==2274== still reachable: 256 bytes in 1 blocks.
4998
4999 Then there is no memory leak, just as memory accounted to global
5000 variables is not a memleak - the memory is still being referenced, and
5001 didn't leak.
5002
5003 Similarly, under some circumstances, valgrind might report kernel bugs
5004 as if it were a bug in libev (e.g. in realloc or in the poll backend,
5005 although an acceptable workaround has been found here), or it might be
5006 confused.
5007
5008 Keep in mind that valgrind is a very good tool, but only a tool. Don't
5009 make it into some kind of religion.
5010
5011 If you are unsure about something, feel free to contact the mailing
5012 list with the full valgrind report and an explanation on why you think
5013 this is a bug in libev (best check the archives, too :). However, don't
5014 be annoyed when you get a brisk "this is no bug" answer and take the
5015 chance of learning how to interpret valgrind properly.
5016
5017 If you need, for some reason, empty reports from valgrind for your
5018 project I suggest using suppression lists.
5019
5021 GNU/LINUX 32 BIT LIMITATIONS
5022 GNU/Linux is the only common platform that supports 64 bit file/large
5023 file interfaces but disables them by default.
5024
5025 That means that libev compiled in the default environment doesn't
5026 support files larger than 2GiB or so, which mainly affects "ev_stat"
5027 watchers.
5028
5029 Unfortunately, many programs try to work around this GNU/Linux issue by
5030 enabling the large file API, which makes them incompatible with the
5031 standard libev compiled for their system.
5032
5033 Likewise, libev cannot enable the large file API itself as this would
5034 suddenly make it incompatible to the default compile time environment,
5035 i.e. all programs not using special compile switches.
5036
5037 OS/X AND DARWIN BUGS
5038 The whole thing is a bug if you ask me - basically any system interface
5039 you touch is broken, whether it is locales, poll, kqueue or even the
5040 OpenGL drivers.
5041
5042 "kqueue" is buggy
5043
5044 The kqueue syscall is broken in all known versions - most versions
5045 support only sockets, many support pipes.
5046
5047 Libev tries to work around this by not using "kqueue" by default on
5048 this rotten platform, but of course you can still ask for it when
5049 creating a loop - embedding a socket-only kqueue loop into a select-
5050 based one is probably going to work well.
5051
5052 "poll" is buggy
5053
5054 Instead of fixing "kqueue", Apple replaced their (working) "poll"
5055 implementation by something calling "kqueue" internally around the
5056 10.5.6 release, so now "kqueue" and "poll" are broken.
5057
5058 Libev tries to work around this by not using "poll" by default on this
5059 rotten platform, but of course you can still ask for it when creating a
5060 loop.
5061
5062 "select" is buggy
5063
5064 All that's left is "select", and of course Apple found a way to fuck
5065 this one up as well: On OS/X, "select" actively limits the number of
5066 file descriptors you can pass in to 1024 - your program suddenly
5067 crashes when you use more.
5068
5069 There is an undocumented "workaround" for this - defining
5070 "_DARWIN_UNLIMITED_SELECT", which libev tries to use, so select should
5071 work on OS/X.
5072
5073 SOLARIS PROBLEMS AND WORKAROUNDS
5074 "errno" reentrancy
5075
5076 The default compile environment on Solaris is unfortunately so thread-
5077 unsafe that you can't even use components/libraries compiled without
5078 "-D_REENTRANT" in a threaded program, which, of course, isn't defined
5079 by default. A valid, if stupid, implementation choice.
5080
5081 If you want to use libev in threaded environments you have to make sure
5082 it's compiled with "_REENTRANT" defined.
5083
5084 Event port backend
5085
5086 The scalable event interface for Solaris is called "event ports".
5087 Unfortunately, this mechanism is very buggy in all major releases. If
5088 you run into high CPU usage, your program freezes or you get a large
5089 number of spurious wakeups, make sure you have all the relevant and
5090 latest kernel patches applied. No, I don't know which ones, but there
5091 are multiple ones to apply, and afterwards, event ports actually work
5092 great.
5093
5094 If you can't get it to work, you can try running the program by setting
5095 the environment variable "LIBEV_FLAGS=3" to only allow "poll" and
5096 "select" backends.
5097
5098 AIX POLL BUG
5099 AIX unfortunately has a broken "poll.h" header. Libev works around this
5100 by trying to avoid the poll backend altogether (i.e. it's not even
5101 compiled in), which normally isn't a big problem as "select" works fine
5102 with large bitsets on AIX, and AIX is dead anyway.
5103
5104 WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS
5105 General issues
5106
5107 Win32 doesn't support any of the standards (e.g. POSIX) that libev
5108 requires, and its I/O model is fundamentally incompatible with the
5109 POSIX model. Libev still offers limited functionality on this platform
5110 in the form of the "EVBACKEND_SELECT" backend, and only supports socket
5111 descriptors. This only applies when using Win32 natively, not when
5112 using e.g. cygwin. Actually, it only applies to the microsofts own
5113 compilers, as every compiler comes with a slightly differently
5114 broken/incompatible environment.
5115
5116 Lifting these limitations would basically require the full re-
5117 implementation of the I/O system. If you are into this kind of thing,
5118 then note that glib does exactly that for you in a very portable way
5119 (note also that glib is the slowest event library known to man).
5120
5121 There is no supported compilation method available on windows except
5122 embedding it into other applications.
5123
5124 Sensible signal handling is officially unsupported by Microsoft - libev
5125 tries its best, but under most conditions, signals will simply not
5126 work.
5127
5128 Not a libev limitation but worth mentioning: windows apparently doesn't
5129 accept large writes: instead of resulting in a partial write, windows
5130 will either accept everything or return "ENOBUFS" if the buffer is too
5131 large, so make sure you only write small amounts into your sockets
5132 (less than a megabyte seems safe, but this apparently depends on the
5133 amount of memory available).
5134
5135 Due to the many, low, and arbitrary limits on the win32 platform and
5136 the abysmal performance of winsockets, using a large number of sockets
5137 is not recommended (and not reasonable). If your program needs to use
5138 more than a hundred or so sockets, then likely it needs to use a
5139 totally different implementation for windows, as libev offers the POSIX
5140 readiness notification model, which cannot be implemented efficiently
5141 on windows (due to Microsoft monopoly games).
5142
5143 A typical way to use libev under windows is to embed it (see the
5144 embedding section for details) and use the following evwrap.h header
5145 file instead of ev.h:
5146
5147 #define EV_STANDALONE /* keeps ev from requiring config.h */
5148 #define EV_SELECT_IS_WINSOCKET 1 /* configure libev for windows select */
5149
5150 #include "ev.h"
5151
5152 And compile the following evwrap.c file into your project (make sure
5153 you do not compile the ev.c or any other embedded source files!):
5154
5155 #include "evwrap.h"
5156 #include "ev.c"
5157
5158 The winsocket "select" function
5159
5160 The winsocket "select" function doesn't follow POSIX in that it
5161 requires socket handles and not socket file descriptors (it is also
5162 extremely buggy). This makes select very inefficient, and also requires
5163 a mapping from file descriptors to socket handles (the Microsoft C
5164 runtime provides the function "_open_osfhandle" for this). See the
5165 discussion of the "EV_SELECT_USE_FD_SET", "EV_SELECT_IS_WINSOCKET" and
5166 "EV_FD_TO_WIN32_HANDLE" preprocessor symbols for more info.
5167
5168 The configuration for a "naked" win32 using the Microsoft runtime
5169 libraries and raw winsocket select is:
5170
5171 #define EV_USE_SELECT 1
5172 #define EV_SELECT_IS_WINSOCKET 1 /* forces EV_SELECT_USE_FD_SET, too */
5173
5174 Note that winsockets handling of fd sets is O(n), so you can easily get
5175 a complexity in the O(n²) range when using win32.
5176
5177 Limited number of file descriptors
5178
5179 Windows has numerous arbitrary (and low) limits on things.
5180
5181 Early versions of winsocket's select only supported waiting for a
5182 maximum of 64 handles (probably owning to the fact that all windows
5183 kernels can only wait for 64 things at the same time internally;
5184 Microsoft recommends spawning a chain of threads and wait for 63
5185 handles and the previous thread in each. Sounds great!).
5186
5187 Newer versions support more handles, but you need to define
5188 "FD_SETSIZE" to some high number (e.g. 2048) before compiling the
5189 winsocket select call (which might be in libev or elsewhere, for
5190 example, perl and many other interpreters do their own select emulation
5191 on windows).
5192
5193 Another limit is the number of file descriptors in the Microsoft
5194 runtime libraries, which by default is 64 (there must be a hidden 64
5195 fetish or something like this inside Microsoft). You can increase this
5196 by calling "_setmaxstdio", which can increase this limit to 2048
5197 (another arbitrary limit), but is broken in many versions of the
5198 Microsoft runtime libraries. This might get you to about 512 or 2048
5199 sockets (depending on windows version and/or the phase of the moon). To
5200 get more, you need to wrap all I/O functions and provide your own fd
5201 management, but the cost of calling select (O(n²)) will likely make
5202 this unworkable.
5203
5204 PORTABILITY REQUIREMENTS
5205 In addition to a working ISO-C implementation and of course the
5206 backend-specific APIs, libev relies on a few additional extensions:
5207
5208 "void (*)(ev_watcher_type *, int revents)" must have compatible calling
5209 conventions regardless of "ev_watcher_type *".
5210 Libev assumes not only that all watcher pointers have the same
5211 internal structure (guaranteed by POSIX but not by ISO C for
5212 example), but it also assumes that the same (machine) code can be
5213 used to call any watcher callback: The watcher callbacks have
5214 different type signatures, but libev calls them using an
5215 "ev_watcher *" internally.
5216
5217 null pointers and integer zero are represented by 0 bytes
5218 Libev uses "memset" to initialise structs and arrays to 0 bytes,
5219 and relies on this setting pointers and integers to null.
5220
5221 pointer accesses must be thread-atomic
5222 Accessing a pointer value must be atomic, it must both be readable
5223 and writable in one piece - this is the case on all current
5224 architectures.
5225
5226 "sig_atomic_t volatile" must be thread-atomic as well
5227 The type "sig_atomic_t volatile" (or whatever is defined as
5228 "EV_ATOMIC_T") must be atomic with respect to accesses from
5229 different threads. This is not part of the specification for
5230 "sig_atomic_t", but is believed to be sufficiently portable.
5231
5232 "sigprocmask" must work in a threaded environment
5233 Libev uses "sigprocmask" to temporarily block signals. This is not
5234 allowed in a threaded program ("pthread_sigmask" has to be used).
5235 Typical pthread implementations will either allow "sigprocmask" in
5236 the "main thread" or will block signals process-wide, both
5237 behaviours would be compatible with libev. Interaction between
5238 "sigprocmask" and "pthread_sigmask" could complicate things,
5239 however.
5240
5241 The most portable way to handle signals is to block signals in all
5242 threads except the initial one, and run the signal handling loop in
5243 the initial thread as well.
5244
5245 "long" must be large enough for common memory allocation sizes
5246 To improve portability and simplify its API, libev uses "long"
5247 internally instead of "size_t" when allocating its data structures.
5248 On non-POSIX systems (Microsoft...) this might be unexpectedly low,
5249 but is still at least 31 bits everywhere, which is enough for
5250 hundreds of millions of watchers.
5251
5252 "double" must hold a time value in seconds with enough accuracy
5253 The type "double" is used to represent timestamps. It is required
5254 to have at least 51 bits of mantissa (and 9 bits of exponent),
5255 which is good enough for at least into the year 4000 with
5256 millisecond accuracy (the design goal for libev). This requirement
5257 is overfulfilled by implementations using IEEE 754, which is
5258 basically all existing ones.
5259
5260 With IEEE 754 doubles, you get microsecond accuracy until at least
5261 the year 2255 (and millisecond accuracy till the year 287396 - by
5262 then, libev is either obsolete or somebody patched it to use "long
5263 double" or something like that, just kidding).
5264
5265 If you know of other additional requirements drop me a note.
5266
5268 In this section the complexities of (many of) the algorithms used
5269 inside libev will be documented. For complexity discussions about
5270 backends see the documentation for "ev_default_init".
5271
5272 All of the following are about amortised time: If an array needs to be
5273 extended, libev needs to realloc and move the whole array, but this
5274 happens asymptotically rarer with higher number of elements, so O(1)
5275 might mean that libev does a lengthy realloc operation in rare cases,
5276 but on average it is much faster and asymptotically approaches constant
5277 time.
5278
5279 Starting and stopping timer/periodic watchers: O(log
5280 skipped_other_timers)
5281 This means that, when you have a watcher that triggers in one hour
5282 and there are 100 watchers that would trigger before that, then
5283 inserting will have to skip roughly seven ("ld 100") of these
5284 watchers.
5285
5286 Changing timer/periodic watchers (by autorepeat or calling again):
5287 O(log skipped_other_timers)
5288 That means that changing a timer costs less than removing/adding
5289 them, as only the relative motion in the event queue has to be paid
5290 for.
5291
5292 Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1)
5293 These just add the watcher into an array or at the head of a list.
5294
5295 Stopping check/prepare/idle/fork/async watchers: O(1)
5296 Stopping an io/signal/child watcher:
5297 O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE))
5298 These watchers are stored in lists, so they need to be walked to
5299 find the correct watcher to remove. The lists are usually short
5300 (you don't usually have many watchers waiting for the same fd or
5301 signal: one is typical, two is rare).
5302
5303 Finding the next timer in each loop iteration: O(1)
5304 By virtue of using a binary or 4-heap, the next timer is always
5305 found at a fixed position in the storage array.
5306
5307 Each change on a file descriptor per loop iteration:
5308 O(number_of_watchers_for_this_fd)
5309 A change means an I/O watcher gets started or stopped, which
5310 requires libev to recalculate its status (and possibly tell the
5311 kernel, depending on backend and whether "ev_io_set" was used).
5312
5313 Activating one watcher (putting it into the pending state): O(1)
5314 Priority handling: O(number_of_priorities)
5315 Priorities are implemented by allocating some space for each
5316 priority. When doing priority-based operations, libev usually has
5317 to linearly search all the priorities, but starting/stopping and
5318 activating watchers becomes O(1) with respect to priority handling.
5319
5320 Sending an ev_async: O(1)
5321 Processing ev_async_send: O(number_of_async_watchers)
5322 Processing signals: O(max_signal_number)
5323 Sending involves a system call iff there were no other
5324 "ev_async_send" calls in the current loop iteration and the loop is
5325 currently blocked. Checking for async and signal events involves
5326 iterating over all running async watchers or all signal numbers.
5327
5329 The major version 4 introduced some incompatible changes to the API.
5330
5331 At the moment, the "ev.h" header file provides compatibility
5332 definitions for all changes, so most programs should still compile. The
5333 compatibility layer might be removed in later versions of libev, so
5334 better update to the new API early than late.
5335
5336 "EV_COMPAT3" backwards compatibility mechanism
5337 The backward compatibility mechanism can be controlled by
5338 "EV_COMPAT3". See "PREPROCESSOR SYMBOLS/MACROS" in the "EMBEDDING"
5339 section.
5340
5341 "ev_default_destroy" and "ev_default_fork" have been removed
5342 These calls can be replaced easily by their "ev_loop_xxx"
5343 counterparts:
5344
5345 ev_loop_destroy (EV_DEFAULT_UC);
5346 ev_loop_fork (EV_DEFAULT);
5347
5348 function/symbol renames
5349 A number of functions and symbols have been renamed:
5350
5351 ev_loop => ev_run
5352 EVLOOP_NONBLOCK => EVRUN_NOWAIT
5353 EVLOOP_ONESHOT => EVRUN_ONCE
5354
5355 ev_unloop => ev_break
5356 EVUNLOOP_CANCEL => EVBREAK_CANCEL
5357 EVUNLOOP_ONE => EVBREAK_ONE
5358 EVUNLOOP_ALL => EVBREAK_ALL
5359
5360 EV_TIMEOUT => EV_TIMER
5361
5362 ev_loop_count => ev_iteration
5363 ev_loop_depth => ev_depth
5364 ev_loop_verify => ev_verify
5365
5366 Most functions working on "struct ev_loop" objects don't have an
5367 "ev_loop_" prefix, so it was removed; "ev_loop", "ev_unloop" and
5368 associated constants have been renamed to not collide with the
5369 "struct ev_loop" anymore and "EV_TIMER" now follows the same naming
5370 scheme as all other watcher types. Note that "ev_loop_fork" is
5371 still called "ev_loop_fork" because it would otherwise clash with
5372 the "ev_fork" typedef.
5373
5374 "EV_MINIMAL" mechanism replaced by "EV_FEATURES"
5375 The preprocessor symbol "EV_MINIMAL" has been replaced by a
5376 different mechanism, "EV_FEATURES". Programs using "EV_MINIMAL"
5377 usually compile and work, but the library code will of course be
5378 larger.
5379
5381 active
5382 A watcher is active as long as it has been started and not yet
5383 stopped. See "WATCHER STATES" for details.
5384
5385 application
5386 In this document, an application is whatever is using libev.
5387
5388 backend
5389 The part of the code dealing with the operating system interfaces.
5390
5391 callback
5392 The address of a function that is called when some event has been
5393 detected. Callbacks are being passed the event loop, the watcher
5394 that received the event, and the actual event bitset.
5395
5396 callback/watcher invocation
5397 The act of calling the callback associated with a watcher.
5398
5399 event
5400 A change of state of some external event, such as data now being
5401 available for reading on a file descriptor, time having passed or
5402 simply not having any other events happening anymore.
5403
5404 In libev, events are represented as single bits (such as "EV_READ"
5405 or "EV_TIMER").
5406
5407 event library
5408 A software package implementing an event model and loop.
5409
5410 event loop
5411 An entity that handles and processes external events and converts
5412 them into callback invocations.
5413
5414 event model
5415 The model used to describe how an event loop handles and processes
5416 watchers and events.
5417
5418 pending
5419 A watcher is pending as soon as the corresponding event has been
5420 detected. See "WATCHER STATES" for details.
5421
5422 real time
5423 The physical time that is observed. It is apparently strictly
5424 monotonic :)
5425
5426 wall-clock time
5427 The time and date as shown on clocks. Unlike real time, it can
5428 actually be wrong and jump forwards and backwards, e.g. when you
5429 adjust your clock.
5430
5431 watcher
5432 A data structure that describes interest in certain events.
5433 Watchers need to be started (attached to an event loop) before they
5434 can receive events.
5435
5437 Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael
5438 Magnusson and Emanuele Giaquinta, and minor corrections by many others.
5439
5440
5441
5442perl v5.30.1 2020-01-29 libev::ev(3)