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