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