… | |
… | |
2 | |
2 | |
3 | libev - a high performance full-featured event loop written in C |
3 | libev - a high performance full-featured event loop written in C |
4 | |
4 | |
5 | =head1 SYNOPSIS |
5 | =head1 SYNOPSIS |
6 | |
6 | |
7 | #include <ev.h> |
7 | #include <ev.h> |
8 | |
8 | |
9 | =head2 EXAMPLE PROGRAM |
9 | =head2 EXAMPLE PROGRAM |
10 | |
10 | |
11 | // a single header file is required |
11 | // a single header file is required |
12 | #include <ev.h> |
12 | #include <ev.h> |
13 | |
13 | |
|
|
14 | #include <stdio.h> // for puts |
|
|
15 | |
14 | // every watcher type has its own typedef'd struct |
16 | // every watcher type has its own typedef'd struct |
15 | // with the name ev_<type> |
17 | // with the name ev_TYPE |
16 | ev_io stdin_watcher; |
18 | ev_io stdin_watcher; |
17 | ev_timer timeout_watcher; |
19 | ev_timer timeout_watcher; |
18 | |
20 | |
19 | // all watcher callbacks have a similar signature |
21 | // all watcher callbacks have a similar signature |
20 | // this callback is called when data is readable on stdin |
22 | // this callback is called when data is readable on stdin |
21 | static void |
23 | static void |
22 | stdin_cb (EV_P_ struct ev_io *w, int revents) |
24 | stdin_cb (EV_P_ ev_io *w, int revents) |
23 | { |
25 | { |
24 | puts ("stdin ready"); |
26 | puts ("stdin ready"); |
25 | // for one-shot events, one must manually stop the watcher |
27 | // for one-shot events, one must manually stop the watcher |
26 | // with its corresponding stop function. |
28 | // with its corresponding stop function. |
27 | ev_io_stop (EV_A_ w); |
29 | ev_io_stop (EV_A_ w); |
28 | |
30 | |
29 | // this causes all nested ev_loop's to stop iterating |
31 | // this causes all nested ev_loop's to stop iterating |
30 | ev_unloop (EV_A_ EVUNLOOP_ALL); |
32 | ev_unloop (EV_A_ EVUNLOOP_ALL); |
31 | } |
33 | } |
32 | |
34 | |
33 | // another callback, this time for a time-out |
35 | // another callback, this time for a time-out |
34 | static void |
36 | static void |
35 | timeout_cb (EV_P_ struct ev_timer *w, int revents) |
37 | timeout_cb (EV_P_ ev_timer *w, int revents) |
36 | { |
38 | { |
37 | puts ("timeout"); |
39 | puts ("timeout"); |
38 | // this causes the innermost ev_loop to stop iterating |
40 | // this causes the innermost ev_loop to stop iterating |
39 | ev_unloop (EV_A_ EVUNLOOP_ONE); |
41 | ev_unloop (EV_A_ EVUNLOOP_ONE); |
40 | } |
42 | } |
41 | |
43 | |
42 | int |
44 | int |
43 | main (void) |
45 | main (void) |
44 | { |
46 | { |
45 | // use the default event loop unless you have special needs |
47 | // use the default event loop unless you have special needs |
46 | struct ev_loop *loop = ev_default_loop (0); |
48 | struct ev_loop *loop = ev_default_loop (0); |
47 | |
49 | |
48 | // initialise an io watcher, then start it |
50 | // initialise an io watcher, then start it |
49 | // this one will watch for stdin to become readable |
51 | // this one will watch for stdin to become readable |
50 | ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); |
52 | ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); |
51 | ev_io_start (loop, &stdin_watcher); |
53 | ev_io_start (loop, &stdin_watcher); |
52 | |
54 | |
53 | // initialise a timer watcher, then start it |
55 | // initialise a timer watcher, then start it |
54 | // simple non-repeating 5.5 second timeout |
56 | // simple non-repeating 5.5 second timeout |
55 | ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); |
57 | ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); |
56 | ev_timer_start (loop, &timeout_watcher); |
58 | ev_timer_start (loop, &timeout_watcher); |
57 | |
59 | |
58 | // now wait for events to arrive |
60 | // now wait for events to arrive |
59 | ev_loop (loop, 0); |
61 | ev_loop (loop, 0); |
60 | |
62 | |
61 | // unloop was called, so exit |
63 | // unloop was called, so exit |
62 | return 0; |
64 | return 0; |
63 | } |
65 | } |
64 | |
66 | |
65 | =head1 DESCRIPTION |
67 | =head1 DESCRIPTION |
66 | |
68 | |
67 | The newest version of this document is also available as an html-formatted |
69 | The newest version of this document is also available as an html-formatted |
68 | web page you might find easier to navigate when reading it for the first |
70 | web page you might find easier to navigate when reading it for the first |
… | |
… | |
103 | Libev is very configurable. In this manual the default (and most common) |
105 | Libev is very configurable. In this manual the default (and most common) |
104 | configuration will be described, which supports multiple event loops. For |
106 | configuration will be described, which supports multiple event loops. For |
105 | more info about various configuration options please have a look at |
107 | more info about various configuration options please have a look at |
106 | B<EMBED> section in this manual. If libev was configured without support |
108 | B<EMBED> section in this manual. If libev was configured without support |
107 | for multiple event loops, then all functions taking an initial argument of |
109 | for multiple event loops, then all functions taking an initial argument of |
108 | name C<loop> (which is always of type C<struct ev_loop *>) will not have |
110 | name C<loop> (which is always of type C<ev_loop *>) will not have |
109 | this argument. |
111 | this argument. |
110 | |
112 | |
111 | =head2 TIME REPRESENTATION |
113 | =head2 TIME REPRESENTATION |
112 | |
114 | |
113 | Libev represents time as a single floating point number, representing the |
115 | Libev represents time as a single floating point number, representing the |
… | |
… | |
178 | not a problem. |
180 | not a problem. |
179 | |
181 | |
180 | Example: Make sure we haven't accidentally been linked against the wrong |
182 | Example: Make sure we haven't accidentally been linked against the wrong |
181 | version. |
183 | version. |
182 | |
184 | |
183 | assert (("libev version mismatch", |
185 | assert (("libev version mismatch", |
184 | ev_version_major () == EV_VERSION_MAJOR |
186 | ev_version_major () == EV_VERSION_MAJOR |
185 | && ev_version_minor () >= EV_VERSION_MINOR)); |
187 | && ev_version_minor () >= EV_VERSION_MINOR)); |
186 | |
188 | |
187 | =item unsigned int ev_supported_backends () |
189 | =item unsigned int ev_supported_backends () |
188 | |
190 | |
189 | Return the set of all backends (i.e. their corresponding C<EV_BACKEND_*> |
191 | Return the set of all backends (i.e. their corresponding C<EV_BACKEND_*> |
190 | value) compiled into this binary of libev (independent of their |
192 | value) compiled into this binary of libev (independent of their |
… | |
… | |
192 | a description of the set values. |
194 | a description of the set values. |
193 | |
195 | |
194 | Example: make sure we have the epoll method, because yeah this is cool and |
196 | Example: make sure we have the epoll method, because yeah this is cool and |
195 | a must have and can we have a torrent of it please!!!11 |
197 | a must have and can we have a torrent of it please!!!11 |
196 | |
198 | |
197 | assert (("sorry, no epoll, no sex", |
199 | assert (("sorry, no epoll, no sex", |
198 | ev_supported_backends () & EVBACKEND_EPOLL)); |
200 | ev_supported_backends () & EVBACKEND_EPOLL)); |
199 | |
201 | |
200 | =item unsigned int ev_recommended_backends () |
202 | =item unsigned int ev_recommended_backends () |
201 | |
203 | |
202 | Return the set of all backends compiled into this binary of libev and also |
204 | Return the set of all backends compiled into this binary of libev and also |
203 | recommended for this platform. This set is often smaller than the one |
205 | recommended for this platform. This set is often smaller than the one |
… | |
… | |
214 | C<ev_embeddable_backends () & ev_supported_backends ()>, likewise for |
216 | C<ev_embeddable_backends () & ev_supported_backends ()>, likewise for |
215 | recommended ones. |
217 | recommended ones. |
216 | |
218 | |
217 | See the description of C<ev_embed> watchers for more info. |
219 | See the description of C<ev_embed> watchers for more info. |
218 | |
220 | |
219 | =item ev_set_allocator (void *(*cb)(void *ptr, long size)) |
221 | =item ev_set_allocator (void *(*cb)(void *ptr, long size)) [NOT REENTRANT] |
220 | |
222 | |
221 | Sets the allocation function to use (the prototype is similar - the |
223 | Sets the allocation function to use (the prototype is similar - the |
222 | semantics are identical to the C<realloc> C89/SuS/POSIX function). It is |
224 | semantics are identical to the C<realloc> C89/SuS/POSIX function). It is |
223 | used to allocate and free memory (no surprises here). If it returns zero |
225 | used to allocate and free memory (no surprises here). If it returns zero |
224 | when memory needs to be allocated (C<size != 0>), the library might abort |
226 | when memory needs to be allocated (C<size != 0>), the library might abort |
… | |
… | |
250 | } |
252 | } |
251 | |
253 | |
252 | ... |
254 | ... |
253 | ev_set_allocator (persistent_realloc); |
255 | ev_set_allocator (persistent_realloc); |
254 | |
256 | |
255 | =item ev_set_syserr_cb (void (*cb)(const char *msg)); |
257 | =item ev_set_syserr_cb (void (*cb)(const char *msg)); [NOT REENTRANT] |
256 | |
258 | |
257 | Set the callback function to call on a retryable system call error (such |
259 | Set the callback function to call on a retryable system call error (such |
258 | as failed select, poll, epoll_wait). The message is a printable string |
260 | as failed select, poll, epoll_wait). The message is a printable string |
259 | indicating the system call or subsystem causing the problem. If this |
261 | indicating the system call or subsystem causing the problem. If this |
260 | callback is set, then libev will expect it to remedy the situation, no |
262 | callback is set, then libev will expect it to remedy the situation, no |
… | |
… | |
276 | |
278 | |
277 | =back |
279 | =back |
278 | |
280 | |
279 | =head1 FUNCTIONS CONTROLLING THE EVENT LOOP |
281 | =head1 FUNCTIONS CONTROLLING THE EVENT LOOP |
280 | |
282 | |
281 | An event loop is described by a C<struct ev_loop *>. The library knows two |
283 | An event loop is described by a C<struct ev_loop *> (the C<struct> |
282 | types of such loops, the I<default> loop, which supports signals and child |
284 | is I<not> optional in this case, as there is also an C<ev_loop> |
283 | events, and dynamically created loops which do not. |
285 | I<function>). |
|
|
286 | |
|
|
287 | The library knows two types of such loops, the I<default> loop, which |
|
|
288 | supports signals and child events, and dynamically created loops which do |
|
|
289 | not. |
284 | |
290 | |
285 | =over 4 |
291 | =over 4 |
286 | |
292 | |
287 | =item struct ev_loop *ev_default_loop (unsigned int flags) |
293 | =item struct ev_loop *ev_default_loop (unsigned int flags) |
288 | |
294 | |
… | |
… | |
294 | If you don't know what event loop to use, use the one returned from this |
300 | If you don't know what event loop to use, use the one returned from this |
295 | function. |
301 | function. |
296 | |
302 | |
297 | Note that this function is I<not> thread-safe, so if you want to use it |
303 | Note that this function is I<not> thread-safe, so if you want to use it |
298 | from multiple threads, you have to lock (note also that this is unlikely, |
304 | from multiple threads, you have to lock (note also that this is unlikely, |
299 | as loops cannot bes hared easily between threads anyway). |
305 | as loops cannot be shared easily between threads anyway). |
300 | |
306 | |
301 | The default loop is the only loop that can handle C<ev_signal> and |
307 | The default loop is the only loop that can handle C<ev_signal> and |
302 | C<ev_child> watchers, and to do this, it always registers a handler |
308 | C<ev_child> watchers, and to do this, it always registers a handler |
303 | for C<SIGCHLD>. If this is a problem for your application you can either |
309 | for C<SIGCHLD>. If this is a problem for your application you can either |
304 | create a dynamic loop with C<ev_loop_new> that doesn't do that, or you |
310 | create a dynamic loop with C<ev_loop_new> that doesn't do that, or you |
… | |
… | |
359 | writing a server, you should C<accept ()> in a loop to accept as many |
365 | writing a server, you should C<accept ()> in a loop to accept as many |
360 | connections as possible during one iteration. You might also want to have |
366 | connections as possible during one iteration. You might also want to have |
361 | a look at C<ev_set_io_collect_interval ()> to increase the amount of |
367 | a look at C<ev_set_io_collect_interval ()> to increase the amount of |
362 | readiness notifications you get per iteration. |
368 | readiness notifications you get per iteration. |
363 | |
369 | |
|
|
370 | This backend maps C<EV_READ> to the C<readfds> set and C<EV_WRITE> to the |
|
|
371 | C<writefds> set (and to work around Microsoft Windows bugs, also onto the |
|
|
372 | C<exceptfds> set on that platform). |
|
|
373 | |
364 | =item C<EVBACKEND_POLL> (value 2, poll backend, available everywhere except on windows) |
374 | =item C<EVBACKEND_POLL> (value 2, poll backend, available everywhere except on windows) |
365 | |
375 | |
366 | And this is your standard poll(2) backend. It's more complicated |
376 | And this is your standard poll(2) backend. It's more complicated |
367 | than select, but handles sparse fds better and has no artificial |
377 | than select, but handles sparse fds better and has no artificial |
368 | limit on the number of fds you can use (except it will slow down |
378 | limit on the number of fds you can use (except it will slow down |
369 | considerably with a lot of inactive fds). It scales similarly to select, |
379 | considerably with a lot of inactive fds). It scales similarly to select, |
370 | i.e. O(total_fds). See the entry for C<EVBACKEND_SELECT>, above, for |
380 | i.e. O(total_fds). See the entry for C<EVBACKEND_SELECT>, above, for |
371 | performance tips. |
381 | performance tips. |
372 | |
382 | |
|
|
383 | This backend maps C<EV_READ> to C<POLLIN | POLLERR | POLLHUP>, and |
|
|
384 | C<EV_WRITE> to C<POLLOUT | POLLERR | POLLHUP>. |
|
|
385 | |
373 | =item C<EVBACKEND_EPOLL> (value 4, Linux) |
386 | =item C<EVBACKEND_EPOLL> (value 4, Linux) |
374 | |
387 | |
375 | For few fds, this backend is a bit little slower than poll and select, |
388 | For few fds, this backend is a bit little slower than poll and select, |
376 | but it scales phenomenally better. While poll and select usually scale |
389 | but it scales phenomenally better. While poll and select usually scale |
377 | like O(total_fds) where n is the total number of fds (or the highest fd), |
390 | like O(total_fds) where n is the total number of fds (or the highest fd), |
378 | epoll scales either O(1) or O(active_fds). The epoll design has a number |
391 | epoll scales either O(1) or O(active_fds). |
379 | of shortcomings, such as silently dropping events in some hard-to-detect |
392 | |
380 | cases and requiring a system call per fd change, no fork support and bad |
393 | The epoll mechanism deserves honorable mention as the most misdesigned |
381 | support for dup. |
394 | of the more advanced event mechanisms: mere annoyances include silently |
|
|
395 | dropping file descriptors, requiring a system call per change per file |
|
|
396 | descriptor (and unnecessary guessing of parameters), problems with dup and |
|
|
397 | so on. The biggest issue is fork races, however - if a program forks then |
|
|
398 | I<both> parent and child process have to recreate the epoll set, which can |
|
|
399 | take considerable time (one syscall per file descriptor) and is of course |
|
|
400 | hard to detect. |
|
|
401 | |
|
|
402 | Epoll is also notoriously buggy - embedding epoll fds I<should> work, but |
|
|
403 | of course I<doesn't>, and epoll just loves to report events for totally |
|
|
404 | I<different> file descriptors (even already closed ones, so one cannot |
|
|
405 | even remove them from the set) than registered in the set (especially |
|
|
406 | on SMP systems). Libev tries to counter these spurious notifications by |
|
|
407 | employing an additional generation counter and comparing that against the |
|
|
408 | events to filter out spurious ones, recreating the set when required. |
382 | |
409 | |
383 | While stopping, setting and starting an I/O watcher in the same iteration |
410 | While stopping, setting and starting an I/O watcher in the same iteration |
384 | will result in some caching, there is still a system call per such incident |
411 | will result in some caching, there is still a system call per such |
385 | (because the fd could point to a different file description now), so its |
412 | incident (because the same I<file descriptor> could point to a different |
386 | best to avoid that. Also, C<dup ()>'ed file descriptors might not work |
413 | I<file description> now), so its best to avoid that. Also, C<dup ()>'ed |
387 | very well if you register events for both fds. |
414 | file descriptors might not work very well if you register events for both |
388 | |
415 | file descriptors. |
389 | Please note that epoll sometimes generates spurious notifications, so you |
|
|
390 | need to use non-blocking I/O or other means to avoid blocking when no data |
|
|
391 | (or space) is available. |
|
|
392 | |
416 | |
393 | Best performance from this backend is achieved by not unregistering all |
417 | Best performance from this backend is achieved by not unregistering all |
394 | watchers for a file descriptor until it has been closed, if possible, i.e. |
418 | watchers for a file descriptor until it has been closed, if possible, |
395 | keep at least one watcher active per fd at all times. |
419 | i.e. keep at least one watcher active per fd at all times. Stopping and |
|
|
420 | starting a watcher (without re-setting it) also usually doesn't cause |
|
|
421 | extra overhead. A fork can both result in spurious notifications as well |
|
|
422 | as in libev having to destroy and recreate the epoll object, which can |
|
|
423 | take considerable time and thus should be avoided. |
|
|
424 | |
|
|
425 | All this means that, in practice, C<EVBACKEND_SELECT> can be as fast or |
|
|
426 | faster than epoll for maybe up to a hundred file descriptors, depending on |
|
|
427 | the usage. So sad. |
396 | |
428 | |
397 | While nominally embeddable in other event loops, this feature is broken in |
429 | While nominally embeddable in other event loops, this feature is broken in |
398 | all kernel versions tested so far. |
430 | all kernel versions tested so far. |
|
|
431 | |
|
|
432 | This backend maps C<EV_READ> and C<EV_WRITE> in the same way as |
|
|
433 | C<EVBACKEND_POLL>. |
399 | |
434 | |
400 | =item C<EVBACKEND_KQUEUE> (value 8, most BSD clones) |
435 | =item C<EVBACKEND_KQUEUE> (value 8, most BSD clones) |
401 | |
436 | |
402 | Kqueue deserves special mention, as at the time of this writing, it |
437 | Kqueue deserves special mention, as at the time of this writing, it |
403 | was broken on all BSDs except NetBSD (usually it doesn't work reliably |
438 | was broken on all BSDs except NetBSD (usually it doesn't work reliably |
404 | with anything but sockets and pipes, except on Darwin, where of course |
439 | with anything but sockets and pipes, except on Darwin, where of course |
405 | it's completely useless). For this reason it's not being "auto-detected" |
440 | it's completely useless). Unlike epoll, however, whose brokenness |
|
|
441 | is by design, these kqueue bugs can (and eventually will) be fixed |
|
|
442 | without API changes to existing programs. For this reason it's not being |
406 | unless you explicitly specify it explicitly in the flags (i.e. using |
443 | "auto-detected" unless you explicitly specify it in the flags (i.e. using |
407 | C<EVBACKEND_KQUEUE>) or libev was compiled on a known-to-be-good (-enough) |
444 | C<EVBACKEND_KQUEUE>) or libev was compiled on a known-to-be-good (-enough) |
408 | system like NetBSD. |
445 | system like NetBSD. |
409 | |
446 | |
410 | You still can embed kqueue into a normal poll or select backend and use it |
447 | You still can embed kqueue into a normal poll or select backend and use it |
411 | only for sockets (after having made sure that sockets work with kqueue on |
448 | only for sockets (after having made sure that sockets work with kqueue on |
… | |
… | |
413 | |
450 | |
414 | It scales in the same way as the epoll backend, but the interface to the |
451 | It scales in the same way as the epoll backend, but the interface to the |
415 | kernel is more efficient (which says nothing about its actual speed, of |
452 | kernel is more efficient (which says nothing about its actual speed, of |
416 | course). While stopping, setting and starting an I/O watcher does never |
453 | course). While stopping, setting and starting an I/O watcher does never |
417 | cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to |
454 | cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to |
418 | two event changes per incident, support for C<fork ()> is very bad and it |
455 | two event changes per incident. Support for C<fork ()> is very bad (but |
419 | drops fds silently in similarly hard-to-detect cases. |
456 | sane, unlike epoll) and it drops fds silently in similarly hard-to-detect |
|
|
457 | cases |
420 | |
458 | |
421 | This backend usually performs well under most conditions. |
459 | This backend usually performs well under most conditions. |
422 | |
460 | |
423 | While nominally embeddable in other event loops, this doesn't work |
461 | While nominally embeddable in other event loops, this doesn't work |
424 | everywhere, so you might need to test for this. And since it is broken |
462 | everywhere, so you might need to test for this. And since it is broken |
425 | almost everywhere, you should only use it when you have a lot of sockets |
463 | almost everywhere, you should only use it when you have a lot of sockets |
426 | (for which it usually works), by embedding it into another event loop |
464 | (for which it usually works), by embedding it into another event loop |
427 | (e.g. C<EVBACKEND_SELECT> or C<EVBACKEND_POLL>) and using it only for |
465 | (e.g. C<EVBACKEND_SELECT> or C<EVBACKEND_POLL>) and, did I mention it, |
428 | sockets. |
466 | using it only for sockets. |
|
|
467 | |
|
|
468 | This backend maps C<EV_READ> into an C<EVFILT_READ> kevent with |
|
|
469 | C<NOTE_EOF>, and C<EV_WRITE> into an C<EVFILT_WRITE> kevent with |
|
|
470 | C<NOTE_EOF>. |
429 | |
471 | |
430 | =item C<EVBACKEND_DEVPOLL> (value 16, Solaris 8) |
472 | =item C<EVBACKEND_DEVPOLL> (value 16, Solaris 8) |
431 | |
473 | |
432 | This is not implemented yet (and might never be, unless you send me an |
474 | This is not implemented yet (and might never be, unless you send me an |
433 | implementation). According to reports, C</dev/poll> only supports sockets |
475 | implementation). According to reports, C</dev/poll> only supports sockets |
… | |
… | |
446 | While this backend scales well, it requires one system call per active |
488 | While this backend scales well, it requires one system call per active |
447 | file descriptor per loop iteration. For small and medium numbers of file |
489 | file descriptor per loop iteration. For small and medium numbers of file |
448 | descriptors a "slow" C<EVBACKEND_SELECT> or C<EVBACKEND_POLL> backend |
490 | descriptors a "slow" C<EVBACKEND_SELECT> or C<EVBACKEND_POLL> backend |
449 | might perform better. |
491 | might perform better. |
450 | |
492 | |
451 | On the positive side, ignoring the spurious readiness notifications, this |
493 | On the positive side, with the exception of the spurious readiness |
452 | backend actually performed to specification in all tests and is fully |
494 | notifications, this backend actually performed fully to specification |
453 | embeddable, which is a rare feat among the OS-specific backends. |
495 | in all tests and is fully embeddable, which is a rare feat among the |
|
|
496 | OS-specific backends (I vastly prefer correctness over speed hacks). |
|
|
497 | |
|
|
498 | This backend maps C<EV_READ> and C<EV_WRITE> in the same way as |
|
|
499 | C<EVBACKEND_POLL>. |
454 | |
500 | |
455 | =item C<EVBACKEND_ALL> |
501 | =item C<EVBACKEND_ALL> |
456 | |
502 | |
457 | Try all backends (even potentially broken ones that wouldn't be tried |
503 | Try all backends (even potentially broken ones that wouldn't be tried |
458 | with C<EVFLAG_AUTO>). Since this is a mask, you can do stuff such as |
504 | with C<EVFLAG_AUTO>). Since this is a mask, you can do stuff such as |
… | |
… | |
464 | |
510 | |
465 | If one or more of these are or'ed into the flags value, then only these |
511 | If one or more of these are or'ed into the flags value, then only these |
466 | backends will be tried (in the reverse order as listed here). If none are |
512 | backends will be tried (in the reverse order as listed here). If none are |
467 | specified, all backends in C<ev_recommended_backends ()> will be tried. |
513 | specified, all backends in C<ev_recommended_backends ()> will be tried. |
468 | |
514 | |
469 | The most typical usage is like this: |
515 | Example: This is the most typical usage. |
470 | |
516 | |
471 | if (!ev_default_loop (0)) |
517 | if (!ev_default_loop (0)) |
472 | fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?"); |
518 | fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?"); |
473 | |
519 | |
474 | Restrict libev to the select and poll backends, and do not allow |
520 | Example: Restrict libev to the select and poll backends, and do not allow |
475 | environment settings to be taken into account: |
521 | environment settings to be taken into account: |
476 | |
522 | |
477 | ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV); |
523 | ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV); |
478 | |
524 | |
479 | Use whatever libev has to offer, but make sure that kqueue is used if |
525 | Example: Use whatever libev has to offer, but make sure that kqueue is |
480 | available (warning, breaks stuff, best use only with your own private |
526 | used if available (warning, breaks stuff, best use only with your own |
481 | event loop and only if you know the OS supports your types of fds): |
527 | private event loop and only if you know the OS supports your types of |
|
|
528 | fds): |
482 | |
529 | |
483 | ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE); |
530 | ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE); |
484 | |
531 | |
485 | =item struct ev_loop *ev_loop_new (unsigned int flags) |
532 | =item struct ev_loop *ev_loop_new (unsigned int flags) |
486 | |
533 | |
487 | Similar to C<ev_default_loop>, but always creates a new event loop that is |
534 | Similar to C<ev_default_loop>, but always creates a new event loop that is |
488 | always distinct from the default loop. Unlike the default loop, it cannot |
535 | always distinct from the default loop. Unlike the default loop, it cannot |
… | |
… | |
493 | libev with threads is indeed to create one loop per thread, and using the |
540 | libev with threads is indeed to create one loop per thread, and using the |
494 | default loop in the "main" or "initial" thread. |
541 | default loop in the "main" or "initial" thread. |
495 | |
542 | |
496 | Example: Try to create a event loop that uses epoll and nothing else. |
543 | Example: Try to create a event loop that uses epoll and nothing else. |
497 | |
544 | |
498 | struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV); |
545 | struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV); |
499 | if (!epoller) |
546 | if (!epoller) |
500 | fatal ("no epoll found here, maybe it hides under your chair"); |
547 | fatal ("no epoll found here, maybe it hides under your chair"); |
501 | |
548 | |
502 | =item ev_default_destroy () |
549 | =item ev_default_destroy () |
503 | |
550 | |
504 | Destroys the default loop again (frees all memory and kernel state |
551 | Destroys the default loop again (frees all memory and kernel state |
505 | etc.). None of the active event watchers will be stopped in the normal |
552 | etc.). None of the active event watchers will be stopped in the normal |
… | |
… | |
507 | responsibility to either stop all watchers cleanly yourself I<before> |
554 | responsibility to either stop all watchers cleanly yourself I<before> |
508 | calling this function, or cope with the fact afterwards (which is usually |
555 | calling this function, or cope with the fact afterwards (which is usually |
509 | the easiest thing, you can just ignore the watchers and/or C<free ()> them |
556 | the easiest thing, you can just ignore the watchers and/or C<free ()> them |
510 | for example). |
557 | for example). |
511 | |
558 | |
512 | Note that certain global state, such as signal state, will not be freed by |
559 | Note that certain global state, such as signal state (and installed signal |
513 | this function, and related watchers (such as signal and child watchers) |
560 | handlers), will not be freed by this function, and related watchers (such |
514 | would need to be stopped manually. |
561 | as signal and child watchers) would need to be stopped manually. |
515 | |
562 | |
516 | In general it is not advisable to call this function except in the |
563 | In general it is not advisable to call this function except in the |
517 | rare occasion where you really need to free e.g. the signal handling |
564 | rare occasion where you really need to free e.g. the signal handling |
518 | pipe fds. If you need dynamically allocated loops it is better to use |
565 | pipe fds. If you need dynamically allocated loops it is better to use |
519 | C<ev_loop_new> and C<ev_loop_destroy>). |
566 | C<ev_loop_new> and C<ev_loop_destroy>). |
… | |
… | |
544 | |
591 | |
545 | =item ev_loop_fork (loop) |
592 | =item ev_loop_fork (loop) |
546 | |
593 | |
547 | Like C<ev_default_fork>, but acts on an event loop created by |
594 | Like C<ev_default_fork>, but acts on an event loop created by |
548 | C<ev_loop_new>. Yes, you have to call this on every allocated event loop |
595 | C<ev_loop_new>. Yes, you have to call this on every allocated event loop |
549 | after fork, and how you do this is entirely your own problem. |
596 | after fork that you want to re-use in the child, and how you do this is |
|
|
597 | entirely your own problem. |
550 | |
598 | |
551 | =item int ev_is_default_loop (loop) |
599 | =item int ev_is_default_loop (loop) |
552 | |
600 | |
553 | Returns true when the given loop actually is the default loop, false otherwise. |
601 | Returns true when the given loop is, in fact, the default loop, and false |
|
|
602 | otherwise. |
554 | |
603 | |
555 | =item unsigned int ev_loop_count (loop) |
604 | =item unsigned int ev_loop_count (loop) |
556 | |
605 | |
557 | Returns the count of loop iterations for the loop, which is identical to |
606 | Returns the count of loop iterations for the loop, which is identical to |
558 | the number of times libev did poll for new events. It starts at C<0> and |
607 | the number of times libev did poll for new events. It starts at C<0> and |
… | |
… | |
573 | received events and started processing them. This timestamp does not |
622 | received events and started processing them. This timestamp does not |
574 | change as long as callbacks are being processed, and this is also the base |
623 | change as long as callbacks are being processed, and this is also the base |
575 | time used for relative timers. You can treat it as the timestamp of the |
624 | time used for relative timers. You can treat it as the timestamp of the |
576 | event occurring (or more correctly, libev finding out about it). |
625 | event occurring (or more correctly, libev finding out about it). |
577 | |
626 | |
|
|
627 | =item ev_now_update (loop) |
|
|
628 | |
|
|
629 | Establishes the current time by querying the kernel, updating the time |
|
|
630 | returned by C<ev_now ()> in the progress. This is a costly operation and |
|
|
631 | is usually done automatically within C<ev_loop ()>. |
|
|
632 | |
|
|
633 | This function is rarely useful, but when some event callback runs for a |
|
|
634 | very long time without entering the event loop, updating libev's idea of |
|
|
635 | the current time is a good idea. |
|
|
636 | |
|
|
637 | See also "The special problem of time updates" in the C<ev_timer> section. |
|
|
638 | |
578 | =item ev_loop (loop, int flags) |
639 | =item ev_loop (loop, int flags) |
579 | |
640 | |
580 | Finally, this is it, the event handler. This function usually is called |
641 | Finally, this is it, the event handler. This function usually is called |
581 | after you initialised all your watchers and you want to start handling |
642 | after you initialised all your watchers and you want to start handling |
582 | events. |
643 | events. |
… | |
… | |
584 | If the flags argument is specified as C<0>, it will not return until |
645 | If the flags argument is specified as C<0>, it will not return until |
585 | either no event watchers are active anymore or C<ev_unloop> was called. |
646 | either no event watchers are active anymore or C<ev_unloop> was called. |
586 | |
647 | |
587 | Please note that an explicit C<ev_unloop> is usually better than |
648 | Please note that an explicit C<ev_unloop> is usually better than |
588 | relying on all watchers to be stopped when deciding when a program has |
649 | relying on all watchers to be stopped when deciding when a program has |
589 | finished (especially in interactive programs), but having a program that |
650 | finished (especially in interactive programs), but having a program |
590 | automatically loops as long as it has to and no longer by virtue of |
651 | that automatically loops as long as it has to and no longer by virtue |
591 | relying on its watchers stopping correctly is a thing of beauty. |
652 | of relying on its watchers stopping correctly, that is truly a thing of |
|
|
653 | beauty. |
592 | |
654 | |
593 | A flags value of C<EVLOOP_NONBLOCK> will look for new events, will handle |
655 | A flags value of C<EVLOOP_NONBLOCK> will look for new events, will handle |
594 | those events and any outstanding ones, but will not block your process in |
656 | those events and any already outstanding ones, but will not block your |
595 | case there are no events and will return after one iteration of the loop. |
657 | process in case there are no events and will return after one iteration of |
|
|
658 | the loop. |
596 | |
659 | |
597 | A flags value of C<EVLOOP_ONESHOT> will look for new events (waiting if |
660 | A flags value of C<EVLOOP_ONESHOT> will look for new events (waiting if |
598 | necessary) and will handle those and any outstanding ones. It will block |
661 | necessary) and will handle those and any already outstanding ones. It |
599 | your process until at least one new event arrives, and will return after |
662 | will block your process until at least one new event arrives (which could |
600 | one iteration of the loop. This is useful if you are waiting for some |
663 | be an event internal to libev itself, so there is no guarantee that a |
601 | external event in conjunction with something not expressible using other |
664 | user-registered callback will be called), and will return after one |
|
|
665 | iteration of the loop. |
|
|
666 | |
|
|
667 | This is useful if you are waiting for some external event in conjunction |
|
|
668 | with something not expressible using other libev watchers (i.e. "roll your |
602 | libev watchers. However, a pair of C<ev_prepare>/C<ev_check> watchers is |
669 | own C<ev_loop>"). However, a pair of C<ev_prepare>/C<ev_check> watchers is |
603 | usually a better approach for this kind of thing. |
670 | usually a better approach for this kind of thing. |
604 | |
671 | |
605 | Here are the gory details of what C<ev_loop> does: |
672 | Here are the gory details of what C<ev_loop> does: |
606 | |
673 | |
607 | - Before the first iteration, call any pending watchers. |
674 | - Before the first iteration, call any pending watchers. |
608 | * If EVFLAG_FORKCHECK was used, check for a fork. |
675 | * If EVFLAG_FORKCHECK was used, check for a fork. |
609 | - If a fork was detected, queue and call all fork watchers. |
676 | - If a fork was detected (by any means), queue and call all fork watchers. |
610 | - Queue and call all prepare watchers. |
677 | - Queue and call all prepare watchers. |
611 | - If we have been forked, recreate the kernel state. |
678 | - If we have been forked, detach and recreate the kernel state |
|
|
679 | as to not disturb the other process. |
612 | - Update the kernel state with all outstanding changes. |
680 | - Update the kernel state with all outstanding changes. |
613 | - Update the "event loop time". |
681 | - Update the "event loop time" (ev_now ()). |
614 | - Calculate for how long to sleep or block, if at all |
682 | - Calculate for how long to sleep or block, if at all |
615 | (active idle watchers, EVLOOP_NONBLOCK or not having |
683 | (active idle watchers, EVLOOP_NONBLOCK or not having |
616 | any active watchers at all will result in not sleeping). |
684 | any active watchers at all will result in not sleeping). |
617 | - Sleep if the I/O and timer collect interval say so. |
685 | - Sleep if the I/O and timer collect interval say so. |
618 | - Block the process, waiting for any events. |
686 | - Block the process, waiting for any events. |
619 | - Queue all outstanding I/O (fd) events. |
687 | - Queue all outstanding I/O (fd) events. |
620 | - Update the "event loop time" and do time jump handling. |
688 | - Update the "event loop time" (ev_now ()), and do time jump adjustments. |
621 | - Queue all outstanding timers. |
689 | - Queue all expired timers. |
622 | - Queue all outstanding periodics. |
690 | - Queue all expired periodics. |
623 | - If no events are pending now, queue all idle watchers. |
691 | - Unless any events are pending now, queue all idle watchers. |
624 | - Queue all check watchers. |
692 | - Queue all check watchers. |
625 | - Call all queued watchers in reverse order (i.e. check watchers first). |
693 | - Call all queued watchers in reverse order (i.e. check watchers first). |
626 | Signals and child watchers are implemented as I/O watchers, and will |
694 | Signals and child watchers are implemented as I/O watchers, and will |
627 | be handled here by queueing them when their watcher gets executed. |
695 | be handled here by queueing them when their watcher gets executed. |
628 | - If ev_unloop has been called, or EVLOOP_ONESHOT or EVLOOP_NONBLOCK |
696 | - If ev_unloop has been called, or EVLOOP_ONESHOT or EVLOOP_NONBLOCK |
… | |
… | |
633 | anymore. |
701 | anymore. |
634 | |
702 | |
635 | ... queue jobs here, make sure they register event watchers as long |
703 | ... queue jobs here, make sure they register event watchers as long |
636 | ... as they still have work to do (even an idle watcher will do..) |
704 | ... as they still have work to do (even an idle watcher will do..) |
637 | ev_loop (my_loop, 0); |
705 | ev_loop (my_loop, 0); |
638 | ... jobs done. yeah! |
706 | ... jobs done or somebody called unloop. yeah! |
639 | |
707 | |
640 | =item ev_unloop (loop, how) |
708 | =item ev_unloop (loop, how) |
641 | |
709 | |
642 | Can be used to make a call to C<ev_loop> return early (but only after it |
710 | Can be used to make a call to C<ev_loop> return early (but only after it |
643 | has processed all outstanding events). The C<how> argument must be either |
711 | has processed all outstanding events). The C<how> argument must be either |
644 | C<EVUNLOOP_ONE>, which will make the innermost C<ev_loop> call return, or |
712 | C<EVUNLOOP_ONE>, which will make the innermost C<ev_loop> call return, or |
645 | C<EVUNLOOP_ALL>, which will make all nested C<ev_loop> calls return. |
713 | C<EVUNLOOP_ALL>, which will make all nested C<ev_loop> calls return. |
646 | |
714 | |
647 | This "unloop state" will be cleared when entering C<ev_loop> again. |
715 | This "unloop state" will be cleared when entering C<ev_loop> again. |
648 | |
716 | |
|
|
717 | It is safe to call C<ev_unloop> from otuside any C<ev_loop> calls. |
|
|
718 | |
649 | =item ev_ref (loop) |
719 | =item ev_ref (loop) |
650 | |
720 | |
651 | =item ev_unref (loop) |
721 | =item ev_unref (loop) |
652 | |
722 | |
653 | Ref/unref can be used to add or remove a reference count on the event |
723 | Ref/unref can be used to add or remove a reference count on the event |
654 | loop: Every watcher keeps one reference, and as long as the reference |
724 | loop: Every watcher keeps one reference, and as long as the reference |
655 | count is nonzero, C<ev_loop> will not return on its own. If you have |
725 | count is nonzero, C<ev_loop> will not return on its own. |
|
|
726 | |
656 | a watcher you never unregister that should not keep C<ev_loop> from |
727 | If you have a watcher you never unregister that should not keep C<ev_loop> |
657 | returning, ev_unref() after starting, and ev_ref() before stopping it. For |
728 | from returning, call ev_unref() after starting, and ev_ref() before |
|
|
729 | stopping it. |
|
|
730 | |
658 | example, libev itself uses this for its internal signal pipe: It is not |
731 | As an example, libev itself uses this for its internal signal pipe: It is |
659 | visible to the libev user and should not keep C<ev_loop> from exiting if |
732 | not visible to the libev user and should not keep C<ev_loop> from exiting |
660 | no event watchers registered by it are active. It is also an excellent |
733 | if no event watchers registered by it are active. It is also an excellent |
661 | way to do this for generic recurring timers or from within third-party |
734 | way to do this for generic recurring timers or from within third-party |
662 | libraries. Just remember to I<unref after start> and I<ref before stop> |
735 | libraries. Just remember to I<unref after start> and I<ref before stop> |
663 | (but only if the watcher wasn't active before, or was active before, |
736 | (but only if the watcher wasn't active before, or was active before, |
664 | respectively). |
737 | respectively). |
665 | |
738 | |
666 | Example: Create a signal watcher, but keep it from keeping C<ev_loop> |
739 | Example: Create a signal watcher, but keep it from keeping C<ev_loop> |
667 | running when nothing else is active. |
740 | running when nothing else is active. |
668 | |
741 | |
669 | struct ev_signal exitsig; |
742 | ev_signal exitsig; |
670 | ev_signal_init (&exitsig, sig_cb, SIGINT); |
743 | ev_signal_init (&exitsig, sig_cb, SIGINT); |
671 | ev_signal_start (loop, &exitsig); |
744 | ev_signal_start (loop, &exitsig); |
672 | evf_unref (loop); |
745 | evf_unref (loop); |
673 | |
746 | |
674 | Example: For some weird reason, unregister the above signal handler again. |
747 | Example: For some weird reason, unregister the above signal handler again. |
675 | |
748 | |
676 | ev_ref (loop); |
749 | ev_ref (loop); |
677 | ev_signal_stop (loop, &exitsig); |
750 | ev_signal_stop (loop, &exitsig); |
678 | |
751 | |
679 | =item ev_set_io_collect_interval (loop, ev_tstamp interval) |
752 | =item ev_set_io_collect_interval (loop, ev_tstamp interval) |
680 | |
753 | |
681 | =item ev_set_timeout_collect_interval (loop, ev_tstamp interval) |
754 | =item ev_set_timeout_collect_interval (loop, ev_tstamp interval) |
682 | |
755 | |
683 | These advanced functions influence the time that libev will spend waiting |
756 | These advanced functions influence the time that libev will spend waiting |
684 | for events. Both are by default C<0>, meaning that libev will try to |
757 | for events. Both time intervals are by default C<0>, meaning that libev |
685 | invoke timer/periodic callbacks and I/O callbacks with minimum latency. |
758 | will try to invoke timer/periodic callbacks and I/O callbacks with minimum |
|
|
759 | latency. |
686 | |
760 | |
687 | Setting these to a higher value (the C<interval> I<must> be >= C<0>) |
761 | Setting these to a higher value (the C<interval> I<must> be >= C<0>) |
688 | allows libev to delay invocation of I/O and timer/periodic callbacks to |
762 | allows libev to delay invocation of I/O and timer/periodic callbacks |
689 | increase efficiency of loop iterations. |
763 | to increase efficiency of loop iterations (or to increase power-saving |
|
|
764 | opportunities). |
690 | |
765 | |
691 | The background is that sometimes your program runs just fast enough to |
766 | The idea is that sometimes your program runs just fast enough to handle |
692 | handle one (or very few) event(s) per loop iteration. While this makes |
767 | one (or very few) event(s) per loop iteration. While this makes the |
693 | the program responsive, it also wastes a lot of CPU time to poll for new |
768 | program responsive, it also wastes a lot of CPU time to poll for new |
694 | events, especially with backends like C<select ()> which have a high |
769 | events, especially with backends like C<select ()> which have a high |
695 | overhead for the actual polling but can deliver many events at once. |
770 | overhead for the actual polling but can deliver many events at once. |
696 | |
771 | |
697 | By setting a higher I<io collect interval> you allow libev to spend more |
772 | By setting a higher I<io collect interval> you allow libev to spend more |
698 | time collecting I/O events, so you can handle more events per iteration, |
773 | time collecting I/O events, so you can handle more events per iteration, |
… | |
… | |
700 | C<ev_timer>) will be not affected. Setting this to a non-null value will |
775 | C<ev_timer>) will be not affected. Setting this to a non-null value will |
701 | introduce an additional C<ev_sleep ()> call into most loop iterations. |
776 | introduce an additional C<ev_sleep ()> call into most loop iterations. |
702 | |
777 | |
703 | Likewise, by setting a higher I<timeout collect interval> you allow libev |
778 | Likewise, by setting a higher I<timeout collect interval> you allow libev |
704 | to spend more time collecting timeouts, at the expense of increased |
779 | to spend more time collecting timeouts, at the expense of increased |
705 | latency (the watcher callback will be called later). C<ev_io> watchers |
780 | latency/jitter/inexactness (the watcher callback will be called |
706 | will not be affected. Setting this to a non-null value will not introduce |
781 | later). C<ev_io> watchers will not be affected. Setting this to a non-null |
707 | any overhead in libev. |
782 | value will not introduce any overhead in libev. |
708 | |
783 | |
709 | Many (busy) programs can usually benefit by setting the I/O collect |
784 | Many (busy) programs can usually benefit by setting the I/O collect |
710 | interval to a value near C<0.1> or so, which is often enough for |
785 | interval to a value near C<0.1> or so, which is often enough for |
711 | interactive servers (of course not for games), likewise for timeouts. It |
786 | interactive servers (of course not for games), likewise for timeouts. It |
712 | usually doesn't make much sense to set it to a lower value than C<0.01>, |
787 | usually doesn't make much sense to set it to a lower value than C<0.01>, |
713 | as this approaches the timing granularity of most systems. |
788 | as this approaches the timing granularity of most systems. |
714 | |
789 | |
|
|
790 | Setting the I<timeout collect interval> can improve the opportunity for |
|
|
791 | saving power, as the program will "bundle" timer callback invocations that |
|
|
792 | are "near" in time together, by delaying some, thus reducing the number of |
|
|
793 | times the process sleeps and wakes up again. Another useful technique to |
|
|
794 | reduce iterations/wake-ups is to use C<ev_periodic> watchers and make sure |
|
|
795 | they fire on, say, one-second boundaries only. |
|
|
796 | |
715 | =item ev_loop_verify (loop) |
797 | =item ev_loop_verify (loop) |
716 | |
798 | |
717 | This function only does something when C<EV_VERIFY> support has been |
799 | This function only does something when C<EV_VERIFY> support has been |
718 | compiled in. It tries to go through all internal structures and checks |
800 | compiled in, which is the default for non-minimal builds. It tries to go |
719 | them for validity. If anything is found to be inconsistent, it will print |
801 | through all internal structures and checks them for validity. If anything |
720 | an error message to standard error and call C<abort ()>. |
802 | is found to be inconsistent, it will print an error message to standard |
|
|
803 | error and call C<abort ()>. |
721 | |
804 | |
722 | This can be used to catch bugs inside libev itself: under normal |
805 | This can be used to catch bugs inside libev itself: under normal |
723 | circumstances, this function will never abort as of course libev keeps its |
806 | circumstances, this function will never abort as of course libev keeps its |
724 | data structures consistent. |
807 | data structures consistent. |
725 | |
808 | |
726 | =back |
809 | =back |
727 | |
810 | |
728 | |
811 | |
729 | =head1 ANATOMY OF A WATCHER |
812 | =head1 ANATOMY OF A WATCHER |
730 | |
813 | |
|
|
814 | In the following description, uppercase C<TYPE> in names stands for the |
|
|
815 | watcher type, e.g. C<ev_TYPE_start> can mean C<ev_timer_start> for timer |
|
|
816 | watchers and C<ev_io_start> for I/O watchers. |
|
|
817 | |
731 | A watcher is a structure that you create and register to record your |
818 | A watcher is a structure that you create and register to record your |
732 | interest in some event. For instance, if you want to wait for STDIN to |
819 | interest in some event. For instance, if you want to wait for STDIN to |
733 | become readable, you would create an C<ev_io> watcher for that: |
820 | become readable, you would create an C<ev_io> watcher for that: |
734 | |
821 | |
735 | static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents) |
822 | static void my_cb (struct ev_loop *loop, ev_io *w, int revents) |
736 | { |
823 | { |
737 | ev_io_stop (w); |
824 | ev_io_stop (w); |
738 | ev_unloop (loop, EVUNLOOP_ALL); |
825 | ev_unloop (loop, EVUNLOOP_ALL); |
739 | } |
826 | } |
740 | |
827 | |
741 | struct ev_loop *loop = ev_default_loop (0); |
828 | struct ev_loop *loop = ev_default_loop (0); |
|
|
829 | |
742 | struct ev_io stdin_watcher; |
830 | ev_io stdin_watcher; |
|
|
831 | |
743 | ev_init (&stdin_watcher, my_cb); |
832 | ev_init (&stdin_watcher, my_cb); |
744 | ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); |
833 | ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); |
745 | ev_io_start (loop, &stdin_watcher); |
834 | ev_io_start (loop, &stdin_watcher); |
|
|
835 | |
746 | ev_loop (loop, 0); |
836 | ev_loop (loop, 0); |
747 | |
837 | |
748 | As you can see, you are responsible for allocating the memory for your |
838 | As you can see, you are responsible for allocating the memory for your |
749 | watcher structures (and it is usually a bad idea to do this on the stack, |
839 | watcher structures (and it is I<usually> a bad idea to do this on the |
750 | although this can sometimes be quite valid). |
840 | stack). |
|
|
841 | |
|
|
842 | Each watcher has an associated watcher structure (called C<struct ev_TYPE> |
|
|
843 | or simply C<ev_TYPE>, as typedefs are provided for all watcher structs). |
751 | |
844 | |
752 | Each watcher structure must be initialised by a call to C<ev_init |
845 | Each watcher structure must be initialised by a call to C<ev_init |
753 | (watcher *, callback)>, which expects a callback to be provided. This |
846 | (watcher *, callback)>, which expects a callback to be provided. This |
754 | callback gets invoked each time the event occurs (or, in the case of I/O |
847 | callback gets invoked each time the event occurs (or, in the case of I/O |
755 | watchers, each time the event loop detects that the file descriptor given |
848 | watchers, each time the event loop detects that the file descriptor given |
756 | is readable and/or writable). |
849 | is readable and/or writable). |
757 | |
850 | |
758 | Each watcher type has its own C<< ev_<type>_set (watcher *, ...) >> macro |
851 | Each watcher type further has its own C<< ev_TYPE_set (watcher *, ...) >> |
759 | with arguments specific to this watcher type. There is also a macro |
852 | macro to configure it, with arguments specific to the watcher type. There |
760 | to combine initialisation and setting in one call: C<< ev_<type>_init |
853 | is also a macro to combine initialisation and setting in one call: C<< |
761 | (watcher *, callback, ...) >>. |
854 | ev_TYPE_init (watcher *, callback, ...) >>. |
762 | |
855 | |
763 | To make the watcher actually watch out for events, you have to start it |
856 | To make the watcher actually watch out for events, you have to start it |
764 | with a watcher-specific start function (C<< ev_<type>_start (loop, watcher |
857 | with a watcher-specific start function (C<< ev_TYPE_start (loop, watcher |
765 | *) >>), and you can stop watching for events at any time by calling the |
858 | *) >>), and you can stop watching for events at any time by calling the |
766 | corresponding stop function (C<< ev_<type>_stop (loop, watcher *) >>. |
859 | corresponding stop function (C<< ev_TYPE_stop (loop, watcher *) >>. |
767 | |
860 | |
768 | As long as your watcher is active (has been started but not stopped) you |
861 | As long as your watcher is active (has been started but not stopped) you |
769 | must not touch the values stored in it. Most specifically you must never |
862 | must not touch the values stored in it. Most specifically you must never |
770 | reinitialise it or call its C<set> macro. |
863 | reinitialise it or call its C<ev_TYPE_set> macro. |
771 | |
864 | |
772 | Each and every callback receives the event loop pointer as first, the |
865 | Each and every callback receives the event loop pointer as first, the |
773 | registered watcher structure as second, and a bitset of received events as |
866 | registered watcher structure as second, and a bitset of received events as |
774 | third argument. |
867 | third argument. |
775 | |
868 | |
… | |
… | |
838 | =item C<EV_ERROR> |
931 | =item C<EV_ERROR> |
839 | |
932 | |
840 | An unspecified error has occurred, the watcher has been stopped. This might |
933 | An unspecified error has occurred, the watcher has been stopped. This might |
841 | happen because the watcher could not be properly started because libev |
934 | happen because the watcher could not be properly started because libev |
842 | ran out of memory, a file descriptor was found to be closed or any other |
935 | ran out of memory, a file descriptor was found to be closed or any other |
|
|
936 | problem. Libev considers these application bugs. |
|
|
937 | |
843 | problem. You best act on it by reporting the problem and somehow coping |
938 | You best act on it by reporting the problem and somehow coping with the |
844 | with the watcher being stopped. |
939 | watcher being stopped. Note that well-written programs should not receive |
|
|
940 | an error ever, so when your watcher receives it, this usually indicates a |
|
|
941 | bug in your program. |
845 | |
942 | |
846 | Libev will usually signal a few "dummy" events together with an error, |
943 | Libev will usually signal a few "dummy" events together with an error, for |
847 | for example it might indicate that a fd is readable or writable, and if |
944 | example it might indicate that a fd is readable or writable, and if your |
848 | your callbacks is well-written it can just attempt the operation and cope |
945 | callbacks is well-written it can just attempt the operation and cope with |
849 | with the error from read() or write(). This will not work in multi-threaded |
946 | the error from read() or write(). This will not work in multi-threaded |
850 | programs, though, so beware. |
947 | programs, though, as the fd could already be closed and reused for another |
|
|
948 | thing, so beware. |
851 | |
949 | |
852 | =back |
950 | =back |
853 | |
951 | |
854 | =head2 GENERIC WATCHER FUNCTIONS |
952 | =head2 GENERIC WATCHER FUNCTIONS |
855 | |
|
|
856 | In the following description, C<TYPE> stands for the watcher type, |
|
|
857 | e.g. C<timer> for C<ev_timer> watchers and C<io> for C<ev_io> watchers. |
|
|
858 | |
953 | |
859 | =over 4 |
954 | =over 4 |
860 | |
955 | |
861 | =item C<ev_init> (ev_TYPE *watcher, callback) |
956 | =item C<ev_init> (ev_TYPE *watcher, callback) |
862 | |
957 | |
… | |
… | |
868 | which rolls both calls into one. |
963 | which rolls both calls into one. |
869 | |
964 | |
870 | You can reinitialise a watcher at any time as long as it has been stopped |
965 | You can reinitialise a watcher at any time as long as it has been stopped |
871 | (or never started) and there are no pending events outstanding. |
966 | (or never started) and there are no pending events outstanding. |
872 | |
967 | |
873 | The callback is always of type C<void (*)(ev_loop *loop, ev_TYPE *watcher, |
968 | The callback is always of type C<void (*)(struct ev_loop *loop, ev_TYPE *watcher, |
874 | int revents)>. |
969 | int revents)>. |
|
|
970 | |
|
|
971 | Example: Initialise an C<ev_io> watcher in two steps. |
|
|
972 | |
|
|
973 | ev_io w; |
|
|
974 | ev_init (&w, my_cb); |
|
|
975 | ev_io_set (&w, STDIN_FILENO, EV_READ); |
875 | |
976 | |
876 | =item C<ev_TYPE_set> (ev_TYPE *, [args]) |
977 | =item C<ev_TYPE_set> (ev_TYPE *, [args]) |
877 | |
978 | |
878 | This macro initialises the type-specific parts of a watcher. You need to |
979 | This macro initialises the type-specific parts of a watcher. You need to |
879 | call C<ev_init> at least once before you call this macro, but you can |
980 | call C<ev_init> at least once before you call this macro, but you can |
… | |
… | |
882 | difference to the C<ev_init> macro). |
983 | difference to the C<ev_init> macro). |
883 | |
984 | |
884 | Although some watcher types do not have type-specific arguments |
985 | Although some watcher types do not have type-specific arguments |
885 | (e.g. C<ev_prepare>) you still need to call its C<set> macro. |
986 | (e.g. C<ev_prepare>) you still need to call its C<set> macro. |
886 | |
987 | |
|
|
988 | See C<ev_init>, above, for an example. |
|
|
989 | |
887 | =item C<ev_TYPE_init> (ev_TYPE *watcher, callback, [args]) |
990 | =item C<ev_TYPE_init> (ev_TYPE *watcher, callback, [args]) |
888 | |
991 | |
889 | This convenience macro rolls both C<ev_init> and C<ev_TYPE_set> macro |
992 | This convenience macro rolls both C<ev_init> and C<ev_TYPE_set> macro |
890 | calls into a single call. This is the most convenient method to initialise |
993 | calls into a single call. This is the most convenient method to initialise |
891 | a watcher. The same limitations apply, of course. |
994 | a watcher. The same limitations apply, of course. |
892 | |
995 | |
|
|
996 | Example: Initialise and set an C<ev_io> watcher in one step. |
|
|
997 | |
|
|
998 | ev_io_init (&w, my_cb, STDIN_FILENO, EV_READ); |
|
|
999 | |
893 | =item C<ev_TYPE_start> (loop *, ev_TYPE *watcher) |
1000 | =item C<ev_TYPE_start> (loop *, ev_TYPE *watcher) |
894 | |
1001 | |
895 | Starts (activates) the given watcher. Only active watchers will receive |
1002 | Starts (activates) the given watcher. Only active watchers will receive |
896 | events. If the watcher is already active nothing will happen. |
1003 | events. If the watcher is already active nothing will happen. |
897 | |
1004 | |
|
|
1005 | Example: Start the C<ev_io> watcher that is being abused as example in this |
|
|
1006 | whole section. |
|
|
1007 | |
|
|
1008 | ev_io_start (EV_DEFAULT_UC, &w); |
|
|
1009 | |
898 | =item C<ev_TYPE_stop> (loop *, ev_TYPE *watcher) |
1010 | =item C<ev_TYPE_stop> (loop *, ev_TYPE *watcher) |
899 | |
1011 | |
900 | Stops the given watcher again (if active) and clears the pending |
1012 | Stops the given watcher if active, and clears the pending status (whether |
|
|
1013 | the watcher was active or not). |
|
|
1014 | |
901 | status. It is possible that stopped watchers are pending (for example, |
1015 | It is possible that stopped watchers are pending - for example, |
902 | non-repeating timers are being stopped when they become pending), but |
1016 | non-repeating timers are being stopped when they become pending - but |
903 | C<ev_TYPE_stop> ensures that the watcher is neither active nor pending. If |
1017 | calling C<ev_TYPE_stop> ensures that the watcher is neither active nor |
904 | you want to free or reuse the memory used by the watcher it is therefore a |
1018 | pending. If you want to free or reuse the memory used by the watcher it is |
905 | good idea to always call its C<ev_TYPE_stop> function. |
1019 | therefore a good idea to always call its C<ev_TYPE_stop> function. |
906 | |
1020 | |
907 | =item bool ev_is_active (ev_TYPE *watcher) |
1021 | =item bool ev_is_active (ev_TYPE *watcher) |
908 | |
1022 | |
909 | Returns a true value iff the watcher is active (i.e. it has been started |
1023 | Returns a true value iff the watcher is active (i.e. it has been started |
910 | and not yet been stopped). As long as a watcher is active you must not modify |
1024 | and not yet been stopped). As long as a watcher is active you must not modify |
… | |
… | |
952 | The default priority used by watchers when no priority has been set is |
1066 | The default priority used by watchers when no priority has been set is |
953 | always C<0>, which is supposed to not be too high and not be too low :). |
1067 | always C<0>, which is supposed to not be too high and not be too low :). |
954 | |
1068 | |
955 | Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is |
1069 | Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is |
956 | fine, as long as you do not mind that the priority value you query might |
1070 | fine, as long as you do not mind that the priority value you query might |
957 | or might not have been adjusted to be within valid range. |
1071 | or might not have been clamped to the valid range. |
958 | |
1072 | |
959 | =item ev_invoke (loop, ev_TYPE *watcher, int revents) |
1073 | =item ev_invoke (loop, ev_TYPE *watcher, int revents) |
960 | |
1074 | |
961 | Invoke the C<watcher> with the given C<loop> and C<revents>. Neither |
1075 | Invoke the C<watcher> with the given C<loop> and C<revents>. Neither |
962 | C<loop> nor C<revents> need to be valid as long as the watcher callback |
1076 | C<loop> nor C<revents> need to be valid as long as the watcher callback |
963 | can deal with that fact. |
1077 | can deal with that fact, as both are simply passed through to the |
|
|
1078 | callback. |
964 | |
1079 | |
965 | =item int ev_clear_pending (loop, ev_TYPE *watcher) |
1080 | =item int ev_clear_pending (loop, ev_TYPE *watcher) |
966 | |
1081 | |
967 | If the watcher is pending, this function returns clears its pending status |
1082 | If the watcher is pending, this function clears its pending status and |
968 | and returns its C<revents> bitset (as if its callback was invoked). If the |
1083 | returns its C<revents> bitset (as if its callback was invoked). If the |
969 | watcher isn't pending it does nothing and returns C<0>. |
1084 | watcher isn't pending it does nothing and returns C<0>. |
970 | |
1085 | |
|
|
1086 | Sometimes it can be useful to "poll" a watcher instead of waiting for its |
|
|
1087 | callback to be invoked, which can be accomplished with this function. |
|
|
1088 | |
971 | =back |
1089 | =back |
972 | |
1090 | |
973 | |
1091 | |
974 | =head2 ASSOCIATING CUSTOM DATA WITH A WATCHER |
1092 | =head2 ASSOCIATING CUSTOM DATA WITH A WATCHER |
975 | |
1093 | |
976 | Each watcher has, by default, a member C<void *data> that you can change |
1094 | Each watcher has, by default, a member C<void *data> that you can change |
977 | and read at any time, libev will completely ignore it. This can be used |
1095 | and read at any time: libev will completely ignore it. This can be used |
978 | to associate arbitrary data with your watcher. If you need more data and |
1096 | to associate arbitrary data with your watcher. If you need more data and |
979 | don't want to allocate memory and store a pointer to it in that data |
1097 | don't want to allocate memory and store a pointer to it in that data |
980 | member, you can also "subclass" the watcher type and provide your own |
1098 | member, you can also "subclass" the watcher type and provide your own |
981 | data: |
1099 | data: |
982 | |
1100 | |
983 | struct my_io |
1101 | struct my_io |
984 | { |
1102 | { |
985 | struct ev_io io; |
1103 | ev_io io; |
986 | int otherfd; |
1104 | int otherfd; |
987 | void *somedata; |
1105 | void *somedata; |
988 | struct whatever *mostinteresting; |
1106 | struct whatever *mostinteresting; |
989 | } |
1107 | }; |
|
|
1108 | |
|
|
1109 | ... |
|
|
1110 | struct my_io w; |
|
|
1111 | ev_io_init (&w.io, my_cb, fd, EV_READ); |
990 | |
1112 | |
991 | And since your callback will be called with a pointer to the watcher, you |
1113 | And since your callback will be called with a pointer to the watcher, you |
992 | can cast it back to your own type: |
1114 | can cast it back to your own type: |
993 | |
1115 | |
994 | static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents) |
1116 | static void my_cb (struct ev_loop *loop, ev_io *w_, int revents) |
995 | { |
1117 | { |
996 | struct my_io *w = (struct my_io *)w_; |
1118 | struct my_io *w = (struct my_io *)w_; |
997 | ... |
1119 | ... |
998 | } |
1120 | } |
999 | |
1121 | |
1000 | More interesting and less C-conformant ways of casting your callback type |
1122 | More interesting and less C-conformant ways of casting your callback type |
1001 | instead have been omitted. |
1123 | instead have been omitted. |
1002 | |
1124 | |
1003 | Another common scenario is having some data structure with multiple |
1125 | Another common scenario is to use some data structure with multiple |
1004 | watchers: |
1126 | embedded watchers: |
1005 | |
1127 | |
1006 | struct my_biggy |
1128 | struct my_biggy |
1007 | { |
1129 | { |
1008 | int some_data; |
1130 | int some_data; |
1009 | ev_timer t1; |
1131 | ev_timer t1; |
1010 | ev_timer t2; |
1132 | ev_timer t2; |
1011 | } |
1133 | } |
1012 | |
1134 | |
1013 | In this case getting the pointer to C<my_biggy> is a bit more complicated, |
1135 | In this case getting the pointer to C<my_biggy> is a bit more |
1014 | you need to use C<offsetof>: |
1136 | complicated: Either you store the address of your C<my_biggy> struct |
|
|
1137 | in the C<data> member of the watcher (for woozies), or you need to use |
|
|
1138 | some pointer arithmetic using C<offsetof> inside your watchers (for real |
|
|
1139 | programmers): |
1015 | |
1140 | |
1016 | #include <stddef.h> |
1141 | #include <stddef.h> |
1017 | |
1142 | |
1018 | static void |
1143 | static void |
1019 | t1_cb (EV_P_ struct ev_timer *w, int revents) |
1144 | t1_cb (EV_P_ ev_timer *w, int revents) |
1020 | { |
1145 | { |
1021 | struct my_biggy big = (struct my_biggy * |
1146 | struct my_biggy big = (struct my_biggy * |
1022 | (((char *)w) - offsetof (struct my_biggy, t1)); |
1147 | (((char *)w) - offsetof (struct my_biggy, t1)); |
1023 | } |
1148 | } |
1024 | |
1149 | |
1025 | static void |
1150 | static void |
1026 | t2_cb (EV_P_ struct ev_timer *w, int revents) |
1151 | t2_cb (EV_P_ ev_timer *w, int revents) |
1027 | { |
1152 | { |
1028 | struct my_biggy big = (struct my_biggy * |
1153 | struct my_biggy big = (struct my_biggy * |
1029 | (((char *)w) - offsetof (struct my_biggy, t2)); |
1154 | (((char *)w) - offsetof (struct my_biggy, t2)); |
1030 | } |
1155 | } |
1031 | |
1156 | |
1032 | |
1157 | |
1033 | =head1 WATCHER TYPES |
1158 | =head1 WATCHER TYPES |
1034 | |
1159 | |
1035 | This section describes each watcher in detail, but will not repeat |
1160 | This section describes each watcher in detail, but will not repeat |
… | |
… | |
1059 | In general you can register as many read and/or write event watchers per |
1184 | In general you can register as many read and/or write event watchers per |
1060 | fd as you want (as long as you don't confuse yourself). Setting all file |
1185 | fd as you want (as long as you don't confuse yourself). Setting all file |
1061 | descriptors to non-blocking mode is also usually a good idea (but not |
1186 | descriptors to non-blocking mode is also usually a good idea (but not |
1062 | required if you know what you are doing). |
1187 | required if you know what you are doing). |
1063 | |
1188 | |
1064 | If you must do this, then force the use of a known-to-be-good backend |
1189 | If you cannot use non-blocking mode, then force the use of a |
1065 | (at the time of this writing, this includes only C<EVBACKEND_SELECT> and |
1190 | known-to-be-good backend (at the time of this writing, this includes only |
1066 | C<EVBACKEND_POLL>). |
1191 | C<EVBACKEND_SELECT> and C<EVBACKEND_POLL>). |
1067 | |
1192 | |
1068 | Another thing you have to watch out for is that it is quite easy to |
1193 | Another thing you have to watch out for is that it is quite easy to |
1069 | receive "spurious" readiness notifications, that is your callback might |
1194 | receive "spurious" readiness notifications, that is your callback might |
1070 | be called with C<EV_READ> but a subsequent C<read>(2) will actually block |
1195 | be called with C<EV_READ> but a subsequent C<read>(2) will actually block |
1071 | because there is no data. Not only are some backends known to create a |
1196 | because there is no data. Not only are some backends known to create a |
1072 | lot of those (for example Solaris ports), it is very easy to get into |
1197 | lot of those (for example Solaris ports), it is very easy to get into |
1073 | this situation even with a relatively standard program structure. Thus |
1198 | this situation even with a relatively standard program structure. Thus |
1074 | it is best to always use non-blocking I/O: An extra C<read>(2) returning |
1199 | it is best to always use non-blocking I/O: An extra C<read>(2) returning |
1075 | C<EAGAIN> is far preferable to a program hanging until some data arrives. |
1200 | C<EAGAIN> is far preferable to a program hanging until some data arrives. |
1076 | |
1201 | |
1077 | If you cannot run the fd in non-blocking mode (for example you should not |
1202 | If you cannot run the fd in non-blocking mode (for example you should |
1078 | play around with an Xlib connection), then you have to separately re-test |
1203 | not play around with an Xlib connection), then you have to separately |
1079 | whether a file descriptor is really ready with a known-to-be good interface |
1204 | re-test whether a file descriptor is really ready with a known-to-be good |
1080 | such as poll (fortunately in our Xlib example, Xlib already does this on |
1205 | interface such as poll (fortunately in our Xlib example, Xlib already |
1081 | its own, so its quite safe to use). |
1206 | does this on its own, so its quite safe to use). Some people additionally |
|
|
1207 | use C<SIGALRM> and an interval timer, just to be sure you won't block |
|
|
1208 | indefinitely. |
|
|
1209 | |
|
|
1210 | But really, best use non-blocking mode. |
1082 | |
1211 | |
1083 | =head3 The special problem of disappearing file descriptors |
1212 | =head3 The special problem of disappearing file descriptors |
1084 | |
1213 | |
1085 | Some backends (e.g. kqueue, epoll) need to be told about closing a file |
1214 | Some backends (e.g. kqueue, epoll) need to be told about closing a file |
1086 | descriptor (either by calling C<close> explicitly or by any other means, |
1215 | descriptor (either due to calling C<close> explicitly or any other means, |
1087 | such as C<dup>). The reason is that you register interest in some file |
1216 | such as C<dup2>). The reason is that you register interest in some file |
1088 | descriptor, but when it goes away, the operating system will silently drop |
1217 | descriptor, but when it goes away, the operating system will silently drop |
1089 | this interest. If another file descriptor with the same number then is |
1218 | this interest. If another file descriptor with the same number then is |
1090 | registered with libev, there is no efficient way to see that this is, in |
1219 | registered with libev, there is no efficient way to see that this is, in |
1091 | fact, a different file descriptor. |
1220 | fact, a different file descriptor. |
1092 | |
1221 | |
… | |
… | |
1123 | enable C<EVFLAG_FORKCHECK>, or resort to C<EVBACKEND_SELECT> or |
1252 | enable C<EVFLAG_FORKCHECK>, or resort to C<EVBACKEND_SELECT> or |
1124 | C<EVBACKEND_POLL>. |
1253 | C<EVBACKEND_POLL>. |
1125 | |
1254 | |
1126 | =head3 The special problem of SIGPIPE |
1255 | =head3 The special problem of SIGPIPE |
1127 | |
1256 | |
1128 | While not really specific to libev, it is easy to forget about SIGPIPE: |
1257 | While not really specific to libev, it is easy to forget about C<SIGPIPE>: |
1129 | when reading from a pipe whose other end has been closed, your program |
1258 | when writing to a pipe whose other end has been closed, your program gets |
1130 | gets send a SIGPIPE, which, by default, aborts your program. For most |
1259 | sent a SIGPIPE, which, by default, aborts your program. For most programs |
1131 | programs this is sensible behaviour, for daemons, this is usually |
1260 | this is sensible behaviour, for daemons, this is usually undesirable. |
1132 | undesirable. |
|
|
1133 | |
1261 | |
1134 | So when you encounter spurious, unexplained daemon exits, make sure you |
1262 | So when you encounter spurious, unexplained daemon exits, make sure you |
1135 | ignore SIGPIPE (and maybe make sure you log the exit status of your daemon |
1263 | ignore SIGPIPE (and maybe make sure you log the exit status of your daemon |
1136 | somewhere, as that would have given you a big clue). |
1264 | somewhere, as that would have given you a big clue). |
1137 | |
1265 | |
… | |
… | |
1143 | =item ev_io_init (ev_io *, callback, int fd, int events) |
1271 | =item ev_io_init (ev_io *, callback, int fd, int events) |
1144 | |
1272 | |
1145 | =item ev_io_set (ev_io *, int fd, int events) |
1273 | =item ev_io_set (ev_io *, int fd, int events) |
1146 | |
1274 | |
1147 | Configures an C<ev_io> watcher. The C<fd> is the file descriptor to |
1275 | Configures an C<ev_io> watcher. The C<fd> is the file descriptor to |
1148 | receive events for and events is either C<EV_READ>, C<EV_WRITE> or |
1276 | receive events for and C<events> is either C<EV_READ>, C<EV_WRITE> or |
1149 | C<EV_READ | EV_WRITE> to receive the given events. |
1277 | C<EV_READ | EV_WRITE>, to express the desire to receive the given events. |
1150 | |
1278 | |
1151 | =item int fd [read-only] |
1279 | =item int fd [read-only] |
1152 | |
1280 | |
1153 | The file descriptor being watched. |
1281 | The file descriptor being watched. |
1154 | |
1282 | |
… | |
… | |
1162 | |
1290 | |
1163 | Example: Call C<stdin_readable_cb> when STDIN_FILENO has become, well |
1291 | Example: Call C<stdin_readable_cb> when STDIN_FILENO has become, well |
1164 | readable, but only once. Since it is likely line-buffered, you could |
1292 | readable, but only once. Since it is likely line-buffered, you could |
1165 | attempt to read a whole line in the callback. |
1293 | attempt to read a whole line in the callback. |
1166 | |
1294 | |
1167 | static void |
1295 | static void |
1168 | stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents) |
1296 | stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents) |
1169 | { |
1297 | { |
1170 | ev_io_stop (loop, w); |
1298 | ev_io_stop (loop, w); |
1171 | .. read from stdin here (or from w->fd) and haqndle any I/O errors |
1299 | .. read from stdin here (or from w->fd) and handle any I/O errors |
1172 | } |
1300 | } |
1173 | |
1301 | |
1174 | ... |
1302 | ... |
1175 | struct ev_loop *loop = ev_default_init (0); |
1303 | struct ev_loop *loop = ev_default_init (0); |
1176 | struct ev_io stdin_readable; |
1304 | ev_io stdin_readable; |
1177 | ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); |
1305 | ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); |
1178 | ev_io_start (loop, &stdin_readable); |
1306 | ev_io_start (loop, &stdin_readable); |
1179 | ev_loop (loop, 0); |
1307 | ev_loop (loop, 0); |
1180 | |
1308 | |
1181 | |
1309 | |
1182 | =head2 C<ev_timer> - relative and optionally repeating timeouts |
1310 | =head2 C<ev_timer> - relative and optionally repeating timeouts |
1183 | |
1311 | |
1184 | Timer watchers are simple relative timers that generate an event after a |
1312 | Timer watchers are simple relative timers that generate an event after a |
1185 | given time, and optionally repeating in regular intervals after that. |
1313 | given time, and optionally repeating in regular intervals after that. |
1186 | |
1314 | |
1187 | The timers are based on real time, that is, if you register an event that |
1315 | The timers are based on real time, that is, if you register an event that |
1188 | times out after an hour and you reset your system clock to January last |
1316 | times out after an hour and you reset your system clock to January last |
1189 | year, it will still time out after (roughly) and hour. "Roughly" because |
1317 | year, it will still time out after (roughly) one hour. "Roughly" because |
1190 | detecting time jumps is hard, and some inaccuracies are unavoidable (the |
1318 | detecting time jumps is hard, and some inaccuracies are unavoidable (the |
1191 | monotonic clock option helps a lot here). |
1319 | monotonic clock option helps a lot here). |
|
|
1320 | |
|
|
1321 | The callback is guaranteed to be invoked only I<after> its timeout has |
|
|
1322 | passed, but if multiple timers become ready during the same loop iteration |
|
|
1323 | then order of execution is undefined. |
|
|
1324 | |
|
|
1325 | =head3 Be smart about timeouts |
|
|
1326 | |
|
|
1327 | Many real-world problems involve some kind of timeout, usually for error |
|
|
1328 | recovery. A typical example is an HTTP request - if the other side hangs, |
|
|
1329 | you want to raise some error after a while. |
|
|
1330 | |
|
|
1331 | What follows are some ways to handle this problem, from obvious and |
|
|
1332 | inefficient to smart and efficient. |
|
|
1333 | |
|
|
1334 | In the following, a 60 second activity timeout is assumed - a timeout that |
|
|
1335 | gets reset to 60 seconds each time there is activity (e.g. each time some |
|
|
1336 | data or other life sign was received). |
|
|
1337 | |
|
|
1338 | =over 4 |
|
|
1339 | |
|
|
1340 | =item 1. Use a timer and stop, reinitialise and start it on activity. |
|
|
1341 | |
|
|
1342 | This is the most obvious, but not the most simple way: In the beginning, |
|
|
1343 | start the watcher: |
|
|
1344 | |
|
|
1345 | ev_timer_init (timer, callback, 60., 0.); |
|
|
1346 | ev_timer_start (loop, timer); |
|
|
1347 | |
|
|
1348 | Then, each time there is some activity, C<ev_timer_stop> it, initialise it |
|
|
1349 | and start it again: |
|
|
1350 | |
|
|
1351 | ev_timer_stop (loop, timer); |
|
|
1352 | ev_timer_set (timer, 60., 0.); |
|
|
1353 | ev_timer_start (loop, timer); |
|
|
1354 | |
|
|
1355 | This is relatively simple to implement, but means that each time there is |
|
|
1356 | some activity, libev will first have to remove the timer from its internal |
|
|
1357 | data structure and then add it again. Libev tries to be fast, but it's |
|
|
1358 | still not a constant-time operation. |
|
|
1359 | |
|
|
1360 | =item 2. Use a timer and re-start it with C<ev_timer_again> inactivity. |
|
|
1361 | |
|
|
1362 | This is the easiest way, and involves using C<ev_timer_again> instead of |
|
|
1363 | C<ev_timer_start>. |
|
|
1364 | |
|
|
1365 | To implement this, configure an C<ev_timer> with a C<repeat> value |
|
|
1366 | of C<60> and then call C<ev_timer_again> at start and each time you |
|
|
1367 | successfully read or write some data. If you go into an idle state where |
|
|
1368 | you do not expect data to travel on the socket, you can C<ev_timer_stop> |
|
|
1369 | the timer, and C<ev_timer_again> will automatically restart it if need be. |
|
|
1370 | |
|
|
1371 | That means you can ignore both the C<ev_timer_start> function and the |
|
|
1372 | C<after> argument to C<ev_timer_set>, and only ever use the C<repeat> |
|
|
1373 | member and C<ev_timer_again>. |
|
|
1374 | |
|
|
1375 | At start: |
|
|
1376 | |
|
|
1377 | ev_timer_init (timer, callback); |
|
|
1378 | timer->repeat = 60.; |
|
|
1379 | ev_timer_again (loop, timer); |
|
|
1380 | |
|
|
1381 | Each time there is some activity: |
|
|
1382 | |
|
|
1383 | ev_timer_again (loop, timer); |
|
|
1384 | |
|
|
1385 | It is even possible to change the time-out on the fly, regardless of |
|
|
1386 | whether the watcher is active or not: |
|
|
1387 | |
|
|
1388 | timer->repeat = 30.; |
|
|
1389 | ev_timer_again (loop, timer); |
|
|
1390 | |
|
|
1391 | This is slightly more efficient then stopping/starting the timer each time |
|
|
1392 | you want to modify its timeout value, as libev does not have to completely |
|
|
1393 | remove and re-insert the timer from/into its internal data structure. |
|
|
1394 | |
|
|
1395 | It is, however, even simpler than the "obvious" way to do it. |
|
|
1396 | |
|
|
1397 | =item 3. Let the timer time out, but then re-arm it as required. |
|
|
1398 | |
|
|
1399 | This method is more tricky, but usually most efficient: Most timeouts are |
|
|
1400 | relatively long compared to the intervals between other activity - in |
|
|
1401 | our example, within 60 seconds, there are usually many I/O events with |
|
|
1402 | associated activity resets. |
|
|
1403 | |
|
|
1404 | In this case, it would be more efficient to leave the C<ev_timer> alone, |
|
|
1405 | but remember the time of last activity, and check for a real timeout only |
|
|
1406 | within the callback: |
|
|
1407 | |
|
|
1408 | ev_tstamp last_activity; // time of last activity |
|
|
1409 | |
|
|
1410 | static void |
|
|
1411 | callback (EV_P_ ev_timer *w, int revents) |
|
|
1412 | { |
|
|
1413 | ev_tstamp now = ev_now (EV_A); |
|
|
1414 | ev_tstamp timeout = last_activity + 60.; |
|
|
1415 | |
|
|
1416 | // if last_activity + 60. is older than now, we did time out |
|
|
1417 | if (timeout < now) |
|
|
1418 | { |
|
|
1419 | // timeout occured, take action |
|
|
1420 | } |
|
|
1421 | else |
|
|
1422 | { |
|
|
1423 | // callback was invoked, but there was some activity, re-arm |
|
|
1424 | // the watcher to fire in last_activity + 60, which is |
|
|
1425 | // guaranteed to be in the future, so "again" is positive: |
|
|
1426 | w->repeat = timeout - now; |
|
|
1427 | ev_timer_again (EV_A_ w); |
|
|
1428 | } |
|
|
1429 | } |
|
|
1430 | |
|
|
1431 | To summarise the callback: first calculate the real timeout (defined |
|
|
1432 | as "60 seconds after the last activity"), then check if that time has |
|
|
1433 | been reached, which means something I<did>, in fact, time out. Otherwise |
|
|
1434 | the callback was invoked too early (C<timeout> is in the future), so |
|
|
1435 | re-schedule the timer to fire at that future time, to see if maybe we have |
|
|
1436 | a timeout then. |
|
|
1437 | |
|
|
1438 | Note how C<ev_timer_again> is used, taking advantage of the |
|
|
1439 | C<ev_timer_again> optimisation when the timer is already running. |
|
|
1440 | |
|
|
1441 | This scheme causes more callback invocations (about one every 60 seconds |
|
|
1442 | minus half the average time between activity), but virtually no calls to |
|
|
1443 | libev to change the timeout. |
|
|
1444 | |
|
|
1445 | To start the timer, simply initialise the watcher and set C<last_activity> |
|
|
1446 | to the current time (meaning we just have some activity :), then call the |
|
|
1447 | callback, which will "do the right thing" and start the timer: |
|
|
1448 | |
|
|
1449 | ev_timer_init (timer, callback); |
|
|
1450 | last_activity = ev_now (loop); |
|
|
1451 | callback (loop, timer, EV_TIMEOUT); |
|
|
1452 | |
|
|
1453 | And when there is some activity, simply store the current time in |
|
|
1454 | C<last_activity>, no libev calls at all: |
|
|
1455 | |
|
|
1456 | last_actiivty = ev_now (loop); |
|
|
1457 | |
|
|
1458 | This technique is slightly more complex, but in most cases where the |
|
|
1459 | time-out is unlikely to be triggered, much more efficient. |
|
|
1460 | |
|
|
1461 | Changing the timeout is trivial as well (if it isn't hard-coded in the |
|
|
1462 | callback :) - just change the timeout and invoke the callback, which will |
|
|
1463 | fix things for you. |
|
|
1464 | |
|
|
1465 | =item 4. Wee, just use a double-linked list for your timeouts. |
|
|
1466 | |
|
|
1467 | If there is not one request, but many thousands (millions...), all |
|
|
1468 | employing some kind of timeout with the same timeout value, then one can |
|
|
1469 | do even better: |
|
|
1470 | |
|
|
1471 | When starting the timeout, calculate the timeout value and put the timeout |
|
|
1472 | at the I<end> of the list. |
|
|
1473 | |
|
|
1474 | Then use an C<ev_timer> to fire when the timeout at the I<beginning> of |
|
|
1475 | the list is expected to fire (for example, using the technique #3). |
|
|
1476 | |
|
|
1477 | When there is some activity, remove the timer from the list, recalculate |
|
|
1478 | the timeout, append it to the end of the list again, and make sure to |
|
|
1479 | update the C<ev_timer> if it was taken from the beginning of the list. |
|
|
1480 | |
|
|
1481 | This way, one can manage an unlimited number of timeouts in O(1) time for |
|
|
1482 | starting, stopping and updating the timers, at the expense of a major |
|
|
1483 | complication, and having to use a constant timeout. The constant timeout |
|
|
1484 | ensures that the list stays sorted. |
|
|
1485 | |
|
|
1486 | =back |
|
|
1487 | |
|
|
1488 | So which method the best? |
|
|
1489 | |
|
|
1490 | Method #2 is a simple no-brain-required solution that is adequate in most |
|
|
1491 | situations. Method #3 requires a bit more thinking, but handles many cases |
|
|
1492 | better, and isn't very complicated either. In most case, choosing either |
|
|
1493 | one is fine, with #3 being better in typical situations. |
|
|
1494 | |
|
|
1495 | Method #1 is almost always a bad idea, and buys you nothing. Method #4 is |
|
|
1496 | rather complicated, but extremely efficient, something that really pays |
|
|
1497 | off after the first million or so of active timers, i.e. it's usually |
|
|
1498 | overkill :) |
|
|
1499 | |
|
|
1500 | =head3 The special problem of time updates |
|
|
1501 | |
|
|
1502 | Establishing the current time is a costly operation (it usually takes at |
|
|
1503 | least two system calls): EV therefore updates its idea of the current |
|
|
1504 | time only before and after C<ev_loop> collects new events, which causes a |
|
|
1505 | growing difference between C<ev_now ()> and C<ev_time ()> when handling |
|
|
1506 | lots of events in one iteration. |
1192 | |
1507 | |
1193 | The relative timeouts are calculated relative to the C<ev_now ()> |
1508 | The relative timeouts are calculated relative to the C<ev_now ()> |
1194 | time. This is usually the right thing as this timestamp refers to the time |
1509 | time. This is usually the right thing as this timestamp refers to the time |
1195 | of the event triggering whatever timeout you are modifying/starting. If |
1510 | of the event triggering whatever timeout you are modifying/starting. If |
1196 | you suspect event processing to be delayed and you I<need> to base the timeout |
1511 | you suspect event processing to be delayed and you I<need> to base the |
1197 | on the current time, use something like this to adjust for this: |
1512 | timeout on the current time, use something like this to adjust for this: |
1198 | |
1513 | |
1199 | ev_timer_set (&timer, after + ev_now () - ev_time (), 0.); |
1514 | ev_timer_set (&timer, after + ev_now () - ev_time (), 0.); |
1200 | |
1515 | |
1201 | The callback is guaranteed to be invoked only after its timeout has passed, |
1516 | If the event loop is suspended for a long time, you can also force an |
1202 | but if multiple timers become ready during the same loop iteration then |
1517 | update of the time returned by C<ev_now ()> by calling C<ev_now_update |
1203 | order of execution is undefined. |
1518 | ()>. |
1204 | |
1519 | |
1205 | =head3 Watcher-Specific Functions and Data Members |
1520 | =head3 Watcher-Specific Functions and Data Members |
1206 | |
1521 | |
1207 | =over 4 |
1522 | =over 4 |
1208 | |
1523 | |
… | |
… | |
1232 | If the timer is started but non-repeating, stop it (as if it timed out). |
1547 | If the timer is started but non-repeating, stop it (as if it timed out). |
1233 | |
1548 | |
1234 | If the timer is repeating, either start it if necessary (with the |
1549 | If the timer is repeating, either start it if necessary (with the |
1235 | C<repeat> value), or reset the running timer to the C<repeat> value. |
1550 | C<repeat> value), or reset the running timer to the C<repeat> value. |
1236 | |
1551 | |
1237 | This sounds a bit complicated, but here is a useful and typical |
1552 | This sounds a bit complicated, see "Be smart about timeouts", above, for a |
1238 | example: Imagine you have a TCP connection and you want a so-called idle |
1553 | usage example. |
1239 | timeout, that is, you want to be called when there have been, say, 60 |
|
|
1240 | seconds of inactivity on the socket. The easiest way to do this is to |
|
|
1241 | configure an C<ev_timer> with a C<repeat> value of C<60> and then call |
|
|
1242 | C<ev_timer_again> each time you successfully read or write some data. If |
|
|
1243 | you go into an idle state where you do not expect data to travel on the |
|
|
1244 | socket, you can C<ev_timer_stop> the timer, and C<ev_timer_again> will |
|
|
1245 | automatically restart it if need be. |
|
|
1246 | |
|
|
1247 | That means you can ignore the C<after> value and C<ev_timer_start> |
|
|
1248 | altogether and only ever use the C<repeat> value and C<ev_timer_again>: |
|
|
1249 | |
|
|
1250 | ev_timer_init (timer, callback, 0., 5.); |
|
|
1251 | ev_timer_again (loop, timer); |
|
|
1252 | ... |
|
|
1253 | timer->again = 17.; |
|
|
1254 | ev_timer_again (loop, timer); |
|
|
1255 | ... |
|
|
1256 | timer->again = 10.; |
|
|
1257 | ev_timer_again (loop, timer); |
|
|
1258 | |
|
|
1259 | This is more slightly efficient then stopping/starting the timer each time |
|
|
1260 | you want to modify its timeout value. |
|
|
1261 | |
1554 | |
1262 | =item ev_tstamp repeat [read-write] |
1555 | =item ev_tstamp repeat [read-write] |
1263 | |
1556 | |
1264 | The current C<repeat> value. Will be used each time the watcher times out |
1557 | The current C<repeat> value. Will be used each time the watcher times out |
1265 | or C<ev_timer_again> is called and determines the next timeout (if any), |
1558 | or C<ev_timer_again> is called, and determines the next timeout (if any), |
1266 | which is also when any modifications are taken into account. |
1559 | which is also when any modifications are taken into account. |
1267 | |
1560 | |
1268 | =back |
1561 | =back |
1269 | |
1562 | |
1270 | =head3 Examples |
1563 | =head3 Examples |
1271 | |
1564 | |
1272 | Example: Create a timer that fires after 60 seconds. |
1565 | Example: Create a timer that fires after 60 seconds. |
1273 | |
1566 | |
1274 | static void |
1567 | static void |
1275 | one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents) |
1568 | one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents) |
1276 | { |
1569 | { |
1277 | .. one minute over, w is actually stopped right here |
1570 | .. one minute over, w is actually stopped right here |
1278 | } |
1571 | } |
1279 | |
1572 | |
1280 | struct ev_timer mytimer; |
1573 | ev_timer mytimer; |
1281 | ev_timer_init (&mytimer, one_minute_cb, 60., 0.); |
1574 | ev_timer_init (&mytimer, one_minute_cb, 60., 0.); |
1282 | ev_timer_start (loop, &mytimer); |
1575 | ev_timer_start (loop, &mytimer); |
1283 | |
1576 | |
1284 | Example: Create a timeout timer that times out after 10 seconds of |
1577 | Example: Create a timeout timer that times out after 10 seconds of |
1285 | inactivity. |
1578 | inactivity. |
1286 | |
1579 | |
1287 | static void |
1580 | static void |
1288 | timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents) |
1581 | timeout_cb (struct ev_loop *loop, ev_timer *w, int revents) |
1289 | { |
1582 | { |
1290 | .. ten seconds without any activity |
1583 | .. ten seconds without any activity |
1291 | } |
1584 | } |
1292 | |
1585 | |
1293 | struct ev_timer mytimer; |
1586 | ev_timer mytimer; |
1294 | ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ |
1587 | ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ |
1295 | ev_timer_again (&mytimer); /* start timer */ |
1588 | ev_timer_again (&mytimer); /* start timer */ |
1296 | ev_loop (loop, 0); |
1589 | ev_loop (loop, 0); |
1297 | |
1590 | |
1298 | // and in some piece of code that gets executed on any "activity": |
1591 | // and in some piece of code that gets executed on any "activity": |
1299 | // reset the timeout to start ticking again at 10 seconds |
1592 | // reset the timeout to start ticking again at 10 seconds |
1300 | ev_timer_again (&mytimer); |
1593 | ev_timer_again (&mytimer); |
1301 | |
1594 | |
1302 | |
1595 | |
1303 | =head2 C<ev_periodic> - to cron or not to cron? |
1596 | =head2 C<ev_periodic> - to cron or not to cron? |
1304 | |
1597 | |
1305 | Periodic watchers are also timers of a kind, but they are very versatile |
1598 | Periodic watchers are also timers of a kind, but they are very versatile |
… | |
… | |
1314 | to trigger the event (unlike an C<ev_timer>, which would still trigger |
1607 | to trigger the event (unlike an C<ev_timer>, which would still trigger |
1315 | roughly 10 seconds later as it uses a relative timeout). |
1608 | roughly 10 seconds later as it uses a relative timeout). |
1316 | |
1609 | |
1317 | C<ev_periodic>s can also be used to implement vastly more complex timers, |
1610 | C<ev_periodic>s can also be used to implement vastly more complex timers, |
1318 | such as triggering an event on each "midnight, local time", or other |
1611 | such as triggering an event on each "midnight, local time", or other |
1319 | complicated, rules. |
1612 | complicated rules. |
1320 | |
1613 | |
1321 | As with timers, the callback is guaranteed to be invoked only when the |
1614 | As with timers, the callback is guaranteed to be invoked only when the |
1322 | time (C<at>) has passed, but if multiple periodic timers become ready |
1615 | time (C<at>) has passed, but if multiple periodic timers become ready |
1323 | during the same loop iteration then order of execution is undefined. |
1616 | during the same loop iteration, then order of execution is undefined. |
1324 | |
1617 | |
1325 | =head3 Watcher-Specific Functions and Data Members |
1618 | =head3 Watcher-Specific Functions and Data Members |
1326 | |
1619 | |
1327 | =over 4 |
1620 | =over 4 |
1328 | |
1621 | |
1329 | =item ev_periodic_init (ev_periodic *, callback, ev_tstamp at, ev_tstamp interval, reschedule_cb) |
1622 | =item ev_periodic_init (ev_periodic *, callback, ev_tstamp at, ev_tstamp interval, reschedule_cb) |
1330 | |
1623 | |
1331 | =item ev_periodic_set (ev_periodic *, ev_tstamp after, ev_tstamp repeat, reschedule_cb) |
1624 | =item ev_periodic_set (ev_periodic *, ev_tstamp after, ev_tstamp repeat, reschedule_cb) |
1332 | |
1625 | |
1333 | Lots of arguments, lets sort it out... There are basically three modes of |
1626 | Lots of arguments, lets sort it out... There are basically three modes of |
1334 | operation, and we will explain them from simplest to complex: |
1627 | operation, and we will explain them from simplest to most complex: |
1335 | |
1628 | |
1336 | =over 4 |
1629 | =over 4 |
1337 | |
1630 | |
1338 | =item * absolute timer (at = time, interval = reschedule_cb = 0) |
1631 | =item * absolute timer (at = time, interval = reschedule_cb = 0) |
1339 | |
1632 | |
1340 | In this configuration the watcher triggers an event after the wall clock |
1633 | In this configuration the watcher triggers an event after the wall clock |
1341 | time C<at> has passed and doesn't repeat. It will not adjust when a time |
1634 | time C<at> has passed. It will not repeat and will not adjust when a time |
1342 | jump occurs, that is, if it is to be run at January 1st 2011 then it will |
1635 | jump occurs, that is, if it is to be run at January 1st 2011 then it will |
1343 | run when the system time reaches or surpasses this time. |
1636 | only run when the system clock reaches or surpasses this time. |
1344 | |
1637 | |
1345 | =item * repeating interval timer (at = offset, interval > 0, reschedule_cb = 0) |
1638 | =item * repeating interval timer (at = offset, interval > 0, reschedule_cb = 0) |
1346 | |
1639 | |
1347 | In this mode the watcher will always be scheduled to time out at the next |
1640 | In this mode the watcher will always be scheduled to time out at the next |
1348 | C<at + N * interval> time (for some integer N, which can also be negative) |
1641 | C<at + N * interval> time (for some integer N, which can also be negative) |
1349 | and then repeat, regardless of any time jumps. |
1642 | and then repeat, regardless of any time jumps. |
1350 | |
1643 | |
1351 | This can be used to create timers that do not drift with respect to system |
1644 | This can be used to create timers that do not drift with respect to the |
1352 | time, for example, here is a C<ev_periodic> that triggers each hour, on |
1645 | system clock, for example, here is a C<ev_periodic> that triggers each |
1353 | the hour: |
1646 | hour, on the hour: |
1354 | |
1647 | |
1355 | ev_periodic_set (&periodic, 0., 3600., 0); |
1648 | ev_periodic_set (&periodic, 0., 3600., 0); |
1356 | |
1649 | |
1357 | This doesn't mean there will always be 3600 seconds in between triggers, |
1650 | This doesn't mean there will always be 3600 seconds in between triggers, |
1358 | but only that the callback will be called when the system time shows a |
1651 | but only that the callback will be called when the system time shows a |
… | |
… | |
1384 | |
1677 | |
1385 | If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop |
1678 | If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop |
1386 | it afterwards (e.g. by starting an C<ev_prepare> watcher, which is the |
1679 | it afterwards (e.g. by starting an C<ev_prepare> watcher, which is the |
1387 | only event loop modification you are allowed to do). |
1680 | only event loop modification you are allowed to do). |
1388 | |
1681 | |
1389 | The callback prototype is C<ev_tstamp (*reschedule_cb)(struct ev_periodic |
1682 | The callback prototype is C<ev_tstamp (*reschedule_cb)(ev_periodic |
1390 | *w, ev_tstamp now)>, e.g.: |
1683 | *w, ev_tstamp now)>, e.g.: |
1391 | |
1684 | |
|
|
1685 | static ev_tstamp |
1392 | static ev_tstamp my_rescheduler (struct ev_periodic *w, ev_tstamp now) |
1686 | my_rescheduler (ev_periodic *w, ev_tstamp now) |
1393 | { |
1687 | { |
1394 | return now + 60.; |
1688 | return now + 60.; |
1395 | } |
1689 | } |
1396 | |
1690 | |
1397 | It must return the next time to trigger, based on the passed time value |
1691 | It must return the next time to trigger, based on the passed time value |
… | |
… | |
1434 | |
1728 | |
1435 | The current interval value. Can be modified any time, but changes only |
1729 | The current interval value. Can be modified any time, but changes only |
1436 | take effect when the periodic timer fires or C<ev_periodic_again> is being |
1730 | take effect when the periodic timer fires or C<ev_periodic_again> is being |
1437 | called. |
1731 | called. |
1438 | |
1732 | |
1439 | =item ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now) [read-write] |
1733 | =item ev_tstamp (*reschedule_cb)(ev_periodic *w, ev_tstamp now) [read-write] |
1440 | |
1734 | |
1441 | The current reschedule callback, or C<0>, if this functionality is |
1735 | The current reschedule callback, or C<0>, if this functionality is |
1442 | switched off. Can be changed any time, but changes only take effect when |
1736 | switched off. Can be changed any time, but changes only take effect when |
1443 | the periodic timer fires or C<ev_periodic_again> is being called. |
1737 | the periodic timer fires or C<ev_periodic_again> is being called. |
1444 | |
1738 | |
1445 | =back |
1739 | =back |
1446 | |
1740 | |
1447 | =head3 Examples |
1741 | =head3 Examples |
1448 | |
1742 | |
1449 | Example: Call a callback every hour, or, more precisely, whenever the |
1743 | Example: Call a callback every hour, or, more precisely, whenever the |
1450 | system clock is divisible by 3600. The callback invocation times have |
1744 | system time is divisible by 3600. The callback invocation times have |
1451 | potentially a lot of jitter, but good long-term stability. |
1745 | potentially a lot of jitter, but good long-term stability. |
1452 | |
1746 | |
1453 | static void |
1747 | static void |
1454 | clock_cb (struct ev_loop *loop, struct ev_io *w, int revents) |
1748 | clock_cb (struct ev_loop *loop, ev_io *w, int revents) |
1455 | { |
1749 | { |
1456 | ... its now a full hour (UTC, or TAI or whatever your clock follows) |
1750 | ... its now a full hour (UTC, or TAI or whatever your clock follows) |
1457 | } |
1751 | } |
1458 | |
1752 | |
1459 | struct ev_periodic hourly_tick; |
1753 | ev_periodic hourly_tick; |
1460 | ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); |
1754 | ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); |
1461 | ev_periodic_start (loop, &hourly_tick); |
1755 | ev_periodic_start (loop, &hourly_tick); |
1462 | |
1756 | |
1463 | Example: The same as above, but use a reschedule callback to do it: |
1757 | Example: The same as above, but use a reschedule callback to do it: |
1464 | |
1758 | |
1465 | #include <math.h> |
1759 | #include <math.h> |
1466 | |
1760 | |
1467 | static ev_tstamp |
1761 | static ev_tstamp |
1468 | my_scheduler_cb (struct ev_periodic *w, ev_tstamp now) |
1762 | my_scheduler_cb (ev_periodic *w, ev_tstamp now) |
1469 | { |
1763 | { |
1470 | return fmod (now, 3600.) + 3600.; |
1764 | return now + (3600. - fmod (now, 3600.)); |
1471 | } |
1765 | } |
1472 | |
1766 | |
1473 | ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb); |
1767 | ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb); |
1474 | |
1768 | |
1475 | Example: Call a callback every hour, starting now: |
1769 | Example: Call a callback every hour, starting now: |
1476 | |
1770 | |
1477 | struct ev_periodic hourly_tick; |
1771 | ev_periodic hourly_tick; |
1478 | ev_periodic_init (&hourly_tick, clock_cb, |
1772 | ev_periodic_init (&hourly_tick, clock_cb, |
1479 | fmod (ev_now (loop), 3600.), 3600., 0); |
1773 | fmod (ev_now (loop), 3600.), 3600., 0); |
1480 | ev_periodic_start (loop, &hourly_tick); |
1774 | ev_periodic_start (loop, &hourly_tick); |
1481 | |
1775 | |
1482 | |
1776 | |
1483 | =head2 C<ev_signal> - signal me when a signal gets signalled! |
1777 | =head2 C<ev_signal> - signal me when a signal gets signalled! |
1484 | |
1778 | |
1485 | Signal watchers will trigger an event when the process receives a specific |
1779 | Signal watchers will trigger an event when the process receives a specific |
1486 | signal one or more times. Even though signals are very asynchronous, libev |
1780 | signal one or more times. Even though signals are very asynchronous, libev |
1487 | will try it's best to deliver signals synchronously, i.e. as part of the |
1781 | will try it's best to deliver signals synchronously, i.e. as part of the |
1488 | normal event processing, like any other event. |
1782 | normal event processing, like any other event. |
1489 | |
1783 | |
|
|
1784 | If you want signals asynchronously, just use C<sigaction> as you would |
|
|
1785 | do without libev and forget about sharing the signal. You can even use |
|
|
1786 | C<ev_async> from a signal handler to synchronously wake up an event loop. |
|
|
1787 | |
1490 | You can configure as many watchers as you like per signal. Only when the |
1788 | You can configure as many watchers as you like per signal. Only when the |
1491 | first watcher gets started will libev actually register a signal watcher |
1789 | first watcher gets started will libev actually register a signal handler |
1492 | with the kernel (thus it coexists with your own signal handlers as long |
1790 | with the kernel (thus it coexists with your own signal handlers as long as |
1493 | as you don't register any with libev). Similarly, when the last signal |
1791 | you don't register any with libev for the same signal). Similarly, when |
1494 | watcher for a signal is stopped libev will reset the signal handler to |
1792 | the last signal watcher for a signal is stopped, libev will reset the |
1495 | SIG_DFL (regardless of what it was set to before). |
1793 | signal handler to SIG_DFL (regardless of what it was set to before). |
1496 | |
1794 | |
1497 | If possible and supported, libev will install its handlers with |
1795 | If possible and supported, libev will install its handlers with |
1498 | C<SA_RESTART> behaviour enabled, so system calls should not be unduly |
1796 | C<SA_RESTART> behaviour enabled, so system calls should not be unduly |
1499 | interrupted. If you have a problem with system calls getting interrupted by |
1797 | interrupted. If you have a problem with system calls getting interrupted by |
1500 | signals you can block all signals in an C<ev_check> watcher and unblock |
1798 | signals you can block all signals in an C<ev_check> watcher and unblock |
… | |
… | |
1517 | |
1815 | |
1518 | =back |
1816 | =back |
1519 | |
1817 | |
1520 | =head3 Examples |
1818 | =head3 Examples |
1521 | |
1819 | |
1522 | Example: Try to exit cleanly on SIGINT and SIGTERM. |
1820 | Example: Try to exit cleanly on SIGINT. |
1523 | |
1821 | |
1524 | static void |
1822 | static void |
1525 | sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents) |
1823 | sigint_cb (struct ev_loop *loop, ev_signal *w, int revents) |
1526 | { |
1824 | { |
1527 | ev_unloop (loop, EVUNLOOP_ALL); |
1825 | ev_unloop (loop, EVUNLOOP_ALL); |
1528 | } |
1826 | } |
1529 | |
1827 | |
1530 | struct ev_signal signal_watcher; |
1828 | ev_signal signal_watcher; |
1531 | ev_signal_init (&signal_watcher, sigint_cb, SIGINT); |
1829 | ev_signal_init (&signal_watcher, sigint_cb, SIGINT); |
1532 | ev_signal_start (loop, &sigint_cb); |
1830 | ev_signal_start (loop, &signal_watcher); |
1533 | |
1831 | |
1534 | |
1832 | |
1535 | =head2 C<ev_child> - watch out for process status changes |
1833 | =head2 C<ev_child> - watch out for process status changes |
1536 | |
1834 | |
1537 | Child watchers trigger when your process receives a SIGCHLD in response to |
1835 | Child watchers trigger when your process receives a SIGCHLD in response to |
1538 | some child status changes (most typically when a child of yours dies). It |
1836 | some child status changes (most typically when a child of yours dies or |
1539 | is permissible to install a child watcher I<after> the child has been |
1837 | exits). It is permissible to install a child watcher I<after> the child |
1540 | forked (which implies it might have already exited), as long as the event |
1838 | has been forked (which implies it might have already exited), as long |
1541 | loop isn't entered (or is continued from a watcher). |
1839 | as the event loop isn't entered (or is continued from a watcher), i.e., |
|
|
1840 | forking and then immediately registering a watcher for the child is fine, |
|
|
1841 | but forking and registering a watcher a few event loop iterations later is |
|
|
1842 | not. |
1542 | |
1843 | |
1543 | Only the default event loop is capable of handling signals, and therefore |
1844 | Only the default event loop is capable of handling signals, and therefore |
1544 | you can only register child watchers in the default event loop. |
1845 | you can only register child watchers in the default event loop. |
1545 | |
1846 | |
1546 | =head3 Process Interaction |
1847 | =head3 Process Interaction |
… | |
… | |
1559 | handler, you can override it easily by installing your own handler for |
1860 | handler, you can override it easily by installing your own handler for |
1560 | C<SIGCHLD> after initialising the default loop, and making sure the |
1861 | C<SIGCHLD> after initialising the default loop, and making sure the |
1561 | default loop never gets destroyed. You are encouraged, however, to use an |
1862 | default loop never gets destroyed. You are encouraged, however, to use an |
1562 | event-based approach to child reaping and thus use libev's support for |
1863 | event-based approach to child reaping and thus use libev's support for |
1563 | that, so other libev users can use C<ev_child> watchers freely. |
1864 | that, so other libev users can use C<ev_child> watchers freely. |
|
|
1865 | |
|
|
1866 | =head3 Stopping the Child Watcher |
|
|
1867 | |
|
|
1868 | Currently, the child watcher never gets stopped, even when the |
|
|
1869 | child terminates, so normally one needs to stop the watcher in the |
|
|
1870 | callback. Future versions of libev might stop the watcher automatically |
|
|
1871 | when a child exit is detected. |
1564 | |
1872 | |
1565 | =head3 Watcher-Specific Functions and Data Members |
1873 | =head3 Watcher-Specific Functions and Data Members |
1566 | |
1874 | |
1567 | =over 4 |
1875 | =over 4 |
1568 | |
1876 | |
… | |
… | |
1597 | =head3 Examples |
1905 | =head3 Examples |
1598 | |
1906 | |
1599 | Example: C<fork()> a new process and install a child handler to wait for |
1907 | Example: C<fork()> a new process and install a child handler to wait for |
1600 | its completion. |
1908 | its completion. |
1601 | |
1909 | |
1602 | ev_child cw; |
1910 | ev_child cw; |
1603 | |
1911 | |
1604 | static void |
1912 | static void |
1605 | child_cb (EV_P_ struct ev_child *w, int revents) |
1913 | child_cb (EV_P_ ev_child *w, int revents) |
1606 | { |
1914 | { |
1607 | ev_child_stop (EV_A_ w); |
1915 | ev_child_stop (EV_A_ w); |
1608 | printf ("process %d exited with status %x\n", w->rpid, w->rstatus); |
1916 | printf ("process %d exited with status %x\n", w->rpid, w->rstatus); |
1609 | } |
1917 | } |
1610 | |
1918 | |
1611 | pid_t pid = fork (); |
1919 | pid_t pid = fork (); |
1612 | |
1920 | |
1613 | if (pid < 0) |
1921 | if (pid < 0) |
1614 | // error |
1922 | // error |
1615 | else if (pid == 0) |
1923 | else if (pid == 0) |
1616 | { |
1924 | { |
1617 | // the forked child executes here |
1925 | // the forked child executes here |
1618 | exit (1); |
1926 | exit (1); |
1619 | } |
1927 | } |
1620 | else |
1928 | else |
1621 | { |
1929 | { |
1622 | ev_child_init (&cw, child_cb, pid, 0); |
1930 | ev_child_init (&cw, child_cb, pid, 0); |
1623 | ev_child_start (EV_DEFAULT_ &cw); |
1931 | ev_child_start (EV_DEFAULT_ &cw); |
1624 | } |
1932 | } |
1625 | |
1933 | |
1626 | |
1934 | |
1627 | =head2 C<ev_stat> - did the file attributes just change? |
1935 | =head2 C<ev_stat> - did the file attributes just change? |
1628 | |
1936 | |
1629 | This watches a file system path for attribute changes. That is, it calls |
1937 | This watches a file system path for attribute changes. That is, it calls |
1630 | C<stat> regularly (or when the OS says it changed) and sees if it changed |
1938 | C<stat> on that path in regular intervals (or when the OS says it changed) |
1631 | compared to the last time, invoking the callback if it did. |
1939 | and sees if it changed compared to the last time, invoking the callback if |
|
|
1940 | it did. |
1632 | |
1941 | |
1633 | The path does not need to exist: changing from "path exists" to "path does |
1942 | The path does not need to exist: changing from "path exists" to "path does |
1634 | not exist" is a status change like any other. The condition "path does |
1943 | not exist" is a status change like any other. The condition "path does not |
1635 | not exist" is signified by the C<st_nlink> field being zero (which is |
1944 | exist" (or more correctly "path cannot be stat'ed") is signified by the |
1636 | otherwise always forced to be at least one) and all the other fields of |
1945 | C<st_nlink> field being zero (which is otherwise always forced to be at |
1637 | the stat buffer having unspecified contents. |
1946 | least one) and all the other fields of the stat buffer having unspecified |
|
|
1947 | contents. |
1638 | |
1948 | |
1639 | The path I<should> be absolute and I<must not> end in a slash. If it is |
1949 | The path I<must not> end in a slash or contain special components such as |
|
|
1950 | C<.> or C<..>. The path I<should> be absolute: If it is relative and |
1640 | relative and your working directory changes, the behaviour is undefined. |
1951 | your working directory changes, then the behaviour is undefined. |
1641 | |
1952 | |
1642 | Since there is no standard to do this, the portable implementation simply |
1953 | Since there is no portable change notification interface available, the |
1643 | calls C<stat (2)> regularly on the path to see if it changed somehow. You |
1954 | portable implementation simply calls C<stat(2)> regularly on the path |
1644 | can specify a recommended polling interval for this case. If you specify |
1955 | to see if it changed somehow. You can specify a recommended polling |
1645 | a polling interval of C<0> (highly recommended!) then a I<suitable, |
1956 | interval for this case. If you specify a polling interval of C<0> (highly |
1646 | unspecified default> value will be used (which you can expect to be around |
1957 | recommended!) then a I<suitable, unspecified default> value will be used |
1647 | five seconds, although this might change dynamically). Libev will also |
1958 | (which you can expect to be around five seconds, although this might |
1648 | impose a minimum interval which is currently around C<0.1>, but thats |
1959 | change dynamically). Libev will also impose a minimum interval which is |
1649 | usually overkill. |
1960 | currently around C<0.1>, but that's usually overkill. |
1650 | |
1961 | |
1651 | This watcher type is not meant for massive numbers of stat watchers, |
1962 | This watcher type is not meant for massive numbers of stat watchers, |
1652 | as even with OS-supported change notifications, this can be |
1963 | as even with OS-supported change notifications, this can be |
1653 | resource-intensive. |
1964 | resource-intensive. |
1654 | |
1965 | |
1655 | At the time of this writing, only the Linux inotify interface is |
1966 | At the time of this writing, the only OS-specific interface implemented |
1656 | implemented (implementing kqueue support is left as an exercise for the |
1967 | is the Linux inotify interface (implementing kqueue support is left as an |
1657 | reader, note, however, that the author sees no way of implementing ev_stat |
1968 | exercise for the reader. Note, however, that the author sees no way of |
1658 | semantics with kqueue). Inotify will be used to give hints only and should |
1969 | implementing C<ev_stat> semantics with kqueue, except as a hint). |
1659 | not change the semantics of C<ev_stat> watchers, which means that libev |
|
|
1660 | sometimes needs to fall back to regular polling again even with inotify, |
|
|
1661 | but changes are usually detected immediately, and if the file exists there |
|
|
1662 | will be no polling. |
|
|
1663 | |
1970 | |
1664 | =head3 ABI Issues (Largefile Support) |
1971 | =head3 ABI Issues (Largefile Support) |
1665 | |
1972 | |
1666 | Libev by default (unless the user overrides this) uses the default |
1973 | Libev by default (unless the user overrides this) uses the default |
1667 | compilation environment, which means that on systems with optionally |
1974 | compilation environment, which means that on systems with large file |
1668 | disabled large file support, you get the 32 bit version of the stat |
1975 | support disabled by default, you get the 32 bit version of the stat |
1669 | structure. When using the library from programs that change the ABI to |
1976 | structure. When using the library from programs that change the ABI to |
1670 | use 64 bit file offsets the programs will fail. In that case you have to |
1977 | use 64 bit file offsets the programs will fail. In that case you have to |
1671 | compile libev with the same flags to get binary compatibility. This is |
1978 | compile libev with the same flags to get binary compatibility. This is |
1672 | obviously the case with any flags that change the ABI, but the problem is |
1979 | obviously the case with any flags that change the ABI, but the problem is |
1673 | most noticeably with ev_stat and large file support. |
1980 | most noticeably displayed with ev_stat and large file support. |
1674 | |
1981 | |
1675 | =head3 Inotify |
1982 | The solution for this is to lobby your distribution maker to make large |
|
|
1983 | file interfaces available by default (as e.g. FreeBSD does) and not |
|
|
1984 | optional. Libev cannot simply switch on large file support because it has |
|
|
1985 | to exchange stat structures with application programs compiled using the |
|
|
1986 | default compilation environment. |
1676 | |
1987 | |
|
|
1988 | =head3 Inotify and Kqueue |
|
|
1989 | |
1677 | When C<inotify (7)> support has been compiled into libev (generally only |
1990 | When C<inotify (7)> support has been compiled into libev and present at |
1678 | available on Linux) and present at runtime, it will be used to speed up |
1991 | runtime, it will be used to speed up change detection where possible. The |
1679 | change detection where possible. The inotify descriptor will be created lazily |
1992 | inotify descriptor will be created lazily when the first C<ev_stat> |
1680 | when the first C<ev_stat> watcher is being started. |
1993 | watcher is being started. |
1681 | |
1994 | |
1682 | Inotify presence does not change the semantics of C<ev_stat> watchers |
1995 | Inotify presence does not change the semantics of C<ev_stat> watchers |
1683 | except that changes might be detected earlier, and in some cases, to avoid |
1996 | except that changes might be detected earlier, and in some cases, to avoid |
1684 | making regular C<stat> calls. Even in the presence of inotify support |
1997 | making regular C<stat> calls. Even in the presence of inotify support |
1685 | there are many cases where libev has to resort to regular C<stat> polling. |
1998 | there are many cases where libev has to resort to regular C<stat> polling, |
|
|
1999 | but as long as kernel 2.6.25 or newer is used (2.6.24 and older have too |
|
|
2000 | many bugs), the path exists (i.e. stat succeeds), and the path resides on |
|
|
2001 | a local filesystem (libev currently assumes only ext2/3, jfs, reiserfs and |
|
|
2002 | xfs are fully working) libev usually gets away without polling. |
1686 | |
2003 | |
1687 | (There is no support for kqueue, as apparently it cannot be used to |
2004 | There is no support for kqueue, as apparently it cannot be used to |
1688 | implement this functionality, due to the requirement of having a file |
2005 | implement this functionality, due to the requirement of having a file |
1689 | descriptor open on the object at all times). |
2006 | descriptor open on the object at all times, and detecting renames, unlinks |
|
|
2007 | etc. is difficult. |
|
|
2008 | |
|
|
2009 | =head3 C<stat ()> is a synchronous operation |
|
|
2010 | |
|
|
2011 | Libev doesn't normally do any kind of I/O itself, and so is not blocking |
|
|
2012 | the process. The exception are C<ev_stat> watchers - those call C<stat |
|
|
2013 | ()>, which is a synchronous operation. |
|
|
2014 | |
|
|
2015 | For local paths, this usually doesn't matter: unless the system is very |
|
|
2016 | busy or the intervals between stat's are large, a stat call will be fast, |
|
|
2017 | as the path data is usually in memory already (except when starting the |
|
|
2018 | watcher). |
|
|
2019 | |
|
|
2020 | For networked file systems, calling C<stat ()> can block an indefinite |
|
|
2021 | time due to network issues, and even under good conditions, a stat call |
|
|
2022 | often takes multiple milliseconds. |
|
|
2023 | |
|
|
2024 | Therefore, it is best to avoid using C<ev_stat> watchers on networked |
|
|
2025 | paths, although this is fully supported by libev. |
1690 | |
2026 | |
1691 | =head3 The special problem of stat time resolution |
2027 | =head3 The special problem of stat time resolution |
1692 | |
2028 | |
1693 | The C<stat ()> system call only supports full-second resolution portably, and |
2029 | The C<stat ()> system call only supports full-second resolution portably, |
1694 | even on systems where the resolution is higher, many file systems still |
2030 | and even on systems where the resolution is higher, most file systems |
1695 | only support whole seconds. |
2031 | still only support whole seconds. |
1696 | |
2032 | |
1697 | That means that, if the time is the only thing that changes, you can |
2033 | That means that, if the time is the only thing that changes, you can |
1698 | easily miss updates: on the first update, C<ev_stat> detects a change and |
2034 | easily miss updates: on the first update, C<ev_stat> detects a change and |
1699 | calls your callback, which does something. When there is another update |
2035 | calls your callback, which does something. When there is another update |
1700 | within the same second, C<ev_stat> will be unable to detect it as the stat |
2036 | within the same second, C<ev_stat> will be unable to detect unless the |
1701 | data does not change. |
2037 | stat data does change in other ways (e.g. file size). |
1702 | |
2038 | |
1703 | The solution to this is to delay acting on a change for slightly more |
2039 | The solution to this is to delay acting on a change for slightly more |
1704 | than a second (or till slightly after the next full second boundary), using |
2040 | than a second (or till slightly after the next full second boundary), using |
1705 | a roughly one-second-delay C<ev_timer> (e.g. C<ev_timer_set (w, 0., 1.02); |
2041 | a roughly one-second-delay C<ev_timer> (e.g. C<ev_timer_set (w, 0., 1.02); |
1706 | ev_timer_again (loop, w)>). |
2042 | ev_timer_again (loop, w)>). |
… | |
… | |
1726 | C<path>. The C<interval> is a hint on how quickly a change is expected to |
2062 | C<path>. The C<interval> is a hint on how quickly a change is expected to |
1727 | be detected and should normally be specified as C<0> to let libev choose |
2063 | be detected and should normally be specified as C<0> to let libev choose |
1728 | a suitable value. The memory pointed to by C<path> must point to the same |
2064 | a suitable value. The memory pointed to by C<path> must point to the same |
1729 | path for as long as the watcher is active. |
2065 | path for as long as the watcher is active. |
1730 | |
2066 | |
1731 | The callback will receive C<EV_STAT> when a change was detected, relative |
2067 | The callback will receive an C<EV_STAT> event when a change was detected, |
1732 | to the attributes at the time the watcher was started (or the last change |
2068 | relative to the attributes at the time the watcher was started (or the |
1733 | was detected). |
2069 | last change was detected). |
1734 | |
2070 | |
1735 | =item ev_stat_stat (loop, ev_stat *) |
2071 | =item ev_stat_stat (loop, ev_stat *) |
1736 | |
2072 | |
1737 | Updates the stat buffer immediately with new values. If you change the |
2073 | Updates the stat buffer immediately with new values. If you change the |
1738 | watched path in your callback, you could call this function to avoid |
2074 | watched path in your callback, you could call this function to avoid |
… | |
… | |
1767 | |
2103 | |
1768 | =head3 Examples |
2104 | =head3 Examples |
1769 | |
2105 | |
1770 | Example: Watch C</etc/passwd> for attribute changes. |
2106 | Example: Watch C</etc/passwd> for attribute changes. |
1771 | |
2107 | |
1772 | static void |
2108 | static void |
1773 | passwd_cb (struct ev_loop *loop, ev_stat *w, int revents) |
2109 | passwd_cb (struct ev_loop *loop, ev_stat *w, int revents) |
1774 | { |
2110 | { |
1775 | /* /etc/passwd changed in some way */ |
2111 | /* /etc/passwd changed in some way */ |
1776 | if (w->attr.st_nlink) |
2112 | if (w->attr.st_nlink) |
1777 | { |
2113 | { |
1778 | printf ("passwd current size %ld\n", (long)w->attr.st_size); |
2114 | printf ("passwd current size %ld\n", (long)w->attr.st_size); |
1779 | printf ("passwd current atime %ld\n", (long)w->attr.st_mtime); |
2115 | printf ("passwd current atime %ld\n", (long)w->attr.st_mtime); |
1780 | printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime); |
2116 | printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime); |
1781 | } |
2117 | } |
1782 | else |
2118 | else |
1783 | /* you shalt not abuse printf for puts */ |
2119 | /* you shalt not abuse printf for puts */ |
1784 | puts ("wow, /etc/passwd is not there, expect problems. " |
2120 | puts ("wow, /etc/passwd is not there, expect problems. " |
1785 | "if this is windows, they already arrived\n"); |
2121 | "if this is windows, they already arrived\n"); |
1786 | } |
2122 | } |
1787 | |
2123 | |
1788 | ... |
2124 | ... |
1789 | ev_stat passwd; |
2125 | ev_stat passwd; |
1790 | |
2126 | |
1791 | ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.); |
2127 | ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.); |
1792 | ev_stat_start (loop, &passwd); |
2128 | ev_stat_start (loop, &passwd); |
1793 | |
2129 | |
1794 | Example: Like above, but additionally use a one-second delay so we do not |
2130 | Example: Like above, but additionally use a one-second delay so we do not |
1795 | miss updates (however, frequent updates will delay processing, too, so |
2131 | miss updates (however, frequent updates will delay processing, too, so |
1796 | one might do the work both on C<ev_stat> callback invocation I<and> on |
2132 | one might do the work both on C<ev_stat> callback invocation I<and> on |
1797 | C<ev_timer> callback invocation). |
2133 | C<ev_timer> callback invocation). |
1798 | |
2134 | |
1799 | static ev_stat passwd; |
2135 | static ev_stat passwd; |
1800 | static ev_timer timer; |
2136 | static ev_timer timer; |
1801 | |
2137 | |
1802 | static void |
2138 | static void |
1803 | timer_cb (EV_P_ ev_timer *w, int revents) |
2139 | timer_cb (EV_P_ ev_timer *w, int revents) |
1804 | { |
2140 | { |
1805 | ev_timer_stop (EV_A_ w); |
2141 | ev_timer_stop (EV_A_ w); |
1806 | |
2142 | |
1807 | /* now it's one second after the most recent passwd change */ |
2143 | /* now it's one second after the most recent passwd change */ |
1808 | } |
2144 | } |
1809 | |
2145 | |
1810 | static void |
2146 | static void |
1811 | stat_cb (EV_P_ ev_stat *w, int revents) |
2147 | stat_cb (EV_P_ ev_stat *w, int revents) |
1812 | { |
2148 | { |
1813 | /* reset the one-second timer */ |
2149 | /* reset the one-second timer */ |
1814 | ev_timer_again (EV_A_ &timer); |
2150 | ev_timer_again (EV_A_ &timer); |
1815 | } |
2151 | } |
1816 | |
2152 | |
1817 | ... |
2153 | ... |
1818 | ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.); |
2154 | ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.); |
1819 | ev_stat_start (loop, &passwd); |
2155 | ev_stat_start (loop, &passwd); |
1820 | ev_timer_init (&timer, timer_cb, 0., 1.02); |
2156 | ev_timer_init (&timer, timer_cb, 0., 1.02); |
1821 | |
2157 | |
1822 | |
2158 | |
1823 | =head2 C<ev_idle> - when you've got nothing better to do... |
2159 | =head2 C<ev_idle> - when you've got nothing better to do... |
1824 | |
2160 | |
1825 | Idle watchers trigger events when no other events of the same or higher |
2161 | Idle watchers trigger events when no other events of the same or higher |
1826 | priority are pending (prepare, check and other idle watchers do not |
2162 | priority are pending (prepare, check and other idle watchers do not count |
1827 | count). |
2163 | as receiving "events"). |
1828 | |
2164 | |
1829 | That is, as long as your process is busy handling sockets or timeouts |
2165 | That is, as long as your process is busy handling sockets or timeouts |
1830 | (or even signals, imagine) of the same or higher priority it will not be |
2166 | (or even signals, imagine) of the same or higher priority it will not be |
1831 | triggered. But when your process is idle (or only lower-priority watchers |
2167 | triggered. But when your process is idle (or only lower-priority watchers |
1832 | are pending), the idle watchers are being called once per event loop |
2168 | are pending), the idle watchers are being called once per event loop |
… | |
… | |
1856 | =head3 Examples |
2192 | =head3 Examples |
1857 | |
2193 | |
1858 | Example: Dynamically allocate an C<ev_idle> watcher, start it, and in the |
2194 | Example: Dynamically allocate an C<ev_idle> watcher, start it, and in the |
1859 | callback, free it. Also, use no error checking, as usual. |
2195 | callback, free it. Also, use no error checking, as usual. |
1860 | |
2196 | |
1861 | static void |
2197 | static void |
1862 | idle_cb (struct ev_loop *loop, struct ev_idle *w, int revents) |
2198 | idle_cb (struct ev_loop *loop, ev_idle *w, int revents) |
1863 | { |
2199 | { |
1864 | free (w); |
2200 | free (w); |
1865 | // now do something you wanted to do when the program has |
2201 | // now do something you wanted to do when the program has |
1866 | // no longer anything immediate to do. |
2202 | // no longer anything immediate to do. |
1867 | } |
2203 | } |
1868 | |
2204 | |
1869 | struct ev_idle *idle_watcher = malloc (sizeof (struct ev_idle)); |
2205 | ev_idle *idle_watcher = malloc (sizeof (ev_idle)); |
1870 | ev_idle_init (idle_watcher, idle_cb); |
2206 | ev_idle_init (idle_watcher, idle_cb); |
1871 | ev_idle_start (loop, idle_cb); |
2207 | ev_idle_start (loop, idle_cb); |
1872 | |
2208 | |
1873 | |
2209 | |
1874 | =head2 C<ev_prepare> and C<ev_check> - customise your event loop! |
2210 | =head2 C<ev_prepare> and C<ev_check> - customise your event loop! |
1875 | |
2211 | |
1876 | Prepare and check watchers are usually (but not always) used in tandem: |
2212 | Prepare and check watchers are usually (but not always) used in pairs: |
1877 | prepare watchers get invoked before the process blocks and check watchers |
2213 | prepare watchers get invoked before the process blocks and check watchers |
1878 | afterwards. |
2214 | afterwards. |
1879 | |
2215 | |
1880 | You I<must not> call C<ev_loop> or similar functions that enter |
2216 | You I<must not> call C<ev_loop> or similar functions that enter |
1881 | the current event loop from either C<ev_prepare> or C<ev_check> |
2217 | the current event loop from either C<ev_prepare> or C<ev_check> |
… | |
… | |
1884 | those watchers, i.e. the sequence will always be C<ev_prepare>, blocking, |
2220 | those watchers, i.e. the sequence will always be C<ev_prepare>, blocking, |
1885 | C<ev_check> so if you have one watcher of each kind they will always be |
2221 | C<ev_check> so if you have one watcher of each kind they will always be |
1886 | called in pairs bracketing the blocking call. |
2222 | called in pairs bracketing the blocking call. |
1887 | |
2223 | |
1888 | Their main purpose is to integrate other event mechanisms into libev and |
2224 | Their main purpose is to integrate other event mechanisms into libev and |
1889 | their use is somewhat advanced. This could be used, for example, to track |
2225 | their use is somewhat advanced. They could be used, for example, to track |
1890 | variable changes, implement your own watchers, integrate net-snmp or a |
2226 | variable changes, implement your own watchers, integrate net-snmp or a |
1891 | coroutine library and lots more. They are also occasionally useful if |
2227 | coroutine library and lots more. They are also occasionally useful if |
1892 | you cache some data and want to flush it before blocking (for example, |
2228 | you cache some data and want to flush it before blocking (for example, |
1893 | in X programs you might want to do an C<XFlush ()> in an C<ev_prepare> |
2229 | in X programs you might want to do an C<XFlush ()> in an C<ev_prepare> |
1894 | watcher). |
2230 | watcher). |
1895 | |
2231 | |
1896 | This is done by examining in each prepare call which file descriptors need |
2232 | This is done by examining in each prepare call which file descriptors |
1897 | to be watched by the other library, registering C<ev_io> watchers for |
2233 | need to be watched by the other library, registering C<ev_io> watchers |
1898 | them and starting an C<ev_timer> watcher for any timeouts (many libraries |
2234 | for them and starting an C<ev_timer> watcher for any timeouts (many |
1899 | provide just this functionality). Then, in the check watcher you check for |
2235 | libraries provide exactly this functionality). Then, in the check watcher, |
1900 | any events that occurred (by checking the pending status of all watchers |
2236 | you check for any events that occurred (by checking the pending status |
1901 | and stopping them) and call back into the library. The I/O and timer |
2237 | of all watchers and stopping them) and call back into the library. The |
1902 | callbacks will never actually be called (but must be valid nevertheless, |
2238 | I/O and timer callbacks will never actually be called (but must be valid |
1903 | because you never know, you know?). |
2239 | nevertheless, because you never know, you know?). |
1904 | |
2240 | |
1905 | As another example, the Perl Coro module uses these hooks to integrate |
2241 | As another example, the Perl Coro module uses these hooks to integrate |
1906 | coroutines into libev programs, by yielding to other active coroutines |
2242 | coroutines into libev programs, by yielding to other active coroutines |
1907 | during each prepare and only letting the process block if no coroutines |
2243 | during each prepare and only letting the process block if no coroutines |
1908 | are ready to run (it's actually more complicated: it only runs coroutines |
2244 | are ready to run (it's actually more complicated: it only runs coroutines |
… | |
… | |
1911 | loop from blocking if lower-priority coroutines are active, thus mapping |
2247 | loop from blocking if lower-priority coroutines are active, thus mapping |
1912 | low-priority coroutines to idle/background tasks). |
2248 | low-priority coroutines to idle/background tasks). |
1913 | |
2249 | |
1914 | It is recommended to give C<ev_check> watchers highest (C<EV_MAXPRI>) |
2250 | It is recommended to give C<ev_check> watchers highest (C<EV_MAXPRI>) |
1915 | priority, to ensure that they are being run before any other watchers |
2251 | priority, to ensure that they are being run before any other watchers |
|
|
2252 | after the poll (this doesn't matter for C<ev_prepare> watchers). |
|
|
2253 | |
1916 | after the poll. Also, C<ev_check> watchers (and C<ev_prepare> watchers, |
2254 | Also, C<ev_check> watchers (and C<ev_prepare> watchers, too) should not |
1917 | too) should not activate ("feed") events into libev. While libev fully |
2255 | activate ("feed") events into libev. While libev fully supports this, they |
1918 | supports this, they might get executed before other C<ev_check> watchers |
2256 | might get executed before other C<ev_check> watchers did their job. As |
1919 | did their job. As C<ev_check> watchers are often used to embed other |
2257 | C<ev_check> watchers are often used to embed other (non-libev) event |
1920 | (non-libev) event loops those other event loops might be in an unusable |
2258 | loops those other event loops might be in an unusable state until their |
1921 | state until their C<ev_check> watcher ran (always remind yourself to |
2259 | C<ev_check> watcher ran (always remind yourself to coexist peacefully with |
1922 | coexist peacefully with others). |
2260 | others). |
1923 | |
2261 | |
1924 | =head3 Watcher-Specific Functions and Data Members |
2262 | =head3 Watcher-Specific Functions and Data Members |
1925 | |
2263 | |
1926 | =over 4 |
2264 | =over 4 |
1927 | |
2265 | |
… | |
… | |
1929 | |
2267 | |
1930 | =item ev_check_init (ev_check *, callback) |
2268 | =item ev_check_init (ev_check *, callback) |
1931 | |
2269 | |
1932 | Initialises and configures the prepare or check watcher - they have no |
2270 | Initialises and configures the prepare or check watcher - they have no |
1933 | parameters of any kind. There are C<ev_prepare_set> and C<ev_check_set> |
2271 | parameters of any kind. There are C<ev_prepare_set> and C<ev_check_set> |
1934 | macros, but using them is utterly, utterly and completely pointless. |
2272 | macros, but using them is utterly, utterly, utterly and completely |
|
|
2273 | pointless. |
1935 | |
2274 | |
1936 | =back |
2275 | =back |
1937 | |
2276 | |
1938 | =head3 Examples |
2277 | =head3 Examples |
1939 | |
2278 | |
… | |
… | |
1948 | and in a check watcher, destroy them and call into libadns. What follows |
2287 | and in a check watcher, destroy them and call into libadns. What follows |
1949 | is pseudo-code only of course. This requires you to either use a low |
2288 | is pseudo-code only of course. This requires you to either use a low |
1950 | priority for the check watcher or use C<ev_clear_pending> explicitly, as |
2289 | priority for the check watcher or use C<ev_clear_pending> explicitly, as |
1951 | the callbacks for the IO/timeout watchers might not have been called yet. |
2290 | the callbacks for the IO/timeout watchers might not have been called yet. |
1952 | |
2291 | |
1953 | static ev_io iow [nfd]; |
2292 | static ev_io iow [nfd]; |
1954 | static ev_timer tw; |
2293 | static ev_timer tw; |
1955 | |
2294 | |
1956 | static void |
2295 | static void |
1957 | io_cb (ev_loop *loop, ev_io *w, int revents) |
2296 | io_cb (struct ev_loop *loop, ev_io *w, int revents) |
1958 | { |
2297 | { |
1959 | } |
2298 | } |
1960 | |
2299 | |
1961 | // create io watchers for each fd and a timer before blocking |
2300 | // create io watchers for each fd and a timer before blocking |
1962 | static void |
2301 | static void |
1963 | adns_prepare_cb (ev_loop *loop, ev_prepare *w, int revents) |
2302 | adns_prepare_cb (struct ev_loop *loop, ev_prepare *w, int revents) |
1964 | { |
2303 | { |
1965 | int timeout = 3600000; |
2304 | int timeout = 3600000; |
1966 | struct pollfd fds [nfd]; |
2305 | struct pollfd fds [nfd]; |
1967 | // actual code will need to loop here and realloc etc. |
2306 | // actual code will need to loop here and realloc etc. |
1968 | adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); |
2307 | adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); |
1969 | |
2308 | |
1970 | /* the callback is illegal, but won't be called as we stop during check */ |
2309 | /* the callback is illegal, but won't be called as we stop during check */ |
1971 | ev_timer_init (&tw, 0, timeout * 1e-3); |
2310 | ev_timer_init (&tw, 0, timeout * 1e-3); |
1972 | ev_timer_start (loop, &tw); |
2311 | ev_timer_start (loop, &tw); |
1973 | |
2312 | |
1974 | // create one ev_io per pollfd |
2313 | // create one ev_io per pollfd |
1975 | for (int i = 0; i < nfd; ++i) |
2314 | for (int i = 0; i < nfd; ++i) |
1976 | { |
2315 | { |
1977 | ev_io_init (iow + i, io_cb, fds [i].fd, |
2316 | ev_io_init (iow + i, io_cb, fds [i].fd, |
1978 | ((fds [i].events & POLLIN ? EV_READ : 0) |
2317 | ((fds [i].events & POLLIN ? EV_READ : 0) |
1979 | | (fds [i].events & POLLOUT ? EV_WRITE : 0))); |
2318 | | (fds [i].events & POLLOUT ? EV_WRITE : 0))); |
1980 | |
2319 | |
1981 | fds [i].revents = 0; |
2320 | fds [i].revents = 0; |
1982 | ev_io_start (loop, iow + i); |
2321 | ev_io_start (loop, iow + i); |
1983 | } |
2322 | } |
1984 | } |
2323 | } |
1985 | |
2324 | |
1986 | // stop all watchers after blocking |
2325 | // stop all watchers after blocking |
1987 | static void |
2326 | static void |
1988 | adns_check_cb (ev_loop *loop, ev_check *w, int revents) |
2327 | adns_check_cb (struct ev_loop *loop, ev_check *w, int revents) |
1989 | { |
2328 | { |
1990 | ev_timer_stop (loop, &tw); |
2329 | ev_timer_stop (loop, &tw); |
1991 | |
2330 | |
1992 | for (int i = 0; i < nfd; ++i) |
2331 | for (int i = 0; i < nfd; ++i) |
1993 | { |
2332 | { |
1994 | // set the relevant poll flags |
2333 | // set the relevant poll flags |
1995 | // could also call adns_processreadable etc. here |
2334 | // could also call adns_processreadable etc. here |
1996 | struct pollfd *fd = fds + i; |
2335 | struct pollfd *fd = fds + i; |
1997 | int revents = ev_clear_pending (iow + i); |
2336 | int revents = ev_clear_pending (iow + i); |
1998 | if (revents & EV_READ ) fd->revents |= fd->events & POLLIN; |
2337 | if (revents & EV_READ ) fd->revents |= fd->events & POLLIN; |
1999 | if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT; |
2338 | if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT; |
2000 | |
2339 | |
2001 | // now stop the watcher |
2340 | // now stop the watcher |
2002 | ev_io_stop (loop, iow + i); |
2341 | ev_io_stop (loop, iow + i); |
2003 | } |
2342 | } |
2004 | |
2343 | |
2005 | adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop)); |
2344 | adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop)); |
2006 | } |
2345 | } |
2007 | |
2346 | |
2008 | Method 2: This would be just like method 1, but you run C<adns_afterpoll> |
2347 | Method 2: This would be just like method 1, but you run C<adns_afterpoll> |
2009 | in the prepare watcher and would dispose of the check watcher. |
2348 | in the prepare watcher and would dispose of the check watcher. |
2010 | |
2349 | |
2011 | Method 3: If the module to be embedded supports explicit event |
2350 | Method 3: If the module to be embedded supports explicit event |
2012 | notification (libadns does), you can also make use of the actual watcher |
2351 | notification (libadns does), you can also make use of the actual watcher |
2013 | callbacks, and only destroy/create the watchers in the prepare watcher. |
2352 | callbacks, and only destroy/create the watchers in the prepare watcher. |
2014 | |
2353 | |
2015 | static void |
2354 | static void |
2016 | timer_cb (EV_P_ ev_timer *w, int revents) |
2355 | timer_cb (EV_P_ ev_timer *w, int revents) |
2017 | { |
2356 | { |
2018 | adns_state ads = (adns_state)w->data; |
2357 | adns_state ads = (adns_state)w->data; |
2019 | update_now (EV_A); |
2358 | update_now (EV_A); |
2020 | |
2359 | |
2021 | adns_processtimeouts (ads, &tv_now); |
2360 | adns_processtimeouts (ads, &tv_now); |
2022 | } |
2361 | } |
2023 | |
2362 | |
2024 | static void |
2363 | static void |
2025 | io_cb (EV_P_ ev_io *w, int revents) |
2364 | io_cb (EV_P_ ev_io *w, int revents) |
2026 | { |
2365 | { |
2027 | adns_state ads = (adns_state)w->data; |
2366 | adns_state ads = (adns_state)w->data; |
2028 | update_now (EV_A); |
2367 | update_now (EV_A); |
2029 | |
2368 | |
2030 | if (revents & EV_READ ) adns_processreadable (ads, w->fd, &tv_now); |
2369 | if (revents & EV_READ ) adns_processreadable (ads, w->fd, &tv_now); |
2031 | if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now); |
2370 | if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now); |
2032 | } |
2371 | } |
2033 | |
2372 | |
2034 | // do not ever call adns_afterpoll |
2373 | // do not ever call adns_afterpoll |
2035 | |
2374 | |
2036 | Method 4: Do not use a prepare or check watcher because the module you |
2375 | Method 4: Do not use a prepare or check watcher because the module you |
2037 | want to embed is too inflexible to support it. Instead, you can override |
2376 | want to embed is not flexible enough to support it. Instead, you can |
2038 | their poll function. The drawback with this solution is that the main |
2377 | override their poll function. The drawback with this solution is that the |
2039 | loop is now no longer controllable by EV. The C<Glib::EV> module does |
2378 | main loop is now no longer controllable by EV. The C<Glib::EV> module uses |
2040 | this. |
2379 | this approach, effectively embedding EV as a client into the horrible |
|
|
2380 | libglib event loop. |
2041 | |
2381 | |
2042 | static gint |
2382 | static gint |
2043 | event_poll_func (GPollFD *fds, guint nfds, gint timeout) |
2383 | event_poll_func (GPollFD *fds, guint nfds, gint timeout) |
2044 | { |
2384 | { |
2045 | int got_events = 0; |
2385 | int got_events = 0; |
2046 | |
2386 | |
2047 | for (n = 0; n < nfds; ++n) |
2387 | for (n = 0; n < nfds; ++n) |
2048 | // create/start io watcher that sets the relevant bits in fds[n] and increment got_events |
2388 | // create/start io watcher that sets the relevant bits in fds[n] and increment got_events |
2049 | |
2389 | |
2050 | if (timeout >= 0) |
2390 | if (timeout >= 0) |
2051 | // create/start timer |
2391 | // create/start timer |
2052 | |
2392 | |
2053 | // poll |
2393 | // poll |
2054 | ev_loop (EV_A_ 0); |
2394 | ev_loop (EV_A_ 0); |
2055 | |
2395 | |
2056 | // stop timer again |
2396 | // stop timer again |
2057 | if (timeout >= 0) |
2397 | if (timeout >= 0) |
2058 | ev_timer_stop (EV_A_ &to); |
2398 | ev_timer_stop (EV_A_ &to); |
2059 | |
2399 | |
2060 | // stop io watchers again - their callbacks should have set |
2400 | // stop io watchers again - their callbacks should have set |
2061 | for (n = 0; n < nfds; ++n) |
2401 | for (n = 0; n < nfds; ++n) |
2062 | ev_io_stop (EV_A_ iow [n]); |
2402 | ev_io_stop (EV_A_ iow [n]); |
2063 | |
2403 | |
2064 | return got_events; |
2404 | return got_events; |
2065 | } |
2405 | } |
2066 | |
2406 | |
2067 | |
2407 | |
2068 | =head2 C<ev_embed> - when one backend isn't enough... |
2408 | =head2 C<ev_embed> - when one backend isn't enough... |
2069 | |
2409 | |
2070 | This is a rather advanced watcher type that lets you embed one event loop |
2410 | This is a rather advanced watcher type that lets you embed one event loop |
… | |
… | |
2076 | prioritise I/O. |
2416 | prioritise I/O. |
2077 | |
2417 | |
2078 | As an example for a bug workaround, the kqueue backend might only support |
2418 | As an example for a bug workaround, the kqueue backend might only support |
2079 | sockets on some platform, so it is unusable as generic backend, but you |
2419 | sockets on some platform, so it is unusable as generic backend, but you |
2080 | still want to make use of it because you have many sockets and it scales |
2420 | still want to make use of it because you have many sockets and it scales |
2081 | so nicely. In this case, you would create a kqueue-based loop and embed it |
2421 | so nicely. In this case, you would create a kqueue-based loop and embed |
2082 | into your default loop (which might use e.g. poll). Overall operation will |
2422 | it into your default loop (which might use e.g. poll). Overall operation |
2083 | be a bit slower because first libev has to poll and then call kevent, but |
2423 | will be a bit slower because first libev has to call C<poll> and then |
2084 | at least you can use both at what they are best. |
2424 | C<kevent>, but at least you can use both mechanisms for what they are |
|
|
2425 | best: C<kqueue> for scalable sockets and C<poll> if you want it to work :) |
2085 | |
2426 | |
2086 | As for prioritising I/O: rarely you have the case where some fds have |
2427 | As for prioritising I/O: under rare circumstances you have the case where |
2087 | to be watched and handled very quickly (with low latency), and even |
2428 | some fds have to be watched and handled very quickly (with low latency), |
2088 | priorities and idle watchers might have too much overhead. In this case |
2429 | and even priorities and idle watchers might have too much overhead. In |
2089 | you would put all the high priority stuff in one loop and all the rest in |
2430 | this case you would put all the high priority stuff in one loop and all |
2090 | a second one, and embed the second one in the first. |
2431 | the rest in a second one, and embed the second one in the first. |
2091 | |
2432 | |
2092 | As long as the watcher is active, the callback will be invoked every time |
2433 | As long as the watcher is active, the callback will be invoked every time |
2093 | there might be events pending in the embedded loop. The callback must then |
2434 | there might be events pending in the embedded loop. The callback must then |
2094 | call C<ev_embed_sweep (mainloop, watcher)> to make a single sweep and invoke |
2435 | call C<ev_embed_sweep (mainloop, watcher)> to make a single sweep and invoke |
2095 | their callbacks (you could also start an idle watcher to give the embedded |
2436 | their callbacks (you could also start an idle watcher to give the embedded |
… | |
… | |
2103 | interested in that. |
2444 | interested in that. |
2104 | |
2445 | |
2105 | Also, there have not currently been made special provisions for forking: |
2446 | Also, there have not currently been made special provisions for forking: |
2106 | when you fork, you not only have to call C<ev_loop_fork> on both loops, |
2447 | when you fork, you not only have to call C<ev_loop_fork> on both loops, |
2107 | but you will also have to stop and restart any C<ev_embed> watchers |
2448 | but you will also have to stop and restart any C<ev_embed> watchers |
2108 | yourself. |
2449 | yourself - but you can use a fork watcher to handle this automatically, |
|
|
2450 | and future versions of libev might do just that. |
2109 | |
2451 | |
2110 | Unfortunately, not all backends are embeddable, only the ones returned by |
2452 | Unfortunately, not all backends are embeddable: only the ones returned by |
2111 | C<ev_embeddable_backends> are, which, unfortunately, does not include any |
2453 | C<ev_embeddable_backends> are, which, unfortunately, does not include any |
2112 | portable one. |
2454 | portable one. |
2113 | |
2455 | |
2114 | So when you want to use this feature you will always have to be prepared |
2456 | So when you want to use this feature you will always have to be prepared |
2115 | that you cannot get an embeddable loop. The recommended way to get around |
2457 | that you cannot get an embeddable loop. The recommended way to get around |
2116 | this is to have a separate variables for your embeddable loop, try to |
2458 | this is to have a separate variables for your embeddable loop, try to |
2117 | create it, and if that fails, use the normal loop for everything. |
2459 | create it, and if that fails, use the normal loop for everything. |
|
|
2460 | |
|
|
2461 | =head3 C<ev_embed> and fork |
|
|
2462 | |
|
|
2463 | While the C<ev_embed> watcher is running, forks in the embedding loop will |
|
|
2464 | automatically be applied to the embedded loop as well, so no special |
|
|
2465 | fork handling is required in that case. When the watcher is not running, |
|
|
2466 | however, it is still the task of the libev user to call C<ev_loop_fork ()> |
|
|
2467 | as applicable. |
2118 | |
2468 | |
2119 | =head3 Watcher-Specific Functions and Data Members |
2469 | =head3 Watcher-Specific Functions and Data Members |
2120 | |
2470 | |
2121 | =over 4 |
2471 | =over 4 |
2122 | |
2472 | |
… | |
… | |
2148 | event loop. If that is not possible, use the default loop. The default |
2498 | event loop. If that is not possible, use the default loop. The default |
2149 | loop is stored in C<loop_hi>, while the embeddable loop is stored in |
2499 | loop is stored in C<loop_hi>, while the embeddable loop is stored in |
2150 | C<loop_lo> (which is C<loop_hi> in the case no embeddable loop can be |
2500 | C<loop_lo> (which is C<loop_hi> in the case no embeddable loop can be |
2151 | used). |
2501 | used). |
2152 | |
2502 | |
2153 | struct ev_loop *loop_hi = ev_default_init (0); |
2503 | struct ev_loop *loop_hi = ev_default_init (0); |
2154 | struct ev_loop *loop_lo = 0; |
2504 | struct ev_loop *loop_lo = 0; |
2155 | struct ev_embed embed; |
2505 | ev_embed embed; |
2156 | |
2506 | |
2157 | // see if there is a chance of getting one that works |
2507 | // see if there is a chance of getting one that works |
2158 | // (remember that a flags value of 0 means autodetection) |
2508 | // (remember that a flags value of 0 means autodetection) |
2159 | loop_lo = ev_embeddable_backends () & ev_recommended_backends () |
2509 | loop_lo = ev_embeddable_backends () & ev_recommended_backends () |
2160 | ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) |
2510 | ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) |
2161 | : 0; |
2511 | : 0; |
2162 | |
2512 | |
2163 | // if we got one, then embed it, otherwise default to loop_hi |
2513 | // if we got one, then embed it, otherwise default to loop_hi |
2164 | if (loop_lo) |
2514 | if (loop_lo) |
2165 | { |
2515 | { |
2166 | ev_embed_init (&embed, 0, loop_lo); |
2516 | ev_embed_init (&embed, 0, loop_lo); |
2167 | ev_embed_start (loop_hi, &embed); |
2517 | ev_embed_start (loop_hi, &embed); |
2168 | } |
2518 | } |
2169 | else |
2519 | else |
2170 | loop_lo = loop_hi; |
2520 | loop_lo = loop_hi; |
2171 | |
2521 | |
2172 | Example: Check if kqueue is available but not recommended and create |
2522 | Example: Check if kqueue is available but not recommended and create |
2173 | a kqueue backend for use with sockets (which usually work with any |
2523 | a kqueue backend for use with sockets (which usually work with any |
2174 | kqueue implementation). Store the kqueue/socket-only event loop in |
2524 | kqueue implementation). Store the kqueue/socket-only event loop in |
2175 | C<loop_socket>. (One might optionally use C<EVFLAG_NOENV>, too). |
2525 | C<loop_socket>. (One might optionally use C<EVFLAG_NOENV>, too). |
2176 | |
2526 | |
2177 | struct ev_loop *loop = ev_default_init (0); |
2527 | struct ev_loop *loop = ev_default_init (0); |
2178 | struct ev_loop *loop_socket = 0; |
2528 | struct ev_loop *loop_socket = 0; |
2179 | struct ev_embed embed; |
2529 | ev_embed embed; |
2180 | |
2530 | |
2181 | if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) |
2531 | if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) |
2182 | if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) |
2532 | if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) |
2183 | { |
2533 | { |
2184 | ev_embed_init (&embed, 0, loop_socket); |
2534 | ev_embed_init (&embed, 0, loop_socket); |
2185 | ev_embed_start (loop, &embed); |
2535 | ev_embed_start (loop, &embed); |
2186 | } |
2536 | } |
2187 | |
2537 | |
2188 | if (!loop_socket) |
2538 | if (!loop_socket) |
2189 | loop_socket = loop; |
2539 | loop_socket = loop; |
2190 | |
2540 | |
2191 | // now use loop_socket for all sockets, and loop for everything else |
2541 | // now use loop_socket for all sockets, and loop for everything else |
2192 | |
2542 | |
2193 | |
2543 | |
2194 | =head2 C<ev_fork> - the audacity to resume the event loop after a fork |
2544 | =head2 C<ev_fork> - the audacity to resume the event loop after a fork |
2195 | |
2545 | |
2196 | Fork watchers are called when a C<fork ()> was detected (usually because |
2546 | Fork watchers are called when a C<fork ()> was detected (usually because |
… | |
… | |
2240 | is that the author does not know of a simple (or any) algorithm for a |
2590 | is that the author does not know of a simple (or any) algorithm for a |
2241 | multiple-writer-single-reader queue that works in all cases and doesn't |
2591 | multiple-writer-single-reader queue that works in all cases and doesn't |
2242 | need elaborate support such as pthreads. |
2592 | need elaborate support such as pthreads. |
2243 | |
2593 | |
2244 | That means that if you want to queue data, you have to provide your own |
2594 | That means that if you want to queue data, you have to provide your own |
2245 | queue. But at least I can tell you would implement locking around your |
2595 | queue. But at least I can tell you how to implement locking around your |
2246 | queue: |
2596 | queue: |
2247 | |
2597 | |
2248 | =over 4 |
2598 | =over 4 |
2249 | |
2599 | |
2250 | =item queueing from a signal handler context |
2600 | =item queueing from a signal handler context |
2251 | |
2601 | |
2252 | To implement race-free queueing, you simply add to the queue in the signal |
2602 | To implement race-free queueing, you simply add to the queue in the signal |
2253 | handler but you block the signal handler in the watcher callback. Here is an example that does that for |
2603 | handler but you block the signal handler in the watcher callback. Here is |
2254 | some fictitious SIGUSR1 handler: |
2604 | an example that does that for some fictitious SIGUSR1 handler: |
2255 | |
2605 | |
2256 | static ev_async mysig; |
2606 | static ev_async mysig; |
2257 | |
2607 | |
2258 | static void |
2608 | static void |
2259 | sigusr1_handler (void) |
2609 | sigusr1_handler (void) |
… | |
… | |
2325 | =over 4 |
2675 | =over 4 |
2326 | |
2676 | |
2327 | =item ev_async_init (ev_async *, callback) |
2677 | =item ev_async_init (ev_async *, callback) |
2328 | |
2678 | |
2329 | Initialises and configures the async watcher - it has no parameters of any |
2679 | Initialises and configures the async watcher - it has no parameters of any |
2330 | kind. There is a C<ev_asynd_set> macro, but using it is utterly pointless, |
2680 | kind. There is a C<ev_async_set> macro, but using it is utterly pointless, |
2331 | believe me. |
2681 | trust me. |
2332 | |
2682 | |
2333 | =item ev_async_send (loop, ev_async *) |
2683 | =item ev_async_send (loop, ev_async *) |
2334 | |
2684 | |
2335 | Sends/signals/activates the given C<ev_async> watcher, that is, feeds |
2685 | Sends/signals/activates the given C<ev_async> watcher, that is, feeds |
2336 | an C<EV_ASYNC> event on the watcher into the event loop. Unlike |
2686 | an C<EV_ASYNC> event on the watcher into the event loop. Unlike |
2337 | C<ev_feed_event>, this call is safe to do in other threads, signal or |
2687 | C<ev_feed_event>, this call is safe to do from other threads, signal or |
2338 | similar contexts (see the discussion of C<EV_ATOMIC_T> in the embedding |
2688 | similar contexts (see the discussion of C<EV_ATOMIC_T> in the embedding |
2339 | section below on what exactly this means). |
2689 | section below on what exactly this means). |
2340 | |
2690 | |
2341 | This call incurs the overhead of a system call only once per loop iteration, |
2691 | This call incurs the overhead of a system call only once per loop iteration, |
2342 | so while the overhead might be noticeable, it doesn't apply to repeated |
2692 | so while the overhead might be noticeable, it doesn't apply to repeated |
… | |
… | |
2366 | =over 4 |
2716 | =over 4 |
2367 | |
2717 | |
2368 | =item ev_once (loop, int fd, int events, ev_tstamp timeout, callback) |
2718 | =item ev_once (loop, int fd, int events, ev_tstamp timeout, callback) |
2369 | |
2719 | |
2370 | This function combines a simple timer and an I/O watcher, calls your |
2720 | This function combines a simple timer and an I/O watcher, calls your |
2371 | callback on whichever event happens first and automatically stop both |
2721 | callback on whichever event happens first and automatically stops both |
2372 | watchers. This is useful if you want to wait for a single event on an fd |
2722 | watchers. This is useful if you want to wait for a single event on an fd |
2373 | or timeout without having to allocate/configure/start/stop/free one or |
2723 | or timeout without having to allocate/configure/start/stop/free one or |
2374 | more watchers yourself. |
2724 | more watchers yourself. |
2375 | |
2725 | |
2376 | If C<fd> is less than 0, then no I/O watcher will be started and events |
2726 | If C<fd> is less than 0, then no I/O watcher will be started and the |
2377 | is being ignored. Otherwise, an C<ev_io> watcher for the given C<fd> and |
2727 | C<events> argument is being ignored. Otherwise, an C<ev_io> watcher for |
2378 | C<events> set will be created and started. |
2728 | the given C<fd> and C<events> set will be created and started. |
2379 | |
2729 | |
2380 | If C<timeout> is less than 0, then no timeout watcher will be |
2730 | If C<timeout> is less than 0, then no timeout watcher will be |
2381 | started. Otherwise an C<ev_timer> watcher with after = C<timeout> (and |
2731 | started. Otherwise an C<ev_timer> watcher with after = C<timeout> (and |
2382 | repeat = 0) will be started. While C<0> is a valid timeout, it is of |
2732 | repeat = 0) will be started. C<0> is a valid timeout. |
2383 | dubious value. |
|
|
2384 | |
2733 | |
2385 | The callback has the type C<void (*cb)(int revents, void *arg)> and gets |
2734 | The callback has the type C<void (*cb)(int revents, void *arg)> and gets |
2386 | passed an C<revents> set like normal event callbacks (a combination of |
2735 | passed an C<revents> set like normal event callbacks (a combination of |
2387 | C<EV_ERROR>, C<EV_READ>, C<EV_WRITE> or C<EV_TIMEOUT>) and the C<arg> |
2736 | C<EV_ERROR>, C<EV_READ>, C<EV_WRITE> or C<EV_TIMEOUT>) and the C<arg> |
2388 | value passed to C<ev_once>: |
2737 | value passed to C<ev_once>. Note that it is possible to receive I<both> |
|
|
2738 | a timeout and an io event at the same time - you probably should give io |
|
|
2739 | events precedence. |
2389 | |
2740 | |
|
|
2741 | Example: wait up to ten seconds for data to appear on STDIN_FILENO. |
|
|
2742 | |
2390 | static void stdin_ready (int revents, void *arg) |
2743 | static void stdin_ready (int revents, void *arg) |
2391 | { |
2744 | { |
2392 | if (revents & EV_TIMEOUT) |
|
|
2393 | /* doh, nothing entered */; |
|
|
2394 | else if (revents & EV_READ) |
2745 | if (revents & EV_READ) |
2395 | /* stdin might have data for us, joy! */; |
2746 | /* stdin might have data for us, joy! */; |
|
|
2747 | else if (revents & EV_TIMEOUT) |
|
|
2748 | /* doh, nothing entered */; |
2396 | } |
2749 | } |
2397 | |
2750 | |
2398 | ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); |
2751 | ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); |
2399 | |
2752 | |
2400 | =item ev_feed_event (ev_loop *, watcher *, int revents) |
2753 | =item ev_feed_event (struct ev_loop *, watcher *, int revents) |
2401 | |
2754 | |
2402 | Feeds the given event set into the event loop, as if the specified event |
2755 | Feeds the given event set into the event loop, as if the specified event |
2403 | had happened for the specified watcher (which must be a pointer to an |
2756 | had happened for the specified watcher (which must be a pointer to an |
2404 | initialised but not necessarily started event watcher). |
2757 | initialised but not necessarily started event watcher). |
2405 | |
2758 | |
2406 | =item ev_feed_fd_event (ev_loop *, int fd, int revents) |
2759 | =item ev_feed_fd_event (struct ev_loop *, int fd, int revents) |
2407 | |
2760 | |
2408 | Feed an event on the given fd, as if a file descriptor backend detected |
2761 | Feed an event on the given fd, as if a file descriptor backend detected |
2409 | the given events it. |
2762 | the given events it. |
2410 | |
2763 | |
2411 | =item ev_feed_signal_event (ev_loop *loop, int signum) |
2764 | =item ev_feed_signal_event (struct ev_loop *loop, int signum) |
2412 | |
2765 | |
2413 | Feed an event as if the given signal occurred (C<loop> must be the default |
2766 | Feed an event as if the given signal occurred (C<loop> must be the default |
2414 | loop!). |
2767 | loop!). |
2415 | |
2768 | |
2416 | =back |
2769 | =back |
… | |
… | |
2452 | you to use some convenience methods to start/stop watchers and also change |
2805 | you to use some convenience methods to start/stop watchers and also change |
2453 | the callback model to a model using method callbacks on objects. |
2806 | the callback model to a model using method callbacks on objects. |
2454 | |
2807 | |
2455 | To use it, |
2808 | To use it, |
2456 | |
2809 | |
2457 | #include <ev++.h> |
2810 | #include <ev++.h> |
2458 | |
2811 | |
2459 | This automatically includes F<ev.h> and puts all of its definitions (many |
2812 | This automatically includes F<ev.h> and puts all of its definitions (many |
2460 | of them macros) into the global namespace. All C++ specific things are |
2813 | of them macros) into the global namespace. All C++ specific things are |
2461 | put into the C<ev> namespace. It should support all the same embedding |
2814 | put into the C<ev> namespace. It should support all the same embedding |
2462 | options as F<ev.h>, most notably C<EV_MULTIPLICITY>. |
2815 | options as F<ev.h>, most notably C<EV_MULTIPLICITY>. |
… | |
… | |
2529 | your compiler is good :), then the method will be fully inlined into the |
2882 | your compiler is good :), then the method will be fully inlined into the |
2530 | thunking function, making it as fast as a direct C callback. |
2883 | thunking function, making it as fast as a direct C callback. |
2531 | |
2884 | |
2532 | Example: simple class declaration and watcher initialisation |
2885 | Example: simple class declaration and watcher initialisation |
2533 | |
2886 | |
2534 | struct myclass |
2887 | struct myclass |
2535 | { |
2888 | { |
2536 | void io_cb (ev::io &w, int revents) { } |
2889 | void io_cb (ev::io &w, int revents) { } |
2537 | } |
2890 | } |
2538 | |
2891 | |
2539 | myclass obj; |
2892 | myclass obj; |
2540 | ev::io iow; |
2893 | ev::io iow; |
2541 | iow.set <myclass, &myclass::io_cb> (&obj); |
2894 | iow.set <myclass, &myclass::io_cb> (&obj); |
|
|
2895 | |
|
|
2896 | =item w->set (object *) |
|
|
2897 | |
|
|
2898 | This is an B<experimental> feature that might go away in a future version. |
|
|
2899 | |
|
|
2900 | This is a variation of a method callback - leaving out the method to call |
|
|
2901 | will default the method to C<operator ()>, which makes it possible to use |
|
|
2902 | functor objects without having to manually specify the C<operator ()> all |
|
|
2903 | the time. Incidentally, you can then also leave out the template argument |
|
|
2904 | list. |
|
|
2905 | |
|
|
2906 | The C<operator ()> method prototype must be C<void operator ()(watcher &w, |
|
|
2907 | int revents)>. |
|
|
2908 | |
|
|
2909 | See the method-C<set> above for more details. |
|
|
2910 | |
|
|
2911 | Example: use a functor object as callback. |
|
|
2912 | |
|
|
2913 | struct myfunctor |
|
|
2914 | { |
|
|
2915 | void operator() (ev::io &w, int revents) |
|
|
2916 | { |
|
|
2917 | ... |
|
|
2918 | } |
|
|
2919 | } |
|
|
2920 | |
|
|
2921 | myfunctor f; |
|
|
2922 | |
|
|
2923 | ev::io w; |
|
|
2924 | w.set (&f); |
2542 | |
2925 | |
2543 | =item w->set<function> (void *data = 0) |
2926 | =item w->set<function> (void *data = 0) |
2544 | |
2927 | |
2545 | Also sets a callback, but uses a static method or plain function as |
2928 | Also sets a callback, but uses a static method or plain function as |
2546 | callback. The optional C<data> argument will be stored in the watcher's |
2929 | callback. The optional C<data> argument will be stored in the watcher's |
… | |
… | |
2548 | |
2931 | |
2549 | The prototype of the C<function> must be C<void (*)(ev::TYPE &w, int)>. |
2932 | The prototype of the C<function> must be C<void (*)(ev::TYPE &w, int)>. |
2550 | |
2933 | |
2551 | See the method-C<set> above for more details. |
2934 | See the method-C<set> above for more details. |
2552 | |
2935 | |
2553 | Example: |
2936 | Example: Use a plain function as callback. |
2554 | |
2937 | |
2555 | static void io_cb (ev::io &w, int revents) { } |
2938 | static void io_cb (ev::io &w, int revents) { } |
2556 | iow.set <io_cb> (); |
2939 | iow.set <io_cb> (); |
2557 | |
2940 | |
2558 | =item w->set (struct ev_loop *) |
2941 | =item w->set (struct ev_loop *) |
2559 | |
2942 | |
2560 | Associates a different C<struct ev_loop> with this watcher. You can only |
2943 | Associates a different C<struct ev_loop> with this watcher. You can only |
2561 | do this when the watcher is inactive (and not pending either). |
2944 | do this when the watcher is inactive (and not pending either). |
… | |
… | |
2594 | =back |
2977 | =back |
2595 | |
2978 | |
2596 | Example: Define a class with an IO and idle watcher, start one of them in |
2979 | Example: Define a class with an IO and idle watcher, start one of them in |
2597 | the constructor. |
2980 | the constructor. |
2598 | |
2981 | |
2599 | class myclass |
2982 | class myclass |
2600 | { |
2983 | { |
2601 | ev::io io; void io_cb (ev::io &w, int revents); |
2984 | ev::io io ; void io_cb (ev::io &w, int revents); |
2602 | ev:idle idle void idle_cb (ev::idle &w, int revents); |
2985 | ev::idle idle; void idle_cb (ev::idle &w, int revents); |
2603 | |
2986 | |
2604 | myclass (int fd) |
2987 | myclass (int fd) |
2605 | { |
2988 | { |
2606 | io .set <myclass, &myclass::io_cb > (this); |
2989 | io .set <myclass, &myclass::io_cb > (this); |
2607 | idle.set <myclass, &myclass::idle_cb> (this); |
2990 | idle.set <myclass, &myclass::idle_cb> (this); |
2608 | |
2991 | |
2609 | io.start (fd, ev::READ); |
2992 | io.start (fd, ev::READ); |
2610 | } |
2993 | } |
2611 | }; |
2994 | }; |
2612 | |
2995 | |
2613 | |
2996 | |
2614 | =head1 OTHER LANGUAGE BINDINGS |
2997 | =head1 OTHER LANGUAGE BINDINGS |
2615 | |
2998 | |
2616 | Libev does not offer other language bindings itself, but bindings for a |
2999 | Libev does not offer other language bindings itself, but bindings for a |
… | |
… | |
2623 | =item Perl |
3006 | =item Perl |
2624 | |
3007 | |
2625 | The EV module implements the full libev API and is actually used to test |
3008 | The EV module implements the full libev API and is actually used to test |
2626 | libev. EV is developed together with libev. Apart from the EV core module, |
3009 | libev. EV is developed together with libev. Apart from the EV core module, |
2627 | there are additional modules that implement libev-compatible interfaces |
3010 | there are additional modules that implement libev-compatible interfaces |
2628 | to C<libadns> (C<EV::ADNS>), C<Net::SNMP> (C<Net::SNMP::EV>) and the |
3011 | to C<libadns> (C<EV::ADNS>, but C<AnyEvent::DNS> is preferred nowadays), |
2629 | C<libglib> event core (C<Glib::EV> and C<EV::Glib>). |
3012 | C<Net::SNMP> (C<Net::SNMP::EV>) and the C<libglib> event core (C<Glib::EV> |
|
|
3013 | and C<EV::Glib>). |
2630 | |
3014 | |
2631 | It can be found and installed via CPAN, its homepage is found at |
3015 | It can be found and installed via CPAN, its homepage is at |
2632 | L<http://software.schmorp.de/pkg/EV>. |
3016 | L<http://software.schmorp.de/pkg/EV>. |
|
|
3017 | |
|
|
3018 | =item Python |
|
|
3019 | |
|
|
3020 | Python bindings can be found at L<http://code.google.com/p/pyev/>. It |
|
|
3021 | seems to be quite complete and well-documented. Note, however, that the |
|
|
3022 | patch they require for libev is outright dangerous as it breaks the ABI |
|
|
3023 | for everybody else, and therefore, should never be applied in an installed |
|
|
3024 | libev (if python requires an incompatible ABI then it needs to embed |
|
|
3025 | libev). |
2633 | |
3026 | |
2634 | =item Ruby |
3027 | =item Ruby |
2635 | |
3028 | |
2636 | Tony Arcieri has written a ruby extension that offers access to a subset |
3029 | Tony Arcieri has written a ruby extension that offers access to a subset |
2637 | of the libev API and adds file handle abstractions, asynchronous DNS and |
3030 | of the libev API and adds file handle abstractions, asynchronous DNS and |
2638 | more on top of it. It can be found via gem servers. Its homepage is at |
3031 | more on top of it. It can be found via gem servers. Its homepage is at |
2639 | L<http://rev.rubyforge.org/>. |
3032 | L<http://rev.rubyforge.org/>. |
2640 | |
3033 | |
|
|
3034 | Roger Pack reports that using the link order C<-lws2_32 -lmsvcrt-ruby-190> |
|
|
3035 | makes rev work even on mingw. |
|
|
3036 | |
2641 | =item D |
3037 | =item D |
2642 | |
3038 | |
2643 | Leandro Lucarella has written a D language binding (F<ev.d>) for libev, to |
3039 | Leandro Lucarella has written a D language binding (F<ev.d>) for libev, to |
2644 | be found at L<http://git.llucax.com.ar/?p=software/ev.d.git;a=summary>. |
3040 | be found at L<http://proj.llucax.com.ar/wiki/evd>. |
|
|
3041 | |
|
|
3042 | =item Ocaml |
|
|
3043 | |
|
|
3044 | Erkki Seppala has written Ocaml bindings for libev, to be found at |
|
|
3045 | L<http://modeemi.cs.tut.fi/~flux/software/ocaml-ev/>. |
2645 | |
3046 | |
2646 | =back |
3047 | =back |
2647 | |
3048 | |
2648 | |
3049 | |
2649 | =head1 MACRO MAGIC |
3050 | =head1 MACRO MAGIC |
… | |
… | |
2661 | |
3062 | |
2662 | This provides the loop I<argument> for functions, if one is required ("ev |
3063 | This provides the loop I<argument> for functions, if one is required ("ev |
2663 | loop argument"). The C<EV_A> form is used when this is the sole argument, |
3064 | loop argument"). The C<EV_A> form is used when this is the sole argument, |
2664 | C<EV_A_> is used when other arguments are following. Example: |
3065 | C<EV_A_> is used when other arguments are following. Example: |
2665 | |
3066 | |
2666 | ev_unref (EV_A); |
3067 | ev_unref (EV_A); |
2667 | ev_timer_add (EV_A_ watcher); |
3068 | ev_timer_add (EV_A_ watcher); |
2668 | ev_loop (EV_A_ 0); |
3069 | ev_loop (EV_A_ 0); |
2669 | |
3070 | |
2670 | It assumes the variable C<loop> of type C<struct ev_loop *> is in scope, |
3071 | It assumes the variable C<loop> of type C<struct ev_loop *> is in scope, |
2671 | which is often provided by the following macro. |
3072 | which is often provided by the following macro. |
2672 | |
3073 | |
2673 | =item C<EV_P>, C<EV_P_> |
3074 | =item C<EV_P>, C<EV_P_> |
2674 | |
3075 | |
2675 | This provides the loop I<parameter> for functions, if one is required ("ev |
3076 | This provides the loop I<parameter> for functions, if one is required ("ev |
2676 | loop parameter"). The C<EV_P> form is used when this is the sole parameter, |
3077 | loop parameter"). The C<EV_P> form is used when this is the sole parameter, |
2677 | C<EV_P_> is used when other parameters are following. Example: |
3078 | C<EV_P_> is used when other parameters are following. Example: |
2678 | |
3079 | |
2679 | // this is how ev_unref is being declared |
3080 | // this is how ev_unref is being declared |
2680 | static void ev_unref (EV_P); |
3081 | static void ev_unref (EV_P); |
2681 | |
3082 | |
2682 | // this is how you can declare your typical callback |
3083 | // this is how you can declare your typical callback |
2683 | static void cb (EV_P_ ev_timer *w, int revents) |
3084 | static void cb (EV_P_ ev_timer *w, int revents) |
2684 | |
3085 | |
2685 | It declares a parameter C<loop> of type C<struct ev_loop *>, quite |
3086 | It declares a parameter C<loop> of type C<struct ev_loop *>, quite |
2686 | suitable for use with C<EV_A>. |
3087 | suitable for use with C<EV_A>. |
2687 | |
3088 | |
2688 | =item C<EV_DEFAULT>, C<EV_DEFAULT_> |
3089 | =item C<EV_DEFAULT>, C<EV_DEFAULT_> |
… | |
… | |
2704 | |
3105 | |
2705 | Example: Declare and initialise a check watcher, utilising the above |
3106 | Example: Declare and initialise a check watcher, utilising the above |
2706 | macros so it will work regardless of whether multiple loops are supported |
3107 | macros so it will work regardless of whether multiple loops are supported |
2707 | or not. |
3108 | or not. |
2708 | |
3109 | |
2709 | static void |
3110 | static void |
2710 | check_cb (EV_P_ ev_timer *w, int revents) |
3111 | check_cb (EV_P_ ev_timer *w, int revents) |
2711 | { |
3112 | { |
2712 | ev_check_stop (EV_A_ w); |
3113 | ev_check_stop (EV_A_ w); |
2713 | } |
3114 | } |
2714 | |
3115 | |
2715 | ev_check check; |
3116 | ev_check check; |
2716 | ev_check_init (&check, check_cb); |
3117 | ev_check_init (&check, check_cb); |
2717 | ev_check_start (EV_DEFAULT_ &check); |
3118 | ev_check_start (EV_DEFAULT_ &check); |
2718 | ev_loop (EV_DEFAULT_ 0); |
3119 | ev_loop (EV_DEFAULT_ 0); |
2719 | |
3120 | |
2720 | =head1 EMBEDDING |
3121 | =head1 EMBEDDING |
2721 | |
3122 | |
2722 | Libev can (and often is) directly embedded into host |
3123 | Libev can (and often is) directly embedded into host |
2723 | applications. Examples of applications that embed it include the Deliantra |
3124 | applications. Examples of applications that embed it include the Deliantra |
… | |
… | |
2737 | =head3 CORE EVENT LOOP |
3138 | =head3 CORE EVENT LOOP |
2738 | |
3139 | |
2739 | To include only the libev core (all the C<ev_*> functions), with manual |
3140 | To include only the libev core (all the C<ev_*> functions), with manual |
2740 | configuration (no autoconf): |
3141 | configuration (no autoconf): |
2741 | |
3142 | |
2742 | #define EV_STANDALONE 1 |
3143 | #define EV_STANDALONE 1 |
2743 | #include "ev.c" |
3144 | #include "ev.c" |
2744 | |
3145 | |
2745 | This will automatically include F<ev.h>, too, and should be done in a |
3146 | This will automatically include F<ev.h>, too, and should be done in a |
2746 | single C source file only to provide the function implementations. To use |
3147 | single C source file only to provide the function implementations. To use |
2747 | it, do the same for F<ev.h> in all files wishing to use this API (best |
3148 | it, do the same for F<ev.h> in all files wishing to use this API (best |
2748 | done by writing a wrapper around F<ev.h> that you can include instead and |
3149 | done by writing a wrapper around F<ev.h> that you can include instead and |
2749 | where you can put other configuration options): |
3150 | where you can put other configuration options): |
2750 | |
3151 | |
2751 | #define EV_STANDALONE 1 |
3152 | #define EV_STANDALONE 1 |
2752 | #include "ev.h" |
3153 | #include "ev.h" |
2753 | |
3154 | |
2754 | Both header files and implementation files can be compiled with a C++ |
3155 | Both header files and implementation files can be compiled with a C++ |
2755 | compiler (at least, thats a stated goal, and breakage will be treated |
3156 | compiler (at least, that's a stated goal, and breakage will be treated |
2756 | as a bug). |
3157 | as a bug). |
2757 | |
3158 | |
2758 | You need the following files in your source tree, or in a directory |
3159 | You need the following files in your source tree, or in a directory |
2759 | in your include path (e.g. in libev/ when using -Ilibev): |
3160 | in your include path (e.g. in libev/ when using -Ilibev): |
2760 | |
3161 | |
2761 | ev.h |
3162 | ev.h |
2762 | ev.c |
3163 | ev.c |
2763 | ev_vars.h |
3164 | ev_vars.h |
2764 | ev_wrap.h |
3165 | ev_wrap.h |
2765 | |
3166 | |
2766 | ev_win32.c required on win32 platforms only |
3167 | ev_win32.c required on win32 platforms only |
2767 | |
3168 | |
2768 | ev_select.c only when select backend is enabled (which is enabled by default) |
3169 | ev_select.c only when select backend is enabled (which is enabled by default) |
2769 | ev_poll.c only when poll backend is enabled (disabled by default) |
3170 | ev_poll.c only when poll backend is enabled (disabled by default) |
2770 | ev_epoll.c only when the epoll backend is enabled (disabled by default) |
3171 | ev_epoll.c only when the epoll backend is enabled (disabled by default) |
2771 | ev_kqueue.c only when the kqueue backend is enabled (disabled by default) |
3172 | ev_kqueue.c only when the kqueue backend is enabled (disabled by default) |
2772 | ev_port.c only when the solaris port backend is enabled (disabled by default) |
3173 | ev_port.c only when the solaris port backend is enabled (disabled by default) |
2773 | |
3174 | |
2774 | F<ev.c> includes the backend files directly when enabled, so you only need |
3175 | F<ev.c> includes the backend files directly when enabled, so you only need |
2775 | to compile this single file. |
3176 | to compile this single file. |
2776 | |
3177 | |
2777 | =head3 LIBEVENT COMPATIBILITY API |
3178 | =head3 LIBEVENT COMPATIBILITY API |
2778 | |
3179 | |
2779 | To include the libevent compatibility API, also include: |
3180 | To include the libevent compatibility API, also include: |
2780 | |
3181 | |
2781 | #include "event.c" |
3182 | #include "event.c" |
2782 | |
3183 | |
2783 | in the file including F<ev.c>, and: |
3184 | in the file including F<ev.c>, and: |
2784 | |
3185 | |
2785 | #include "event.h" |
3186 | #include "event.h" |
2786 | |
3187 | |
2787 | in the files that want to use the libevent API. This also includes F<ev.h>. |
3188 | in the files that want to use the libevent API. This also includes F<ev.h>. |
2788 | |
3189 | |
2789 | You need the following additional files for this: |
3190 | You need the following additional files for this: |
2790 | |
3191 | |
2791 | event.h |
3192 | event.h |
2792 | event.c |
3193 | event.c |
2793 | |
3194 | |
2794 | =head3 AUTOCONF SUPPORT |
3195 | =head3 AUTOCONF SUPPORT |
2795 | |
3196 | |
2796 | Instead of using C<EV_STANDALONE=1> and providing your configuration in |
3197 | Instead of using C<EV_STANDALONE=1> and providing your configuration in |
2797 | whatever way you want, you can also C<m4_include([libev.m4])> in your |
3198 | whatever way you want, you can also C<m4_include([libev.m4])> in your |
2798 | F<configure.ac> and leave C<EV_STANDALONE> undefined. F<ev.c> will then |
3199 | F<configure.ac> and leave C<EV_STANDALONE> undefined. F<ev.c> will then |
2799 | include F<config.h> and configure itself accordingly. |
3200 | include F<config.h> and configure itself accordingly. |
2800 | |
3201 | |
2801 | For this of course you need the m4 file: |
3202 | For this of course you need the m4 file: |
2802 | |
3203 | |
2803 | libev.m4 |
3204 | libev.m4 |
2804 | |
3205 | |
2805 | =head2 PREPROCESSOR SYMBOLS/MACROS |
3206 | =head2 PREPROCESSOR SYMBOLS/MACROS |
2806 | |
3207 | |
2807 | Libev can be configured via a variety of preprocessor symbols you have to |
3208 | Libev can be configured via a variety of preprocessor symbols you have to |
2808 | define before including any of its files. The default in the absence of |
3209 | define before including any of its files. The default in the absence of |
2809 | autoconf is noted for every option. |
3210 | autoconf is documented for every option. |
2810 | |
3211 | |
2811 | =over 4 |
3212 | =over 4 |
2812 | |
3213 | |
2813 | =item EV_STANDALONE |
3214 | =item EV_STANDALONE |
2814 | |
3215 | |
… | |
… | |
2816 | keeps libev from including F<config.h>, and it also defines dummy |
3217 | keeps libev from including F<config.h>, and it also defines dummy |
2817 | implementations for some libevent functions (such as logging, which is not |
3218 | implementations for some libevent functions (such as logging, which is not |
2818 | supported). It will also not define any of the structs usually found in |
3219 | supported). It will also not define any of the structs usually found in |
2819 | F<event.h> that are not directly supported by the libev core alone. |
3220 | F<event.h> that are not directly supported by the libev core alone. |
2820 | |
3221 | |
|
|
3222 | In stanbdalone mode, libev will still try to automatically deduce the |
|
|
3223 | configuration, but has to be more conservative. |
|
|
3224 | |
2821 | =item EV_USE_MONOTONIC |
3225 | =item EV_USE_MONOTONIC |
2822 | |
3226 | |
2823 | If defined to be C<1>, libev will try to detect the availability of the |
3227 | If defined to be C<1>, libev will try to detect the availability of the |
2824 | monotonic clock option at both compile time and runtime. Otherwise no use |
3228 | monotonic clock option at both compile time and runtime. Otherwise no |
2825 | of the monotonic clock option will be attempted. If you enable this, you |
3229 | use of the monotonic clock option will be attempted. If you enable this, |
2826 | usually have to link against librt or something similar. Enabling it when |
3230 | you usually have to link against librt or something similar. Enabling it |
2827 | the functionality isn't available is safe, though, although you have |
3231 | when the functionality isn't available is safe, though, although you have |
2828 | to make sure you link against any libraries where the C<clock_gettime> |
3232 | to make sure you link against any libraries where the C<clock_gettime> |
2829 | function is hiding in (often F<-lrt>). |
3233 | function is hiding in (often F<-lrt>). See also C<EV_USE_CLOCK_SYSCALL>. |
2830 | |
3234 | |
2831 | =item EV_USE_REALTIME |
3235 | =item EV_USE_REALTIME |
2832 | |
3236 | |
2833 | If defined to be C<1>, libev will try to detect the availability of the |
3237 | If defined to be C<1>, libev will try to detect the availability of the |
2834 | real-time clock option at compile time (and assume its availability at |
3238 | real-time clock option at compile time (and assume its availability at |
2835 | runtime if successful). Otherwise no use of the real-time clock option will |
3239 | runtime if successful). Otherwise no use of the real-time clock option will |
2836 | be attempted. This effectively replaces C<gettimeofday> by C<clock_get |
3240 | be attempted. This effectively replaces C<gettimeofday> by C<clock_get |
2837 | (CLOCK_REALTIME, ...)> and will not normally affect correctness. See the |
3241 | (CLOCK_REALTIME, ...)> and will not normally affect correctness. See the |
2838 | note about libraries in the description of C<EV_USE_MONOTONIC>, though. |
3242 | note about libraries in the description of C<EV_USE_MONOTONIC>, though. |
2839 | |
3243 | |
|
|
3244 | =item EV_USE_CLOCK_SYSCALL |
|
|
3245 | |
|
|
3246 | If defined to be C<1>, libev will try to use a direct syscall instead |
|
|
3247 | of calling the system-provided C<clock_gettime> function. This option |
|
|
3248 | exists because on GNU/Linux, C<clock_gettime> is in C<librt>, but C<librt> |
|
|
3249 | unconditionally pulls in C<libpthread>, slowing down single-threaded |
|
|
3250 | programs needlessly. Using a direct syscall is slightly slower (in |
|
|
3251 | theory), because no optimised vdso implementation can be used, but avoids |
|
|
3252 | the pthread dependency. Defaults to C<1> on GNU/Linux with glibc 2.x or |
|
|
3253 | higher, as it simplifies linking (no need for C<-lrt>). |
|
|
3254 | |
2840 | =item EV_USE_NANOSLEEP |
3255 | =item EV_USE_NANOSLEEP |
2841 | |
3256 | |
2842 | If defined to be C<1>, libev will assume that C<nanosleep ()> is available |
3257 | If defined to be C<1>, libev will assume that C<nanosleep ()> is available |
2843 | and will use it for delays. Otherwise it will use C<select ()>. |
3258 | and will use it for delays. Otherwise it will use C<select ()>. |
2844 | |
3259 | |
… | |
… | |
2859 | |
3274 | |
2860 | =item EV_SELECT_USE_FD_SET |
3275 | =item EV_SELECT_USE_FD_SET |
2861 | |
3276 | |
2862 | If defined to C<1>, then the select backend will use the system C<fd_set> |
3277 | If defined to C<1>, then the select backend will use the system C<fd_set> |
2863 | structure. This is useful if libev doesn't compile due to a missing |
3278 | structure. This is useful if libev doesn't compile due to a missing |
2864 | C<NFDBITS> or C<fd_mask> definition or it mis-guesses the bitset layout on |
3279 | C<NFDBITS> or C<fd_mask> definition or it mis-guesses the bitset layout |
2865 | exotic systems. This usually limits the range of file descriptors to some |
3280 | on exotic systems. This usually limits the range of file descriptors to |
2866 | low limit such as 1024 or might have other limitations (winsocket only |
3281 | some low limit such as 1024 or might have other limitations (winsocket |
2867 | allows 64 sockets). The C<FD_SETSIZE> macro, set before compilation, might |
3282 | only allows 64 sockets). The C<FD_SETSIZE> macro, set before compilation, |
2868 | influence the size of the C<fd_set> used. |
3283 | configures the maximum size of the C<fd_set>. |
2869 | |
3284 | |
2870 | =item EV_SELECT_IS_WINSOCKET |
3285 | =item EV_SELECT_IS_WINSOCKET |
2871 | |
3286 | |
2872 | When defined to C<1>, the select backend will assume that |
3287 | When defined to C<1>, the select backend will assume that |
2873 | select/socket/connect etc. don't understand file descriptors but |
3288 | select/socket/connect etc. don't understand file descriptors but |
… | |
… | |
2984 | When doing priority-based operations, libev usually has to linearly search |
3399 | When doing priority-based operations, libev usually has to linearly search |
2985 | all the priorities, so having many of them (hundreds) uses a lot of space |
3400 | all the priorities, so having many of them (hundreds) uses a lot of space |
2986 | and time, so using the defaults of five priorities (-2 .. +2) is usually |
3401 | and time, so using the defaults of five priorities (-2 .. +2) is usually |
2987 | fine. |
3402 | fine. |
2988 | |
3403 | |
2989 | If your embedding application does not need any priorities, defining these both to |
3404 | If your embedding application does not need any priorities, defining these |
2990 | C<0> will save some memory and CPU. |
3405 | both to C<0> will save some memory and CPU. |
2991 | |
3406 | |
2992 | =item EV_PERIODIC_ENABLE |
3407 | =item EV_PERIODIC_ENABLE |
2993 | |
3408 | |
2994 | If undefined or defined to be C<1>, then periodic timers are supported. If |
3409 | If undefined or defined to be C<1>, then periodic timers are supported. If |
2995 | defined to be C<0>, then they are not. Disabling them saves a few kB of |
3410 | defined to be C<0>, then they are not. Disabling them saves a few kB of |
… | |
… | |
3002 | code. |
3417 | code. |
3003 | |
3418 | |
3004 | =item EV_EMBED_ENABLE |
3419 | =item EV_EMBED_ENABLE |
3005 | |
3420 | |
3006 | If undefined or defined to be C<1>, then embed watchers are supported. If |
3421 | If undefined or defined to be C<1>, then embed watchers are supported. If |
3007 | defined to be C<0>, then they are not. |
3422 | defined to be C<0>, then they are not. Embed watchers rely on most other |
|
|
3423 | watcher types, which therefore must not be disabled. |
3008 | |
3424 | |
3009 | =item EV_STAT_ENABLE |
3425 | =item EV_STAT_ENABLE |
3010 | |
3426 | |
3011 | If undefined or defined to be C<1>, then stat watchers are supported. If |
3427 | If undefined or defined to be C<1>, then stat watchers are supported. If |
3012 | defined to be C<0>, then they are not. |
3428 | defined to be C<0>, then they are not. |
… | |
… | |
3044 | two). |
3460 | two). |
3045 | |
3461 | |
3046 | =item EV_USE_4HEAP |
3462 | =item EV_USE_4HEAP |
3047 | |
3463 | |
3048 | Heaps are not very cache-efficient. To improve the cache-efficiency of the |
3464 | Heaps are not very cache-efficient. To improve the cache-efficiency of the |
3049 | timer and periodics heap, libev uses a 4-heap when this symbol is defined |
3465 | timer and periodics heaps, libev uses a 4-heap when this symbol is defined |
3050 | to C<1>. The 4-heap uses more complicated (longer) code but has |
3466 | to C<1>. The 4-heap uses more complicated (longer) code but has noticeably |
3051 | noticeably faster performance with many (thousands) of watchers. |
3467 | faster performance with many (thousands) of watchers. |
3052 | |
3468 | |
3053 | The default is C<1> unless C<EV_MINIMAL> is set in which case it is C<0> |
3469 | The default is C<1> unless C<EV_MINIMAL> is set in which case it is C<0> |
3054 | (disabled). |
3470 | (disabled). |
3055 | |
3471 | |
3056 | =item EV_HEAP_CACHE_AT |
3472 | =item EV_HEAP_CACHE_AT |
3057 | |
3473 | |
3058 | Heaps are not very cache-efficient. To improve the cache-efficiency of the |
3474 | Heaps are not very cache-efficient. To improve the cache-efficiency of the |
3059 | timer and periodics heap, libev can cache the timestamp (I<at>) within |
3475 | timer and periodics heaps, libev can cache the timestamp (I<at>) within |
3060 | the heap structure (selected by defining C<EV_HEAP_CACHE_AT> to C<1>), |
3476 | the heap structure (selected by defining C<EV_HEAP_CACHE_AT> to C<1>), |
3061 | which uses 8-12 bytes more per watcher and a few hundred bytes more code, |
3477 | which uses 8-12 bytes more per watcher and a few hundred bytes more code, |
3062 | but avoids random read accesses on heap changes. This improves performance |
3478 | but avoids random read accesses on heap changes. This improves performance |
3063 | noticeably with with many (hundreds) of watchers. |
3479 | noticeably with many (hundreds) of watchers. |
3064 | |
3480 | |
3065 | The default is C<1> unless C<EV_MINIMAL> is set in which case it is C<0> |
3481 | The default is C<1> unless C<EV_MINIMAL> is set in which case it is C<0> |
3066 | (disabled). |
3482 | (disabled). |
3067 | |
3483 | |
3068 | =item EV_VERIFY |
3484 | =item EV_VERIFY |
… | |
… | |
3074 | called once per loop, which can slow down libev. If set to C<3>, then the |
3490 | called once per loop, which can slow down libev. If set to C<3>, then the |
3075 | verification code will be called very frequently, which will slow down |
3491 | verification code will be called very frequently, which will slow down |
3076 | libev considerably. |
3492 | libev considerably. |
3077 | |
3493 | |
3078 | The default is C<1>, unless C<EV_MINIMAL> is set, in which case it will be |
3494 | The default is C<1>, unless C<EV_MINIMAL> is set, in which case it will be |
3079 | C<0.> |
3495 | C<0>. |
3080 | |
3496 | |
3081 | =item EV_COMMON |
3497 | =item EV_COMMON |
3082 | |
3498 | |
3083 | By default, all watchers have a C<void *data> member. By redefining |
3499 | By default, all watchers have a C<void *data> member. By redefining |
3084 | this macro to a something else you can include more and other types of |
3500 | this macro to a something else you can include more and other types of |
3085 | members. You have to define it each time you include one of the files, |
3501 | members. You have to define it each time you include one of the files, |
3086 | though, and it must be identical each time. |
3502 | though, and it must be identical each time. |
3087 | |
3503 | |
3088 | For example, the perl EV module uses something like this: |
3504 | For example, the perl EV module uses something like this: |
3089 | |
3505 | |
3090 | #define EV_COMMON \ |
3506 | #define EV_COMMON \ |
3091 | SV *self; /* contains this struct */ \ |
3507 | SV *self; /* contains this struct */ \ |
3092 | SV *cb_sv, *fh /* note no trailing ";" */ |
3508 | SV *cb_sv, *fh /* note no trailing ";" */ |
3093 | |
3509 | |
3094 | =item EV_CB_DECLARE (type) |
3510 | =item EV_CB_DECLARE (type) |
3095 | |
3511 | |
3096 | =item EV_CB_INVOKE (watcher, revents) |
3512 | =item EV_CB_INVOKE (watcher, revents) |
3097 | |
3513 | |
… | |
… | |
3102 | definition and a statement, respectively. See the F<ev.h> header file for |
3518 | definition and a statement, respectively. See the F<ev.h> header file for |
3103 | their default definitions. One possible use for overriding these is to |
3519 | their default definitions. One possible use for overriding these is to |
3104 | avoid the C<struct ev_loop *> as first argument in all cases, or to use |
3520 | avoid the C<struct ev_loop *> as first argument in all cases, or to use |
3105 | method calls instead of plain function calls in C++. |
3521 | method calls instead of plain function calls in C++. |
3106 | |
3522 | |
|
|
3523 | =back |
|
|
3524 | |
3107 | =head2 EXPORTED API SYMBOLS |
3525 | =head2 EXPORTED API SYMBOLS |
3108 | |
3526 | |
3109 | If you need to re-export the API (e.g. via a DLL) and you need a list of |
3527 | If you need to re-export the API (e.g. via a DLL) and you need a list of |
3110 | exported symbols, you can use the provided F<Symbol.*> files which list |
3528 | exported symbols, you can use the provided F<Symbol.*> files which list |
3111 | all public symbols, one per line: |
3529 | all public symbols, one per line: |
3112 | |
3530 | |
3113 | Symbols.ev for libev proper |
3531 | Symbols.ev for libev proper |
3114 | Symbols.event for the libevent emulation |
3532 | Symbols.event for the libevent emulation |
3115 | |
3533 | |
3116 | This can also be used to rename all public symbols to avoid clashes with |
3534 | This can also be used to rename all public symbols to avoid clashes with |
3117 | multiple versions of libev linked together (which is obviously bad in |
3535 | multiple versions of libev linked together (which is obviously bad in |
3118 | itself, but sometimes it is inconvenient to avoid this). |
3536 | itself, but sometimes it is inconvenient to avoid this). |
3119 | |
3537 | |
… | |
… | |
3140 | file. |
3558 | file. |
3141 | |
3559 | |
3142 | The usage in rxvt-unicode is simpler. It has a F<ev_cpp.h> header file |
3560 | The usage in rxvt-unicode is simpler. It has a F<ev_cpp.h> header file |
3143 | that everybody includes and which overrides some configure choices: |
3561 | that everybody includes and which overrides some configure choices: |
3144 | |
3562 | |
3145 | #define EV_MINIMAL 1 |
3563 | #define EV_MINIMAL 1 |
3146 | #define EV_USE_POLL 0 |
3564 | #define EV_USE_POLL 0 |
3147 | #define EV_MULTIPLICITY 0 |
3565 | #define EV_MULTIPLICITY 0 |
3148 | #define EV_PERIODIC_ENABLE 0 |
3566 | #define EV_PERIODIC_ENABLE 0 |
3149 | #define EV_STAT_ENABLE 0 |
3567 | #define EV_STAT_ENABLE 0 |
3150 | #define EV_FORK_ENABLE 0 |
3568 | #define EV_FORK_ENABLE 0 |
3151 | #define EV_CONFIG_H <config.h> |
3569 | #define EV_CONFIG_H <config.h> |
3152 | #define EV_MINPRI 0 |
3570 | #define EV_MINPRI 0 |
3153 | #define EV_MAXPRI 0 |
3571 | #define EV_MAXPRI 0 |
3154 | |
3572 | |
3155 | #include "ev++.h" |
3573 | #include "ev++.h" |
3156 | |
3574 | |
3157 | And a F<ev_cpp.C> implementation file that contains libev proper and is compiled: |
3575 | And a F<ev_cpp.C> implementation file that contains libev proper and is compiled: |
3158 | |
3576 | |
3159 | #include "ev_cpp.h" |
3577 | #include "ev_cpp.h" |
3160 | #include "ev.c" |
3578 | #include "ev.c" |
3161 | |
3579 | |
|
|
3580 | =head1 INTERACTION WITH OTHER PROGRAMS OR LIBRARIES |
3162 | |
3581 | |
3163 | =head1 THREADS AND COROUTINES |
3582 | =head2 THREADS AND COROUTINES |
3164 | |
3583 | |
3165 | =head2 THREADS |
3584 | =head3 THREADS |
3166 | |
3585 | |
3167 | Libev itself is completely thread-safe, but it uses no locking. This |
3586 | All libev functions are reentrant and thread-safe unless explicitly |
|
|
3587 | documented otherwise, but libev implements no locking itself. This means |
3168 | means that you can use as many loops as you want in parallel, as long as |
3588 | that you can use as many loops as you want in parallel, as long as there |
3169 | only one thread ever calls into one libev function with the same loop |
3589 | are no concurrent calls into any libev function with the same loop |
3170 | parameter. |
3590 | parameter (C<ev_default_*> calls have an implicit default loop parameter, |
|
|
3591 | of course): libev guarantees that different event loops share no data |
|
|
3592 | structures that need any locking. |
3171 | |
3593 | |
3172 | Or put differently: calls with different loop parameters can be done in |
3594 | Or to put it differently: calls with different loop parameters can be done |
3173 | parallel from multiple threads, calls with the same loop parameter must be |
3595 | concurrently from multiple threads, calls with the same loop parameter |
3174 | done serially (but can be done from different threads, as long as only one |
3596 | must be done serially (but can be done from different threads, as long as |
3175 | thread ever is inside a call at any point in time, e.g. by using a mutex |
3597 | only one thread ever is inside a call at any point in time, e.g. by using |
3176 | per loop). |
3598 | a mutex per loop). |
3177 | |
3599 | |
3178 | If you want to know which design is best for your problem, then I cannot |
3600 | Specifically to support threads (and signal handlers), libev implements |
|
|
3601 | so-called C<ev_async> watchers, which allow some limited form of |
|
|
3602 | concurrency on the same event loop, namely waking it up "from the |
|
|
3603 | outside". |
|
|
3604 | |
|
|
3605 | If you want to know which design (one loop, locking, or multiple loops |
|
|
3606 | without or something else still) is best for your problem, then I cannot |
3179 | help you but by giving some generic advice: |
3607 | help you, but here is some generic advice: |
3180 | |
3608 | |
3181 | =over 4 |
3609 | =over 4 |
3182 | |
3610 | |
3183 | =item * most applications have a main thread: use the default libev loop |
3611 | =item * most applications have a main thread: use the default libev loop |
3184 | in that thread, or create a separate thread running only the default loop. |
3612 | in that thread, or create a separate thread running only the default loop. |
… | |
… | |
3196 | |
3624 | |
3197 | Choosing a model is hard - look around, learn, know that usually you can do |
3625 | Choosing a model is hard - look around, learn, know that usually you can do |
3198 | better than you currently do :-) |
3626 | better than you currently do :-) |
3199 | |
3627 | |
3200 | =item * often you need to talk to some other thread which blocks in the |
3628 | =item * often you need to talk to some other thread which blocks in the |
|
|
3629 | event loop. |
|
|
3630 | |
3201 | event loop - C<ev_async> watchers can be used to wake them up from other |
3631 | C<ev_async> watchers can be used to wake them up from other threads safely |
3202 | threads safely (or from signal contexts...). |
3632 | (or from signal contexts...). |
|
|
3633 | |
|
|
3634 | An example use would be to communicate signals or other events that only |
|
|
3635 | work in the default loop by registering the signal watcher with the |
|
|
3636 | default loop and triggering an C<ev_async> watcher from the default loop |
|
|
3637 | watcher callback into the event loop interested in the signal. |
3203 | |
3638 | |
3204 | =back |
3639 | =back |
3205 | |
3640 | |
3206 | =head2 COROUTINES |
3641 | =head3 COROUTINES |
3207 | |
3642 | |
3208 | Libev is much more accommodating to coroutines ("cooperative threads"): |
3643 | Libev is very accommodating to coroutines ("cooperative threads"): |
3209 | libev fully supports nesting calls to it's functions from different |
3644 | libev fully supports nesting calls to its functions from different |
3210 | coroutines (e.g. you can call C<ev_loop> on the same loop from two |
3645 | coroutines (e.g. you can call C<ev_loop> on the same loop from two |
3211 | different coroutines and switch freely between both coroutines running the |
3646 | different coroutines, and switch freely between both coroutines running the |
3212 | loop, as long as you don't confuse yourself). The only exception is that |
3647 | loop, as long as you don't confuse yourself). The only exception is that |
3213 | you must not do this from C<ev_periodic> reschedule callbacks. |
3648 | you must not do this from C<ev_periodic> reschedule callbacks. |
3214 | |
3649 | |
3215 | Care has been invested into making sure that libev does not keep local |
3650 | Care has been taken to ensure that libev does not keep local state inside |
3216 | state inside C<ev_loop>, and other calls do not usually allow coroutine |
3651 | C<ev_loop>, and other calls do not usually allow for coroutine switches as |
3217 | switches. |
3652 | they do not call any callbacks. |
3218 | |
3653 | |
|
|
3654 | =head2 COMPILER WARNINGS |
3219 | |
3655 | |
3220 | =head1 COMPLEXITIES |
3656 | Depending on your compiler and compiler settings, you might get no or a |
|
|
3657 | lot of warnings when compiling libev code. Some people are apparently |
|
|
3658 | scared by this. |
3221 | |
3659 | |
3222 | In this section the complexities of (many of) the algorithms used inside |
3660 | However, these are unavoidable for many reasons. For one, each compiler |
3223 | libev will be explained. For complexity discussions about backends see the |
3661 | has different warnings, and each user has different tastes regarding |
3224 | documentation for C<ev_default_init>. |
3662 | warning options. "Warn-free" code therefore cannot be a goal except when |
|
|
3663 | targeting a specific compiler and compiler-version. |
3225 | |
3664 | |
3226 | All of the following are about amortised time: If an array needs to be |
3665 | Another reason is that some compiler warnings require elaborate |
3227 | extended, libev needs to realloc and move the whole array, but this |
3666 | workarounds, or other changes to the code that make it less clear and less |
3228 | happens asymptotically never with higher number of elements, so O(1) might |
3667 | maintainable. |
3229 | mean it might do a lengthy realloc operation in rare cases, but on average |
|
|
3230 | it is much faster and asymptotically approaches constant time. |
|
|
3231 | |
3668 | |
3232 | =over 4 |
3669 | And of course, some compiler warnings are just plain stupid, or simply |
|
|
3670 | wrong (because they don't actually warn about the condition their message |
|
|
3671 | seems to warn about). For example, certain older gcc versions had some |
|
|
3672 | warnings that resulted an extreme number of false positives. These have |
|
|
3673 | been fixed, but some people still insist on making code warn-free with |
|
|
3674 | such buggy versions. |
3233 | |
3675 | |
3234 | =item Starting and stopping timer/periodic watchers: O(log skipped_other_timers) |
3676 | While libev is written to generate as few warnings as possible, |
|
|
3677 | "warn-free" code is not a goal, and it is recommended not to build libev |
|
|
3678 | with any compiler warnings enabled unless you are prepared to cope with |
|
|
3679 | them (e.g. by ignoring them). Remember that warnings are just that: |
|
|
3680 | warnings, not errors, or proof of bugs. |
3235 | |
3681 | |
3236 | This means that, when you have a watcher that triggers in one hour and |
|
|
3237 | there are 100 watchers that would trigger before that then inserting will |
|
|
3238 | have to skip roughly seven (C<ld 100>) of these watchers. |
|
|
3239 | |
3682 | |
3240 | =item Changing timer/periodic watchers (by autorepeat or calling again): O(log skipped_other_timers) |
3683 | =head2 VALGRIND |
3241 | |
3684 | |
3242 | That means that changing a timer costs less than removing/adding them |
3685 | Valgrind has a special section here because it is a popular tool that is |
3243 | as only the relative motion in the event queue has to be paid for. |
3686 | highly useful. Unfortunately, valgrind reports are very hard to interpret. |
3244 | |
3687 | |
3245 | =item Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1) |
3688 | If you think you found a bug (memory leak, uninitialised data access etc.) |
|
|
3689 | in libev, then check twice: If valgrind reports something like: |
3246 | |
3690 | |
3247 | These just add the watcher into an array or at the head of a list. |
3691 | ==2274== definitely lost: 0 bytes in 0 blocks. |
|
|
3692 | ==2274== possibly lost: 0 bytes in 0 blocks. |
|
|
3693 | ==2274== still reachable: 256 bytes in 1 blocks. |
3248 | |
3694 | |
3249 | =item Stopping check/prepare/idle/fork/async watchers: O(1) |
3695 | Then there is no memory leak, just as memory accounted to global variables |
|
|
3696 | is not a memleak - the memory is still being referenced, and didn't leak. |
3250 | |
3697 | |
3251 | =item Stopping an io/signal/child watcher: O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE)) |
3698 | Similarly, under some circumstances, valgrind might report kernel bugs |
|
|
3699 | as if it were a bug in libev (e.g. in realloc or in the poll backend, |
|
|
3700 | although an acceptable workaround has been found here), or it might be |
|
|
3701 | confused. |
3252 | |
3702 | |
3253 | These watchers are stored in lists then need to be walked to find the |
3703 | Keep in mind that valgrind is a very good tool, but only a tool. Don't |
3254 | correct watcher to remove. The lists are usually short (you don't usually |
3704 | make it into some kind of religion. |
3255 | have many watchers waiting for the same fd or signal). |
|
|
3256 | |
3705 | |
3257 | =item Finding the next timer in each loop iteration: O(1) |
3706 | If you are unsure about something, feel free to contact the mailing list |
|
|
3707 | with the full valgrind report and an explanation on why you think this |
|
|
3708 | is a bug in libev (best check the archives, too :). However, don't be |
|
|
3709 | annoyed when you get a brisk "this is no bug" answer and take the chance |
|
|
3710 | of learning how to interpret valgrind properly. |
3258 | |
3711 | |
3259 | By virtue of using a binary or 4-heap, the next timer is always found at a |
3712 | If you need, for some reason, empty reports from valgrind for your project |
3260 | fixed position in the storage array. |
3713 | I suggest using suppression lists. |
3261 | |
3714 | |
3262 | =item Each change on a file descriptor per loop iteration: O(number_of_watchers_for_this_fd) |
|
|
3263 | |
3715 | |
3264 | A change means an I/O watcher gets started or stopped, which requires |
3716 | =head1 PORTABILITY NOTES |
3265 | libev to recalculate its status (and possibly tell the kernel, depending |
|
|
3266 | on backend and whether C<ev_io_set> was used). |
|
|
3267 | |
3717 | |
3268 | =item Activating one watcher (putting it into the pending state): O(1) |
3718 | =head2 WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS |
3269 | |
|
|
3270 | =item Priority handling: O(number_of_priorities) |
|
|
3271 | |
|
|
3272 | Priorities are implemented by allocating some space for each |
|
|
3273 | priority. When doing priority-based operations, libev usually has to |
|
|
3274 | linearly search all the priorities, but starting/stopping and activating |
|
|
3275 | watchers becomes O(1) w.r.t. priority handling. |
|
|
3276 | |
|
|
3277 | =item Sending an ev_async: O(1) |
|
|
3278 | |
|
|
3279 | =item Processing ev_async_send: O(number_of_async_watchers) |
|
|
3280 | |
|
|
3281 | =item Processing signals: O(max_signal_number) |
|
|
3282 | |
|
|
3283 | Sending involves a system call I<iff> there were no other C<ev_async_send> |
|
|
3284 | calls in the current loop iteration. Checking for async and signal events |
|
|
3285 | involves iterating over all running async watchers or all signal numbers. |
|
|
3286 | |
|
|
3287 | =back |
|
|
3288 | |
|
|
3289 | |
|
|
3290 | =head1 Win32 platform limitations and workarounds |
|
|
3291 | |
3719 | |
3292 | Win32 doesn't support any of the standards (e.g. POSIX) that libev |
3720 | Win32 doesn't support any of the standards (e.g. POSIX) that libev |
3293 | requires, and its I/O model is fundamentally incompatible with the POSIX |
3721 | requires, and its I/O model is fundamentally incompatible with the POSIX |
3294 | model. Libev still offers limited functionality on this platform in |
3722 | model. Libev still offers limited functionality on this platform in |
3295 | the form of the C<EVBACKEND_SELECT> backend, and only supports socket |
3723 | the form of the C<EVBACKEND_SELECT> backend, and only supports socket |
… | |
… | |
3306 | |
3734 | |
3307 | Not a libev limitation but worth mentioning: windows apparently doesn't |
3735 | Not a libev limitation but worth mentioning: windows apparently doesn't |
3308 | accept large writes: instead of resulting in a partial write, windows will |
3736 | accept large writes: instead of resulting in a partial write, windows will |
3309 | either accept everything or return C<ENOBUFS> if the buffer is too large, |
3737 | either accept everything or return C<ENOBUFS> if the buffer is too large, |
3310 | so make sure you only write small amounts into your sockets (less than a |
3738 | so make sure you only write small amounts into your sockets (less than a |
3311 | megabyte seems safe, but thsi apparently depends on the amount of memory |
3739 | megabyte seems safe, but this apparently depends on the amount of memory |
3312 | available). |
3740 | available). |
3313 | |
3741 | |
3314 | Due to the many, low, and arbitrary limits on the win32 platform and |
3742 | Due to the many, low, and arbitrary limits on the win32 platform and |
3315 | the abysmal performance of winsockets, using a large number of sockets |
3743 | the abysmal performance of winsockets, using a large number of sockets |
3316 | is not recommended (and not reasonable). If your program needs to use |
3744 | is not recommended (and not reasonable). If your program needs to use |
3317 | more than a hundred or so sockets, then likely it needs to use a totally |
3745 | more than a hundred or so sockets, then likely it needs to use a totally |
3318 | different implementation for windows, as libev offers the POSIX readiness |
3746 | different implementation for windows, as libev offers the POSIX readiness |
3319 | notification model, which cannot be implemented efficiently on windows |
3747 | notification model, which cannot be implemented efficiently on windows |
3320 | (Microsoft monopoly games). |
3748 | (Microsoft monopoly games). |
3321 | |
3749 | |
|
|
3750 | A typical way to use libev under windows is to embed it (see the embedding |
|
|
3751 | section for details) and use the following F<evwrap.h> header file instead |
|
|
3752 | of F<ev.h>: |
|
|
3753 | |
|
|
3754 | #define EV_STANDALONE /* keeps ev from requiring config.h */ |
|
|
3755 | #define EV_SELECT_IS_WINSOCKET 1 /* configure libev for windows select */ |
|
|
3756 | |
|
|
3757 | #include "ev.h" |
|
|
3758 | |
|
|
3759 | And compile the following F<evwrap.c> file into your project (make sure |
|
|
3760 | you do I<not> compile the F<ev.c> or any other embedded source files!): |
|
|
3761 | |
|
|
3762 | #include "evwrap.h" |
|
|
3763 | #include "ev.c" |
|
|
3764 | |
3322 | =over 4 |
3765 | =over 4 |
3323 | |
3766 | |
3324 | =item The winsocket select function |
3767 | =item The winsocket select function |
3325 | |
3768 | |
3326 | The winsocket C<select> function doesn't follow POSIX in that it |
3769 | The winsocket C<select> function doesn't follow POSIX in that it |
3327 | requires socket I<handles> and not socket I<file descriptors> (it is |
3770 | requires socket I<handles> and not socket I<file descriptors> (it is |
3328 | also extremely buggy). This makes select very inefficient, and also |
3771 | also extremely buggy). This makes select very inefficient, and also |
3329 | requires a mapping from file descriptors to socket handles. See the |
3772 | requires a mapping from file descriptors to socket handles (the Microsoft |
|
|
3773 | C runtime provides the function C<_open_osfhandle> for this). See the |
3330 | discussion of the C<EV_SELECT_USE_FD_SET>, C<EV_SELECT_IS_WINSOCKET> and |
3774 | discussion of the C<EV_SELECT_USE_FD_SET>, C<EV_SELECT_IS_WINSOCKET> and |
3331 | C<EV_FD_TO_WIN32_HANDLE> preprocessor symbols for more info. |
3775 | C<EV_FD_TO_WIN32_HANDLE> preprocessor symbols for more info. |
3332 | |
3776 | |
3333 | The configuration for a "naked" win32 using the Microsoft runtime |
3777 | The configuration for a "naked" win32 using the Microsoft runtime |
3334 | libraries and raw winsocket select is: |
3778 | libraries and raw winsocket select is: |
3335 | |
3779 | |
3336 | #define EV_USE_SELECT 1 |
3780 | #define EV_USE_SELECT 1 |
3337 | #define EV_SELECT_IS_WINSOCKET 1 /* forces EV_SELECT_USE_FD_SET, too */ |
3781 | #define EV_SELECT_IS_WINSOCKET 1 /* forces EV_SELECT_USE_FD_SET, too */ |
3338 | |
3782 | |
3339 | Note that winsockets handling of fd sets is O(n), so you can easily get a |
3783 | Note that winsockets handling of fd sets is O(n), so you can easily get a |
3340 | complexity in the O(n²) range when using win32. |
3784 | complexity in the O(n²) range when using win32. |
3341 | |
3785 | |
3342 | =item Limited number of file descriptors |
3786 | =item Limited number of file descriptors |
… | |
… | |
3366 | wrap all I/O functions and provide your own fd management, but the cost of |
3810 | wrap all I/O functions and provide your own fd management, but the cost of |
3367 | calling select (O(n²)) will likely make this unworkable. |
3811 | calling select (O(n²)) will likely make this unworkable. |
3368 | |
3812 | |
3369 | =back |
3813 | =back |
3370 | |
3814 | |
3371 | |
|
|
3372 | =head1 PORTABILITY REQUIREMENTS |
3815 | =head2 PORTABILITY REQUIREMENTS |
3373 | |
3816 | |
3374 | In addition to a working ISO-C implementation, libev relies on a few |
3817 | In addition to a working ISO-C implementation and of course the |
3375 | additional extensions: |
3818 | backend-specific APIs, libev relies on a few additional extensions: |
3376 | |
3819 | |
3377 | =over 4 |
3820 | =over 4 |
3378 | |
3821 | |
|
|
3822 | =item C<void (*)(ev_watcher_type *, int revents)> must have compatible |
|
|
3823 | calling conventions regardless of C<ev_watcher_type *>. |
|
|
3824 | |
|
|
3825 | Libev assumes not only that all watcher pointers have the same internal |
|
|
3826 | structure (guaranteed by POSIX but not by ISO C for example), but it also |
|
|
3827 | assumes that the same (machine) code can be used to call any watcher |
|
|
3828 | callback: The watcher callbacks have different type signatures, but libev |
|
|
3829 | calls them using an C<ev_watcher *> internally. |
|
|
3830 | |
3379 | =item C<sig_atomic_t volatile> must be thread-atomic as well |
3831 | =item C<sig_atomic_t volatile> must be thread-atomic as well |
3380 | |
3832 | |
3381 | The type C<sig_atomic_t volatile> (or whatever is defined as |
3833 | The type C<sig_atomic_t volatile> (or whatever is defined as |
3382 | C<EV_ATOMIC_T>) must be atomic w.r.t. accesses from different |
3834 | C<EV_ATOMIC_T>) must be atomic with respect to accesses from different |
3383 | threads. This is not part of the specification for C<sig_atomic_t>, but is |
3835 | threads. This is not part of the specification for C<sig_atomic_t>, but is |
3384 | believed to be sufficiently portable. |
3836 | believed to be sufficiently portable. |
3385 | |
3837 | |
3386 | =item C<sigprocmask> must work in a threaded environment |
3838 | =item C<sigprocmask> must work in a threaded environment |
3387 | |
3839 | |
… | |
… | |
3396 | except the initial one, and run the default loop in the initial thread as |
3848 | except the initial one, and run the default loop in the initial thread as |
3397 | well. |
3849 | well. |
3398 | |
3850 | |
3399 | =item C<long> must be large enough for common memory allocation sizes |
3851 | =item C<long> must be large enough for common memory allocation sizes |
3400 | |
3852 | |
3401 | To improve portability and simplify using libev, libev uses C<long> |
3853 | To improve portability and simplify its API, libev uses C<long> internally |
3402 | internally instead of C<size_t> when allocating its data structures. On |
3854 | instead of C<size_t> when allocating its data structures. On non-POSIX |
3403 | non-POSIX systems (Microsoft...) this might be unexpectedly low, but |
3855 | systems (Microsoft...) this might be unexpectedly low, but is still at |
3404 | is still at least 31 bits everywhere, which is enough for hundreds of |
3856 | least 31 bits everywhere, which is enough for hundreds of millions of |
3405 | millions of watchers. |
3857 | watchers. |
3406 | |
3858 | |
3407 | =item C<double> must hold a time value in seconds with enough accuracy |
3859 | =item C<double> must hold a time value in seconds with enough accuracy |
3408 | |
3860 | |
3409 | The type C<double> is used to represent timestamps. It is required to |
3861 | The type C<double> is used to represent timestamps. It is required to |
3410 | have at least 51 bits of mantissa (and 9 bits of exponent), which is good |
3862 | have at least 51 bits of mantissa (and 9 bits of exponent), which is good |
… | |
… | |
3414 | =back |
3866 | =back |
3415 | |
3867 | |
3416 | If you know of other additional requirements drop me a note. |
3868 | If you know of other additional requirements drop me a note. |
3417 | |
3869 | |
3418 | |
3870 | |
3419 | =head1 COMPILER WARNINGS |
3871 | =head1 ALGORITHMIC COMPLEXITIES |
3420 | |
3872 | |
3421 | Depending on your compiler and compiler settings, you might get no or a |
3873 | In this section the complexities of (many of) the algorithms used inside |
3422 | lot of warnings when compiling libev code. Some people are apparently |
3874 | libev will be documented. For complexity discussions about backends see |
3423 | scared by this. |
3875 | the documentation for C<ev_default_init>. |
3424 | |
3876 | |
3425 | However, these are unavoidable for many reasons. For one, each compiler |
3877 | All of the following are about amortised time: If an array needs to be |
3426 | has different warnings, and each user has different tastes regarding |
3878 | extended, libev needs to realloc and move the whole array, but this |
3427 | warning options. "Warn-free" code therefore cannot be a goal except when |
3879 | happens asymptotically rarer with higher number of elements, so O(1) might |
3428 | targeting a specific compiler and compiler-version. |
3880 | mean that libev does a lengthy realloc operation in rare cases, but on |
|
|
3881 | average it is much faster and asymptotically approaches constant time. |
3429 | |
3882 | |
3430 | Another reason is that some compiler warnings require elaborate |
3883 | =over 4 |
3431 | workarounds, or other changes to the code that make it less clear and less |
|
|
3432 | maintainable. |
|
|
3433 | |
3884 | |
3434 | And of course, some compiler warnings are just plain stupid, or simply |
3885 | =item Starting and stopping timer/periodic watchers: O(log skipped_other_timers) |
3435 | wrong (because they don't actually warn about the condition their message |
|
|
3436 | seems to warn about). |
|
|
3437 | |
3886 | |
3438 | While libev is written to generate as few warnings as possible, |
3887 | This means that, when you have a watcher that triggers in one hour and |
3439 | "warn-free" code is not a goal, and it is recommended not to build libev |
3888 | there are 100 watchers that would trigger before that, then inserting will |
3440 | with any compiler warnings enabled unless you are prepared to cope with |
3889 | have to skip roughly seven (C<ld 100>) of these watchers. |
3441 | them (e.g. by ignoring them). Remember that warnings are just that: |
|
|
3442 | warnings, not errors, or proof of bugs. |
|
|
3443 | |
3890 | |
|
|
3891 | =item Changing timer/periodic watchers (by autorepeat or calling again): O(log skipped_other_timers) |
3444 | |
3892 | |
3445 | =head1 VALGRIND |
3893 | That means that changing a timer costs less than removing/adding them, |
|
|
3894 | as only the relative motion in the event queue has to be paid for. |
3446 | |
3895 | |
3447 | Valgrind has a special section here because it is a popular tool that is |
3896 | =item Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1) |
3448 | highly useful, but valgrind reports are very hard to interpret. |
|
|
3449 | |
3897 | |
3450 | If you think you found a bug (memory leak, uninitialised data access etc.) |
3898 | These just add the watcher into an array or at the head of a list. |
3451 | in libev, then check twice: If valgrind reports something like: |
|
|
3452 | |
3899 | |
3453 | ==2274== definitely lost: 0 bytes in 0 blocks. |
3900 | =item Stopping check/prepare/idle/fork/async watchers: O(1) |
3454 | ==2274== possibly lost: 0 bytes in 0 blocks. |
|
|
3455 | ==2274== still reachable: 256 bytes in 1 blocks. |
|
|
3456 | |
3901 | |
3457 | Then there is no memory leak. Similarly, under some circumstances, |
3902 | =item Stopping an io/signal/child watcher: O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE)) |
3458 | valgrind might report kernel bugs as if it were a bug in libev, or it |
|
|
3459 | might be confused (it is a very good tool, but only a tool). |
|
|
3460 | |
3903 | |
3461 | If you are unsure about something, feel free to contact the mailing list |
3904 | These watchers are stored in lists, so they need to be walked to find the |
3462 | with the full valgrind report and an explanation on why you think this is |
3905 | correct watcher to remove. The lists are usually short (you don't usually |
3463 | a bug in libev. However, don't be annoyed when you get a brisk "this is |
3906 | have many watchers waiting for the same fd or signal: one is typical, two |
3464 | no bug" answer and take the chance of learning how to interpret valgrind |
3907 | is rare). |
3465 | properly. |
|
|
3466 | |
3908 | |
3467 | If you need, for some reason, empty reports from valgrind for your project |
3909 | =item Finding the next timer in each loop iteration: O(1) |
3468 | I suggest using suppression lists. |
3910 | |
|
|
3911 | By virtue of using a binary or 4-heap, the next timer is always found at a |
|
|
3912 | fixed position in the storage array. |
|
|
3913 | |
|
|
3914 | =item Each change on a file descriptor per loop iteration: O(number_of_watchers_for_this_fd) |
|
|
3915 | |
|
|
3916 | A change means an I/O watcher gets started or stopped, which requires |
|
|
3917 | libev to recalculate its status (and possibly tell the kernel, depending |
|
|
3918 | on backend and whether C<ev_io_set> was used). |
|
|
3919 | |
|
|
3920 | =item Activating one watcher (putting it into the pending state): O(1) |
|
|
3921 | |
|
|
3922 | =item Priority handling: O(number_of_priorities) |
|
|
3923 | |
|
|
3924 | Priorities are implemented by allocating some space for each |
|
|
3925 | priority. When doing priority-based operations, libev usually has to |
|
|
3926 | linearly search all the priorities, but starting/stopping and activating |
|
|
3927 | watchers becomes O(1) with respect to priority handling. |
|
|
3928 | |
|
|
3929 | =item Sending an ev_async: O(1) |
|
|
3930 | |
|
|
3931 | =item Processing ev_async_send: O(number_of_async_watchers) |
|
|
3932 | |
|
|
3933 | =item Processing signals: O(max_signal_number) |
|
|
3934 | |
|
|
3935 | Sending involves a system call I<iff> there were no other C<ev_async_send> |
|
|
3936 | calls in the current loop iteration. Checking for async and signal events |
|
|
3937 | involves iterating over all running async watchers or all signal numbers. |
|
|
3938 | |
|
|
3939 | =back |
3469 | |
3940 | |
3470 | |
3941 | |
3471 | =head1 AUTHOR |
3942 | =head1 AUTHOR |
3472 | |
3943 | |
3473 | Marc Lehmann <libev@schmorp.de>. |
3944 | Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael Magnusson. |
3474 | |
3945 | |