… | |
… | |
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); |
… | |
… | |
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 | } |
… | |
… | |
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 ABOUT THIS DOCUMENT |
|
|
68 | |
|
|
69 | This document documents the libev software package. |
66 | |
70 | |
67 | The newest version of this document is also available as an html-formatted |
71 | 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 |
72 | web page you might find easier to navigate when reading it for the first |
69 | time: L<http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod>. |
73 | time: L<http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod>. |
|
|
74 | |
|
|
75 | While this document tries to be as complete as possible in documenting |
|
|
76 | libev, its usage and the rationale behind its design, it is not a tutorial |
|
|
77 | on event-based programming, nor will it introduce event-based programming |
|
|
78 | with libev. |
|
|
79 | |
|
|
80 | Familarity with event based programming techniques in general is assumed |
|
|
81 | throughout this document. |
|
|
82 | |
|
|
83 | =head1 ABOUT LIBEV |
70 | |
84 | |
71 | Libev is an event loop: you register interest in certain events (such as a |
85 | Libev is an event loop: you register interest in certain events (such as a |
72 | file descriptor being readable or a timeout occurring), and it will manage |
86 | file descriptor being readable or a timeout occurring), and it will manage |
73 | these event sources and provide your program with events. |
87 | these event sources and provide your program with events. |
74 | |
88 | |
… | |
… | |
103 | Libev is very configurable. In this manual the default (and most common) |
117 | Libev is very configurable. In this manual the default (and most common) |
104 | configuration will be described, which supports multiple event loops. For |
118 | configuration will be described, which supports multiple event loops. For |
105 | more info about various configuration options please have a look at |
119 | more info about various configuration options please have a look at |
106 | B<EMBED> section in this manual. If libev was configured without support |
120 | 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 |
121 | 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 |
122 | name C<loop> (which is always of type C<ev_loop *>) will not have |
109 | this argument. |
123 | this argument. |
110 | |
124 | |
111 | =head2 TIME REPRESENTATION |
125 | =head2 TIME REPRESENTATION |
112 | |
126 | |
113 | Libev represents time as a single floating point number, representing the |
127 | Libev represents time as a single floating point number, representing |
114 | (fractional) number of seconds since the (POSIX) epoch (somewhere near |
128 | the (fractional) number of seconds since the (POSIX) epoch (somewhere |
115 | the beginning of 1970, details are complicated, don't ask). This type is |
129 | near the beginning of 1970, details are complicated, don't ask). This |
116 | called C<ev_tstamp>, which is what you should use too. It usually aliases |
130 | type is called C<ev_tstamp>, which is what you should use too. It usually |
117 | to the C<double> type in C, and when you need to do any calculations on |
131 | aliases to the C<double> type in C. When you need to do any calculations |
118 | it, you should treat it as some floating point value. Unlike the name |
132 | on it, you should treat it as some floating point value. Unlike the name |
119 | component C<stamp> might indicate, it is also used for time differences |
133 | component C<stamp> might indicate, it is also used for time differences |
120 | throughout libev. |
134 | throughout libev. |
121 | |
135 | |
122 | =head1 ERROR HANDLING |
136 | =head1 ERROR HANDLING |
123 | |
137 | |
… | |
… | |
276 | |
290 | |
277 | =back |
291 | =back |
278 | |
292 | |
279 | =head1 FUNCTIONS CONTROLLING THE EVENT LOOP |
293 | =head1 FUNCTIONS CONTROLLING THE EVENT LOOP |
280 | |
294 | |
281 | An event loop is described by a C<struct ev_loop *>. The library knows two |
295 | 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 |
296 | is I<not> optional in this case, as there is also an C<ev_loop> |
283 | events, and dynamically created loops which do not. |
297 | I<function>). |
|
|
298 | |
|
|
299 | The library knows two types of such loops, the I<default> loop, which |
|
|
300 | supports signals and child events, and dynamically created loops which do |
|
|
301 | not. |
284 | |
302 | |
285 | =over 4 |
303 | =over 4 |
286 | |
304 | |
287 | =item struct ev_loop *ev_default_loop (unsigned int flags) |
305 | =item struct ev_loop *ev_default_loop (unsigned int flags) |
288 | |
306 | |
… | |
… | |
294 | If you don't know what event loop to use, use the one returned from this |
312 | If you don't know what event loop to use, use the one returned from this |
295 | function. |
313 | function. |
296 | |
314 | |
297 | Note that this function is I<not> thread-safe, so if you want to use it |
315 | 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, |
316 | from multiple threads, you have to lock (note also that this is unlikely, |
299 | as loops cannot bes hared easily between threads anyway). |
317 | as loops cannot be shared easily between threads anyway). |
300 | |
318 | |
301 | The default loop is the only loop that can handle C<ev_signal> and |
319 | 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 |
320 | 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 |
321 | 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 |
322 | create a dynamic loop with C<ev_loop_new> that doesn't do that, or you |
… | |
… | |
380 | =item C<EVBACKEND_EPOLL> (value 4, Linux) |
398 | =item C<EVBACKEND_EPOLL> (value 4, Linux) |
381 | |
399 | |
382 | For few fds, this backend is a bit little slower than poll and select, |
400 | For few fds, this backend is a bit little slower than poll and select, |
383 | but it scales phenomenally better. While poll and select usually scale |
401 | but it scales phenomenally better. While poll and select usually scale |
384 | like O(total_fds) where n is the total number of fds (or the highest fd), |
402 | like O(total_fds) where n is the total number of fds (or the highest fd), |
385 | epoll scales either O(1) or O(active_fds). The epoll design has a number |
403 | epoll scales either O(1) or O(active_fds). |
386 | of shortcomings, such as silently dropping events in some hard-to-detect |
404 | |
387 | cases and requiring a system call per fd change, no fork support and bad |
405 | The epoll mechanism deserves honorable mention as the most misdesigned |
388 | support for dup. |
406 | of the more advanced event mechanisms: mere annoyances include silently |
|
|
407 | dropping file descriptors, requiring a system call per change per file |
|
|
408 | descriptor (and unnecessary guessing of parameters), problems with dup and |
|
|
409 | so on. The biggest issue is fork races, however - if a program forks then |
|
|
410 | I<both> parent and child process have to recreate the epoll set, which can |
|
|
411 | take considerable time (one syscall per file descriptor) and is of course |
|
|
412 | hard to detect. |
|
|
413 | |
|
|
414 | Epoll is also notoriously buggy - embedding epoll fds I<should> work, but |
|
|
415 | of course I<doesn't>, and epoll just loves to report events for totally |
|
|
416 | I<different> file descriptors (even already closed ones, so one cannot |
|
|
417 | even remove them from the set) than registered in the set (especially |
|
|
418 | on SMP systems). Libev tries to counter these spurious notifications by |
|
|
419 | employing an additional generation counter and comparing that against the |
|
|
420 | events to filter out spurious ones, recreating the set when required. |
389 | |
421 | |
390 | While stopping, setting and starting an I/O watcher in the same iteration |
422 | While stopping, setting and starting an I/O watcher in the same iteration |
391 | will result in some caching, there is still a system call per such incident |
423 | will result in some caching, there is still a system call per such |
392 | (because the fd could point to a different file description now), so its |
424 | incident (because the same I<file descriptor> could point to a different |
393 | best to avoid that. Also, C<dup ()>'ed file descriptors might not work |
425 | I<file description> now), so its best to avoid that. Also, C<dup ()>'ed |
394 | very well if you register events for both fds. |
426 | file descriptors might not work very well if you register events for both |
395 | |
427 | file descriptors. |
396 | Please note that epoll sometimes generates spurious notifications, so you |
|
|
397 | need to use non-blocking I/O or other means to avoid blocking when no data |
|
|
398 | (or space) is available. |
|
|
399 | |
428 | |
400 | Best performance from this backend is achieved by not unregistering all |
429 | Best performance from this backend is achieved by not unregistering all |
401 | watchers for a file descriptor until it has been closed, if possible, |
430 | watchers for a file descriptor until it has been closed, if possible, |
402 | i.e. keep at least one watcher active per fd at all times. Stopping and |
431 | i.e. keep at least one watcher active per fd at all times. Stopping and |
403 | starting a watcher (without re-setting it) also usually doesn't cause |
432 | starting a watcher (without re-setting it) also usually doesn't cause |
404 | extra overhead. |
433 | extra overhead. A fork can both result in spurious notifications as well |
|
|
434 | as in libev having to destroy and recreate the epoll object, which can |
|
|
435 | take considerable time and thus should be avoided. |
|
|
436 | |
|
|
437 | All this means that, in practice, C<EVBACKEND_SELECT> can be as fast or |
|
|
438 | faster than epoll for maybe up to a hundred file descriptors, depending on |
|
|
439 | the usage. So sad. |
405 | |
440 | |
406 | While nominally embeddable in other event loops, this feature is broken in |
441 | While nominally embeddable in other event loops, this feature is broken in |
407 | all kernel versions tested so far. |
442 | all kernel versions tested so far. |
408 | |
443 | |
409 | This backend maps C<EV_READ> and C<EV_WRITE> in the same way as |
444 | This backend maps C<EV_READ> and C<EV_WRITE> in the same way as |
410 | C<EVBACKEND_POLL>. |
445 | C<EVBACKEND_POLL>. |
411 | |
446 | |
412 | =item C<EVBACKEND_KQUEUE> (value 8, most BSD clones) |
447 | =item C<EVBACKEND_KQUEUE> (value 8, most BSD clones) |
413 | |
448 | |
414 | Kqueue deserves special mention, as at the time of this writing, it was |
449 | Kqueue deserves special mention, as at the time of this writing, it |
415 | broken on all BSDs except NetBSD (usually it doesn't work reliably with |
450 | was broken on all BSDs except NetBSD (usually it doesn't work reliably |
416 | anything but sockets and pipes, except on Darwin, where of course it's |
451 | with anything but sockets and pipes, except on Darwin, where of course |
417 | completely useless). For this reason it's not being "auto-detected" unless |
452 | it's completely useless). Unlike epoll, however, whose brokenness |
418 | you explicitly specify it in the flags (i.e. using C<EVBACKEND_KQUEUE>) or |
453 | is by design, these kqueue bugs can (and eventually will) be fixed |
419 | libev was compiled on a known-to-be-good (-enough) system like NetBSD. |
454 | without API changes to existing programs. For this reason it's not being |
|
|
455 | "auto-detected" unless you explicitly specify it in the flags (i.e. using |
|
|
456 | C<EVBACKEND_KQUEUE>) or libev was compiled on a known-to-be-good (-enough) |
|
|
457 | system like NetBSD. |
420 | |
458 | |
421 | You still can embed kqueue into a normal poll or select backend and use it |
459 | You still can embed kqueue into a normal poll or select backend and use it |
422 | only for sockets (after having made sure that sockets work with kqueue on |
460 | only for sockets (after having made sure that sockets work with kqueue on |
423 | the target platform). See C<ev_embed> watchers for more info. |
461 | the target platform). See C<ev_embed> watchers for more info. |
424 | |
462 | |
425 | It scales in the same way as the epoll backend, but the interface to the |
463 | It scales in the same way as the epoll backend, but the interface to the |
426 | kernel is more efficient (which says nothing about its actual speed, of |
464 | kernel is more efficient (which says nothing about its actual speed, of |
427 | course). While stopping, setting and starting an I/O watcher does never |
465 | course). While stopping, setting and starting an I/O watcher does never |
428 | cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to |
466 | cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to |
429 | two event changes per incident. Support for C<fork ()> is very bad and it |
467 | two event changes per incident. Support for C<fork ()> is very bad (but |
430 | drops fds silently in similarly hard-to-detect cases. |
468 | sane, unlike epoll) and it drops fds silently in similarly hard-to-detect |
|
|
469 | cases |
431 | |
470 | |
432 | This backend usually performs well under most conditions. |
471 | This backend usually performs well under most conditions. |
433 | |
472 | |
434 | While nominally embeddable in other event loops, this doesn't work |
473 | While nominally embeddable in other event loops, this doesn't work |
435 | everywhere, so you might need to test for this. And since it is broken |
474 | everywhere, so you might need to test for this. And since it is broken |
436 | almost everywhere, you should only use it when you have a lot of sockets |
475 | almost everywhere, you should only use it when you have a lot of sockets |
437 | (for which it usually works), by embedding it into another event loop |
476 | (for which it usually works), by embedding it into another event loop |
438 | (e.g. C<EVBACKEND_SELECT> or C<EVBACKEND_POLL>) and, did I mention it, |
477 | (e.g. C<EVBACKEND_SELECT> or C<EVBACKEND_POLL> (but C<poll> is of course |
439 | using it only for sockets. |
478 | also broken on OS X)) and, did I mention it, using it only for sockets. |
440 | |
479 | |
441 | This backend maps C<EV_READ> into an C<EVFILT_READ> kevent with |
480 | This backend maps C<EV_READ> into an C<EVFILT_READ> kevent with |
442 | C<NOTE_EOF>, and C<EV_WRITE> into an C<EVFILT_WRITE> kevent with |
481 | C<NOTE_EOF>, and C<EV_WRITE> into an C<EVFILT_WRITE> kevent with |
443 | C<NOTE_EOF>. |
482 | C<NOTE_EOF>. |
444 | |
483 | |
… | |
… | |
464 | might perform better. |
503 | might perform better. |
465 | |
504 | |
466 | On the positive side, with the exception of the spurious readiness |
505 | On the positive side, with the exception of the spurious readiness |
467 | notifications, this backend actually performed fully to specification |
506 | notifications, this backend actually performed fully to specification |
468 | in all tests and is fully embeddable, which is a rare feat among the |
507 | in all tests and is fully embeddable, which is a rare feat among the |
469 | OS-specific backends. |
508 | OS-specific backends (I vastly prefer correctness over speed hacks). |
470 | |
509 | |
471 | This backend maps C<EV_READ> and C<EV_WRITE> in the same way as |
510 | This backend maps C<EV_READ> and C<EV_WRITE> in the same way as |
472 | C<EVBACKEND_POLL>. |
511 | C<EVBACKEND_POLL>. |
473 | |
512 | |
474 | =item C<EVBACKEND_ALL> |
513 | =item C<EVBACKEND_ALL> |
… | |
… | |
527 | responsibility to either stop all watchers cleanly yourself I<before> |
566 | responsibility to either stop all watchers cleanly yourself I<before> |
528 | calling this function, or cope with the fact afterwards (which is usually |
567 | calling this function, or cope with the fact afterwards (which is usually |
529 | the easiest thing, you can just ignore the watchers and/or C<free ()> them |
568 | the easiest thing, you can just ignore the watchers and/or C<free ()> them |
530 | for example). |
569 | for example). |
531 | |
570 | |
532 | Note that certain global state, such as signal state, will not be freed by |
571 | Note that certain global state, such as signal state (and installed signal |
533 | this function, and related watchers (such as signal and child watchers) |
572 | handlers), will not be freed by this function, and related watchers (such |
534 | would need to be stopped manually. |
573 | as signal and child watchers) would need to be stopped manually. |
535 | |
574 | |
536 | In general it is not advisable to call this function except in the |
575 | In general it is not advisable to call this function except in the |
537 | rare occasion where you really need to free e.g. the signal handling |
576 | rare occasion where you really need to free e.g. the signal handling |
538 | pipe fds. If you need dynamically allocated loops it is better to use |
577 | pipe fds. If you need dynamically allocated loops it is better to use |
539 | C<ev_loop_new> and C<ev_loop_destroy>). |
578 | C<ev_loop_new> and C<ev_loop_destroy>). |
… | |
… | |
582 | |
621 | |
583 | This value can sometimes be useful as a generation counter of sorts (it |
622 | This value can sometimes be useful as a generation counter of sorts (it |
584 | "ticks" the number of loop iterations), as it roughly corresponds with |
623 | "ticks" the number of loop iterations), as it roughly corresponds with |
585 | C<ev_prepare> and C<ev_check> calls. |
624 | C<ev_prepare> and C<ev_check> calls. |
586 | |
625 | |
|
|
626 | =item unsigned int ev_loop_depth (loop) |
|
|
627 | |
|
|
628 | Returns the number of times C<ev_loop> was entered minus the number of |
|
|
629 | times C<ev_loop> was exited, in other words, the recursion depth. |
|
|
630 | |
|
|
631 | Outside C<ev_loop>, this number is zero. In a callback, this number is |
|
|
632 | C<1>, unless C<ev_loop> was invoked recursively (or from another thread), |
|
|
633 | in which case it is higher. |
|
|
634 | |
|
|
635 | Leaving C<ev_loop> abnormally (setjmp/longjmp, cancelling the thread |
|
|
636 | etc.), doesn't count as exit. |
|
|
637 | |
587 | =item unsigned int ev_backend (loop) |
638 | =item unsigned int ev_backend (loop) |
588 | |
639 | |
589 | Returns one of the C<EVBACKEND_*> flags indicating the event backend in |
640 | Returns one of the C<EVBACKEND_*> flags indicating the event backend in |
590 | use. |
641 | use. |
591 | |
642 | |
… | |
… | |
605 | |
656 | |
606 | This function is rarely useful, but when some event callback runs for a |
657 | This function is rarely useful, but when some event callback runs for a |
607 | very long time without entering the event loop, updating libev's idea of |
658 | very long time without entering the event loop, updating libev's idea of |
608 | the current time is a good idea. |
659 | the current time is a good idea. |
609 | |
660 | |
610 | See also "The special problem of time updates" in the C<ev_timer> section. |
661 | See also L<The special problem of time updates> in the C<ev_timer> section. |
|
|
662 | |
|
|
663 | =item ev_suspend (loop) |
|
|
664 | |
|
|
665 | =item ev_resume (loop) |
|
|
666 | |
|
|
667 | These two functions suspend and resume a loop, for use when the loop is |
|
|
668 | not used for a while and timeouts should not be processed. |
|
|
669 | |
|
|
670 | A typical use case would be an interactive program such as a game: When |
|
|
671 | the user presses C<^Z> to suspend the game and resumes it an hour later it |
|
|
672 | would be best to handle timeouts as if no time had actually passed while |
|
|
673 | the program was suspended. This can be achieved by calling C<ev_suspend> |
|
|
674 | in your C<SIGTSTP> handler, sending yourself a C<SIGSTOP> and calling |
|
|
675 | C<ev_resume> directly afterwards to resume timer processing. |
|
|
676 | |
|
|
677 | Effectively, all C<ev_timer> watchers will be delayed by the time spend |
|
|
678 | between C<ev_suspend> and C<ev_resume>, and all C<ev_periodic> watchers |
|
|
679 | will be rescheduled (that is, they will lose any events that would have |
|
|
680 | occured while suspended). |
|
|
681 | |
|
|
682 | After calling C<ev_suspend> you B<must not> call I<any> function on the |
|
|
683 | given loop other than C<ev_resume>, and you B<must not> call C<ev_resume> |
|
|
684 | without a previous call to C<ev_suspend>. |
|
|
685 | |
|
|
686 | Calling C<ev_suspend>/C<ev_resume> has the side effect of updating the |
|
|
687 | event loop time (see C<ev_now_update>). |
611 | |
688 | |
612 | =item ev_loop (loop, int flags) |
689 | =item ev_loop (loop, int flags) |
613 | |
690 | |
614 | Finally, this is it, the event handler. This function usually is called |
691 | Finally, this is it, the event handler. This function usually is called |
615 | after you initialised all your watchers and you want to start handling |
692 | after you initialised all your watchers and you want to start handling |
… | |
… | |
631 | the loop. |
708 | the loop. |
632 | |
709 | |
633 | A flags value of C<EVLOOP_ONESHOT> will look for new events (waiting if |
710 | A flags value of C<EVLOOP_ONESHOT> will look for new events (waiting if |
634 | necessary) and will handle those and any already outstanding ones. It |
711 | necessary) and will handle those and any already outstanding ones. It |
635 | will block your process until at least one new event arrives (which could |
712 | will block your process until at least one new event arrives (which could |
636 | be an event internal to libev itself, so there is no guarentee that a |
713 | be an event internal to libev itself, so there is no guarantee that a |
637 | user-registered callback will be called), and will return after one |
714 | user-registered callback will be called), and will return after one |
638 | iteration of the loop. |
715 | iteration of the loop. |
639 | |
716 | |
640 | This is useful if you are waiting for some external event in conjunction |
717 | This is useful if you are waiting for some external event in conjunction |
641 | with something not expressible using other libev watchers (i.e. "roll your |
718 | with something not expressible using other libev watchers (i.e. "roll your |
… | |
… | |
699 | |
776 | |
700 | If you have a watcher you never unregister that should not keep C<ev_loop> |
777 | If you have a watcher you never unregister that should not keep C<ev_loop> |
701 | from returning, call ev_unref() after starting, and ev_ref() before |
778 | from returning, call ev_unref() after starting, and ev_ref() before |
702 | stopping it. |
779 | stopping it. |
703 | |
780 | |
704 | As an example, libev itself uses this for its internal signal pipe: It is |
781 | As an example, libev itself uses this for its internal signal pipe: It |
705 | not visible to the libev user and should not keep C<ev_loop> from exiting |
782 | is not visible to the libev user and should not keep C<ev_loop> from |
706 | if no event watchers registered by it are active. It is also an excellent |
783 | exiting if no event watchers registered by it are active. It is also an |
707 | way to do this for generic recurring timers or from within third-party |
784 | excellent way to do this for generic recurring timers or from within |
708 | libraries. Just remember to I<unref after start> and I<ref before stop> |
785 | third-party libraries. Just remember to I<unref after start> and I<ref |
709 | (but only if the watcher wasn't active before, or was active before, |
786 | before stop> (but only if the watcher wasn't active before, or was active |
710 | respectively). |
787 | before, respectively. Note also that libev might stop watchers itself |
|
|
788 | (e.g. non-repeating timers) in which case you have to C<ev_ref> |
|
|
789 | in the callback). |
711 | |
790 | |
712 | Example: Create a signal watcher, but keep it from keeping C<ev_loop> |
791 | Example: Create a signal watcher, but keep it from keeping C<ev_loop> |
713 | running when nothing else is active. |
792 | running when nothing else is active. |
714 | |
793 | |
715 | struct ev_signal exitsig; |
794 | ev_signal exitsig; |
716 | ev_signal_init (&exitsig, sig_cb, SIGINT); |
795 | ev_signal_init (&exitsig, sig_cb, SIGINT); |
717 | ev_signal_start (loop, &exitsig); |
796 | ev_signal_start (loop, &exitsig); |
718 | evf_unref (loop); |
797 | evf_unref (loop); |
719 | |
798 | |
720 | Example: For some weird reason, unregister the above signal handler again. |
799 | Example: For some weird reason, unregister the above signal handler again. |
… | |
… | |
744 | |
823 | |
745 | By setting a higher I<io collect interval> you allow libev to spend more |
824 | By setting a higher I<io collect interval> you allow libev to spend more |
746 | time collecting I/O events, so you can handle more events per iteration, |
825 | time collecting I/O events, so you can handle more events per iteration, |
747 | at the cost of increasing latency. Timeouts (both C<ev_periodic> and |
826 | at the cost of increasing latency. Timeouts (both C<ev_periodic> and |
748 | C<ev_timer>) will be not affected. Setting this to a non-null value will |
827 | C<ev_timer>) will be not affected. Setting this to a non-null value will |
749 | introduce an additional C<ev_sleep ()> call into most loop iterations. |
828 | introduce an additional C<ev_sleep ()> call into most loop iterations. The |
|
|
829 | sleep time ensures that libev will not poll for I/O events more often then |
|
|
830 | once per this interval, on average. |
750 | |
831 | |
751 | Likewise, by setting a higher I<timeout collect interval> you allow libev |
832 | Likewise, by setting a higher I<timeout collect interval> you allow libev |
752 | to spend more time collecting timeouts, at the expense of increased |
833 | to spend more time collecting timeouts, at the expense of increased |
753 | latency/jitter/inexactness (the watcher callback will be called |
834 | latency/jitter/inexactness (the watcher callback will be called |
754 | later). C<ev_io> watchers will not be affected. Setting this to a non-null |
835 | later). C<ev_io> watchers will not be affected. Setting this to a non-null |
… | |
… | |
756 | |
837 | |
757 | Many (busy) programs can usually benefit by setting the I/O collect |
838 | Many (busy) programs can usually benefit by setting the I/O collect |
758 | interval to a value near C<0.1> or so, which is often enough for |
839 | interval to a value near C<0.1> or so, which is often enough for |
759 | interactive servers (of course not for games), likewise for timeouts. It |
840 | interactive servers (of course not for games), likewise for timeouts. It |
760 | usually doesn't make much sense to set it to a lower value than C<0.01>, |
841 | usually doesn't make much sense to set it to a lower value than C<0.01>, |
761 | as this approaches the timing granularity of most systems. |
842 | as this approaches the timing granularity of most systems. Note that if |
|
|
843 | you do transactions with the outside world and you can't increase the |
|
|
844 | parallelity, then this setting will limit your transaction rate (if you |
|
|
845 | need to poll once per transaction and the I/O collect interval is 0.01, |
|
|
846 | then you can't do more than 100 transations per second). |
762 | |
847 | |
763 | Setting the I<timeout collect interval> can improve the opportunity for |
848 | Setting the I<timeout collect interval> can improve the opportunity for |
764 | saving power, as the program will "bundle" timer callback invocations that |
849 | saving power, as the program will "bundle" timer callback invocations that |
765 | are "near" in time together, by delaying some, thus reducing the number of |
850 | are "near" in time together, by delaying some, thus reducing the number of |
766 | times the process sleeps and wakes up again. Another useful technique to |
851 | times the process sleeps and wakes up again. Another useful technique to |
767 | reduce iterations/wake-ups is to use C<ev_periodic> watchers and make sure |
852 | reduce iterations/wake-ups is to use C<ev_periodic> watchers and make sure |
768 | they fire on, say, one-second boundaries only. |
853 | they fire on, say, one-second boundaries only. |
769 | |
854 | |
|
|
855 | Example: we only need 0.1s timeout granularity, and we wish not to poll |
|
|
856 | more often than 100 times per second: |
|
|
857 | |
|
|
858 | ev_set_timeout_collect_interval (EV_DEFAULT_UC_ 0.1); |
|
|
859 | ev_set_io_collect_interval (EV_DEFAULT_UC_ 0.01); |
|
|
860 | |
770 | =item ev_loop_verify (loop) |
861 | =item ev_loop_verify (loop) |
771 | |
862 | |
772 | This function only does something when C<EV_VERIFY> support has been |
863 | This function only does something when C<EV_VERIFY> support has been |
773 | compiled in. which is the default for non-minimal builds. It tries to go |
864 | compiled in, which is the default for non-minimal builds. It tries to go |
774 | through all internal structures and checks them for validity. If anything |
865 | through all internal structures and checks them for validity. If anything |
775 | is found to be inconsistent, it will print an error message to standard |
866 | is found to be inconsistent, it will print an error message to standard |
776 | error and call C<abort ()>. |
867 | error and call C<abort ()>. |
777 | |
868 | |
778 | This can be used to catch bugs inside libev itself: under normal |
869 | This can be used to catch bugs inside libev itself: under normal |
… | |
… | |
782 | =back |
873 | =back |
783 | |
874 | |
784 | |
875 | |
785 | =head1 ANATOMY OF A WATCHER |
876 | =head1 ANATOMY OF A WATCHER |
786 | |
877 | |
|
|
878 | In the following description, uppercase C<TYPE> in names stands for the |
|
|
879 | watcher type, e.g. C<ev_TYPE_start> can mean C<ev_timer_start> for timer |
|
|
880 | watchers and C<ev_io_start> for I/O watchers. |
|
|
881 | |
787 | A watcher is a structure that you create and register to record your |
882 | A watcher is a structure that you create and register to record your |
788 | interest in some event. For instance, if you want to wait for STDIN to |
883 | interest in some event. For instance, if you want to wait for STDIN to |
789 | become readable, you would create an C<ev_io> watcher for that: |
884 | become readable, you would create an C<ev_io> watcher for that: |
790 | |
885 | |
791 | static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents) |
886 | static void my_cb (struct ev_loop *loop, ev_io *w, int revents) |
792 | { |
887 | { |
793 | ev_io_stop (w); |
888 | ev_io_stop (w); |
794 | ev_unloop (loop, EVUNLOOP_ALL); |
889 | ev_unloop (loop, EVUNLOOP_ALL); |
795 | } |
890 | } |
796 | |
891 | |
797 | struct ev_loop *loop = ev_default_loop (0); |
892 | struct ev_loop *loop = ev_default_loop (0); |
|
|
893 | |
798 | struct ev_io stdin_watcher; |
894 | ev_io stdin_watcher; |
|
|
895 | |
799 | ev_init (&stdin_watcher, my_cb); |
896 | ev_init (&stdin_watcher, my_cb); |
800 | ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); |
897 | ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); |
801 | ev_io_start (loop, &stdin_watcher); |
898 | ev_io_start (loop, &stdin_watcher); |
|
|
899 | |
802 | ev_loop (loop, 0); |
900 | ev_loop (loop, 0); |
803 | |
901 | |
804 | As you can see, you are responsible for allocating the memory for your |
902 | As you can see, you are responsible for allocating the memory for your |
805 | watcher structures (and it is usually a bad idea to do this on the stack, |
903 | watcher structures (and it is I<usually> a bad idea to do this on the |
806 | although this can sometimes be quite valid). |
904 | stack). |
|
|
905 | |
|
|
906 | Each watcher has an associated watcher structure (called C<struct ev_TYPE> |
|
|
907 | or simply C<ev_TYPE>, as typedefs are provided for all watcher structs). |
807 | |
908 | |
808 | Each watcher structure must be initialised by a call to C<ev_init |
909 | Each watcher structure must be initialised by a call to C<ev_init |
809 | (watcher *, callback)>, which expects a callback to be provided. This |
910 | (watcher *, callback)>, which expects a callback to be provided. This |
810 | callback gets invoked each time the event occurs (or, in the case of I/O |
911 | callback gets invoked each time the event occurs (or, in the case of I/O |
811 | watchers, each time the event loop detects that the file descriptor given |
912 | watchers, each time the event loop detects that the file descriptor given |
812 | is readable and/or writable). |
913 | is readable and/or writable). |
813 | |
914 | |
814 | Each watcher type has its own C<< ev_<type>_set (watcher *, ...) >> macro |
915 | Each watcher type further has its own C<< ev_TYPE_set (watcher *, ...) >> |
815 | with arguments specific to this watcher type. There is also a macro |
916 | macro to configure it, with arguments specific to the watcher type. There |
816 | to combine initialisation and setting in one call: C<< ev_<type>_init |
917 | is also a macro to combine initialisation and setting in one call: C<< |
817 | (watcher *, callback, ...) >>. |
918 | ev_TYPE_init (watcher *, callback, ...) >>. |
818 | |
919 | |
819 | To make the watcher actually watch out for events, you have to start it |
920 | To make the watcher actually watch out for events, you have to start it |
820 | with a watcher-specific start function (C<< ev_<type>_start (loop, watcher |
921 | with a watcher-specific start function (C<< ev_TYPE_start (loop, watcher |
821 | *) >>), and you can stop watching for events at any time by calling the |
922 | *) >>), and you can stop watching for events at any time by calling the |
822 | corresponding stop function (C<< ev_<type>_stop (loop, watcher *) >>. |
923 | corresponding stop function (C<< ev_TYPE_stop (loop, watcher *) >>. |
823 | |
924 | |
824 | As long as your watcher is active (has been started but not stopped) you |
925 | As long as your watcher is active (has been started but not stopped) you |
825 | must not touch the values stored in it. Most specifically you must never |
926 | must not touch the values stored in it. Most specifically you must never |
826 | reinitialise it or call its C<set> macro. |
927 | reinitialise it or call its C<ev_TYPE_set> macro. |
827 | |
928 | |
828 | Each and every callback receives the event loop pointer as first, the |
929 | Each and every callback receives the event loop pointer as first, the |
829 | registered watcher structure as second, and a bitset of received events as |
930 | registered watcher structure as second, and a bitset of received events as |
830 | third argument. |
931 | third argument. |
831 | |
932 | |
… | |
… | |
889 | |
990 | |
890 | =item C<EV_ASYNC> |
991 | =item C<EV_ASYNC> |
891 | |
992 | |
892 | The given async watcher has been asynchronously notified (see C<ev_async>). |
993 | The given async watcher has been asynchronously notified (see C<ev_async>). |
893 | |
994 | |
|
|
995 | =item C<EV_CUSTOM> |
|
|
996 | |
|
|
997 | Not ever sent (or otherwise used) by libev itself, but can be freely used |
|
|
998 | by libev users to signal watchers (e.g. via C<ev_feed_event>). |
|
|
999 | |
894 | =item C<EV_ERROR> |
1000 | =item C<EV_ERROR> |
895 | |
1001 | |
896 | An unspecified error has occurred, the watcher has been stopped. This might |
1002 | An unspecified error has occurred, the watcher has been stopped. This might |
897 | happen because the watcher could not be properly started because libev |
1003 | happen because the watcher could not be properly started because libev |
898 | ran out of memory, a file descriptor was found to be closed or any other |
1004 | ran out of memory, a file descriptor was found to be closed or any other |
|
|
1005 | problem. Libev considers these application bugs. |
|
|
1006 | |
899 | problem. You best act on it by reporting the problem and somehow coping |
1007 | You best act on it by reporting the problem and somehow coping with the |
900 | with the watcher being stopped. |
1008 | watcher being stopped. Note that well-written programs should not receive |
|
|
1009 | an error ever, so when your watcher receives it, this usually indicates a |
|
|
1010 | bug in your program. |
901 | |
1011 | |
902 | Libev will usually signal a few "dummy" events together with an error, for |
1012 | Libev will usually signal a few "dummy" events together with an error, for |
903 | example it might indicate that a fd is readable or writable, and if your |
1013 | example it might indicate that a fd is readable or writable, and if your |
904 | callbacks is well-written it can just attempt the operation and cope with |
1014 | callbacks is well-written it can just attempt the operation and cope with |
905 | the error from read() or write(). This will not work in multi-threaded |
1015 | the error from read() or write(). This will not work in multi-threaded |
… | |
… | |
908 | |
1018 | |
909 | =back |
1019 | =back |
910 | |
1020 | |
911 | =head2 GENERIC WATCHER FUNCTIONS |
1021 | =head2 GENERIC WATCHER FUNCTIONS |
912 | |
1022 | |
913 | In the following description, C<TYPE> stands for the watcher type, |
|
|
914 | e.g. C<timer> for C<ev_timer> watchers and C<io> for C<ev_io> watchers. |
|
|
915 | |
|
|
916 | =over 4 |
1023 | =over 4 |
917 | |
1024 | |
918 | =item C<ev_init> (ev_TYPE *watcher, callback) |
1025 | =item C<ev_init> (ev_TYPE *watcher, callback) |
919 | |
1026 | |
920 | This macro initialises the generic portion of a watcher. The contents |
1027 | This macro initialises the generic portion of a watcher. The contents |
… | |
… | |
925 | which rolls both calls into one. |
1032 | which rolls both calls into one. |
926 | |
1033 | |
927 | You can reinitialise a watcher at any time as long as it has been stopped |
1034 | You can reinitialise a watcher at any time as long as it has been stopped |
928 | (or never started) and there are no pending events outstanding. |
1035 | (or never started) and there are no pending events outstanding. |
929 | |
1036 | |
930 | The callback is always of type C<void (*)(ev_loop *loop, ev_TYPE *watcher, |
1037 | The callback is always of type C<void (*)(struct ev_loop *loop, ev_TYPE *watcher, |
931 | int revents)>. |
1038 | int revents)>. |
932 | |
1039 | |
933 | Example: Initialise an C<ev_io> watcher in two steps. |
1040 | Example: Initialise an C<ev_io> watcher in two steps. |
934 | |
1041 | |
935 | ev_io w; |
1042 | ev_io w; |
… | |
… | |
1012 | integer between C<EV_MAXPRI> (default: C<2>) and C<EV_MINPRI> |
1119 | integer between C<EV_MAXPRI> (default: C<2>) and C<EV_MINPRI> |
1013 | (default: C<-2>). Pending watchers with higher priority will be invoked |
1120 | (default: C<-2>). Pending watchers with higher priority will be invoked |
1014 | before watchers with lower priority, but priority will not keep watchers |
1121 | before watchers with lower priority, but priority will not keep watchers |
1015 | from being executed (except for C<ev_idle> watchers). |
1122 | from being executed (except for C<ev_idle> watchers). |
1016 | |
1123 | |
1017 | This means that priorities are I<only> used for ordering callback |
|
|
1018 | invocation after new events have been received. This is useful, for |
|
|
1019 | example, to reduce latency after idling, or more often, to bind two |
|
|
1020 | watchers on the same event and make sure one is called first. |
|
|
1021 | |
|
|
1022 | If you need to suppress invocation when higher priority events are pending |
1124 | If you need to suppress invocation when higher priority events are pending |
1023 | you need to look at C<ev_idle> watchers, which provide this functionality. |
1125 | you need to look at C<ev_idle> watchers, which provide this functionality. |
1024 | |
1126 | |
1025 | You I<must not> change the priority of a watcher as long as it is active or |
1127 | You I<must not> change the priority of a watcher as long as it is active or |
1026 | pending. |
1128 | pending. |
1027 | |
1129 | |
|
|
1130 | Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is |
|
|
1131 | fine, as long as you do not mind that the priority value you query might |
|
|
1132 | or might not have been clamped to the valid range. |
|
|
1133 | |
1028 | The default priority used by watchers when no priority has been set is |
1134 | The default priority used by watchers when no priority has been set is |
1029 | always C<0>, which is supposed to not be too high and not be too low :). |
1135 | always C<0>, which is supposed to not be too high and not be too low :). |
1030 | |
1136 | |
1031 | Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is |
1137 | See L<WATCHER PRIORITY MODELS>, below, for a more thorough treatment of |
1032 | fine, as long as you do not mind that the priority value you query might |
1138 | priorities. |
1033 | or might not have been adjusted to be within valid range. |
|
|
1034 | |
1139 | |
1035 | =item ev_invoke (loop, ev_TYPE *watcher, int revents) |
1140 | =item ev_invoke (loop, ev_TYPE *watcher, int revents) |
1036 | |
1141 | |
1037 | Invoke the C<watcher> with the given C<loop> and C<revents>. Neither |
1142 | Invoke the C<watcher> with the given C<loop> and C<revents>. Neither |
1038 | C<loop> nor C<revents> need to be valid as long as the watcher callback |
1143 | C<loop> nor C<revents> need to be valid as long as the watcher callback |
… | |
… | |
1060 | member, you can also "subclass" the watcher type and provide your own |
1165 | member, you can also "subclass" the watcher type and provide your own |
1061 | data: |
1166 | data: |
1062 | |
1167 | |
1063 | struct my_io |
1168 | struct my_io |
1064 | { |
1169 | { |
1065 | struct ev_io io; |
1170 | ev_io io; |
1066 | int otherfd; |
1171 | int otherfd; |
1067 | void *somedata; |
1172 | void *somedata; |
1068 | struct whatever *mostinteresting; |
1173 | struct whatever *mostinteresting; |
1069 | }; |
1174 | }; |
1070 | |
1175 | |
… | |
… | |
1073 | ev_io_init (&w.io, my_cb, fd, EV_READ); |
1178 | ev_io_init (&w.io, my_cb, fd, EV_READ); |
1074 | |
1179 | |
1075 | And since your callback will be called with a pointer to the watcher, you |
1180 | And since your callback will be called with a pointer to the watcher, you |
1076 | can cast it back to your own type: |
1181 | can cast it back to your own type: |
1077 | |
1182 | |
1078 | static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents) |
1183 | static void my_cb (struct ev_loop *loop, ev_io *w_, int revents) |
1079 | { |
1184 | { |
1080 | struct my_io *w = (struct my_io *)w_; |
1185 | struct my_io *w = (struct my_io *)w_; |
1081 | ... |
1186 | ... |
1082 | } |
1187 | } |
1083 | |
1188 | |
… | |
… | |
1101 | programmers): |
1206 | programmers): |
1102 | |
1207 | |
1103 | #include <stddef.h> |
1208 | #include <stddef.h> |
1104 | |
1209 | |
1105 | static void |
1210 | static void |
1106 | t1_cb (EV_P_ struct ev_timer *w, int revents) |
1211 | t1_cb (EV_P_ ev_timer *w, int revents) |
1107 | { |
1212 | { |
1108 | struct my_biggy big = (struct my_biggy * |
1213 | struct my_biggy big = (struct my_biggy *) |
1109 | (((char *)w) - offsetof (struct my_biggy, t1)); |
1214 | (((char *)w) - offsetof (struct my_biggy, t1)); |
1110 | } |
1215 | } |
1111 | |
1216 | |
1112 | static void |
1217 | static void |
1113 | t2_cb (EV_P_ struct ev_timer *w, int revents) |
1218 | t2_cb (EV_P_ ev_timer *w, int revents) |
1114 | { |
1219 | { |
1115 | struct my_biggy big = (struct my_biggy * |
1220 | struct my_biggy big = (struct my_biggy *) |
1116 | (((char *)w) - offsetof (struct my_biggy, t2)); |
1221 | (((char *)w) - offsetof (struct my_biggy, t2)); |
1117 | } |
1222 | } |
|
|
1223 | |
|
|
1224 | =head2 WATCHER PRIORITY MODELS |
|
|
1225 | |
|
|
1226 | Many event loops support I<watcher priorities>, which are usually small |
|
|
1227 | integers that influence the ordering of event callback invocation |
|
|
1228 | between watchers in some way, all else being equal. |
|
|
1229 | |
|
|
1230 | In libev, Watcher priorities can be set using C<ev_set_priority>. See its |
|
|
1231 | description for the more technical details such as the actual priority |
|
|
1232 | range. |
|
|
1233 | |
|
|
1234 | There are two common ways how these these priorities are being interpreted |
|
|
1235 | by event loops: |
|
|
1236 | |
|
|
1237 | In the more common lock-out model, higher priorities "lock out" invocation |
|
|
1238 | of lower priority watchers, which means as long as higher priority |
|
|
1239 | watchers receive events, lower priority watchers are not being invoked. |
|
|
1240 | |
|
|
1241 | The less common only-for-ordering model uses priorities solely to order |
|
|
1242 | callback invocation within a single event loop iteration: Higher priority |
|
|
1243 | watchers are invoked before lower priority ones, but they all get invoked |
|
|
1244 | before polling for new events. |
|
|
1245 | |
|
|
1246 | Libev uses the second (only-for-ordering) model for all its watchers |
|
|
1247 | except for idle watchers (which use the lock-out model). |
|
|
1248 | |
|
|
1249 | The rationale behind this is that implementing the lock-out model for |
|
|
1250 | watchers is not well supported by most kernel interfaces, and most event |
|
|
1251 | libraries will just poll for the same events again and again as long as |
|
|
1252 | their callbacks have not been executed, which is very inefficient in the |
|
|
1253 | common case of one high-priority watcher locking out a mass of lower |
|
|
1254 | priority ones. |
|
|
1255 | |
|
|
1256 | Static (ordering) priorities are most useful when you have two or more |
|
|
1257 | watchers handling the same resource: a typical usage example is having an |
|
|
1258 | C<ev_io> watcher to receive data, and an associated C<ev_timer> to handle |
|
|
1259 | timeouts. Under load, data might be received while the program handles |
|
|
1260 | other jobs, but since timers normally get invoked first, the timeout |
|
|
1261 | handler will be executed before checking for data. In that case, giving |
|
|
1262 | the timer a lower priority than the I/O watcher ensures that I/O will be |
|
|
1263 | handled first even under adverse conditions (which is usually, but not |
|
|
1264 | always, what you want). |
|
|
1265 | |
|
|
1266 | Since idle watchers use the "lock-out" model, meaning that idle watchers |
|
|
1267 | will only be executed when no same or higher priority watchers have |
|
|
1268 | received events, they can be used to implement the "lock-out" model when |
|
|
1269 | required. |
|
|
1270 | |
|
|
1271 | For example, to emulate how many other event libraries handle priorities, |
|
|
1272 | you can associate an C<ev_idle> watcher to each such watcher, and in |
|
|
1273 | the normal watcher callback, you just start the idle watcher. The real |
|
|
1274 | processing is done in the idle watcher callback. This causes libev to |
|
|
1275 | continously poll and process kernel event data for the watcher, but when |
|
|
1276 | the lock-out case is known to be rare (which in turn is rare :), this is |
|
|
1277 | workable. |
|
|
1278 | |
|
|
1279 | Usually, however, the lock-out model implemented that way will perform |
|
|
1280 | miserably under the type of load it was designed to handle. In that case, |
|
|
1281 | it might be preferable to stop the real watcher before starting the |
|
|
1282 | idle watcher, so the kernel will not have to process the event in case |
|
|
1283 | the actual processing will be delayed for considerable time. |
|
|
1284 | |
|
|
1285 | Here is an example of an I/O watcher that should run at a strictly lower |
|
|
1286 | priority than the default, and which should only process data when no |
|
|
1287 | other events are pending: |
|
|
1288 | |
|
|
1289 | ev_idle idle; // actual processing watcher |
|
|
1290 | ev_io io; // actual event watcher |
|
|
1291 | |
|
|
1292 | static void |
|
|
1293 | io_cb (EV_P_ ev_io *w, int revents) |
|
|
1294 | { |
|
|
1295 | // stop the I/O watcher, we received the event, but |
|
|
1296 | // are not yet ready to handle it. |
|
|
1297 | ev_io_stop (EV_A_ w); |
|
|
1298 | |
|
|
1299 | // start the idle watcher to ahndle the actual event. |
|
|
1300 | // it will not be executed as long as other watchers |
|
|
1301 | // with the default priority are receiving events. |
|
|
1302 | ev_idle_start (EV_A_ &idle); |
|
|
1303 | } |
|
|
1304 | |
|
|
1305 | static void |
|
|
1306 | idle_cb (EV_P_ ev_idle *w, int revents) |
|
|
1307 | { |
|
|
1308 | // actual processing |
|
|
1309 | read (STDIN_FILENO, ...); |
|
|
1310 | |
|
|
1311 | // have to start the I/O watcher again, as |
|
|
1312 | // we have handled the event |
|
|
1313 | ev_io_start (EV_P_ &io); |
|
|
1314 | } |
|
|
1315 | |
|
|
1316 | // initialisation |
|
|
1317 | ev_idle_init (&idle, idle_cb); |
|
|
1318 | ev_io_init (&io, io_cb, STDIN_FILENO, EV_READ); |
|
|
1319 | ev_io_start (EV_DEFAULT_ &io); |
|
|
1320 | |
|
|
1321 | In the "real" world, it might also be beneficial to start a timer, so that |
|
|
1322 | low-priority connections can not be locked out forever under load. This |
|
|
1323 | enables your program to keep a lower latency for important connections |
|
|
1324 | during short periods of high load, while not completely locking out less |
|
|
1325 | important ones. |
1118 | |
1326 | |
1119 | |
1327 | |
1120 | =head1 WATCHER TYPES |
1328 | =head1 WATCHER TYPES |
1121 | |
1329 | |
1122 | This section describes each watcher in detail, but will not repeat |
1330 | This section describes each watcher in detail, but will not repeat |
… | |
… | |
1148 | descriptors to non-blocking mode is also usually a good idea (but not |
1356 | descriptors to non-blocking mode is also usually a good idea (but not |
1149 | required if you know what you are doing). |
1357 | required if you know what you are doing). |
1150 | |
1358 | |
1151 | If you cannot use non-blocking mode, then force the use of a |
1359 | If you cannot use non-blocking mode, then force the use of a |
1152 | known-to-be-good backend (at the time of this writing, this includes only |
1360 | known-to-be-good backend (at the time of this writing, this includes only |
1153 | C<EVBACKEND_SELECT> and C<EVBACKEND_POLL>). |
1361 | C<EVBACKEND_SELECT> and C<EVBACKEND_POLL>). The same applies to file |
|
|
1362 | descriptors for which non-blocking operation makes no sense (such as |
|
|
1363 | files) - libev doesn't guarentee any specific behaviour in that case. |
1154 | |
1364 | |
1155 | Another thing you have to watch out for is that it is quite easy to |
1365 | Another thing you have to watch out for is that it is quite easy to |
1156 | receive "spurious" readiness notifications, that is your callback might |
1366 | receive "spurious" readiness notifications, that is your callback might |
1157 | be called with C<EV_READ> but a subsequent C<read>(2) will actually block |
1367 | be called with C<EV_READ> but a subsequent C<read>(2) will actually block |
1158 | because there is no data. Not only are some backends known to create a |
1368 | because there is no data. Not only are some backends known to create a |
… | |
… | |
1253 | Example: Call C<stdin_readable_cb> when STDIN_FILENO has become, well |
1463 | Example: Call C<stdin_readable_cb> when STDIN_FILENO has become, well |
1254 | readable, but only once. Since it is likely line-buffered, you could |
1464 | readable, but only once. Since it is likely line-buffered, you could |
1255 | attempt to read a whole line in the callback. |
1465 | attempt to read a whole line in the callback. |
1256 | |
1466 | |
1257 | static void |
1467 | static void |
1258 | stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents) |
1468 | stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents) |
1259 | { |
1469 | { |
1260 | ev_io_stop (loop, w); |
1470 | ev_io_stop (loop, w); |
1261 | .. read from stdin here (or from w->fd) and handle any I/O errors |
1471 | .. read from stdin here (or from w->fd) and handle any I/O errors |
1262 | } |
1472 | } |
1263 | |
1473 | |
1264 | ... |
1474 | ... |
1265 | struct ev_loop *loop = ev_default_init (0); |
1475 | struct ev_loop *loop = ev_default_init (0); |
1266 | struct ev_io stdin_readable; |
1476 | ev_io stdin_readable; |
1267 | ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); |
1477 | ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); |
1268 | ev_io_start (loop, &stdin_readable); |
1478 | ev_io_start (loop, &stdin_readable); |
1269 | ev_loop (loop, 0); |
1479 | ev_loop (loop, 0); |
1270 | |
1480 | |
1271 | |
1481 | |
… | |
… | |
1279 | year, it will still time out after (roughly) one hour. "Roughly" because |
1489 | year, it will still time out after (roughly) one hour. "Roughly" because |
1280 | detecting time jumps is hard, and some inaccuracies are unavoidable (the |
1490 | detecting time jumps is hard, and some inaccuracies are unavoidable (the |
1281 | monotonic clock option helps a lot here). |
1491 | monotonic clock option helps a lot here). |
1282 | |
1492 | |
1283 | The callback is guaranteed to be invoked only I<after> its timeout has |
1493 | The callback is guaranteed to be invoked only I<after> its timeout has |
1284 | passed, but if multiple timers become ready during the same loop iteration |
1494 | passed (not I<at>, so on systems with very low-resolution clocks this |
1285 | then order of execution is undefined. |
1495 | might introduce a small delay). If multiple timers become ready during the |
|
|
1496 | same loop iteration then the ones with earlier time-out values are invoked |
|
|
1497 | before ones of the same priority with later time-out values (but this is |
|
|
1498 | no longer true when a callback calls C<ev_loop> recursively). |
|
|
1499 | |
|
|
1500 | =head3 Be smart about timeouts |
|
|
1501 | |
|
|
1502 | Many real-world problems involve some kind of timeout, usually for error |
|
|
1503 | recovery. A typical example is an HTTP request - if the other side hangs, |
|
|
1504 | you want to raise some error after a while. |
|
|
1505 | |
|
|
1506 | What follows are some ways to handle this problem, from obvious and |
|
|
1507 | inefficient to smart and efficient. |
|
|
1508 | |
|
|
1509 | In the following, a 60 second activity timeout is assumed - a timeout that |
|
|
1510 | gets reset to 60 seconds each time there is activity (e.g. each time some |
|
|
1511 | data or other life sign was received). |
|
|
1512 | |
|
|
1513 | =over 4 |
|
|
1514 | |
|
|
1515 | =item 1. Use a timer and stop, reinitialise and start it on activity. |
|
|
1516 | |
|
|
1517 | This is the most obvious, but not the most simple way: In the beginning, |
|
|
1518 | start the watcher: |
|
|
1519 | |
|
|
1520 | ev_timer_init (timer, callback, 60., 0.); |
|
|
1521 | ev_timer_start (loop, timer); |
|
|
1522 | |
|
|
1523 | Then, each time there is some activity, C<ev_timer_stop> it, initialise it |
|
|
1524 | and start it again: |
|
|
1525 | |
|
|
1526 | ev_timer_stop (loop, timer); |
|
|
1527 | ev_timer_set (timer, 60., 0.); |
|
|
1528 | ev_timer_start (loop, timer); |
|
|
1529 | |
|
|
1530 | This is relatively simple to implement, but means that each time there is |
|
|
1531 | some activity, libev will first have to remove the timer from its internal |
|
|
1532 | data structure and then add it again. Libev tries to be fast, but it's |
|
|
1533 | still not a constant-time operation. |
|
|
1534 | |
|
|
1535 | =item 2. Use a timer and re-start it with C<ev_timer_again> inactivity. |
|
|
1536 | |
|
|
1537 | This is the easiest way, and involves using C<ev_timer_again> instead of |
|
|
1538 | C<ev_timer_start>. |
|
|
1539 | |
|
|
1540 | To implement this, configure an C<ev_timer> with a C<repeat> value |
|
|
1541 | of C<60> and then call C<ev_timer_again> at start and each time you |
|
|
1542 | successfully read or write some data. If you go into an idle state where |
|
|
1543 | you do not expect data to travel on the socket, you can C<ev_timer_stop> |
|
|
1544 | the timer, and C<ev_timer_again> will automatically restart it if need be. |
|
|
1545 | |
|
|
1546 | That means you can ignore both the C<ev_timer_start> function and the |
|
|
1547 | C<after> argument to C<ev_timer_set>, and only ever use the C<repeat> |
|
|
1548 | member and C<ev_timer_again>. |
|
|
1549 | |
|
|
1550 | At start: |
|
|
1551 | |
|
|
1552 | ev_init (timer, callback); |
|
|
1553 | timer->repeat = 60.; |
|
|
1554 | ev_timer_again (loop, timer); |
|
|
1555 | |
|
|
1556 | Each time there is some activity: |
|
|
1557 | |
|
|
1558 | ev_timer_again (loop, timer); |
|
|
1559 | |
|
|
1560 | It is even possible to change the time-out on the fly, regardless of |
|
|
1561 | whether the watcher is active or not: |
|
|
1562 | |
|
|
1563 | timer->repeat = 30.; |
|
|
1564 | ev_timer_again (loop, timer); |
|
|
1565 | |
|
|
1566 | This is slightly more efficient then stopping/starting the timer each time |
|
|
1567 | you want to modify its timeout value, as libev does not have to completely |
|
|
1568 | remove and re-insert the timer from/into its internal data structure. |
|
|
1569 | |
|
|
1570 | It is, however, even simpler than the "obvious" way to do it. |
|
|
1571 | |
|
|
1572 | =item 3. Let the timer time out, but then re-arm it as required. |
|
|
1573 | |
|
|
1574 | This method is more tricky, but usually most efficient: Most timeouts are |
|
|
1575 | relatively long compared to the intervals between other activity - in |
|
|
1576 | our example, within 60 seconds, there are usually many I/O events with |
|
|
1577 | associated activity resets. |
|
|
1578 | |
|
|
1579 | In this case, it would be more efficient to leave the C<ev_timer> alone, |
|
|
1580 | but remember the time of last activity, and check for a real timeout only |
|
|
1581 | within the callback: |
|
|
1582 | |
|
|
1583 | ev_tstamp last_activity; // time of last activity |
|
|
1584 | |
|
|
1585 | static void |
|
|
1586 | callback (EV_P_ ev_timer *w, int revents) |
|
|
1587 | { |
|
|
1588 | ev_tstamp now = ev_now (EV_A); |
|
|
1589 | ev_tstamp timeout = last_activity + 60.; |
|
|
1590 | |
|
|
1591 | // if last_activity + 60. is older than now, we did time out |
|
|
1592 | if (timeout < now) |
|
|
1593 | { |
|
|
1594 | // timeout occured, take action |
|
|
1595 | } |
|
|
1596 | else |
|
|
1597 | { |
|
|
1598 | // callback was invoked, but there was some activity, re-arm |
|
|
1599 | // the watcher to fire in last_activity + 60, which is |
|
|
1600 | // guaranteed to be in the future, so "again" is positive: |
|
|
1601 | w->repeat = timeout - now; |
|
|
1602 | ev_timer_again (EV_A_ w); |
|
|
1603 | } |
|
|
1604 | } |
|
|
1605 | |
|
|
1606 | To summarise the callback: first calculate the real timeout (defined |
|
|
1607 | as "60 seconds after the last activity"), then check if that time has |
|
|
1608 | been reached, which means something I<did>, in fact, time out. Otherwise |
|
|
1609 | the callback was invoked too early (C<timeout> is in the future), so |
|
|
1610 | re-schedule the timer to fire at that future time, to see if maybe we have |
|
|
1611 | a timeout then. |
|
|
1612 | |
|
|
1613 | Note how C<ev_timer_again> is used, taking advantage of the |
|
|
1614 | C<ev_timer_again> optimisation when the timer is already running. |
|
|
1615 | |
|
|
1616 | This scheme causes more callback invocations (about one every 60 seconds |
|
|
1617 | minus half the average time between activity), but virtually no calls to |
|
|
1618 | libev to change the timeout. |
|
|
1619 | |
|
|
1620 | To start the timer, simply initialise the watcher and set C<last_activity> |
|
|
1621 | to the current time (meaning we just have some activity :), then call the |
|
|
1622 | callback, which will "do the right thing" and start the timer: |
|
|
1623 | |
|
|
1624 | ev_init (timer, callback); |
|
|
1625 | last_activity = ev_now (loop); |
|
|
1626 | callback (loop, timer, EV_TIMEOUT); |
|
|
1627 | |
|
|
1628 | And when there is some activity, simply store the current time in |
|
|
1629 | C<last_activity>, no libev calls at all: |
|
|
1630 | |
|
|
1631 | last_actiivty = ev_now (loop); |
|
|
1632 | |
|
|
1633 | This technique is slightly more complex, but in most cases where the |
|
|
1634 | time-out is unlikely to be triggered, much more efficient. |
|
|
1635 | |
|
|
1636 | Changing the timeout is trivial as well (if it isn't hard-coded in the |
|
|
1637 | callback :) - just change the timeout and invoke the callback, which will |
|
|
1638 | fix things for you. |
|
|
1639 | |
|
|
1640 | =item 4. Wee, just use a double-linked list for your timeouts. |
|
|
1641 | |
|
|
1642 | If there is not one request, but many thousands (millions...), all |
|
|
1643 | employing some kind of timeout with the same timeout value, then one can |
|
|
1644 | do even better: |
|
|
1645 | |
|
|
1646 | When starting the timeout, calculate the timeout value and put the timeout |
|
|
1647 | at the I<end> of the list. |
|
|
1648 | |
|
|
1649 | Then use an C<ev_timer> to fire when the timeout at the I<beginning> of |
|
|
1650 | the list is expected to fire (for example, using the technique #3). |
|
|
1651 | |
|
|
1652 | When there is some activity, remove the timer from the list, recalculate |
|
|
1653 | the timeout, append it to the end of the list again, and make sure to |
|
|
1654 | update the C<ev_timer> if it was taken from the beginning of the list. |
|
|
1655 | |
|
|
1656 | This way, one can manage an unlimited number of timeouts in O(1) time for |
|
|
1657 | starting, stopping and updating the timers, at the expense of a major |
|
|
1658 | complication, and having to use a constant timeout. The constant timeout |
|
|
1659 | ensures that the list stays sorted. |
|
|
1660 | |
|
|
1661 | =back |
|
|
1662 | |
|
|
1663 | So which method the best? |
|
|
1664 | |
|
|
1665 | Method #2 is a simple no-brain-required solution that is adequate in most |
|
|
1666 | situations. Method #3 requires a bit more thinking, but handles many cases |
|
|
1667 | better, and isn't very complicated either. In most case, choosing either |
|
|
1668 | one is fine, with #3 being better in typical situations. |
|
|
1669 | |
|
|
1670 | Method #1 is almost always a bad idea, and buys you nothing. Method #4 is |
|
|
1671 | rather complicated, but extremely efficient, something that really pays |
|
|
1672 | off after the first million or so of active timers, i.e. it's usually |
|
|
1673 | overkill :) |
1286 | |
1674 | |
1287 | =head3 The special problem of time updates |
1675 | =head3 The special problem of time updates |
1288 | |
1676 | |
1289 | Establishing the current time is a costly operation (it usually takes at |
1677 | Establishing the current time is a costly operation (it usually takes at |
1290 | least two system calls): EV therefore updates its idea of the current |
1678 | least two system calls): EV therefore updates its idea of the current |
… | |
… | |
1334 | If the timer is started but non-repeating, stop it (as if it timed out). |
1722 | If the timer is started but non-repeating, stop it (as if it timed out). |
1335 | |
1723 | |
1336 | If the timer is repeating, either start it if necessary (with the |
1724 | If the timer is repeating, either start it if necessary (with the |
1337 | C<repeat> value), or reset the running timer to the C<repeat> value. |
1725 | C<repeat> value), or reset the running timer to the C<repeat> value. |
1338 | |
1726 | |
1339 | This sounds a bit complicated, but here is a useful and typical |
1727 | This sounds a bit complicated, see L<Be smart about timeouts>, above, for a |
1340 | example: Imagine you have a TCP connection and you want a so-called idle |
1728 | usage example. |
1341 | timeout, that is, you want to be called when there have been, say, 60 |
|
|
1342 | seconds of inactivity on the socket. The easiest way to do this is to |
|
|
1343 | configure an C<ev_timer> with a C<repeat> value of C<60> and then call |
|
|
1344 | C<ev_timer_again> each time you successfully read or write some data. If |
|
|
1345 | you go into an idle state where you do not expect data to travel on the |
|
|
1346 | socket, you can C<ev_timer_stop> the timer, and C<ev_timer_again> will |
|
|
1347 | automatically restart it if need be. |
|
|
1348 | |
|
|
1349 | That means you can ignore the C<after> value and C<ev_timer_start> |
|
|
1350 | altogether and only ever use the C<repeat> value and C<ev_timer_again>: |
|
|
1351 | |
|
|
1352 | ev_timer_init (timer, callback, 0., 5.); |
|
|
1353 | ev_timer_again (loop, timer); |
|
|
1354 | ... |
|
|
1355 | timer->again = 17.; |
|
|
1356 | ev_timer_again (loop, timer); |
|
|
1357 | ... |
|
|
1358 | timer->again = 10.; |
|
|
1359 | ev_timer_again (loop, timer); |
|
|
1360 | |
|
|
1361 | This is more slightly efficient then stopping/starting the timer each time |
|
|
1362 | you want to modify its timeout value. |
|
|
1363 | |
|
|
1364 | Note, however, that it is often even more efficient to remember the |
|
|
1365 | time of the last activity and let the timer time-out naturally. In the |
|
|
1366 | callback, you then check whether the time-out is real, or, if there was |
|
|
1367 | some activity, you reschedule the watcher to time-out in "last_activity + |
|
|
1368 | timeout - ev_now ()" seconds. |
|
|
1369 | |
1729 | |
1370 | =item ev_tstamp repeat [read-write] |
1730 | =item ev_tstamp repeat [read-write] |
1371 | |
1731 | |
1372 | The current C<repeat> value. Will be used each time the watcher times out |
1732 | The current C<repeat> value. Will be used each time the watcher times out |
1373 | or C<ev_timer_again> is called, and determines the next timeout (if any), |
1733 | or C<ev_timer_again> is called, and determines the next timeout (if any), |
… | |
… | |
1378 | =head3 Examples |
1738 | =head3 Examples |
1379 | |
1739 | |
1380 | Example: Create a timer that fires after 60 seconds. |
1740 | Example: Create a timer that fires after 60 seconds. |
1381 | |
1741 | |
1382 | static void |
1742 | static void |
1383 | one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents) |
1743 | one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents) |
1384 | { |
1744 | { |
1385 | .. one minute over, w is actually stopped right here |
1745 | .. one minute over, w is actually stopped right here |
1386 | } |
1746 | } |
1387 | |
1747 | |
1388 | struct ev_timer mytimer; |
1748 | ev_timer mytimer; |
1389 | ev_timer_init (&mytimer, one_minute_cb, 60., 0.); |
1749 | ev_timer_init (&mytimer, one_minute_cb, 60., 0.); |
1390 | ev_timer_start (loop, &mytimer); |
1750 | ev_timer_start (loop, &mytimer); |
1391 | |
1751 | |
1392 | Example: Create a timeout timer that times out after 10 seconds of |
1752 | Example: Create a timeout timer that times out after 10 seconds of |
1393 | inactivity. |
1753 | inactivity. |
1394 | |
1754 | |
1395 | static void |
1755 | static void |
1396 | timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents) |
1756 | timeout_cb (struct ev_loop *loop, ev_timer *w, int revents) |
1397 | { |
1757 | { |
1398 | .. ten seconds without any activity |
1758 | .. ten seconds without any activity |
1399 | } |
1759 | } |
1400 | |
1760 | |
1401 | struct ev_timer mytimer; |
1761 | ev_timer mytimer; |
1402 | ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ |
1762 | ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ |
1403 | ev_timer_again (&mytimer); /* start timer */ |
1763 | ev_timer_again (&mytimer); /* start timer */ |
1404 | ev_loop (loop, 0); |
1764 | ev_loop (loop, 0); |
1405 | |
1765 | |
1406 | // and in some piece of code that gets executed on any "activity": |
1766 | // and in some piece of code that gets executed on any "activity": |
… | |
… | |
1411 | =head2 C<ev_periodic> - to cron or not to cron? |
1771 | =head2 C<ev_periodic> - to cron or not to cron? |
1412 | |
1772 | |
1413 | Periodic watchers are also timers of a kind, but they are very versatile |
1773 | Periodic watchers are also timers of a kind, but they are very versatile |
1414 | (and unfortunately a bit complex). |
1774 | (and unfortunately a bit complex). |
1415 | |
1775 | |
1416 | Unlike C<ev_timer>'s, they are not based on real time (or relative time) |
1776 | Unlike C<ev_timer>, periodic watchers are not based on real time (or |
1417 | but on wall clock time (absolute time). You can tell a periodic watcher |
1777 | relative time, the physical time that passes) but on wall clock time |
1418 | to trigger after some specific point in time. For example, if you tell a |
1778 | (absolute time, the thing you can read on your calender or clock). The |
1419 | periodic watcher to trigger in 10 seconds (by specifying e.g. C<ev_now () |
1779 | difference is that wall clock time can run faster or slower than real |
1420 | + 10.>, that is, an absolute time not a delay) and then reset your system |
1780 | time, and time jumps are not uncommon (e.g. when you adjust your |
1421 | clock to January of the previous year, then it will take more than year |
1781 | wrist-watch). |
1422 | to trigger the event (unlike an C<ev_timer>, which would still trigger |
|
|
1423 | roughly 10 seconds later as it uses a relative timeout). |
|
|
1424 | |
1782 | |
|
|
1783 | You can tell a periodic watcher to trigger after some specific point |
|
|
1784 | in time: for example, if you tell a periodic watcher to trigger "in 10 |
|
|
1785 | seconds" (by specifying e.g. C<ev_now () + 10.>, that is, an absolute time |
|
|
1786 | not a delay) and then reset your system clock to January of the previous |
|
|
1787 | year, then it will take a year or more to trigger the event (unlike an |
|
|
1788 | C<ev_timer>, which would still trigger roughly 10 seconds after starting |
|
|
1789 | it, as it uses a relative timeout). |
|
|
1790 | |
1425 | C<ev_periodic>s can also be used to implement vastly more complex timers, |
1791 | C<ev_periodic> watchers can also be used to implement vastly more complex |
1426 | such as triggering an event on each "midnight, local time", or other |
1792 | timers, such as triggering an event on each "midnight, local time", or |
1427 | complicated rules. |
1793 | other complicated rules. This cannot be done with C<ev_timer> watchers, as |
|
|
1794 | those cannot react to time jumps. |
1428 | |
1795 | |
1429 | As with timers, the callback is guaranteed to be invoked only when the |
1796 | As with timers, the callback is guaranteed to be invoked only when the |
1430 | time (C<at>) has passed, but if multiple periodic timers become ready |
1797 | point in time where it is supposed to trigger has passed. If multiple |
1431 | during the same loop iteration, then order of execution is undefined. |
1798 | timers become ready during the same loop iteration then the ones with |
|
|
1799 | earlier time-out values are invoked before ones with later time-out values |
|
|
1800 | (but this is no longer true when a callback calls C<ev_loop> recursively). |
1432 | |
1801 | |
1433 | =head3 Watcher-Specific Functions and Data Members |
1802 | =head3 Watcher-Specific Functions and Data Members |
1434 | |
1803 | |
1435 | =over 4 |
1804 | =over 4 |
1436 | |
1805 | |
1437 | =item ev_periodic_init (ev_periodic *, callback, ev_tstamp at, ev_tstamp interval, reschedule_cb) |
1806 | =item ev_periodic_init (ev_periodic *, callback, ev_tstamp offset, ev_tstamp interval, reschedule_cb) |
1438 | |
1807 | |
1439 | =item ev_periodic_set (ev_periodic *, ev_tstamp after, ev_tstamp repeat, reschedule_cb) |
1808 | =item ev_periodic_set (ev_periodic *, ev_tstamp offset, ev_tstamp interval, reschedule_cb) |
1440 | |
1809 | |
1441 | Lots of arguments, lets sort it out... There are basically three modes of |
1810 | Lots of arguments, let's sort it out... There are basically three modes of |
1442 | operation, and we will explain them from simplest to most complex: |
1811 | operation, and we will explain them from simplest to most complex: |
1443 | |
1812 | |
1444 | =over 4 |
1813 | =over 4 |
1445 | |
1814 | |
1446 | =item * absolute timer (at = time, interval = reschedule_cb = 0) |
1815 | =item * absolute timer (offset = absolute time, interval = 0, reschedule_cb = 0) |
1447 | |
1816 | |
1448 | In this configuration the watcher triggers an event after the wall clock |
1817 | In this configuration the watcher triggers an event after the wall clock |
1449 | time C<at> has passed. It will not repeat and will not adjust when a time |
1818 | time C<offset> has passed. It will not repeat and will not adjust when a |
1450 | jump occurs, that is, if it is to be run at January 1st 2011 then it will |
1819 | time jump occurs, that is, if it is to be run at January 1st 2011 then it |
1451 | only run when the system clock reaches or surpasses this time. |
1820 | will be stopped and invoked when the system clock reaches or surpasses |
|
|
1821 | this point in time. |
1452 | |
1822 | |
1453 | =item * repeating interval timer (at = offset, interval > 0, reschedule_cb = 0) |
1823 | =item * repeating interval timer (offset = offset within interval, interval > 0, reschedule_cb = 0) |
1454 | |
1824 | |
1455 | In this mode the watcher will always be scheduled to time out at the next |
1825 | In this mode the watcher will always be scheduled to time out at the next |
1456 | C<at + N * interval> time (for some integer N, which can also be negative) |
1826 | C<offset + N * interval> time (for some integer N, which can also be |
1457 | and then repeat, regardless of any time jumps. |
1827 | negative) and then repeat, regardless of any time jumps. The C<offset> |
|
|
1828 | argument is merely an offset into the C<interval> periods. |
1458 | |
1829 | |
1459 | This can be used to create timers that do not drift with respect to the |
1830 | This can be used to create timers that do not drift with respect to the |
1460 | system clock, for example, here is a C<ev_periodic> that triggers each |
1831 | system clock, for example, here is an C<ev_periodic> that triggers each |
1461 | hour, on the hour: |
1832 | hour, on the hour (with respect to UTC): |
1462 | |
1833 | |
1463 | ev_periodic_set (&periodic, 0., 3600., 0); |
1834 | ev_periodic_set (&periodic, 0., 3600., 0); |
1464 | |
1835 | |
1465 | This doesn't mean there will always be 3600 seconds in between triggers, |
1836 | This doesn't mean there will always be 3600 seconds in between triggers, |
1466 | but only that the callback will be called when the system time shows a |
1837 | but only that the callback will be called when the system time shows a |
1467 | full hour (UTC), or more correctly, when the system time is evenly divisible |
1838 | full hour (UTC), or more correctly, when the system time is evenly divisible |
1468 | by 3600. |
1839 | by 3600. |
1469 | |
1840 | |
1470 | Another way to think about it (for the mathematically inclined) is that |
1841 | Another way to think about it (for the mathematically inclined) is that |
1471 | C<ev_periodic> will try to run the callback in this mode at the next possible |
1842 | C<ev_periodic> will try to run the callback in this mode at the next possible |
1472 | time where C<time = at (mod interval)>, regardless of any time jumps. |
1843 | time where C<time = offset (mod interval)>, regardless of any time jumps. |
1473 | |
1844 | |
1474 | For numerical stability it is preferable that the C<at> value is near |
1845 | For numerical stability it is preferable that the C<offset> value is near |
1475 | C<ev_now ()> (the current time), but there is no range requirement for |
1846 | C<ev_now ()> (the current time), but there is no range requirement for |
1476 | this value, and in fact is often specified as zero. |
1847 | this value, and in fact is often specified as zero. |
1477 | |
1848 | |
1478 | Note also that there is an upper limit to how often a timer can fire (CPU |
1849 | Note also that there is an upper limit to how often a timer can fire (CPU |
1479 | speed for example), so if C<interval> is very small then timing stability |
1850 | speed for example), so if C<interval> is very small then timing stability |
1480 | will of course deteriorate. Libev itself tries to be exact to be about one |
1851 | will of course deteriorate. Libev itself tries to be exact to be about one |
1481 | millisecond (if the OS supports it and the machine is fast enough). |
1852 | millisecond (if the OS supports it and the machine is fast enough). |
1482 | |
1853 | |
1483 | =item * manual reschedule mode (at and interval ignored, reschedule_cb = callback) |
1854 | =item * manual reschedule mode (offset ignored, interval ignored, reschedule_cb = callback) |
1484 | |
1855 | |
1485 | In this mode the values for C<interval> and C<at> are both being |
1856 | In this mode the values for C<interval> and C<offset> are both being |
1486 | ignored. Instead, each time the periodic watcher gets scheduled, the |
1857 | ignored. Instead, each time the periodic watcher gets scheduled, the |
1487 | reschedule callback will be called with the watcher as first, and the |
1858 | reschedule callback will be called with the watcher as first, and the |
1488 | current time as second argument. |
1859 | current time as second argument. |
1489 | |
1860 | |
1490 | NOTE: I<This callback MUST NOT stop or destroy any periodic watcher, |
1861 | NOTE: I<This callback MUST NOT stop or destroy any periodic watcher, ever, |
1491 | ever, or make ANY event loop modifications whatsoever>. |
1862 | or make ANY other event loop modifications whatsoever, unless explicitly |
|
|
1863 | allowed by documentation here>. |
1492 | |
1864 | |
1493 | If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop |
1865 | If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop |
1494 | it afterwards (e.g. by starting an C<ev_prepare> watcher, which is the |
1866 | it afterwards (e.g. by starting an C<ev_prepare> watcher, which is the |
1495 | only event loop modification you are allowed to do). |
1867 | only event loop modification you are allowed to do). |
1496 | |
1868 | |
1497 | The callback prototype is C<ev_tstamp (*reschedule_cb)(struct ev_periodic |
1869 | The callback prototype is C<ev_tstamp (*reschedule_cb)(ev_periodic |
1498 | *w, ev_tstamp now)>, e.g.: |
1870 | *w, ev_tstamp now)>, e.g.: |
1499 | |
1871 | |
|
|
1872 | static ev_tstamp |
1500 | static ev_tstamp my_rescheduler (struct ev_periodic *w, ev_tstamp now) |
1873 | my_rescheduler (ev_periodic *w, ev_tstamp now) |
1501 | { |
1874 | { |
1502 | return now + 60.; |
1875 | return now + 60.; |
1503 | } |
1876 | } |
1504 | |
1877 | |
1505 | It must return the next time to trigger, based on the passed time value |
1878 | It must return the next time to trigger, based on the passed time value |
… | |
… | |
1525 | a different time than the last time it was called (e.g. in a crond like |
1898 | a different time than the last time it was called (e.g. in a crond like |
1526 | program when the crontabs have changed). |
1899 | program when the crontabs have changed). |
1527 | |
1900 | |
1528 | =item ev_tstamp ev_periodic_at (ev_periodic *) |
1901 | =item ev_tstamp ev_periodic_at (ev_periodic *) |
1529 | |
1902 | |
1530 | When active, returns the absolute time that the watcher is supposed to |
1903 | When active, returns the absolute time that the watcher is supposed |
1531 | trigger next. |
1904 | to trigger next. This is not the same as the C<offset> argument to |
|
|
1905 | C<ev_periodic_set>, but indeed works even in interval and manual |
|
|
1906 | rescheduling modes. |
1532 | |
1907 | |
1533 | =item ev_tstamp offset [read-write] |
1908 | =item ev_tstamp offset [read-write] |
1534 | |
1909 | |
1535 | When repeating, this contains the offset value, otherwise this is the |
1910 | When repeating, this contains the offset value, otherwise this is the |
1536 | absolute point in time (the C<at> value passed to C<ev_periodic_set>). |
1911 | absolute point in time (the C<offset> value passed to C<ev_periodic_set>, |
|
|
1912 | although libev might modify this value for better numerical stability). |
1537 | |
1913 | |
1538 | Can be modified any time, but changes only take effect when the periodic |
1914 | Can be modified any time, but changes only take effect when the periodic |
1539 | timer fires or C<ev_periodic_again> is being called. |
1915 | timer fires or C<ev_periodic_again> is being called. |
1540 | |
1916 | |
1541 | =item ev_tstamp interval [read-write] |
1917 | =item ev_tstamp interval [read-write] |
1542 | |
1918 | |
1543 | The current interval value. Can be modified any time, but changes only |
1919 | The current interval value. Can be modified any time, but changes only |
1544 | take effect when the periodic timer fires or C<ev_periodic_again> is being |
1920 | take effect when the periodic timer fires or C<ev_periodic_again> is being |
1545 | called. |
1921 | called. |
1546 | |
1922 | |
1547 | =item ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now) [read-write] |
1923 | =item ev_tstamp (*reschedule_cb)(ev_periodic *w, ev_tstamp now) [read-write] |
1548 | |
1924 | |
1549 | The current reschedule callback, or C<0>, if this functionality is |
1925 | The current reschedule callback, or C<0>, if this functionality is |
1550 | switched off. Can be changed any time, but changes only take effect when |
1926 | switched off. Can be changed any time, but changes only take effect when |
1551 | the periodic timer fires or C<ev_periodic_again> is being called. |
1927 | the periodic timer fires or C<ev_periodic_again> is being called. |
1552 | |
1928 | |
… | |
… | |
1557 | Example: Call a callback every hour, or, more precisely, whenever the |
1933 | Example: Call a callback every hour, or, more precisely, whenever the |
1558 | system time is divisible by 3600. The callback invocation times have |
1934 | system time is divisible by 3600. The callback invocation times have |
1559 | potentially a lot of jitter, but good long-term stability. |
1935 | potentially a lot of jitter, but good long-term stability. |
1560 | |
1936 | |
1561 | static void |
1937 | static void |
1562 | clock_cb (struct ev_loop *loop, struct ev_io *w, int revents) |
1938 | clock_cb (struct ev_loop *loop, ev_io *w, int revents) |
1563 | { |
1939 | { |
1564 | ... its now a full hour (UTC, or TAI or whatever your clock follows) |
1940 | ... its now a full hour (UTC, or TAI or whatever your clock follows) |
1565 | } |
1941 | } |
1566 | |
1942 | |
1567 | struct ev_periodic hourly_tick; |
1943 | ev_periodic hourly_tick; |
1568 | ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); |
1944 | ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); |
1569 | ev_periodic_start (loop, &hourly_tick); |
1945 | ev_periodic_start (loop, &hourly_tick); |
1570 | |
1946 | |
1571 | Example: The same as above, but use a reschedule callback to do it: |
1947 | Example: The same as above, but use a reschedule callback to do it: |
1572 | |
1948 | |
1573 | #include <math.h> |
1949 | #include <math.h> |
1574 | |
1950 | |
1575 | static ev_tstamp |
1951 | static ev_tstamp |
1576 | my_scheduler_cb (struct ev_periodic *w, ev_tstamp now) |
1952 | my_scheduler_cb (ev_periodic *w, ev_tstamp now) |
1577 | { |
1953 | { |
1578 | return now + (3600. - fmod (now, 3600.)); |
1954 | return now + (3600. - fmod (now, 3600.)); |
1579 | } |
1955 | } |
1580 | |
1956 | |
1581 | ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb); |
1957 | ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb); |
1582 | |
1958 | |
1583 | Example: Call a callback every hour, starting now: |
1959 | Example: Call a callback every hour, starting now: |
1584 | |
1960 | |
1585 | struct ev_periodic hourly_tick; |
1961 | ev_periodic hourly_tick; |
1586 | ev_periodic_init (&hourly_tick, clock_cb, |
1962 | ev_periodic_init (&hourly_tick, clock_cb, |
1587 | fmod (ev_now (loop), 3600.), 3600., 0); |
1963 | fmod (ev_now (loop), 3600.), 3600., 0); |
1588 | ev_periodic_start (loop, &hourly_tick); |
1964 | ev_periodic_start (loop, &hourly_tick); |
1589 | |
1965 | |
1590 | |
1966 | |
… | |
… | |
1632 | =head3 Examples |
2008 | =head3 Examples |
1633 | |
2009 | |
1634 | Example: Try to exit cleanly on SIGINT. |
2010 | Example: Try to exit cleanly on SIGINT. |
1635 | |
2011 | |
1636 | static void |
2012 | static void |
1637 | sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents) |
2013 | sigint_cb (struct ev_loop *loop, ev_signal *w, int revents) |
1638 | { |
2014 | { |
1639 | ev_unloop (loop, EVUNLOOP_ALL); |
2015 | ev_unloop (loop, EVUNLOOP_ALL); |
1640 | } |
2016 | } |
1641 | |
2017 | |
1642 | struct ev_signal signal_watcher; |
2018 | ev_signal signal_watcher; |
1643 | ev_signal_init (&signal_watcher, sigint_cb, SIGINT); |
2019 | ev_signal_init (&signal_watcher, sigint_cb, SIGINT); |
1644 | ev_signal_start (loop, &signal_watcher); |
2020 | ev_signal_start (loop, &signal_watcher); |
1645 | |
2021 | |
1646 | |
2022 | |
1647 | =head2 C<ev_child> - watch out for process status changes |
2023 | =head2 C<ev_child> - watch out for process status changes |
… | |
… | |
1650 | some child status changes (most typically when a child of yours dies or |
2026 | some child status changes (most typically when a child of yours dies or |
1651 | exits). It is permissible to install a child watcher I<after> the child |
2027 | exits). It is permissible to install a child watcher I<after> the child |
1652 | has been forked (which implies it might have already exited), as long |
2028 | has been forked (which implies it might have already exited), as long |
1653 | as the event loop isn't entered (or is continued from a watcher), i.e., |
2029 | as the event loop isn't entered (or is continued from a watcher), i.e., |
1654 | forking and then immediately registering a watcher for the child is fine, |
2030 | forking and then immediately registering a watcher for the child is fine, |
1655 | but forking and registering a watcher a few event loop iterations later is |
2031 | but forking and registering a watcher a few event loop iterations later or |
1656 | not. |
2032 | in the next callback invocation is not. |
1657 | |
2033 | |
1658 | Only the default event loop is capable of handling signals, and therefore |
2034 | Only the default event loop is capable of handling signals, and therefore |
1659 | you can only register child watchers in the default event loop. |
2035 | you can only register child watchers in the default event loop. |
|
|
2036 | |
|
|
2037 | Due to some design glitches inside libev, child watchers will always be |
|
|
2038 | handled at maximum priority (their priority is set to EV_MAXPRI by libev) |
1660 | |
2039 | |
1661 | =head3 Process Interaction |
2040 | =head3 Process Interaction |
1662 | |
2041 | |
1663 | Libev grabs C<SIGCHLD> as soon as the default event loop is |
2042 | Libev grabs C<SIGCHLD> as soon as the default event loop is |
1664 | initialised. This is necessary to guarantee proper behaviour even if |
2043 | initialised. This is necessary to guarantee proper behaviour even if |
… | |
… | |
1722 | its completion. |
2101 | its completion. |
1723 | |
2102 | |
1724 | ev_child cw; |
2103 | ev_child cw; |
1725 | |
2104 | |
1726 | static void |
2105 | static void |
1727 | child_cb (EV_P_ struct ev_child *w, int revents) |
2106 | child_cb (EV_P_ ev_child *w, int revents) |
1728 | { |
2107 | { |
1729 | ev_child_stop (EV_A_ w); |
2108 | ev_child_stop (EV_A_ w); |
1730 | printf ("process %d exited with status %x\n", w->rpid, w->rstatus); |
2109 | printf ("process %d exited with status %x\n", w->rpid, w->rstatus); |
1731 | } |
2110 | } |
1732 | |
2111 | |
… | |
… | |
1747 | |
2126 | |
1748 | |
2127 | |
1749 | =head2 C<ev_stat> - did the file attributes just change? |
2128 | =head2 C<ev_stat> - did the file attributes just change? |
1750 | |
2129 | |
1751 | This watches a file system path for attribute changes. That is, it calls |
2130 | This watches a file system path for attribute changes. That is, it calls |
1752 | C<stat> regularly (or when the OS says it changed) and sees if it changed |
2131 | C<stat> on that path in regular intervals (or when the OS says it changed) |
1753 | compared to the last time, invoking the callback if it did. |
2132 | and sees if it changed compared to the last time, invoking the callback if |
|
|
2133 | it did. |
1754 | |
2134 | |
1755 | The path does not need to exist: changing from "path exists" to "path does |
2135 | The path does not need to exist: changing from "path exists" to "path does |
1756 | not exist" is a status change like any other. The condition "path does |
2136 | not exist" is a status change like any other. The condition "path does not |
1757 | not exist" is signified by the C<st_nlink> field being zero (which is |
2137 | exist" (or more correctly "path cannot be stat'ed") is signified by the |
1758 | otherwise always forced to be at least one) and all the other fields of |
2138 | C<st_nlink> field being zero (which is otherwise always forced to be at |
1759 | the stat buffer having unspecified contents. |
2139 | least one) and all the other fields of the stat buffer having unspecified |
|
|
2140 | contents. |
1760 | |
2141 | |
1761 | The path I<should> be absolute and I<must not> end in a slash. If it is |
2142 | The path I<must not> end in a slash or contain special components such as |
|
|
2143 | C<.> or C<..>. The path I<should> be absolute: If it is relative and |
1762 | relative and your working directory changes, the behaviour is undefined. |
2144 | your working directory changes, then the behaviour is undefined. |
1763 | |
2145 | |
1764 | Since there is no standard kernel interface to do this, the portable |
2146 | Since there is no portable change notification interface available, the |
1765 | implementation simply calls C<stat (2)> regularly on the path to see if |
2147 | portable implementation simply calls C<stat(2)> regularly on the path |
1766 | it changed somehow. You can specify a recommended polling interval for |
2148 | to see if it changed somehow. You can specify a recommended polling |
1767 | this case. If you specify a polling interval of C<0> (highly recommended!) |
2149 | interval for this case. If you specify a polling interval of C<0> (highly |
1768 | then a I<suitable, unspecified default> value will be used (which |
2150 | recommended!) then a I<suitable, unspecified default> value will be used |
1769 | you can expect to be around five seconds, although this might change |
2151 | (which you can expect to be around five seconds, although this might |
1770 | dynamically). Libev will also impose a minimum interval which is currently |
2152 | change dynamically). Libev will also impose a minimum interval which is |
1771 | around C<0.1>, but thats usually overkill. |
2153 | currently around C<0.1>, but that's usually overkill. |
1772 | |
2154 | |
1773 | This watcher type is not meant for massive numbers of stat watchers, |
2155 | This watcher type is not meant for massive numbers of stat watchers, |
1774 | as even with OS-supported change notifications, this can be |
2156 | as even with OS-supported change notifications, this can be |
1775 | resource-intensive. |
2157 | resource-intensive. |
1776 | |
2158 | |
1777 | At the time of this writing, the only OS-specific interface implemented |
2159 | At the time of this writing, the only OS-specific interface implemented |
1778 | is the Linux inotify interface (implementing kqueue support is left as |
2160 | is the Linux inotify interface (implementing kqueue support is left as an |
1779 | an exercise for the reader. Note, however, that the author sees no way |
2161 | exercise for the reader. Note, however, that the author sees no way of |
1780 | of implementing C<ev_stat> semantics with kqueue). |
2162 | implementing C<ev_stat> semantics with kqueue, except as a hint). |
1781 | |
2163 | |
1782 | =head3 ABI Issues (Largefile Support) |
2164 | =head3 ABI Issues (Largefile Support) |
1783 | |
2165 | |
1784 | Libev by default (unless the user overrides this) uses the default |
2166 | Libev by default (unless the user overrides this) uses the default |
1785 | compilation environment, which means that on systems with large file |
2167 | compilation environment, which means that on systems with large file |
1786 | support disabled by default, you get the 32 bit version of the stat |
2168 | support disabled by default, you get the 32 bit version of the stat |
1787 | structure. When using the library from programs that change the ABI to |
2169 | structure. When using the library from programs that change the ABI to |
1788 | use 64 bit file offsets the programs will fail. In that case you have to |
2170 | use 64 bit file offsets the programs will fail. In that case you have to |
1789 | compile libev with the same flags to get binary compatibility. This is |
2171 | compile libev with the same flags to get binary compatibility. This is |
1790 | obviously the case with any flags that change the ABI, but the problem is |
2172 | obviously the case with any flags that change the ABI, but the problem is |
1791 | most noticeably disabled with ev_stat and large file support. |
2173 | most noticeably displayed with ev_stat and large file support. |
1792 | |
2174 | |
1793 | The solution for this is to lobby your distribution maker to make large |
2175 | The solution for this is to lobby your distribution maker to make large |
1794 | file interfaces available by default (as e.g. FreeBSD does) and not |
2176 | file interfaces available by default (as e.g. FreeBSD does) and not |
1795 | optional. Libev cannot simply switch on large file support because it has |
2177 | optional. Libev cannot simply switch on large file support because it has |
1796 | to exchange stat structures with application programs compiled using the |
2178 | to exchange stat structures with application programs compiled using the |
1797 | default compilation environment. |
2179 | default compilation environment. |
1798 | |
2180 | |
1799 | =head3 Inotify and Kqueue |
2181 | =head3 Inotify and Kqueue |
1800 | |
2182 | |
1801 | When C<inotify (7)> support has been compiled into libev (generally only |
2183 | When C<inotify (7)> support has been compiled into libev and present at |
1802 | available with Linux) and present at runtime, it will be used to speed up |
2184 | runtime, it will be used to speed up change detection where possible. The |
1803 | change detection where possible. The inotify descriptor will be created lazily |
2185 | inotify descriptor will be created lazily when the first C<ev_stat> |
1804 | when the first C<ev_stat> watcher is being started. |
2186 | watcher is being started. |
1805 | |
2187 | |
1806 | Inotify presence does not change the semantics of C<ev_stat> watchers |
2188 | Inotify presence does not change the semantics of C<ev_stat> watchers |
1807 | except that changes might be detected earlier, and in some cases, to avoid |
2189 | except that changes might be detected earlier, and in some cases, to avoid |
1808 | making regular C<stat> calls. Even in the presence of inotify support |
2190 | making regular C<stat> calls. Even in the presence of inotify support |
1809 | there are many cases where libev has to resort to regular C<stat> polling, |
2191 | there are many cases where libev has to resort to regular C<stat> polling, |
1810 | but as long as the path exists, libev usually gets away without polling. |
2192 | but as long as kernel 2.6.25 or newer is used (2.6.24 and older have too |
|
|
2193 | many bugs), the path exists (i.e. stat succeeds), and the path resides on |
|
|
2194 | a local filesystem (libev currently assumes only ext2/3, jfs, reiserfs and |
|
|
2195 | xfs are fully working) libev usually gets away without polling. |
1811 | |
2196 | |
1812 | There is no support for kqueue, as apparently it cannot be used to |
2197 | There is no support for kqueue, as apparently it cannot be used to |
1813 | implement this functionality, due to the requirement of having a file |
2198 | implement this functionality, due to the requirement of having a file |
1814 | descriptor open on the object at all times, and detecting renames, unlinks |
2199 | descriptor open on the object at all times, and detecting renames, unlinks |
1815 | etc. is difficult. |
2200 | etc. is difficult. |
1816 | |
2201 | |
|
|
2202 | =head3 C<stat ()> is a synchronous operation |
|
|
2203 | |
|
|
2204 | Libev doesn't normally do any kind of I/O itself, and so is not blocking |
|
|
2205 | the process. The exception are C<ev_stat> watchers - those call C<stat |
|
|
2206 | ()>, which is a synchronous operation. |
|
|
2207 | |
|
|
2208 | For local paths, this usually doesn't matter: unless the system is very |
|
|
2209 | busy or the intervals between stat's are large, a stat call will be fast, |
|
|
2210 | as the path data is usually in memory already (except when starting the |
|
|
2211 | watcher). |
|
|
2212 | |
|
|
2213 | For networked file systems, calling C<stat ()> can block an indefinite |
|
|
2214 | time due to network issues, and even under good conditions, a stat call |
|
|
2215 | often takes multiple milliseconds. |
|
|
2216 | |
|
|
2217 | Therefore, it is best to avoid using C<ev_stat> watchers on networked |
|
|
2218 | paths, although this is fully supported by libev. |
|
|
2219 | |
1817 | =head3 The special problem of stat time resolution |
2220 | =head3 The special problem of stat time resolution |
1818 | |
2221 | |
1819 | The C<stat ()> system call only supports full-second resolution portably, and |
2222 | The C<stat ()> system call only supports full-second resolution portably, |
1820 | even on systems where the resolution is higher, most file systems still |
2223 | and even on systems where the resolution is higher, most file systems |
1821 | only support whole seconds. |
2224 | still only support whole seconds. |
1822 | |
2225 | |
1823 | That means that, if the time is the only thing that changes, you can |
2226 | That means that, if the time is the only thing that changes, you can |
1824 | easily miss updates: on the first update, C<ev_stat> detects a change and |
2227 | easily miss updates: on the first update, C<ev_stat> detects a change and |
1825 | calls your callback, which does something. When there is another update |
2228 | calls your callback, which does something. When there is another update |
1826 | within the same second, C<ev_stat> will be unable to detect unless the |
2229 | within the same second, C<ev_stat> will be unable to detect unless the |
… | |
… | |
1969 | |
2372 | |
1970 | =head3 Watcher-Specific Functions and Data Members |
2373 | =head3 Watcher-Specific Functions and Data Members |
1971 | |
2374 | |
1972 | =over 4 |
2375 | =over 4 |
1973 | |
2376 | |
1974 | =item ev_idle_init (ev_signal *, callback) |
2377 | =item ev_idle_init (ev_idle *, callback) |
1975 | |
2378 | |
1976 | Initialises and configures the idle watcher - it has no parameters of any |
2379 | Initialises and configures the idle watcher - it has no parameters of any |
1977 | kind. There is a C<ev_idle_set> macro, but using it is utterly pointless, |
2380 | kind. There is a C<ev_idle_set> macro, but using it is utterly pointless, |
1978 | believe me. |
2381 | believe me. |
1979 | |
2382 | |
… | |
… | |
1983 | |
2386 | |
1984 | Example: Dynamically allocate an C<ev_idle> watcher, start it, and in the |
2387 | Example: Dynamically allocate an C<ev_idle> watcher, start it, and in the |
1985 | callback, free it. Also, use no error checking, as usual. |
2388 | callback, free it. Also, use no error checking, as usual. |
1986 | |
2389 | |
1987 | static void |
2390 | static void |
1988 | idle_cb (struct ev_loop *loop, struct ev_idle *w, int revents) |
2391 | idle_cb (struct ev_loop *loop, ev_idle *w, int revents) |
1989 | { |
2392 | { |
1990 | free (w); |
2393 | free (w); |
1991 | // now do something you wanted to do when the program has |
2394 | // now do something you wanted to do when the program has |
1992 | // no longer anything immediate to do. |
2395 | // no longer anything immediate to do. |
1993 | } |
2396 | } |
1994 | |
2397 | |
1995 | struct ev_idle *idle_watcher = malloc (sizeof (struct ev_idle)); |
2398 | ev_idle *idle_watcher = malloc (sizeof (ev_idle)); |
1996 | ev_idle_init (idle_watcher, idle_cb); |
2399 | ev_idle_init (idle_watcher, idle_cb); |
1997 | ev_idle_start (loop, idle_cb); |
2400 | ev_idle_start (loop, idle_watcher); |
1998 | |
2401 | |
1999 | |
2402 | |
2000 | =head2 C<ev_prepare> and C<ev_check> - customise your event loop! |
2403 | =head2 C<ev_prepare> and C<ev_check> - customise your event loop! |
2001 | |
2404 | |
2002 | Prepare and check watchers are usually (but not always) used in pairs: |
2405 | Prepare and check watchers are usually (but not always) used in pairs: |
… | |
… | |
2081 | |
2484 | |
2082 | static ev_io iow [nfd]; |
2485 | static ev_io iow [nfd]; |
2083 | static ev_timer tw; |
2486 | static ev_timer tw; |
2084 | |
2487 | |
2085 | static void |
2488 | static void |
2086 | io_cb (ev_loop *loop, ev_io *w, int revents) |
2489 | io_cb (struct ev_loop *loop, ev_io *w, int revents) |
2087 | { |
2490 | { |
2088 | } |
2491 | } |
2089 | |
2492 | |
2090 | // create io watchers for each fd and a timer before blocking |
2493 | // create io watchers for each fd and a timer before blocking |
2091 | static void |
2494 | static void |
2092 | adns_prepare_cb (ev_loop *loop, ev_prepare *w, int revents) |
2495 | adns_prepare_cb (struct ev_loop *loop, ev_prepare *w, int revents) |
2093 | { |
2496 | { |
2094 | int timeout = 3600000; |
2497 | int timeout = 3600000; |
2095 | struct pollfd fds [nfd]; |
2498 | struct pollfd fds [nfd]; |
2096 | // actual code will need to loop here and realloc etc. |
2499 | // actual code will need to loop here and realloc etc. |
2097 | adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); |
2500 | adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); |
2098 | |
2501 | |
2099 | /* the callback is illegal, but won't be called as we stop during check */ |
2502 | /* the callback is illegal, but won't be called as we stop during check */ |
2100 | ev_timer_init (&tw, 0, timeout * 1e-3); |
2503 | ev_timer_init (&tw, 0, timeout * 1e-3, 0.); |
2101 | ev_timer_start (loop, &tw); |
2504 | ev_timer_start (loop, &tw); |
2102 | |
2505 | |
2103 | // create one ev_io per pollfd |
2506 | // create one ev_io per pollfd |
2104 | for (int i = 0; i < nfd; ++i) |
2507 | for (int i = 0; i < nfd; ++i) |
2105 | { |
2508 | { |
… | |
… | |
2112 | } |
2515 | } |
2113 | } |
2516 | } |
2114 | |
2517 | |
2115 | // stop all watchers after blocking |
2518 | // stop all watchers after blocking |
2116 | static void |
2519 | static void |
2117 | adns_check_cb (ev_loop *loop, ev_check *w, int revents) |
2520 | adns_check_cb (struct ev_loop *loop, ev_check *w, int revents) |
2118 | { |
2521 | { |
2119 | ev_timer_stop (loop, &tw); |
2522 | ev_timer_stop (loop, &tw); |
2120 | |
2523 | |
2121 | for (int i = 0; i < nfd; ++i) |
2524 | for (int i = 0; i < nfd; ++i) |
2122 | { |
2525 | { |
… | |
… | |
2218 | some fds have to be watched and handled very quickly (with low latency), |
2621 | some fds have to be watched and handled very quickly (with low latency), |
2219 | and even priorities and idle watchers might have too much overhead. In |
2622 | and even priorities and idle watchers might have too much overhead. In |
2220 | this case you would put all the high priority stuff in one loop and all |
2623 | this case you would put all the high priority stuff in one loop and all |
2221 | the rest in a second one, and embed the second one in the first. |
2624 | the rest in a second one, and embed the second one in the first. |
2222 | |
2625 | |
2223 | As long as the watcher is active, the callback will be invoked every time |
2626 | As long as the watcher is active, the callback will be invoked every |
2224 | there might be events pending in the embedded loop. The callback must then |
2627 | time there might be events pending in the embedded loop. The callback |
2225 | call C<ev_embed_sweep (mainloop, watcher)> to make a single sweep and invoke |
2628 | must then call C<ev_embed_sweep (mainloop, watcher)> to make a single |
2226 | their callbacks (you could also start an idle watcher to give the embedded |
2629 | sweep and invoke their callbacks (the callback doesn't need to invoke the |
2227 | loop strictly lower priority for example). You can also set the callback |
2630 | C<ev_embed_sweep> function directly, it could also start an idle watcher |
2228 | to C<0>, in which case the embed watcher will automatically execute the |
2631 | to give the embedded loop strictly lower priority for example). |
2229 | embedded loop sweep. |
|
|
2230 | |
2632 | |
2231 | As long as the watcher is started it will automatically handle events. The |
2633 | You can also set the callback to C<0>, in which case the embed watcher |
2232 | callback will be invoked whenever some events have been handled. You can |
2634 | will automatically execute the embedded loop sweep whenever necessary. |
2233 | set the callback to C<0> to avoid having to specify one if you are not |
|
|
2234 | interested in that. |
|
|
2235 | |
2635 | |
2236 | Also, there have not currently been made special provisions for forking: |
2636 | Fork detection will be handled transparently while the C<ev_embed> watcher |
2237 | when you fork, you not only have to call C<ev_loop_fork> on both loops, |
2637 | is active, i.e., the embedded loop will automatically be forked when the |
2238 | but you will also have to stop and restart any C<ev_embed> watchers |
2638 | embedding loop forks. In other cases, the user is responsible for calling |
2239 | yourself - but you can use a fork watcher to handle this automatically, |
2639 | C<ev_loop_fork> on the embedded loop. |
2240 | and future versions of libev might do just that. |
|
|
2241 | |
2640 | |
2242 | Unfortunately, not all backends are embeddable: only the ones returned by |
2641 | Unfortunately, not all backends are embeddable: only the ones returned by |
2243 | C<ev_embeddable_backends> are, which, unfortunately, does not include any |
2642 | C<ev_embeddable_backends> are, which, unfortunately, does not include any |
2244 | portable one. |
2643 | portable one. |
2245 | |
2644 | |
… | |
… | |
2290 | C<loop_lo> (which is C<loop_hi> in the case no embeddable loop can be |
2689 | C<loop_lo> (which is C<loop_hi> in the case no embeddable loop can be |
2291 | used). |
2690 | used). |
2292 | |
2691 | |
2293 | struct ev_loop *loop_hi = ev_default_init (0); |
2692 | struct ev_loop *loop_hi = ev_default_init (0); |
2294 | struct ev_loop *loop_lo = 0; |
2693 | struct ev_loop *loop_lo = 0; |
2295 | struct ev_embed embed; |
2694 | ev_embed embed; |
2296 | |
2695 | |
2297 | // see if there is a chance of getting one that works |
2696 | // see if there is a chance of getting one that works |
2298 | // (remember that a flags value of 0 means autodetection) |
2697 | // (remember that a flags value of 0 means autodetection) |
2299 | loop_lo = ev_embeddable_backends () & ev_recommended_backends () |
2698 | loop_lo = ev_embeddable_backends () & ev_recommended_backends () |
2300 | ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) |
2699 | ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) |
… | |
… | |
2314 | kqueue implementation). Store the kqueue/socket-only event loop in |
2713 | kqueue implementation). Store the kqueue/socket-only event loop in |
2315 | C<loop_socket>. (One might optionally use C<EVFLAG_NOENV>, too). |
2714 | C<loop_socket>. (One might optionally use C<EVFLAG_NOENV>, too). |
2316 | |
2715 | |
2317 | struct ev_loop *loop = ev_default_init (0); |
2716 | struct ev_loop *loop = ev_default_init (0); |
2318 | struct ev_loop *loop_socket = 0; |
2717 | struct ev_loop *loop_socket = 0; |
2319 | struct ev_embed embed; |
2718 | ev_embed embed; |
2320 | |
2719 | |
2321 | if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) |
2720 | if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) |
2322 | if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) |
2721 | if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) |
2323 | { |
2722 | { |
2324 | ev_embed_init (&embed, 0, loop_socket); |
2723 | ev_embed_init (&embed, 0, loop_socket); |
… | |
… | |
2339 | event loop blocks next and before C<ev_check> watchers are being called, |
2738 | event loop blocks next and before C<ev_check> watchers are being called, |
2340 | and only in the child after the fork. If whoever good citizen calling |
2739 | and only in the child after the fork. If whoever good citizen calling |
2341 | C<ev_default_fork> cheats and calls it in the wrong process, the fork |
2740 | C<ev_default_fork> cheats and calls it in the wrong process, the fork |
2342 | handlers will be invoked, too, of course. |
2741 | handlers will be invoked, too, of course. |
2343 | |
2742 | |
|
|
2743 | =head3 The special problem of life after fork - how is it possible? |
|
|
2744 | |
|
|
2745 | Most uses of C<fork()> consist of forking, then some simple calls to ste |
|
|
2746 | up/change the process environment, followed by a call to C<exec()>. This |
|
|
2747 | sequence should be handled by libev without any problems. |
|
|
2748 | |
|
|
2749 | This changes when the application actually wants to do event handling |
|
|
2750 | in the child, or both parent in child, in effect "continuing" after the |
|
|
2751 | fork. |
|
|
2752 | |
|
|
2753 | The default mode of operation (for libev, with application help to detect |
|
|
2754 | forks) is to duplicate all the state in the child, as would be expected |
|
|
2755 | when I<either> the parent I<or> the child process continues. |
|
|
2756 | |
|
|
2757 | When both processes want to continue using libev, then this is usually the |
|
|
2758 | wrong result. In that case, usually one process (typically the parent) is |
|
|
2759 | supposed to continue with all watchers in place as before, while the other |
|
|
2760 | process typically wants to start fresh, i.e. without any active watchers. |
|
|
2761 | |
|
|
2762 | The cleanest and most efficient way to achieve that with libev is to |
|
|
2763 | simply create a new event loop, which of course will be "empty", and |
|
|
2764 | use that for new watchers. This has the advantage of not touching more |
|
|
2765 | memory than necessary, and thus avoiding the copy-on-write, and the |
|
|
2766 | disadvantage of having to use multiple event loops (which do not support |
|
|
2767 | signal watchers). |
|
|
2768 | |
|
|
2769 | When this is not possible, or you want to use the default loop for |
|
|
2770 | other reasons, then in the process that wants to start "fresh", call |
|
|
2771 | C<ev_default_destroy ()> followed by C<ev_default_loop (...)>. Destroying |
|
|
2772 | the default loop will "orphan" (not stop) all registered watchers, so you |
|
|
2773 | have to be careful not to execute code that modifies those watchers. Note |
|
|
2774 | also that in that case, you have to re-register any signal watchers. |
|
|
2775 | |
2344 | =head3 Watcher-Specific Functions and Data Members |
2776 | =head3 Watcher-Specific Functions and Data Members |
2345 | |
2777 | |
2346 | =over 4 |
2778 | =over 4 |
2347 | |
2779 | |
2348 | =item ev_fork_init (ev_signal *, callback) |
2780 | =item ev_fork_init (ev_signal *, callback) |
… | |
… | |
2465 | =over 4 |
2897 | =over 4 |
2466 | |
2898 | |
2467 | =item ev_async_init (ev_async *, callback) |
2899 | =item ev_async_init (ev_async *, callback) |
2468 | |
2900 | |
2469 | Initialises and configures the async watcher - it has no parameters of any |
2901 | Initialises and configures the async watcher - it has no parameters of any |
2470 | kind. There is a C<ev_asynd_set> macro, but using it is utterly pointless, |
2902 | kind. There is a C<ev_async_set> macro, but using it is utterly pointless, |
2471 | trust me. |
2903 | trust me. |
2472 | |
2904 | |
2473 | =item ev_async_send (loop, ev_async *) |
2905 | =item ev_async_send (loop, ev_async *) |
2474 | |
2906 | |
2475 | Sends/signals/activates the given C<ev_async> watcher, that is, feeds |
2907 | Sends/signals/activates the given C<ev_async> watcher, that is, feeds |
2476 | an C<EV_ASYNC> event on the watcher into the event loop. Unlike |
2908 | an C<EV_ASYNC> event on the watcher into the event loop. Unlike |
2477 | C<ev_feed_event>, this call is safe to do from other threads, signal or |
2909 | C<ev_feed_event>, this call is safe to do from other threads, signal or |
2478 | similar contexts (see the discussion of C<EV_ATOMIC_T> in the embedding |
2910 | similar contexts (see the discussion of C<EV_ATOMIC_T> in the embedding |
2479 | section below on what exactly this means). |
2911 | section below on what exactly this means). |
2480 | |
2912 | |
|
|
2913 | Note that, as with other watchers in libev, multiple events might get |
|
|
2914 | compressed into a single callback invocation (another way to look at this |
|
|
2915 | is that C<ev_async> watchers are level-triggered, set on C<ev_async_send>, |
|
|
2916 | reset when the event loop detects that). |
|
|
2917 | |
2481 | This call incurs the overhead of a system call only once per loop iteration, |
2918 | This call incurs the overhead of a system call only once per event loop |
2482 | so while the overhead might be noticeable, it doesn't apply to repeated |
2919 | iteration, so while the overhead might be noticeable, it doesn't apply to |
2483 | calls to C<ev_async_send>. |
2920 | repeated calls to C<ev_async_send> for the same event loop. |
2484 | |
2921 | |
2485 | =item bool = ev_async_pending (ev_async *) |
2922 | =item bool = ev_async_pending (ev_async *) |
2486 | |
2923 | |
2487 | Returns a non-zero value when C<ev_async_send> has been called on the |
2924 | Returns a non-zero value when C<ev_async_send> has been called on the |
2488 | watcher but the event has not yet been processed (or even noted) by the |
2925 | watcher but the event has not yet been processed (or even noted) by the |
… | |
… | |
2491 | C<ev_async_send> sets a flag in the watcher and wakes up the loop. When |
2928 | C<ev_async_send> sets a flag in the watcher and wakes up the loop. When |
2492 | the loop iterates next and checks for the watcher to have become active, |
2929 | the loop iterates next and checks for the watcher to have become active, |
2493 | it will reset the flag again. C<ev_async_pending> can be used to very |
2930 | it will reset the flag again. C<ev_async_pending> can be used to very |
2494 | quickly check whether invoking the loop might be a good idea. |
2931 | quickly check whether invoking the loop might be a good idea. |
2495 | |
2932 | |
2496 | Not that this does I<not> check whether the watcher itself is pending, only |
2933 | Not that this does I<not> check whether the watcher itself is pending, |
2497 | whether it has been requested to make this watcher pending. |
2934 | only whether it has been requested to make this watcher pending: there |
|
|
2935 | is a time window between the event loop checking and resetting the async |
|
|
2936 | notification, and the callback being invoked. |
2498 | |
2937 | |
2499 | =back |
2938 | =back |
2500 | |
2939 | |
2501 | |
2940 | |
2502 | =head1 OTHER FUNCTIONS |
2941 | =head1 OTHER FUNCTIONS |
… | |
… | |
2538 | /* doh, nothing entered */; |
2977 | /* doh, nothing entered */; |
2539 | } |
2978 | } |
2540 | |
2979 | |
2541 | ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); |
2980 | ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); |
2542 | |
2981 | |
2543 | =item ev_feed_event (ev_loop *, watcher *, int revents) |
2982 | =item ev_feed_event (struct ev_loop *, watcher *, int revents) |
2544 | |
2983 | |
2545 | Feeds the given event set into the event loop, as if the specified event |
2984 | Feeds the given event set into the event loop, as if the specified event |
2546 | had happened for the specified watcher (which must be a pointer to an |
2985 | had happened for the specified watcher (which must be a pointer to an |
2547 | initialised but not necessarily started event watcher). |
2986 | initialised but not necessarily started event watcher). |
2548 | |
2987 | |
2549 | =item ev_feed_fd_event (ev_loop *, int fd, int revents) |
2988 | =item ev_feed_fd_event (struct ev_loop *, int fd, int revents) |
2550 | |
2989 | |
2551 | Feed an event on the given fd, as if a file descriptor backend detected |
2990 | Feed an event on the given fd, as if a file descriptor backend detected |
2552 | the given events it. |
2991 | the given events it. |
2553 | |
2992 | |
2554 | =item ev_feed_signal_event (ev_loop *loop, int signum) |
2993 | =item ev_feed_signal_event (struct ev_loop *loop, int signum) |
2555 | |
2994 | |
2556 | Feed an event as if the given signal occurred (C<loop> must be the default |
2995 | Feed an event as if the given signal occurred (C<loop> must be the default |
2557 | loop!). |
2996 | loop!). |
2558 | |
2997 | |
2559 | =back |
2998 | =back |
… | |
… | |
2680 | } |
3119 | } |
2681 | |
3120 | |
2682 | myclass obj; |
3121 | myclass obj; |
2683 | ev::io iow; |
3122 | ev::io iow; |
2684 | iow.set <myclass, &myclass::io_cb> (&obj); |
3123 | iow.set <myclass, &myclass::io_cb> (&obj); |
|
|
3124 | |
|
|
3125 | =item w->set (object *) |
|
|
3126 | |
|
|
3127 | This is an B<experimental> feature that might go away in a future version. |
|
|
3128 | |
|
|
3129 | This is a variation of a method callback - leaving out the method to call |
|
|
3130 | will default the method to C<operator ()>, which makes it possible to use |
|
|
3131 | functor objects without having to manually specify the C<operator ()> all |
|
|
3132 | the time. Incidentally, you can then also leave out the template argument |
|
|
3133 | list. |
|
|
3134 | |
|
|
3135 | The C<operator ()> method prototype must be C<void operator ()(watcher &w, |
|
|
3136 | int revents)>. |
|
|
3137 | |
|
|
3138 | See the method-C<set> above for more details. |
|
|
3139 | |
|
|
3140 | Example: use a functor object as callback. |
|
|
3141 | |
|
|
3142 | struct myfunctor |
|
|
3143 | { |
|
|
3144 | void operator() (ev::io &w, int revents) |
|
|
3145 | { |
|
|
3146 | ... |
|
|
3147 | } |
|
|
3148 | } |
|
|
3149 | |
|
|
3150 | myfunctor f; |
|
|
3151 | |
|
|
3152 | ev::io w; |
|
|
3153 | w.set (&f); |
2685 | |
3154 | |
2686 | =item w->set<function> (void *data = 0) |
3155 | =item w->set<function> (void *data = 0) |
2687 | |
3156 | |
2688 | Also sets a callback, but uses a static method or plain function as |
3157 | Also sets a callback, but uses a static method or plain function as |
2689 | callback. The optional C<data> argument will be stored in the watcher's |
3158 | callback. The optional C<data> argument will be stored in the watcher's |
… | |
… | |
2776 | L<http://software.schmorp.de/pkg/EV>. |
3245 | L<http://software.schmorp.de/pkg/EV>. |
2777 | |
3246 | |
2778 | =item Python |
3247 | =item Python |
2779 | |
3248 | |
2780 | Python bindings can be found at L<http://code.google.com/p/pyev/>. It |
3249 | Python bindings can be found at L<http://code.google.com/p/pyev/>. It |
2781 | seems to be quite complete and well-documented. Note, however, that the |
3250 | seems to be quite complete and well-documented. |
2782 | patch they require for libev is outright dangerous as it breaks the ABI |
|
|
2783 | for everybody else, and therefore, should never be applied in an installed |
|
|
2784 | libev (if python requires an incompatible ABI then it needs to embed |
|
|
2785 | libev). |
|
|
2786 | |
3251 | |
2787 | =item Ruby |
3252 | =item Ruby |
2788 | |
3253 | |
2789 | Tony Arcieri has written a ruby extension that offers access to a subset |
3254 | Tony Arcieri has written a ruby extension that offers access to a subset |
2790 | of the libev API and adds file handle abstractions, asynchronous DNS and |
3255 | of the libev API and adds file handle abstractions, asynchronous DNS and |
2791 | more on top of it. It can be found via gem servers. Its homepage is at |
3256 | more on top of it. It can be found via gem servers. Its homepage is at |
2792 | L<http://rev.rubyforge.org/>. |
3257 | L<http://rev.rubyforge.org/>. |
2793 | |
3258 | |
|
|
3259 | Roger Pack reports that using the link order C<-lws2_32 -lmsvcrt-ruby-190> |
|
|
3260 | makes rev work even on mingw. |
|
|
3261 | |
|
|
3262 | =item Haskell |
|
|
3263 | |
|
|
3264 | A haskell binding to libev is available at |
|
|
3265 | L<http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hlibev>. |
|
|
3266 | |
2794 | =item D |
3267 | =item D |
2795 | |
3268 | |
2796 | Leandro Lucarella has written a D language binding (F<ev.d>) for libev, to |
3269 | Leandro Lucarella has written a D language binding (F<ev.d>) for libev, to |
2797 | be found at L<http://proj.llucax.com.ar/wiki/evd>. |
3270 | be found at L<http://proj.llucax.com.ar/wiki/evd>. |
|
|
3271 | |
|
|
3272 | =item Ocaml |
|
|
3273 | |
|
|
3274 | Erkki Seppala has written Ocaml bindings for libev, to be found at |
|
|
3275 | L<http://modeemi.cs.tut.fi/~flux/software/ocaml-ev/>. |
2798 | |
3276 | |
2799 | =back |
3277 | =back |
2800 | |
3278 | |
2801 | |
3279 | |
2802 | =head1 MACRO MAGIC |
3280 | =head1 MACRO MAGIC |
… | |
… | |
2903 | |
3381 | |
2904 | #define EV_STANDALONE 1 |
3382 | #define EV_STANDALONE 1 |
2905 | #include "ev.h" |
3383 | #include "ev.h" |
2906 | |
3384 | |
2907 | Both header files and implementation files can be compiled with a C++ |
3385 | Both header files and implementation files can be compiled with a C++ |
2908 | compiler (at least, thats a stated goal, and breakage will be treated |
3386 | compiler (at least, that's a stated goal, and breakage will be treated |
2909 | as a bug). |
3387 | as a bug). |
2910 | |
3388 | |
2911 | You need the following files in your source tree, or in a directory |
3389 | You need the following files in your source tree, or in a directory |
2912 | in your include path (e.g. in libev/ when using -Ilibev): |
3390 | in your include path (e.g. in libev/ when using -Ilibev): |
2913 | |
3391 | |
… | |
… | |
2969 | keeps libev from including F<config.h>, and it also defines dummy |
3447 | keeps libev from including F<config.h>, and it also defines dummy |
2970 | implementations for some libevent functions (such as logging, which is not |
3448 | implementations for some libevent functions (such as logging, which is not |
2971 | supported). It will also not define any of the structs usually found in |
3449 | supported). It will also not define any of the structs usually found in |
2972 | F<event.h> that are not directly supported by the libev core alone. |
3450 | F<event.h> that are not directly supported by the libev core alone. |
2973 | |
3451 | |
|
|
3452 | In stanbdalone mode, libev will still try to automatically deduce the |
|
|
3453 | configuration, but has to be more conservative. |
|
|
3454 | |
2974 | =item EV_USE_MONOTONIC |
3455 | =item EV_USE_MONOTONIC |
2975 | |
3456 | |
2976 | If defined to be C<1>, libev will try to detect the availability of the |
3457 | If defined to be C<1>, libev will try to detect the availability of the |
2977 | monotonic clock option at both compile time and runtime. Otherwise no use |
3458 | monotonic clock option at both compile time and runtime. Otherwise no |
2978 | of the monotonic clock option will be attempted. If you enable this, you |
3459 | use of the monotonic clock option will be attempted. If you enable this, |
2979 | usually have to link against librt or something similar. Enabling it when |
3460 | you usually have to link against librt or something similar. Enabling it |
2980 | the functionality isn't available is safe, though, although you have |
3461 | when the functionality isn't available is safe, though, although you have |
2981 | to make sure you link against any libraries where the C<clock_gettime> |
3462 | to make sure you link against any libraries where the C<clock_gettime> |
2982 | function is hiding in (often F<-lrt>). |
3463 | function is hiding in (often F<-lrt>). See also C<EV_USE_CLOCK_SYSCALL>. |
2983 | |
3464 | |
2984 | =item EV_USE_REALTIME |
3465 | =item EV_USE_REALTIME |
2985 | |
3466 | |
2986 | If defined to be C<1>, libev will try to detect the availability of the |
3467 | If defined to be C<1>, libev will try to detect the availability of the |
2987 | real-time clock option at compile time (and assume its availability at |
3468 | real-time clock option at compile time (and assume its availability |
2988 | runtime if successful). Otherwise no use of the real-time clock option will |
3469 | at runtime if successful). Otherwise no use of the real-time clock |
2989 | be attempted. This effectively replaces C<gettimeofday> by C<clock_get |
3470 | option will be attempted. This effectively replaces C<gettimeofday> |
2990 | (CLOCK_REALTIME, ...)> and will not normally affect correctness. See the |
3471 | by C<clock_get (CLOCK_REALTIME, ...)> and will not normally affect |
2991 | note about libraries in the description of C<EV_USE_MONOTONIC>, though. |
3472 | correctness. See the note about libraries in the description of |
|
|
3473 | C<EV_USE_MONOTONIC>, though. Defaults to the opposite value of |
|
|
3474 | C<EV_USE_CLOCK_SYSCALL>. |
|
|
3475 | |
|
|
3476 | =item EV_USE_CLOCK_SYSCALL |
|
|
3477 | |
|
|
3478 | If defined to be C<1>, libev will try to use a direct syscall instead |
|
|
3479 | of calling the system-provided C<clock_gettime> function. This option |
|
|
3480 | exists because on GNU/Linux, C<clock_gettime> is in C<librt>, but C<librt> |
|
|
3481 | unconditionally pulls in C<libpthread>, slowing down single-threaded |
|
|
3482 | programs needlessly. Using a direct syscall is slightly slower (in |
|
|
3483 | theory), because no optimised vdso implementation can be used, but avoids |
|
|
3484 | the pthread dependency. Defaults to C<1> on GNU/Linux with glibc 2.x or |
|
|
3485 | higher, as it simplifies linking (no need for C<-lrt>). |
2992 | |
3486 | |
2993 | =item EV_USE_NANOSLEEP |
3487 | =item EV_USE_NANOSLEEP |
2994 | |
3488 | |
2995 | If defined to be C<1>, libev will assume that C<nanosleep ()> is available |
3489 | If defined to be C<1>, libev will assume that C<nanosleep ()> is available |
2996 | and will use it for delays. Otherwise it will use C<select ()>. |
3490 | and will use it for delays. Otherwise it will use C<select ()>. |
… | |
… | |
3012 | |
3506 | |
3013 | =item EV_SELECT_USE_FD_SET |
3507 | =item EV_SELECT_USE_FD_SET |
3014 | |
3508 | |
3015 | If defined to C<1>, then the select backend will use the system C<fd_set> |
3509 | If defined to C<1>, then the select backend will use the system C<fd_set> |
3016 | structure. This is useful if libev doesn't compile due to a missing |
3510 | structure. This is useful if libev doesn't compile due to a missing |
3017 | C<NFDBITS> or C<fd_mask> definition or it mis-guesses the bitset layout on |
3511 | C<NFDBITS> or C<fd_mask> definition or it mis-guesses the bitset layout |
3018 | exotic systems. This usually limits the range of file descriptors to some |
3512 | on exotic systems. This usually limits the range of file descriptors to |
3019 | low limit such as 1024 or might have other limitations (winsocket only |
3513 | some low limit such as 1024 or might have other limitations (winsocket |
3020 | allows 64 sockets). The C<FD_SETSIZE> macro, set before compilation, might |
3514 | only allows 64 sockets). The C<FD_SETSIZE> macro, set before compilation, |
3021 | influence the size of the C<fd_set> used. |
3515 | configures the maximum size of the C<fd_set>. |
3022 | |
3516 | |
3023 | =item EV_SELECT_IS_WINSOCKET |
3517 | =item EV_SELECT_IS_WINSOCKET |
3024 | |
3518 | |
3025 | When defined to C<1>, the select backend will assume that |
3519 | When defined to C<1>, the select backend will assume that |
3026 | select/socket/connect etc. don't understand file descriptors but |
3520 | select/socket/connect etc. don't understand file descriptors but |
… | |
… | |
3385 | loop, as long as you don't confuse yourself). The only exception is that |
3879 | loop, as long as you don't confuse yourself). The only exception is that |
3386 | you must not do this from C<ev_periodic> reschedule callbacks. |
3880 | you must not do this from C<ev_periodic> reschedule callbacks. |
3387 | |
3881 | |
3388 | Care has been taken to ensure that libev does not keep local state inside |
3882 | Care has been taken to ensure that libev does not keep local state inside |
3389 | C<ev_loop>, and other calls do not usually allow for coroutine switches as |
3883 | C<ev_loop>, and other calls do not usually allow for coroutine switches as |
3390 | they do not clal any callbacks. |
3884 | they do not call any callbacks. |
3391 | |
3885 | |
3392 | =head2 COMPILER WARNINGS |
3886 | =head2 COMPILER WARNINGS |
3393 | |
3887 | |
3394 | Depending on your compiler and compiler settings, you might get no or a |
3888 | Depending on your compiler and compiler settings, you might get no or a |
3395 | lot of warnings when compiling libev code. Some people are apparently |
3889 | lot of warnings when compiling libev code. Some people are apparently |
… | |
… | |
3429 | ==2274== definitely lost: 0 bytes in 0 blocks. |
3923 | ==2274== definitely lost: 0 bytes in 0 blocks. |
3430 | ==2274== possibly lost: 0 bytes in 0 blocks. |
3924 | ==2274== possibly lost: 0 bytes in 0 blocks. |
3431 | ==2274== still reachable: 256 bytes in 1 blocks. |
3925 | ==2274== still reachable: 256 bytes in 1 blocks. |
3432 | |
3926 | |
3433 | Then there is no memory leak, just as memory accounted to global variables |
3927 | Then there is no memory leak, just as memory accounted to global variables |
3434 | is not a memleak - the memory is still being refernced, and didn't leak. |
3928 | is not a memleak - the memory is still being referenced, and didn't leak. |
3435 | |
3929 | |
3436 | Similarly, under some circumstances, valgrind might report kernel bugs |
3930 | Similarly, under some circumstances, valgrind might report kernel bugs |
3437 | as if it were a bug in libev (e.g. in realloc or in the poll backend, |
3931 | as if it were a bug in libev (e.g. in realloc or in the poll backend, |
3438 | although an acceptable workaround has been found here), or it might be |
3932 | although an acceptable workaround has been found here), or it might be |
3439 | confused. |
3933 | confused. |
… | |
… | |
3468 | way (note also that glib is the slowest event library known to man). |
3962 | way (note also that glib is the slowest event library known to man). |
3469 | |
3963 | |
3470 | There is no supported compilation method available on windows except |
3964 | There is no supported compilation method available on windows except |
3471 | embedding it into other applications. |
3965 | embedding it into other applications. |
3472 | |
3966 | |
|
|
3967 | Sensible signal handling is officially unsupported by Microsoft - libev |
|
|
3968 | tries its best, but under most conditions, signals will simply not work. |
|
|
3969 | |
3473 | Not a libev limitation but worth mentioning: windows apparently doesn't |
3970 | Not a libev limitation but worth mentioning: windows apparently doesn't |
3474 | accept large writes: instead of resulting in a partial write, windows will |
3971 | accept large writes: instead of resulting in a partial write, windows will |
3475 | either accept everything or return C<ENOBUFS> if the buffer is too large, |
3972 | either accept everything or return C<ENOBUFS> if the buffer is too large, |
3476 | so make sure you only write small amounts into your sockets (less than a |
3973 | so make sure you only write small amounts into your sockets (less than a |
3477 | megabyte seems safe, but this apparently depends on the amount of memory |
3974 | megabyte seems safe, but this apparently depends on the amount of memory |
… | |
… | |
3481 | the abysmal performance of winsockets, using a large number of sockets |
3978 | the abysmal performance of winsockets, using a large number of sockets |
3482 | is not recommended (and not reasonable). If your program needs to use |
3979 | is not recommended (and not reasonable). If your program needs to use |
3483 | more than a hundred or so sockets, then likely it needs to use a totally |
3980 | more than a hundred or so sockets, then likely it needs to use a totally |
3484 | different implementation for windows, as libev offers the POSIX readiness |
3981 | different implementation for windows, as libev offers the POSIX readiness |
3485 | notification model, which cannot be implemented efficiently on windows |
3982 | notification model, which cannot be implemented efficiently on windows |
3486 | (Microsoft monopoly games). |
3983 | (due to Microsoft monopoly games). |
3487 | |
3984 | |
3488 | A typical way to use libev under windows is to embed it (see the embedding |
3985 | A typical way to use libev under windows is to embed it (see the embedding |
3489 | section for details) and use the following F<evwrap.h> header file instead |
3986 | section for details) and use the following F<evwrap.h> header file instead |
3490 | of F<ev.h>: |
3987 | of F<ev.h>: |
3491 | |
3988 | |
… | |
… | |
3527 | |
4024 | |
3528 | Early versions of winsocket's select only supported waiting for a maximum |
4025 | Early versions of winsocket's select only supported waiting for a maximum |
3529 | of C<64> handles (probably owning to the fact that all windows kernels |
4026 | of C<64> handles (probably owning to the fact that all windows kernels |
3530 | can only wait for C<64> things at the same time internally; Microsoft |
4027 | can only wait for C<64> things at the same time internally; Microsoft |
3531 | recommends spawning a chain of threads and wait for 63 handles and the |
4028 | recommends spawning a chain of threads and wait for 63 handles and the |
3532 | previous thread in each. Great). |
4029 | previous thread in each. Sounds great!). |
3533 | |
4030 | |
3534 | Newer versions support more handles, but you need to define C<FD_SETSIZE> |
4031 | Newer versions support more handles, but you need to define C<FD_SETSIZE> |
3535 | to some high number (e.g. C<2048>) before compiling the winsocket select |
4032 | to some high number (e.g. C<2048>) before compiling the winsocket select |
3536 | call (which might be in libev or elsewhere, for example, perl does its own |
4033 | call (which might be in libev or elsewhere, for example, perl and many |
3537 | select emulation on windows). |
4034 | other interpreters do their own select emulation on windows). |
3538 | |
4035 | |
3539 | Another limit is the number of file descriptors in the Microsoft runtime |
4036 | Another limit is the number of file descriptors in the Microsoft runtime |
3540 | libraries, which by default is C<64> (there must be a hidden I<64> fetish |
4037 | libraries, which by default is C<64> (there must be a hidden I<64> |
3541 | or something like this inside Microsoft). You can increase this by calling |
4038 | fetish or something like this inside Microsoft). You can increase this |
3542 | C<_setmaxstdio>, which can increase this limit to C<2048> (another |
4039 | by calling C<_setmaxstdio>, which can increase this limit to C<2048> |
3543 | arbitrary limit), but is broken in many versions of the Microsoft runtime |
4040 | (another arbitrary limit), but is broken in many versions of the Microsoft |
3544 | libraries. |
|
|
3545 | |
|
|
3546 | This might get you to about C<512> or C<2048> sockets (depending on |
4041 | runtime libraries. This might get you to about C<512> or C<2048> sockets |
3547 | windows version and/or the phase of the moon). To get more, you need to |
4042 | (depending on windows version and/or the phase of the moon). To get more, |
3548 | wrap all I/O functions and provide your own fd management, but the cost of |
4043 | you need to wrap all I/O functions and provide your own fd management, but |
3549 | calling select (O(n²)) will likely make this unworkable. |
4044 | the cost of calling select (O(n²)) will likely make this unworkable. |
3550 | |
4045 | |
3551 | =back |
4046 | =back |
3552 | |
4047 | |
3553 | =head2 PORTABILITY REQUIREMENTS |
4048 | =head2 PORTABILITY REQUIREMENTS |
3554 | |
4049 | |
… | |
… | |
3597 | =item C<double> must hold a time value in seconds with enough accuracy |
4092 | =item C<double> must hold a time value in seconds with enough accuracy |
3598 | |
4093 | |
3599 | The type C<double> is used to represent timestamps. It is required to |
4094 | The type C<double> is used to represent timestamps. It is required to |
3600 | have at least 51 bits of mantissa (and 9 bits of exponent), which is good |
4095 | have at least 51 bits of mantissa (and 9 bits of exponent), which is good |
3601 | enough for at least into the year 4000. This requirement is fulfilled by |
4096 | enough for at least into the year 4000. This requirement is fulfilled by |
3602 | implementations implementing IEEE 754 (basically all existing ones). |
4097 | implementations implementing IEEE 754, which is basically all existing |
|
|
4098 | ones. With IEEE 754 doubles, you get microsecond accuracy until at least |
|
|
4099 | 2200. |
3603 | |
4100 | |
3604 | =back |
4101 | =back |
3605 | |
4102 | |
3606 | If you know of other additional requirements drop me a note. |
4103 | If you know of other additional requirements drop me a note. |
3607 | |
4104 | |
… | |
… | |
3675 | involves iterating over all running async watchers or all signal numbers. |
4172 | involves iterating over all running async watchers or all signal numbers. |
3676 | |
4173 | |
3677 | =back |
4174 | =back |
3678 | |
4175 | |
3679 | |
4176 | |
|
|
4177 | =head1 GLOSSARY |
|
|
4178 | |
|
|
4179 | =over 4 |
|
|
4180 | |
|
|
4181 | =item active |
|
|
4182 | |
|
|
4183 | A watcher is active as long as it has been started (has been attached to |
|
|
4184 | an event loop) but not yet stopped (disassociated from the event loop). |
|
|
4185 | |
|
|
4186 | =item application |
|
|
4187 | |
|
|
4188 | In this document, an application is whatever is using libev. |
|
|
4189 | |
|
|
4190 | =item callback |
|
|
4191 | |
|
|
4192 | The address of a function that is called when some event has been |
|
|
4193 | detected. Callbacks are being passed the event loop, the watcher that |
|
|
4194 | received the event, and the actual event bitset. |
|
|
4195 | |
|
|
4196 | =item callback invocation |
|
|
4197 | |
|
|
4198 | The act of calling the callback associated with a watcher. |
|
|
4199 | |
|
|
4200 | =item event |
|
|
4201 | |
|
|
4202 | A change of state of some external event, such as data now being available |
|
|
4203 | for reading on a file descriptor, time having passed or simply not having |
|
|
4204 | any other events happening anymore. |
|
|
4205 | |
|
|
4206 | In libev, events are represented as single bits (such as C<EV_READ> or |
|
|
4207 | C<EV_TIMEOUT>). |
|
|
4208 | |
|
|
4209 | =item event library |
|
|
4210 | |
|
|
4211 | A software package implementing an event model and loop. |
|
|
4212 | |
|
|
4213 | =item event loop |
|
|
4214 | |
|
|
4215 | An entity that handles and processes external events and converts them |
|
|
4216 | into callback invocations. |
|
|
4217 | |
|
|
4218 | =item event model |
|
|
4219 | |
|
|
4220 | The model used to describe how an event loop handles and processes |
|
|
4221 | watchers and events. |
|
|
4222 | |
|
|
4223 | =item pending |
|
|
4224 | |
|
|
4225 | A watcher is pending as soon as the corresponding event has been detected, |
|
|
4226 | and stops being pending as soon as the watcher will be invoked or its |
|
|
4227 | pending status is explicitly cleared by the application. |
|
|
4228 | |
|
|
4229 | A watcher can be pending, but not active. Stopping a watcher also clears |
|
|
4230 | its pending status. |
|
|
4231 | |
|
|
4232 | =item real time |
|
|
4233 | |
|
|
4234 | The physical time that is observed. It is apparently strictly monotonic :) |
|
|
4235 | |
|
|
4236 | =item wall-clock time |
|
|
4237 | |
|
|
4238 | The time and date as shown on clocks. Unlike real time, it can actually |
|
|
4239 | be wrong and jump forwards and backwards, e.g. when the you adjust your |
|
|
4240 | clock. |
|
|
4241 | |
|
|
4242 | =item watcher |
|
|
4243 | |
|
|
4244 | A data structure that describes interest in certain events. Watchers need |
|
|
4245 | to be started (attached to an event loop) before they can receive events. |
|
|
4246 | |
|
|
4247 | =item watcher invocation |
|
|
4248 | |
|
|
4249 | The act of calling the callback associated with a watcher. |
|
|
4250 | |
|
|
4251 | =back |
|
|
4252 | |
3680 | =head1 AUTHOR |
4253 | =head1 AUTHOR |
3681 | |
4254 | |
3682 | Marc Lehmann <libev@schmorp.de>. |
4255 | Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael Magnusson. |
3683 | |
4256 | |