--- libev/ev.pod 2008/05/20 23:49:41 1.157 +++ libev/ev.pod 2008/09/19 03:52:56 1.182 @@ -4,63 +4,63 @@ =head1 SYNOPSIS - #include + #include =head2 EXAMPLE PROGRAM - // a single header file is required - #include + // a single header file is required + #include - // every watcher type has its own typedef'd struct - // with the name ev_ - ev_io stdin_watcher; - ev_timer timeout_watcher; - - // all watcher callbacks have a similar signature - // this callback is called when data is readable on stdin - static void - stdin_cb (EV_P_ struct ev_io *w, int revents) - { - puts ("stdin ready"); - // for one-shot events, one must manually stop the watcher - // with its corresponding stop function. - ev_io_stop (EV_A_ w); - - // this causes all nested ev_loop's to stop iterating - ev_unloop (EV_A_ EVUNLOOP_ALL); - } - - // another callback, this time for a time-out - static void - timeout_cb (EV_P_ struct ev_timer *w, int revents) - { - puts ("timeout"); - // this causes the innermost ev_loop to stop iterating - ev_unloop (EV_A_ EVUNLOOP_ONE); - } - - int - main (void) - { - // use the default event loop unless you have special needs - struct ev_loop *loop = ev_default_loop (0); - - // initialise an io watcher, then start it - // this one will watch for stdin to become readable - ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); - ev_io_start (loop, &stdin_watcher); - - // initialise a timer watcher, then start it - // simple non-repeating 5.5 second timeout - ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); - ev_timer_start (loop, &timeout_watcher); - - // now wait for events to arrive - ev_loop (loop, 0); - - // unloop was called, so exit - return 0; - } + // every watcher type has its own typedef'd struct + // with the name ev_ + ev_io stdin_watcher; + ev_timer timeout_watcher; + + // all watcher callbacks have a similar signature + // this callback is called when data is readable on stdin + static void + stdin_cb (EV_P_ struct ev_io *w, int revents) + { + puts ("stdin ready"); + // for one-shot events, one must manually stop the watcher + // with its corresponding stop function. + ev_io_stop (EV_A_ w); + + // this causes all nested ev_loop's to stop iterating + ev_unloop (EV_A_ EVUNLOOP_ALL); + } + + // another callback, this time for a time-out + static void + timeout_cb (EV_P_ struct ev_timer *w, int revents) + { + puts ("timeout"); + // this causes the innermost ev_loop to stop iterating + ev_unloop (EV_A_ EVUNLOOP_ONE); + } + + int + main (void) + { + // use the default event loop unless you have special needs + struct ev_loop *loop = ev_default_loop (0); + + // initialise an io watcher, then start it + // this one will watch for stdin to become readable + ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); + ev_io_start (loop, &stdin_watcher); + + // initialise a timer watcher, then start it + // simple non-repeating 5.5 second timeout + ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); + ev_timer_start (loop, &timeout_watcher); + + // now wait for events to arrive + ev_loop (loop, 0); + + // unloop was called, so exit + return 0; + } =head1 DESCRIPTION @@ -115,10 +115,31 @@ the beginning of 1970, details are complicated, don't ask). This type is called C, which is what you should use too. It usually aliases to the C type in C, and when you need to do any calculations on -it, you should treat it as some floatingpoint value. Unlike the name +it, you should treat it as some floating point value. Unlike the name component C might indicate, it is also used for time differences throughout libev. +=head1 ERROR HANDLING + +Libev knows three classes of errors: operating system errors, usage errors +and internal errors (bugs). + +When libev catches an operating system error it cannot handle (for example +a system call indicating a condition libev cannot fix), it calls the callback +set via C, which is supposed to fix the problem or +abort. The default is to print a diagnostic message and to call C. + +When libev detects a usage error such as a negative timer interval, then +it will print a diagnostic message and abort (via the C mechanism, +so C will disable this checking): these are programming errors in +the libev caller and need to be fixed there. + +Libev also has a few internal error-checking Cions, and also has +extensive consistency checking code. These do not trigger under normal +circumstances, as they indicate either a bug in libev or worse. + + =head1 GLOBAL FUNCTIONS These functions can be called anytime, even before initialising the @@ -136,7 +157,7 @@ Sleep for the given interval: The current thread will be blocked until either it is interrupted or the given time interval has passed. Basically -this is a subsecond-resolution C. +this is a sub-second-resolution C. =item int ev_version_major () @@ -159,9 +180,9 @@ Example: Make sure we haven't accidentally been linked against the wrong version. - assert (("libev version mismatch", - ev_version_major () == EV_VERSION_MAJOR - && ev_version_minor () >= EV_VERSION_MINOR)); + assert (("libev version mismatch", + ev_version_major () == EV_VERSION_MAJOR + && ev_version_minor () >= EV_VERSION_MINOR)); =item unsigned int ev_supported_backends () @@ -173,15 +194,15 @@ Example: make sure we have the epoll method, because yeah this is cool and a must have and can we have a torrent of it please!!!11 - assert (("sorry, no epoll, no sex", - ev_supported_backends () & EVBACKEND_EPOLL)); + assert (("sorry, no epoll, no sex", + ev_supported_backends () & EVBACKEND_EPOLL)); =item unsigned int ev_recommended_backends () Return the set of all backends compiled into this binary of libev and also recommended for this platform. This set is often smaller than the one returned by C, as for example kqueue is broken on -most BSDs and will not be autodetected unless you explicitly request it +most BSDs and will not be auto-detected unless you explicitly request it (assuming you know what you are doing). This is the set of backends that libev will probe for if you specify no backends explicitly. @@ -233,10 +254,10 @@ =item ev_set_syserr_cb (void (*cb)(const char *msg)); -Set the callback function to call on a retryable syscall error (such +Set the callback function to call on a retryable system call error (such as failed select, poll, epoll_wait). The message is a printable string indicating the system call or subsystem causing the problem. If this -callback is set, then libev will expect it to remedy the sitution, no +callback is set, then libev will expect it to remedy the situation, no matter what, when it returns. That is, libev will generally retry the requested operation, or, if the condition doesn't go away, do bad stuff (such as abort). @@ -279,7 +300,7 @@ The default loop is the only loop that can handle C and C watchers, and to do this, it always registers a handler -for C. If this is a problem for your app you can either +for C. If this is a problem for your application you can either create a dynamic loop with C that doesn't do that, or you can simply overwrite the C signal handler I calling C. @@ -298,7 +319,7 @@ =item C -If this flag bit is ored into the flag value (or the program runs setuid +If this flag bit is or'ed into the flag value (or the program runs setuid or setgid) then libev will I look at the environment variable C. Otherwise (the default), this environment variable will override the flags completely if it is found in the environment. This is @@ -315,14 +336,14 @@ and thus this might slow down your event loop if you do a lot of loop iterations and little real work, but is usually not noticeable (on my GNU/Linux system for example, C is actually a simple 5-insn sequence -without a syscall and thus I fast, but my GNU/Linux system also has +without a system call and thus I fast, but my GNU/Linux system also has C which is even faster). The big advantage of this flag is that you can forget about fork (and forget about forgetting to tell libev about forking) when you use this flag. -This flag setting cannot be overriden or specified in the C +This flag setting cannot be overridden or specified in the C environment variable. =item C (value 1, portable select backend) @@ -334,12 +355,16 @@ usually the fastest backend for a low number of (low-numbered :) fds. To get good performance out of this backend you need a high amount of -parallelity (most of the file descriptors should be busy). If you are +parallelism (most of the file descriptors should be busy). If you are writing a server, you should C in a loop to accept as many connections as possible during one iteration. You might also want to have a look at C to increase the amount of readiness notifications you get per iteration. +This backend maps C to the C set and C to the +C set (and to work around Microsoft Windows bugs, also onto the +C set on that platform). + =item C (value 2, poll backend, available everywhere except on windows) And this is your standard poll(2) backend. It's more complicated @@ -349,6 +374,9 @@ i.e. O(total_fds). See the entry for C, above, for performance tips. +This backend maps C to C, and +C to C. + =item C (value 4, Linux) For few fds, this backend is a bit little slower than poll and select, @@ -356,11 +384,11 @@ like O(total_fds) where n is the total number of fds (or the highest fd), epoll scales either O(1) or O(active_fds). The epoll design has a number of shortcomings, such as silently dropping events in some hard-to-detect -cases and requiring a syscall per fd change, no fork support and bad +cases and requiring a system call per fd change, no fork support and bad support for dup. While stopping, setting and starting an I/O watcher in the same iteration -will result in some caching, there is still a syscall per such incident +will result in some caching, there is still a system call per such incident (because the fd could point to a different file description now), so its best to avoid that. Also, C'ed file descriptors might not work very well if you register events for both fds. @@ -373,15 +401,18 @@ watchers for a file descriptor until it has been closed, if possible, i.e. keep at least one watcher active per fd at all times. -While nominally embeddeble in other event loops, this feature is broken in +While nominally embeddable in other event loops, this feature is broken in all kernel versions tested so far. +This backend maps C and C in the same way as +C. + =item C (value 8, most BSD clones) Kqueue deserves special mention, as at the time of this writing, it was broken on all BSDs except NetBSD (usually it doesn't work reliably with anything but sockets and pipes, except on Darwin, where of course -it's completely useless). For this reason it's not being "autodetected" +it's completely useless). For this reason it's not being "auto-detected" unless you explicitly specify it explicitly in the flags (i.e. using C) or libev was compiled on a known-to-be-good (-enough) system like NetBSD. @@ -393,7 +424,7 @@ It scales in the same way as the epoll backend, but the interface to the kernel is more efficient (which says nothing about its actual speed, of course). While stopping, setting and starting an I/O watcher does never -cause an extra syscall as with C, it still adds up to +cause an extra system call as with C, it still adds up to two event changes per incident, support for C is very bad and it drops fds silently in similarly hard-to-detect cases. @@ -406,6 +437,10 @@ (e.g. C or C) and using it only for sockets. +This backend maps C into an C kevent with +C, and C into an C kevent with +C. + =item C (value 16, Solaris 8) This is not implemented yet (and might never be, unless you send me an @@ -418,7 +453,7 @@ This uses the Solaris 10 event port mechanism. As with everything on Solaris, it's really slow, but it still scales very well (O(active_fds)). -Please note that solaris event ports can deliver a lot of spurious +Please note that Solaris event ports can deliver a lot of spurious notifications, so you need to use non-blocking I/O or other means to avoid blocking when no data (or space) is available. @@ -431,6 +466,9 @@ backend actually performed to specification in all tests and is fully embeddable, which is a rare feat among the OS-specific backends. +This backend maps C and C in the same way as +C. + =item C Try all backends (even potentially broken ones that wouldn't be tried @@ -441,25 +479,25 @@ =back -If one or more of these are ored into the flags value, then only these +If one or more of these are or'ed into the flags value, then only these backends will be tried (in the reverse order as listed here). If none are specified, all backends in C will be tried. The most typical usage is like this: - if (!ev_default_loop (0)) - fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?"); + if (!ev_default_loop (0)) + fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?"); Restrict libev to the select and poll backends, and do not allow environment settings to be taken into account: - ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV); + ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV); Use whatever libev has to offer, but make sure that kqueue is used if available (warning, breaks stuff, best use only with your own private event loop and only if you know the OS supports your types of fds): - ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE); + ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE); =item struct ev_loop *ev_loop_new (unsigned int flags) @@ -474,16 +512,16 @@ Example: Try to create a event loop that uses epoll and nothing else. - struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV); - if (!epoller) - fatal ("no epoll found here, maybe it hides under your chair"); + struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV); + if (!epoller) + fatal ("no epoll found here, maybe it hides under your chair"); =item ev_default_destroy () Destroys the default loop again (frees all memory and kernel state etc.). None of the active event watchers will be stopped in the normal sense, so e.g. C might still return true. It is your -responsibility to either stop all watchers cleanly yoursef I +responsibility to either stop all watchers cleanly yourself I calling this function, or cope with the fact afterwards (which is usually the easiest thing, you can just ignore the watchers and/or C them for example). @@ -554,6 +592,18 @@ time used for relative timers. You can treat it as the timestamp of the event occurring (or more correctly, libev finding out about it). +=item ev_now_update (loop) + +Establishes the current time by querying the kernel, updating the time +returned by C in the progress. This is a costly operation and +is usually done automatically within C. + +This function is rarely useful, but when some event callback runs for a +very long time without entering the event loop, updating libev's idea of +the current time is a good idea. + +See also "The special problem of time updates" in the C section. + =item ev_loop (loop, int flags) Finally, this is it, the event handler. This function usually is called @@ -574,7 +624,7 @@ case there are no events and will return after one iteration of the loop. A flags value of C will look for new events (waiting if -neccessary) and will handle those and any outstanding ones. It will block +necessary) and will handle those and any outstanding ones. It will block your process until at least one new event arrives, and will return after one iteration of the loop. This is useful if you are waiting for some external event in conjunction with something not expressible using other @@ -585,21 +635,22 @@ - Before the first iteration, call any pending watchers. * If EVFLAG_FORKCHECK was used, check for a fork. - - If a fork was detected, queue and call all fork watchers. + - If a fork was detected (by any means), queue and call all fork watchers. - Queue and call all prepare watchers. - - If we have been forked, recreate the kernel state. + - If we have been forked, detach and recreate the kernel state + as to not disturb the other process. - Update the kernel state with all outstanding changes. - - Update the "event loop time". + - Update the "event loop time" (ev_now ()). - Calculate for how long to sleep or block, if at all (active idle watchers, EVLOOP_NONBLOCK or not having any active watchers at all will result in not sleeping). - Sleep if the I/O and timer collect interval say so. - Block the process, waiting for any events. - Queue all outstanding I/O (fd) events. - - Update the "event loop time" and do time jump handling. + - Update the "event loop time" (ev_now ()), and do time jump adjustments. - Queue all outstanding timers. - Queue all outstanding periodics. - - If no events are pending now, queue all idle watchers. + - Unless any events are pending now, queue all idle watchers. - Queue all check watchers. - Call all queued watchers in reverse order (i.e. check watchers first). Signals and child watchers are implemented as I/O watchers, and will @@ -614,7 +665,7 @@ ... queue jobs here, make sure they register event watchers as long ... as they still have work to do (even an idle watcher will do..) ev_loop (my_loop, 0); - ... jobs done. yeah! + ... jobs done or somebody called unloop. yeah! =item ev_unloop (loop, how) @@ -645,27 +696,29 @@ Example: Create a signal watcher, but keep it from keeping C running when nothing else is active. - struct ev_signal exitsig; - ev_signal_init (&exitsig, sig_cb, SIGINT); - ev_signal_start (loop, &exitsig); - evf_unref (loop); + struct ev_signal exitsig; + ev_signal_init (&exitsig, sig_cb, SIGINT); + ev_signal_start (loop, &exitsig); + evf_unref (loop); Example: For some weird reason, unregister the above signal handler again. - ev_ref (loop); - ev_signal_stop (loop, &exitsig); + ev_ref (loop); + ev_signal_stop (loop, &exitsig); =item ev_set_io_collect_interval (loop, ev_tstamp interval) =item ev_set_timeout_collect_interval (loop, ev_tstamp interval) These advanced functions influence the time that libev will spend waiting -for events. Both are by default C<0>, meaning that libev will try to -invoke timer/periodic callbacks and I/O callbacks with minimum latency. +for events. Both time intervals are by default C<0>, meaning that libev +will try to invoke timer/periodic callbacks and I/O callbacks with minimum +latency. Setting these to a higher value (the C I be >= C<0>) -allows libev to delay invocation of I/O and timer/periodic callbacks to -increase efficiency of loop iterations. +allows libev to delay invocation of I/O and timer/periodic callbacks +to increase efficiency of loop iterations (or to increase power-saving +opportunities). The background is that sometimes your program runs just fast enough to handle one (or very few) event(s) per loop iteration. While this makes @@ -685,11 +738,29 @@ will not be affected. Setting this to a non-null value will not introduce any overhead in libev. -Many (busy) programs can usually benefit by setting the io collect +Many (busy) programs can usually benefit by setting the I/O collect interval to a value near C<0.1> or so, which is often enough for interactive servers (of course not for games), likewise for timeouts. It usually doesn't make much sense to set it to a lower value than C<0.01>, -as this approsaches the timing granularity of most systems. +as this approaches the timing granularity of most systems. + +Setting the I can improve the opportunity for +saving power, as the program will "bundle" timer callback invocations that +are "near" in time together, by delaying some, thus reducing the number of +times the process sleeps and wakes up again. Another useful technique to +reduce iterations/wake-ups is to use C watchers and make sure +they fire on, say, one-second boundaries only. + +=item ev_loop_verify (loop) + +This function only does something when C support has been +compiled in. It tries to go through all internal structures and checks +them for validity. If anything is found to be inconsistent, it will print +an error message to standard error and call C. + +This can be used to catch bugs inside libev itself: under normal +circumstances, this function will never abort as of course libev keeps its +data structures consistent. =back @@ -700,18 +771,18 @@ interest in some event. For instance, if you want to wait for STDIN to become readable, you would create an C watcher for that: - static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents) - { - ev_io_stop (w); - ev_unloop (loop, EVUNLOOP_ALL); - } - - struct ev_loop *loop = ev_default_loop (0); - struct ev_io stdin_watcher; - ev_init (&stdin_watcher, my_cb); - ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); - ev_io_start (loop, &stdin_watcher); - ev_loop (loop, 0); + static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents) + { + ev_io_stop (w); + ev_unloop (loop, EVUNLOOP_ALL); + } + + struct ev_loop *loop = ev_default_loop (0); + struct ev_io stdin_watcher; + ev_init (&stdin_watcher, my_cb); + ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); + ev_io_start (loop, &stdin_watcher); + ev_loop (loop, 0); As you can see, you are responsible for allocating the memory for your watcher structures (and it is usually a bad idea to do this on the stack, @@ -719,7 +790,7 @@ Each watcher structure must be initialised by a call to C, which expects a callback to be provided. This -callback gets invoked each time the event occurs (or, in the case of io +callback gets invoked each time the event occurs (or, in the case of I/O watchers, each time the event loop detects that the file descriptor given is readable and/or writable). @@ -805,7 +876,7 @@ =item C -An unspecified error has occured, the watcher has been stopped. This might +An unspecified error has occurred, the watcher has been stopped. This might happen because the watcher could not be properly started because libev ran out of memory, a file descriptor was found to be closed or any other problem. You best act on it by reporting the problem and somehow coping @@ -814,7 +885,7 @@ Libev will usually signal a few "dummy" events together with an error, for example it might indicate that a fd is readable or writable, and if your callbacks is well-written it can just attempt the operation and cope -with the error from read() or write(). This will not work in multithreaded +with the error from read() or write(). This will not work in multi-threaded programs, though, so beware. =back @@ -854,8 +925,8 @@ =item C (ev_TYPE *watcher, callback, [args]) -This convinience macro rolls both C and C macro -calls into a single call. This is the most convinient method to initialise +This convenience macro rolls both C and C macro +calls into a single call. This is the most convenient method to initialise a watcher. The same limitations apply, of course. =item C (loop *, ev_TYPE *watcher) @@ -948,54 +1019,60 @@ member, you can also "subclass" the watcher type and provide your own data: - struct my_io - { - struct ev_io io; - int otherfd; - void *somedata; - struct whatever *mostinteresting; - } + struct my_io + { + struct ev_io io; + int otherfd; + void *somedata; + struct whatever *mostinteresting; + }; + + ... + struct my_io w; + ev_io_init (&w.io, my_cb, fd, EV_READ); And since your callback will be called with a pointer to the watcher, you can cast it back to your own type: - static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents) - { - struct my_io *w = (struct my_io *)w_; - ... - } + static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents) + { + struct my_io *w = (struct my_io *)w_; + ... + } More interesting and less C-conformant ways of casting your callback type instead have been omitted. -Another common scenario is having some data structure with multiple -watchers: +Another common scenario is to use some data structure with multiple +embedded watchers: - struct my_biggy - { - int some_data; - ev_timer t1; - ev_timer t2; - } - -In this case getting the pointer to C is a bit more complicated, -you need to use C: - - #include - - static void - t1_cb (EV_P_ struct ev_timer *w, int revents) - { - struct my_biggy big = (struct my_biggy * - (((char *)w) - offsetof (struct my_biggy, t1)); - } - - static void - t2_cb (EV_P_ struct ev_timer *w, int revents) - { - struct my_biggy big = (struct my_biggy * - (((char *)w) - offsetof (struct my_biggy, t2)); - } + struct my_biggy + { + int some_data; + ev_timer t1; + ev_timer t2; + } + +In this case getting the pointer to C is a bit more +complicated: Either you store the address of your C struct +in the C member of the watcher, or you need to use some pointer +arithmetic using C inside your watchers: + + #include + + static void + t1_cb (EV_P_ struct ev_timer *w, int revents) + { + struct my_biggy big = (struct my_biggy * + (((char *)w) - offsetof (struct my_biggy, t1)); + } + + static void + t2_cb (EV_P_ struct ev_timer *w, int revents) + { + struct my_biggy big = (struct my_biggy * + (((char *)w) - offsetof (struct my_biggy, t2)); + } =head1 WATCHER TYPES @@ -1037,13 +1114,13 @@ receive "spurious" readiness notifications, that is your callback might be called with C but a subsequent C(2) will actually block because there is no data. Not only are some backends known to create a -lot of those (for example solaris ports), it is very easy to get into +lot of those (for example Solaris ports), it is very easy to get into this situation even with a relatively standard program structure. Thus it is best to always use non-blocking I/O: An extra C(2) returning C is far preferable to a program hanging until some data arrives. If you cannot run the fd in non-blocking mode (for example you should not -play around with an Xlib connection), then you have to seperately re-test +play around with an Xlib connection), then you have to separately re-test whether a file descriptor is really ready with a known-to-be good interface such as poll (fortunately in our Xlib example, Xlib already does this on its own, so its quite safe to use). @@ -1094,10 +1171,9 @@ =head3 The special problem of SIGPIPE While not really specific to libev, it is easy to forget about SIGPIPE: -when reading from a pipe whose other end has been closed, your program -gets send a SIGPIPE, which, by default, aborts your program. For most -programs this is sensible behaviour, for daemons, this is usually -undesirable. +when writing to a pipe whose other end has been closed, your program gets +send a SIGPIPE, which, by default, aborts your program. For most programs +this is sensible behaviour, for daemons, this is usually undesirable. So when you encounter spurious, unexplained daemon exits, make sure you ignore SIGPIPE (and maybe make sure you log the exit status of your daemon @@ -1113,7 +1189,7 @@ =item ev_io_set (ev_io *, int fd, int events) Configures an C watcher. The C is the file descriptor to -rceeive events for and events is either C, C or +receive events for and events is either C, C or C to receive the given events. =item int fd [read-only] @@ -1132,19 +1208,19 @@ readable, but only once. Since it is likely line-buffered, you could attempt to read a whole line in the callback. - static void - stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents) - { - ev_io_stop (loop, w); - .. read from stdin here (or from w->fd) and haqndle any I/O errors - } - - ... - struct ev_loop *loop = ev_default_init (0); - struct ev_io stdin_readable; - ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); - ev_io_start (loop, &stdin_readable); - ev_loop (loop, 0); + static void + stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents) + { + ev_io_stop (loop, w); + .. read from stdin here (or from w->fd) and haqndle any I/O errors + } + + ... + struct ev_loop *loop = ev_default_init (0); + struct ev_io stdin_readable; + ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); + ev_io_start (loop, &stdin_readable); + ev_loop (loop, 0); =head2 C - relative and optionally repeating timeouts @@ -1153,22 +1229,34 @@ given time, and optionally repeating in regular intervals after that. The timers are based on real time, that is, if you register an event that -times out after an hour and you reset your system clock to january last +times out after an hour and you reset your system clock to January last year, it will still time out after (roughly) and hour. "Roughly" because detecting time jumps is hard, and some inaccuracies are unavoidable (the monotonic clock option helps a lot here). +The callback is guaranteed to be invoked only after its timeout has passed, +but if multiple timers become ready during the same loop iteration then +order of execution is undefined. + +=head3 The special problem of time updates + +Establishing the current time is a costly operation (it usually takes at +least two system calls): EV therefore updates its idea of the current +time only before and after C polls for new events, which causes +a growing difference between C and C when handling +lots of events. + The relative timeouts are calculated relative to the C time. This is usually the right thing as this timestamp refers to the time of the event triggering whatever timeout you are modifying/starting. If -you suspect event processing to be delayed and you I to base the timeout -on the current time, use something like this to adjust for this: +you suspect event processing to be delayed and you I to base the +timeout on the current time, use something like this to adjust for this: ev_timer_set (&timer, after + ev_now () - ev_time (), 0.); -The callback is guarenteed to be invoked only after its timeout has passed, -but if multiple timers become ready during the same loop iteration then -order of execution is undefined. +If the event loop is suspended for a long time, you can also force an +update of the time returned by C by calling C. =head3 Watcher-Specific Functions and Data Members @@ -1197,13 +1285,13 @@ If the timer is pending, its pending status is cleared. -If the timer is started but nonrepeating, stop it (as if it timed out). +If the timer is started but non-repeating, stop it (as if it timed out). If the timer is repeating, either start it if necessary (with the C value), or reset the running timer to the C value. This sounds a bit complicated, but here is a useful and typical -example: Imagine you have a tcp connection and you want a so-called idle +example: Imagine you have a TCP connection and you want a so-called idle timeout, that is, you want to be called when there have been, say, 60 seconds of inactivity on the socket. The easiest way to do this is to configure an C with a C value of C<60> and then call @@ -1239,33 +1327,33 @@ Example: Create a timer that fires after 60 seconds. - static void - one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents) - { - .. one minute over, w is actually stopped right here - } - - struct ev_timer mytimer; - ev_timer_init (&mytimer, one_minute_cb, 60., 0.); - ev_timer_start (loop, &mytimer); + static void + one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents) + { + .. one minute over, w is actually stopped right here + } + + struct ev_timer mytimer; + ev_timer_init (&mytimer, one_minute_cb, 60., 0.); + ev_timer_start (loop, &mytimer); Example: Create a timeout timer that times out after 10 seconds of inactivity. - static void - timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents) - { - .. ten seconds without any activity - } - - struct ev_timer mytimer; - ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ - ev_timer_again (&mytimer); /* start timer */ - ev_loop (loop, 0); - - // and in some piece of code that gets executed on any "activity": - // reset the timeout to start ticking again at 10 seconds - ev_timer_again (&mytimer); + static void + timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents) + { + .. ten seconds without any activity + } + + struct ev_timer mytimer; + ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ + ev_timer_again (&mytimer); /* start timer */ + ev_loop (loop, 0); + + // and in some piece of code that gets executed on any "activity": + // reset the timeout to start ticking again at 10 seconds + ev_timer_again (&mytimer); =head2 C - to cron or not to cron? @@ -1274,11 +1362,11 @@ (and unfortunately a bit complex). Unlike C's, they are not based on real time (or relative time) -but on wallclock time (absolute time). You can tell a periodic watcher +but on wall clock time (absolute time). You can tell a periodic watcher to trigger after some specific point in time. For example, if you tell a -periodic watcher to trigger in 10 seconds (by specifiying e.g. C, that is, an absolute time not a delay) and then reset your system -clock to january of the previous year, then it will take more than year +clock to January of the previous year, then it will take more than year to trigger the event (unlike an C, which would still trigger roughly 10 seconds later as it uses a relative timeout). @@ -1286,7 +1374,7 @@ such as triggering an event on each "midnight, local time", or other complicated, rules. -As with timers, the callback is guarenteed to be invoked only when the +As with timers, the callback is guaranteed to be invoked only when the time (C) has passed, but if multiple periodic timers become ready during the same loop iteration then order of execution is undefined. @@ -1305,7 +1393,7 @@ =item * absolute timer (at = time, interval = reschedule_cb = 0) -In this configuration the watcher triggers an event after the wallclock +In this configuration the watcher triggers an event after the wall clock time C has passed and doesn't repeat. It will not adjust when a time jump occurs, that is, if it is to be run at January 1st 2011 then it will run when the system time reaches or surpasses this time. @@ -1323,7 +1411,7 @@ ev_periodic_set (&periodic, 0., 3600., 0); This doesn't mean there will always be 3600 seconds in between triggers, -but only that the the callback will be called when the system time shows a +but only that the callback will be called when the system time shows a full hour (UTC), or more correctly, when the system time is evenly divisible by 3600. @@ -1335,6 +1423,11 @@ C (the current time), but there is no range requirement for this value, and in fact is often specified as zero. +Note also that there is an upper limit to how often a timer can fire (CPU +speed for example), so if C is very small then timing stability +will of course deteriorate. Libev itself tries to be exact to be about one +millisecond (if the OS supports it and the machine is fast enough). + =item * manual reschedule mode (at and interval ignored, reschedule_cb = callback) In this mode the values for C and C are both being @@ -1411,36 +1504,36 @@ Example: Call a callback every hour, or, more precisely, whenever the system clock is divisible by 3600. The callback invocation times have -potentially a lot of jittering, but good long-term stability. +potentially a lot of jitter, but good long-term stability. - static void - clock_cb (struct ev_loop *loop, struct ev_io *w, int revents) - { - ... its now a full hour (UTC, or TAI or whatever your clock follows) - } - - struct ev_periodic hourly_tick; - ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); - ev_periodic_start (loop, &hourly_tick); + static void + clock_cb (struct ev_loop *loop, struct ev_io *w, int revents) + { + ... its now a full hour (UTC, or TAI or whatever your clock follows) + } + + struct ev_periodic hourly_tick; + ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); + ev_periodic_start (loop, &hourly_tick); Example: The same as above, but use a reschedule callback to do it: - #include + #include - static ev_tstamp - my_scheduler_cb (struct ev_periodic *w, ev_tstamp now) - { - return fmod (now, 3600.) + 3600.; - } + static ev_tstamp + my_scheduler_cb (struct ev_periodic *w, ev_tstamp now) + { + return fmod (now, 3600.) + 3600.; + } - ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb); + ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb); Example: Call a callback every hour, starting now: - struct ev_periodic hourly_tick; - ev_periodic_init (&hourly_tick, clock_cb, - fmod (ev_now (loop), 3600.), 3600., 0); - ev_periodic_start (loop, &hourly_tick); + struct ev_periodic hourly_tick; + ev_periodic_init (&hourly_tick, clock_cb, + fmod (ev_now (loop), 3600.), 3600., 0); + ev_periodic_start (loop, &hourly_tick); =head2 C - signal me when a signal gets signalled! @@ -1458,8 +1551,8 @@ SIG_DFL (regardless of what it was set to before). If possible and supported, libev will install its handlers with -C behaviour enabled, so syscalls should not be unduly -interrupted. If you have a problem with syscalls getting interrupted by +C behaviour enabled, so system calls should not be unduly +interrupted. If you have a problem with system calls getting interrupted by signals you can block all signals in an C watcher and unblock them in an C watcher. @@ -1484,15 +1577,15 @@ Example: Try to exit cleanly on SIGINT and SIGTERM. - static void - sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents) - { - ev_unloop (loop, EVUNLOOP_ALL); - } - - struct ev_signal signal_watcher; - ev_signal_init (&signal_watcher, sigint_cb, SIGINT); - ev_signal_start (loop, &sigint_cb); + static void + sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents) + { + ev_unloop (loop, EVUNLOOP_ALL); + } + + struct ev_signal signal_watcher; + ev_signal_init (&signal_watcher, sigint_cb, SIGINT); + ev_signal_start (loop, &sigint_cb); =head2 C - watch out for process status changes @@ -1504,13 +1597,13 @@ loop isn't entered (or is continued from a watcher). Only the default event loop is capable of handling signals, and therefore -you can only rgeister child watchers in the default event loop. +you can only register child watchers in the default event loop. =head3 Process Interaction Libev grabs C as soon as the default event loop is initialised. This is necessary to guarantee proper behaviour even if -the first child watcher is started after the child exits. The occurance +the first child watcher is started after the child exits. The occurrence of C is recorded asynchronously, but child reaping is done synchronously as part of the event loop processing. Libev always reaps all children, even ones not watched. @@ -1525,6 +1618,13 @@ event-based approach to child reaping and thus use libev's support for that, so other libev users can use C watchers freely. +=head3 Stopping the Child Watcher + +Currently, the child watcher never gets stopped, even when the +child terminates, so normally one needs to stop the watcher in the +callback. Future versions of libev might stop the watcher automatically +when a child exit is detected. + =head3 Watcher-Specific Functions and Data Members =over 4 @@ -1562,34 +1662,34 @@ Example: C a new process and install a child handler to wait for its completion. - ev_child cw; + ev_child cw; - static void - child_cb (EV_P_ struct ev_child *w, int revents) - { - ev_child_stop (EV_A_ w); - printf ("process %d exited with status %x\n", w->rpid, w->rstatus); - } - - pid_t pid = fork (); - - if (pid < 0) - // error - else if (pid == 0) - { - // the forked child executes here - exit (1); - } - else - { - ev_child_init (&cw, child_cb, pid, 0); - ev_child_start (EV_DEFAULT_ &cw); - } + static void + child_cb (EV_P_ struct ev_child *w, int revents) + { + ev_child_stop (EV_A_ w); + printf ("process %d exited with status %x\n", w->rpid, w->rstatus); + } + + pid_t pid = fork (); + + if (pid < 0) + // error + else if (pid == 0) + { + // the forked child executes here + exit (1); + } + else + { + ev_child_init (&cw, child_cb, pid, 0); + ev_child_start (EV_DEFAULT_ &cw); + } =head2 C - did the file attributes just change? -This watches a filesystem path for attribute changes. That is, it calls +This watches a file system path for attribute changes. That is, it calls C regularly (or when the OS says it changed) and sees if it changed compared to the last time, invoking the callback if it did. @@ -1627,13 +1727,19 @@ =head3 ABI Issues (Largefile Support) Libev by default (unless the user overrides this) uses the default -compilation environment, which means that on systems with optionally -disabled large file support, you get the 32 bit version of the stat +compilation environment, which means that on systems with large file +support disabled by default, you get the 32 bit version of the stat structure. When using the library from programs that change the ABI to use 64 bit file offsets the programs will fail. In that case you have to compile libev with the same flags to get binary compatibility. This is obviously the case with any flags that change the ABI, but the problem is -most noticably with ev_stat and largefile support. +most noticeably disabled with ev_stat and large file support. + +The solution for this is to lobby your distribution maker to make large +file interfaces available by default (as e.g. FreeBSD does) and not +optional. Libev cannot simply switch on large file support because it has +to exchange stat structures with application programs compiled using the +default compilation environment. =head3 Inotify @@ -1653,8 +1759,8 @@ =head3 The special problem of stat time resolution -The C syscall only supports full-second resolution portably, and -even on systems where the resolution is higher, many filesystems still +The C system call only supports full-second resolution portably, and +even on systems where the resolution is higher, many file systems still only support whole seconds. That means that, if the time is the only thing that changes, you can @@ -1724,7 +1830,7 @@ =item const char *path [read-only] -The filesystem path that is being watched. +The file system path that is being watched. =back @@ -1732,55 +1838,55 @@ Example: Watch C for attribute changes. - static void - passwd_cb (struct ev_loop *loop, ev_stat *w, int revents) - { - /* /etc/passwd changed in some way */ - if (w->attr.st_nlink) - { - printf ("passwd current size %ld\n", (long)w->attr.st_size); - printf ("passwd current atime %ld\n", (long)w->attr.st_mtime); - printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime); - } - else - /* you shalt not abuse printf for puts */ - puts ("wow, /etc/passwd is not there, expect problems. " - "if this is windows, they already arrived\n"); - } + static void + passwd_cb (struct ev_loop *loop, ev_stat *w, int revents) + { + /* /etc/passwd changed in some way */ + if (w->attr.st_nlink) + { + printf ("passwd current size %ld\n", (long)w->attr.st_size); + printf ("passwd current atime %ld\n", (long)w->attr.st_mtime); + printf ("passwd current mtime %ld\n", (long)w->attr.st_mtime); + } + else + /* you shalt not abuse printf for puts */ + puts ("wow, /etc/passwd is not there, expect problems. " + "if this is windows, they already arrived\n"); + } - ... - ev_stat passwd; + ... + ev_stat passwd; - ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.); - ev_stat_start (loop, &passwd); + ev_stat_init (&passwd, passwd_cb, "/etc/passwd", 0.); + ev_stat_start (loop, &passwd); Example: Like above, but additionally use a one-second delay so we do not miss updates (however, frequent updates will delay processing, too, so one might do the work both on C callback invocation I on C callback invocation). - static ev_stat passwd; - static ev_timer timer; + static ev_stat passwd; + static ev_timer timer; + + static void + timer_cb (EV_P_ ev_timer *w, int revents) + { + ev_timer_stop (EV_A_ w); - static void - timer_cb (EV_P_ ev_timer *w, int revents) - { - ev_timer_stop (EV_A_ w); - - /* now it's one second after the most recent passwd change */ - } - - static void - stat_cb (EV_P_ ev_stat *w, int revents) - { - /* reset the one-second timer */ - ev_timer_again (EV_A_ &timer); - } - - ... - ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.); - ev_stat_start (loop, &passwd); - ev_timer_init (&timer, timer_cb, 0., 1.02); + /* now it's one second after the most recent passwd change */ + } + + static void + stat_cb (EV_P_ ev_stat *w, int revents) + { + /* reset the one-second timer */ + ev_timer_again (EV_A_ &timer); + } + + ... + ev_stat_init (&passwd, stat_cb, "/etc/passwd", 0.); + ev_stat_start (loop, &passwd); + ev_timer_init (&timer, timer_cb, 0., 1.02); =head2 C - when you've got nothing better to do... @@ -1821,17 +1927,17 @@ Example: Dynamically allocate an C watcher, start it, and in the callback, free it. Also, use no error checking, as usual. - static void - idle_cb (struct ev_loop *loop, struct ev_idle *w, int revents) - { - free (w); - // now do something you wanted to do when the program has - // no longer anything immediate to do. - } - - struct ev_idle *idle_watcher = malloc (sizeof (struct ev_idle)); - ev_idle_init (idle_watcher, idle_cb); - ev_idle_start (loop, idle_cb); + static void + idle_cb (struct ev_loop *loop, struct ev_idle *w, int revents) + { + free (w); + // now do something you wanted to do when the program has + // no longer anything immediate to do. + } + + struct ev_idle *idle_watcher = malloc (sizeof (struct ev_idle)); + ev_idle_init (idle_watcher, idle_cb); + ev_idle_start (loop, idle_cb); =head2 C and C - customise your event loop! @@ -1860,7 +1966,7 @@ to be watched by the other library, registering C watchers for them and starting an C watcher for any timeouts (many libraries provide just this functionality). Then, in the check watcher you check for -any events that occured (by checking the pending status of all watchers +any events that occurred (by checking the pending status of all watchers and stopping them) and call back into the library. The I/O and timer callbacks will never actually be called (but must be valid nevertheless, because you never know, you know?). @@ -1913,119 +2019,119 @@ priority for the check watcher or use C explicitly, as the callbacks for the IO/timeout watchers might not have been called yet. - static ev_io iow [nfd]; - static ev_timer tw; + static ev_io iow [nfd]; + static ev_timer tw; + + static void + io_cb (ev_loop *loop, ev_io *w, int revents) + { + } + + // create io watchers for each fd and a timer before blocking + static void + adns_prepare_cb (ev_loop *loop, ev_prepare *w, int revents) + { + int timeout = 3600000; + struct pollfd fds [nfd]; + // actual code will need to loop here and realloc etc. + adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); + + /* the callback is illegal, but won't be called as we stop during check */ + ev_timer_init (&tw, 0, timeout * 1e-3); + ev_timer_start (loop, &tw); + + // create one ev_io per pollfd + for (int i = 0; i < nfd; ++i) + { + ev_io_init (iow + i, io_cb, fds [i].fd, + ((fds [i].events & POLLIN ? EV_READ : 0) + | (fds [i].events & POLLOUT ? EV_WRITE : 0))); + + fds [i].revents = 0; + ev_io_start (loop, iow + i); + } + } - static void - io_cb (ev_loop *loop, ev_io *w, int revents) - { - } - - // create io watchers for each fd and a timer before blocking - static void - adns_prepare_cb (ev_loop *loop, ev_prepare *w, int revents) - { - int timeout = 3600000; - struct pollfd fds [nfd]; - // actual code will need to loop here and realloc etc. - adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); - - /* the callback is illegal, but won't be called as we stop during check */ - ev_timer_init (&tw, 0, timeout * 1e-3); - ev_timer_start (loop, &tw); - - // create one ev_io per pollfd - for (int i = 0; i < nfd; ++i) - { - ev_io_init (iow + i, io_cb, fds [i].fd, - ((fds [i].events & POLLIN ? EV_READ : 0) - | (fds [i].events & POLLOUT ? EV_WRITE : 0))); - - fds [i].revents = 0; - ev_io_start (loop, iow + i); - } - } - - // stop all watchers after blocking - static void - adns_check_cb (ev_loop *loop, ev_check *w, int revents) - { - ev_timer_stop (loop, &tw); - - for (int i = 0; i < nfd; ++i) - { - // set the relevant poll flags - // could also call adns_processreadable etc. here - struct pollfd *fd = fds + i; - int revents = ev_clear_pending (iow + i); - if (revents & EV_READ ) fd->revents |= fd->events & POLLIN; - if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT; - - // now stop the watcher - ev_io_stop (loop, iow + i); - } + // stop all watchers after blocking + static void + adns_check_cb (ev_loop *loop, ev_check *w, int revents) + { + ev_timer_stop (loop, &tw); - adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop)); - } + for (int i = 0; i < nfd; ++i) + { + // set the relevant poll flags + // could also call adns_processreadable etc. here + struct pollfd *fd = fds + i; + int revents = ev_clear_pending (iow + i); + if (revents & EV_READ ) fd->revents |= fd->events & POLLIN; + if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT; + + // now stop the watcher + ev_io_stop (loop, iow + i); + } + + adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop)); + } Method 2: This would be just like method 1, but you run C in the prepare watcher and would dispose of the check watcher. Method 3: If the module to be embedded supports explicit event -notification (adns does), you can also make use of the actual watcher +notification (libadns does), you can also make use of the actual watcher callbacks, and only destroy/create the watchers in the prepare watcher. - static void - timer_cb (EV_P_ ev_timer *w, int revents) - { - adns_state ads = (adns_state)w->data; - update_now (EV_A); - - adns_processtimeouts (ads, &tv_now); - } - - static void - io_cb (EV_P_ ev_io *w, int revents) - { - adns_state ads = (adns_state)w->data; - update_now (EV_A); - - if (revents & EV_READ ) adns_processreadable (ads, w->fd, &tv_now); - if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now); - } + static void + timer_cb (EV_P_ ev_timer *w, int revents) + { + adns_state ads = (adns_state)w->data; + update_now (EV_A); - // do not ever call adns_afterpoll + adns_processtimeouts (ads, &tv_now); + } + + static void + io_cb (EV_P_ ev_io *w, int revents) + { + adns_state ads = (adns_state)w->data; + update_now (EV_A); + + if (revents & EV_READ ) adns_processreadable (ads, w->fd, &tv_now); + if (revents & EV_WRITE) adns_processwriteable (ads, w->fd, &tv_now); + } + + // do not ever call adns_afterpoll Method 4: Do not use a prepare or check watcher because the module you -want to embed is too inflexible to support it. Instead, youc na override +want to embed is too inflexible to support it. Instead, you can override their poll function. The drawback with this solution is that the main loop is now no longer controllable by EV. The C module does this. - static gint - event_poll_func (GPollFD *fds, guint nfds, gint timeout) - { - int got_events = 0; - - for (n = 0; n < nfds; ++n) - // create/start io watcher that sets the relevant bits in fds[n] and increment got_events - - if (timeout >= 0) - // create/start timer - - // poll - ev_loop (EV_A_ 0); - - // stop timer again - if (timeout >= 0) - ev_timer_stop (EV_A_ &to); - - // stop io watchers again - their callbacks should have set - for (n = 0; n < nfds; ++n) - ev_io_stop (EV_A_ iow [n]); + static gint + event_poll_func (GPollFD *fds, guint nfds, gint timeout) + { + int got_events = 0; + + for (n = 0; n < nfds; ++n) + // create/start io watcher that sets the relevant bits in fds[n] and increment got_events + + if (timeout >= 0) + // create/start timer + + // poll + ev_loop (EV_A_ 0); + + // stop timer again + if (timeout >= 0) + ev_timer_stop (EV_A_ &to); - return got_events; - } + // stop io watchers again - their callbacks should have set + for (n = 0; n < nfds; ++n) + ev_io_stop (EV_A_ iow [n]); + + return got_events; + } =head2 C - when one backend isn't enough... @@ -2091,13 +2197,13 @@ embeddable. If the callback is C<0>, then C will be invoked automatically, otherwise it is the responsibility of the callback to invoke it (it will continue to be called until the sweep has been done, -if you do not want thta, you need to temporarily stop the embed watcher). +if you do not want that, you need to temporarily stop the embed watcher). =item ev_embed_sweep (loop, ev_embed *) Make a single, non-blocking sweep over the embedded loop. This works similarly to C, but in the most -apropriate way for embedded loops. +appropriate way for embedded loops. =item struct ev_loop *other [read-only] @@ -2109,49 +2215,49 @@ Example: Try to get an embeddable event loop and embed it into the default event loop. If that is not possible, use the default loop. The default -loop is stored in C, while the mebeddable loop is stored in -C (which is C in the acse no embeddable loop can be +loop is stored in C, while the embeddable loop is stored in +C (which is C in the case no embeddable loop can be used). - struct ev_loop *loop_hi = ev_default_init (0); - struct ev_loop *loop_lo = 0; - struct ev_embed embed; - - // see if there is a chance of getting one that works - // (remember that a flags value of 0 means autodetection) - loop_lo = ev_embeddable_backends () & ev_recommended_backends () - ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) - : 0; - - // if we got one, then embed it, otherwise default to loop_hi - if (loop_lo) - { - ev_embed_init (&embed, 0, loop_lo); - ev_embed_start (loop_hi, &embed); - } - else - loop_lo = loop_hi; + struct ev_loop *loop_hi = ev_default_init (0); + struct ev_loop *loop_lo = 0; + struct ev_embed embed; + + // see if there is a chance of getting one that works + // (remember that a flags value of 0 means autodetection) + loop_lo = ev_embeddable_backends () & ev_recommended_backends () + ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) + : 0; + + // if we got one, then embed it, otherwise default to loop_hi + if (loop_lo) + { + ev_embed_init (&embed, 0, loop_lo); + ev_embed_start (loop_hi, &embed); + } + else + loop_lo = loop_hi; Example: Check if kqueue is available but not recommended and create a kqueue backend for use with sockets (which usually work with any kqueue implementation). Store the kqueue/socket-only event loop in C. (One might optionally use C, too). - struct ev_loop *loop = ev_default_init (0); - struct ev_loop *loop_socket = 0; - struct ev_embed embed; - - if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) - if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) - { - ev_embed_init (&embed, 0, loop_socket); - ev_embed_start (loop, &embed); - } + struct ev_loop *loop = ev_default_init (0); + struct ev_loop *loop_socket = 0; + struct ev_embed embed; + + if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) + if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) + { + ev_embed_init (&embed, 0, loop_socket); + ev_embed_start (loop, &embed); + } - if (!loop_socket) - loop_socket = loop; + if (!loop_socket) + loop_socket = loop; - // now use loop_socket for all sockets, and loop for everything else + // now use loop_socket for all sockets, and loop for everything else =head2 C - the audacity to resume the event loop after a fork @@ -2214,7 +2320,7 @@ To implement race-free queueing, you simply add to the queue in the signal handler but you block the signal handler in the watcher callback. Here is an example that does that for -some fictitiuous SIGUSR1 handler: +some fictitious SIGUSR1 handler: static ev_async mysig; @@ -2298,11 +2404,11 @@ Sends/signals/activates the given C watcher, that is, feeds an C event on the watcher into the event loop. Unlike C, this call is safe to do in other threads, signal or -similar contexts (see the dicusssion of C in the embedding +similar contexts (see the discussion of C in the embedding section below on what exactly this means). -This call incurs the overhead of a syscall only once per loop iteration, -so while the overhead might be noticable, it doesn't apply to repeated +This call incurs the overhead of a system call only once per loop iteration, +so while the overhead might be noticeable, it doesn't apply to repeated calls to C. =item bool = ev_async_pending (ev_async *) @@ -2314,10 +2420,10 @@ C sets a flag in the watcher and wakes up the loop. When the loop iterates next and checks for the watcher to have become active, it will reset the flag again. C can be used to very -quickly check wether invoking the loop might be a good idea. +quickly check whether invoking the loop might be a good idea. -Not that this does I check wether the watcher itself is pending, only -wether it has been requested to make this watcher pending. +Not that this does I check whether the watcher itself is pending, only +whether it has been requested to make this watcher pending. =back @@ -2338,7 +2444,7 @@ If C is less than 0, then no I/O watcher will be started and events is being ignored. Otherwise, an C watcher for the given C and -C set will be craeted and started. +C set will be created and started. If C is less than 0, then no timeout watcher will be started. Otherwise an C watcher with after = C (and @@ -2350,15 +2456,15 @@ C, C, C or C) and the C value passed to C: - static void stdin_ready (int revents, void *arg) - { - if (revents & EV_TIMEOUT) - /* doh, nothing entered */; - else if (revents & EV_READ) - /* stdin might have data for us, joy! */; - } + static void stdin_ready (int revents, void *arg) + { + if (revents & EV_TIMEOUT) + /* doh, nothing entered */; + else if (revents & EV_READ) + /* stdin might have data for us, joy! */; + } - ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); + ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); =item ev_feed_event (ev_loop *, watcher *, int revents) @@ -2373,7 +2479,7 @@ =item ev_feed_signal_event (ev_loop *loop, int signum) -Feed an event as if the given signal occured (C must be the default +Feed an event as if the given signal occurred (C must be the default loop!). =back @@ -2412,12 +2518,12 @@ =head1 C++ SUPPORT Libev comes with some simplistic wrapper classes for C++ that mainly allow -you to use some convinience methods to start/stop watchers and also change +you to use some convenience methods to start/stop watchers and also change the callback model to a model using method callbacks on objects. To use it, - #include + #include This automatically includes F and puts all of its definitions (many of them macros) into the global namespace. All C++ specific things are @@ -2494,14 +2600,14 @@ Example: simple class declaration and watcher initialisation - struct myclass - { - void io_cb (ev::io &w, int revents) { } - } - - myclass obj; - ev::io iow; - iow.set (&obj); + struct myclass + { + void io_cb (ev::io &w, int revents) { } + } + + myclass obj; + ev::io iow; + iow.set (&obj); =item w->set (void *data = 0) @@ -2515,17 +2621,17 @@ Example: - static void io_cb (ev::io &w, int revents) { } - iow.set (); + static void io_cb (ev::io &w, int revents) { } + iow.set (); =item w->set (struct ev_loop *) Associates a different C with this watcher. You can only do this when the watcher is inactive (and not pending either). -=item w->set ([args]) +=item w->set ([arguments]) -Basically the same as C, with the same args. Must be +Basically the same as C, with the same arguments. Must be called at least once. Unlike the C counterpart, an active watcher gets automatically stopped and restarted when reconfiguring it with this method. @@ -2559,25 +2665,25 @@ Example: Define a class with an IO and idle watcher, start one of them in the constructor. - class myclass - { - ev::io io; void io_cb (ev::io &w, int revents); - ev:idle idle void idle_cb (ev::idle &w, int revents); - - myclass (int fd) - { - io .set (this); - idle.set (this); - - io.start (fd, ev::READ); - } - }; + class myclass + { + ev::io io; void io_cb (ev::io &w, int revents); + ev:idle idle void idle_cb (ev::idle &w, int revents); + + myclass (int fd) + { + io .set (this); + idle.set (this); + + io.start (fd, ev::READ); + } + }; =head1 OTHER LANGUAGE BINDINGS Libev does not offer other language bindings itself, but bindings for a -numbe rof languages exist in the form of third-party packages. If you know +number of languages exist in the form of third-party packages. If you know any interesting language binding in addition to the ones listed here, drop me a note. @@ -2591,27 +2697,36 @@ to C (C), C (C) and the C event core (C and C). -It can be found and installed via CPAN, its homepage is found at +It can be found and installed via CPAN, its homepage is at L. +=item Python + +Python bindings can be found at L. It +seems to be quite complete and well-documented. Note, however, that the +patch they require for libev is outright dangerous as it breaks the ABI +for everybody else, and therefore, should never be applied in an installed +libev (if python requires an incompatible ABI then it needs to embed +libev). + =item Ruby Tony Arcieri has written a ruby extension that offers access to a subset -of the libev API and adds filehandle abstractions, asynchronous DNS and +of the libev API and adds file handle abstractions, asynchronous DNS and more on top of it. It can be found via gem servers. Its homepage is at L. =item D Leandro Lucarella has written a D language binding (F) for libev, to -be found at L. +be found at L. =back =head1 MACRO MAGIC -Libev can be compiled with a variety of options, the most fundamantal +Libev can be compiled with a variety of options, the most fundamental of which is C. This option determines whether (most) functions and callbacks have an initial C argument. @@ -2626,9 +2741,9 @@ loop argument"). The C form is used when this is the sole argument, C is used when other arguments are following. Example: - ev_unref (EV_A); - ev_timer_add (EV_A_ watcher); - ev_loop (EV_A_ 0); + ev_unref (EV_A); + ev_timer_add (EV_A_ watcher); + ev_loop (EV_A_ 0); It assumes the variable C of type C is in scope, which is often provided by the following macro. @@ -2639,11 +2754,11 @@ loop parameter"). The C form is used when this is the sole parameter, C is used when other parameters are following. Example: - // this is how ev_unref is being declared - static void ev_unref (EV_P); + // this is how ev_unref is being declared + static void ev_unref (EV_P); - // this is how you can declare your typical callback - static void cb (EV_P_ ev_timer *w, int revents) + // this is how you can declare your typical callback + static void cb (EV_P_ ev_timer *w, int revents) It declares a parameter C of type C, quite suitable for use with C. @@ -2669,16 +2784,16 @@ macros so it will work regardless of whether multiple loops are supported or not. - static void - check_cb (EV_P_ ev_timer *w, int revents) - { - ev_check_stop (EV_A_ w); - } - - ev_check check; - ev_check_init (&check, check_cb); - ev_check_start (EV_DEFAULT_ &check); - ev_loop (EV_DEFAULT_ 0); + static void + check_cb (EV_P_ ev_timer *w, int revents) + { + ev_check_stop (EV_A_ w); + } + + ev_check check; + ev_check_init (&check, check_cb); + ev_check_start (EV_DEFAULT_ &check); + ev_loop (EV_DEFAULT_ 0); =head1 EMBEDDING @@ -2695,15 +2810,15 @@ =head2 FILESETS Depending on what features you need you need to include one or more sets of files -in your app. +in your application. =head3 CORE EVENT LOOP To include only the libev core (all the C functions), with manual configuration (no autoconf): - #define EV_STANDALONE 1 - #include "ev.c" + #define EV_STANDALONE 1 + #include "ev.c" This will automatically include F, too, and should be done in a single C source file only to provide the function implementations. To use @@ -2711,8 +2826,8 @@ done by writing a wrapper around F that you can include instead and where you can put other configuration options): - #define EV_STANDALONE 1 - #include "ev.h" + #define EV_STANDALONE 1 + #include "ev.h" Both header files and implementation files can be compiled with a C++ compiler (at least, thats a stated goal, and breakage will be treated @@ -2721,18 +2836,18 @@ You need the following files in your source tree, or in a directory in your include path (e.g. in libev/ when using -Ilibev): - ev.h - ev.c - ev_vars.h - ev_wrap.h - - ev_win32.c required on win32 platforms only - - ev_select.c only when select backend is enabled (which is enabled by default) - ev_poll.c only when poll backend is enabled (disabled by default) - ev_epoll.c only when the epoll backend is enabled (disabled by default) - ev_kqueue.c only when the kqueue backend is enabled (disabled by default) - ev_port.c only when the solaris port backend is enabled (disabled by default) + ev.h + ev.c + ev_vars.h + ev_wrap.h + + ev_win32.c required on win32 platforms only + + ev_select.c only when select backend is enabled (which is enabled by default) + ev_poll.c only when poll backend is enabled (disabled by default) + ev_epoll.c only when the epoll backend is enabled (disabled by default) + ev_kqueue.c only when the kqueue backend is enabled (disabled by default) + ev_port.c only when the solaris port backend is enabled (disabled by default) F includes the backend files directly when enabled, so you only need to compile this single file. @@ -2741,34 +2856,34 @@ To include the libevent compatibility API, also include: - #include "event.c" + #include "event.c" in the file including F, and: - #include "event.h" + #include "event.h" in the files that want to use the libevent API. This also includes F. You need the following additional files for this: - event.h - event.c + event.h + event.c =head3 AUTOCONF SUPPORT -Instead of using C and providing your config in +Instead of using C and providing your configuration in whatever way you want, you can also C in your F and leave C undefined. F will then include F and configure itself accordingly. For this of course you need the m4 file: - libev.m4 + libev.m4 =head2 PREPROCESSOR SYMBOLS/MACROS Libev can be configured via a variety of preprocessor symbols you have to -define before including any of its files. The default in the absense of +define before including any of its files. The default in the absence of autoconf is noted for every option. =over 4 @@ -2784,7 +2899,7 @@ =item EV_USE_MONOTONIC If defined to be C<1>, libev will try to detect the availability of the -monotonic clock option at both compiletime and runtime. Otherwise no use +monotonic clock option at both compile time and runtime. Otherwise no use of the monotonic clock option will be attempted. If you enable this, you usually have to link against librt or something similar. Enabling it when the functionality isn't available is safe, though, although you have @@ -2794,8 +2909,8 @@ =item EV_USE_REALTIME If defined to be C<1>, libev will try to detect the availability of the -realtime clock option at compiletime (and assume its availability at -runtime if successful). Otherwise no use of the realtime clock option will +real-time clock option at compile time (and assume its availability at +runtime if successful). Otherwise no use of the real-time clock option will be attempted. This effectively replaces C by C and will not normally affect correctness. See the note about libraries in the description of C, though. @@ -2816,7 +2931,7 @@ =item EV_USE_SELECT If undefined or defined to be C<1>, libev will compile in support for the -C(2) backend. No attempt at auto-detection will be done: if no other method takes over, select will be it. Otherwise the select backend will not be compiled in. @@ -2824,7 +2939,7 @@ If defined to C<1>, then the select backend will use the system C structure. This is useful if libev doesn't compile due to a missing -C or C definition or it misguesses the bitset layout on +C or C definition or it mis-guesses the bitset layout on exotic systems. This usually limits the range of file descriptors to some low limit such as 1024 or might have other limitations (winsocket only allows 64 sockets). The C macro, set before compilation, might @@ -2883,7 +2998,7 @@ =item EV_USE_DEVPOLL -reserved for future expansion, works like the USE symbols above. +Reserved for future expansion, works like the USE symbols above. =item EV_USE_INOTIFY @@ -2900,7 +3015,7 @@ that you know is safe for your purposes. It is used both for signal handler "locking" as well as for signal and thread safety in C watchers. -In the absense of this define, libev will use C +In the absence of this define, libev will use C (from F), which is usually good enough on most platforms. =item EV_H @@ -2949,8 +3064,8 @@ and time, so using the defaults of five priorities (-2 .. +2) is usually fine. -If your embedding app does not need any priorities, defining these both to -C<0> will save some memory and cpu. +If your embedding application does not need any priorities, defining these both to +C<0> will save some memory and CPU. =item EV_PERIODIC_ENABLE @@ -2988,7 +3103,7 @@ If you need to shave off some kilobytes of code at the expense of some speed, define this symbol to C<1>. Currently this is used to override some -inlining decisions, saves roughly 30% codesize of amd64. It also selects a +inlining decisions, saves roughly 30% code size on amd64. It also selects a much smaller 2-heap for timer management over the default 4-heap. =item EV_PID_HASHSIZE @@ -3011,7 +3126,7 @@ Heaps are not very cache-efficient. To improve the cache-efficiency of the timer and periodics heap, libev uses a 4-heap when this symbol is defined to C<1>. The 4-heap uses more complicated (longer) code but has -noticably faster performance with many (thousands) of watchers. +noticeably faster performance with many (thousands) of watchers. The default is C<1> unless C is set in which case it is C<0> (disabled). @@ -3023,11 +3138,24 @@ the heap structure (selected by defining C to C<1>), which uses 8-12 bytes more per watcher and a few hundred bytes more code, but avoids random read accesses on heap changes. This improves performance -noticably with with many (hundreds) of watchers. +noticeably with with many (hundreds) of watchers. The default is C<1> unless C is set in which case it is C<0> (disabled). +=item EV_VERIFY + +Controls how much internal verification (see C) will +be done: If set to C<0>, no internal verification code will be compiled +in. If set to C<1>, then verification code will be compiled in, but not +called. If set to C<2>, then the internal verification code will be +called once per loop, which can slow down libev. If set to C<3>, then the +verification code will be called very frequently, which will slow down +libev considerably. + +The default is C<1>, unless C is set, in which case it will be +C<0.> + =item EV_COMMON By default, all watchers have a C member. By redefining @@ -3037,9 +3165,9 @@ For example, the perl EV module uses something like this: - #define EV_COMMON \ - SV *self; /* contains this struct */ \ - SV *cb_sv, *fh /* note no trailing ";" */ + #define EV_COMMON \ + SV *self; /* contains this struct */ \ + SV *cb_sv, *fh /* note no trailing ";" */ =item EV_CB_DECLARE (type) @@ -3056,16 +3184,16 @@ =head2 EXPORTED API SYMBOLS -If you need to re-export the API (e.g. via a dll) and you need a list of +If you need to re-export the API (e.g. via a DLL) and you need a list of exported symbols, you can use the provided F files which list all public symbols, one per line: - Symbols.ev for libev proper - Symbols.event for the libevent emulation + Symbols.ev for libev proper + Symbols.event for the libevent emulation This can also be used to rename all public symbols to avoid clashes with multiple versions of libev linked together (which is obviously bad in -itself, but sometimes it is inconvinient to avoid this). +itself, but sometimes it is inconvenient to avoid this). A sed command like this will create wrapper C<#define>'s that you need to include before including F: @@ -3092,46 +3220,53 @@ The usage in rxvt-unicode is simpler. It has a F header file that everybody includes and which overrides some configure choices: - #define EV_MINIMAL 1 - #define EV_USE_POLL 0 - #define EV_MULTIPLICITY 0 - #define EV_PERIODIC_ENABLE 0 - #define EV_STAT_ENABLE 0 - #define EV_FORK_ENABLE 0 - #define EV_CONFIG_H - #define EV_MINPRI 0 - #define EV_MAXPRI 0 + #define EV_MINIMAL 1 + #define EV_USE_POLL 0 + #define EV_MULTIPLICITY 0 + #define EV_PERIODIC_ENABLE 0 + #define EV_STAT_ENABLE 0 + #define EV_FORK_ENABLE 0 + #define EV_CONFIG_H + #define EV_MINPRI 0 + #define EV_MAXPRI 0 - #include "ev++.h" + #include "ev++.h" And a F implementation file that contains libev proper and is compiled: - #include "ev_cpp.h" - #include "ev.c" + #include "ev_cpp.h" + #include "ev.c" =head1 THREADS AND COROUTINES =head2 THREADS -Libev itself is completely threadsafe, but it uses no locking. This -means that you can use as many loops as you want in parallel, as long as -only one thread ever calls into one libev function with the same loop -parameter. - -Or put differently: calls with different loop parameters can be done in -parallel from multiple threads, calls with the same loop parameter must be -done serially (but can be done from different threads, as long as only one -thread ever is inside a call at any point in time, e.g. by using a mutex -per loop). - -If you want to know which design is best for your problem, then I cannot -help you but by giving some generic advice: +Libev itself is thread-safe (unless the opposite is specifically +documented for a function), but it uses no locking itself. This means that +you can use as many loops as you want in parallel, as long as only one +thread ever calls into one libev function with the same loop parameter: +libev guarentees that different event loops share no data structures that +need locking. + +Or to put it differently: calls with different loop parameters can be done +concurrently from multiple threads, calls with the same loop parameter +must be done serially (but can be done from different threads, as long as +only one thread ever is inside a call at any point in time, e.g. by using +a mutex per loop). + +Specifically to support threads (and signal handlers), libev implements +so-called C watchers, which allow some limited form of +concurrency on the same event loop. + +If you want to know which design (one loop, locking, or multiple loops +without or something else still) is best for your problem, then I cannot +help you. I can give some generic advice however: =over 4 =item * most applications have a main thread: use the default libev loop -in that thread, or create a seperate thread running only the default loop. +in that thread, or create a separate thread running only the default loop. This helps integrating other libraries or software modules that use libev themselves and don't care/know about threading. @@ -3142,29 +3277,35 @@ exists, but it is always a good start. =item * other models exist, such as the leader/follower pattern, where one -loop is handed through multiple threads in a kind of round-robbin fashion. +loop is handed through multiple threads in a kind of round-robin fashion. -Chosing a model is hard - look around, learn, know that usually you cna do +Choosing a model is hard - look around, learn, know that usually you can do better than you currently do :-) =item * often you need to talk to some other thread which blocks in the -event loop - C watchers can be used to wake them up from other -threads safely (or from signal contexts...). +event loop. + +C watchers can be used to wake them up from other threads safely +(or from signal contexts...). + +An example use would be to communicate signals or other events that only +work in the default loop by registering the signal watcher with the +default loop and triggering an C watcher from the default loop +watcher callback into the event loop interested in the signal. =back =head2 COROUTINES -Libev is much more accomodating to coroutines ("cooperative threads"): +Libev is much more accommodating to coroutines ("cooperative threads"): libev fully supports nesting calls to it's functions from different coroutines (e.g. you can call C on the same loop from two different coroutines and switch freely between both coroutines running the loop, as long as you don't confuse yourself). The only exception is that you must not do this from C reschedule callbacks. -Care has been invested into making sure that libev does not keep local -state inside C, and other calls do not usually allow coroutine -switches. +Care has been taken to ensure that libev does not keep local state inside +C, and other calls do not usually allow coroutine switches. =head1 COMPLEXITIES @@ -3213,7 +3354,7 @@ A change means an I/O watcher gets started or stopped, which requires libev to recalculate its status (and possibly tell the kernel, depending -on backend and wether C was used). +on backend and whether C was used). =item Activating one watcher (putting it into the pending state): O(1) @@ -3230,14 +3371,14 @@ =item Processing signals: O(max_signal_number) -Sending involves a syscall I there were no other C +Sending involves a system call I there were no other C calls in the current loop iteration. Checking for async and signal events involves iterating over all running async watchers or all signal numbers. =back -=head1 Win32 platform limitations and workarounds +=head1 WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS Win32 doesn't support any of the standards (e.g. POSIX) that libev requires, and its I/O model is fundamentally incompatible with the POSIX @@ -3254,30 +3395,53 @@ There is no supported compilation method available on windows except embedding it into other applications. +Not a libev limitation but worth mentioning: windows apparently doesn't +accept large writes: instead of resulting in a partial write, windows will +either accept everything or return C if the buffer is too large, +so make sure you only write small amounts into your sockets (less than a +megabyte seems safe, but thsi apparently depends on the amount of memory +available). + Due to the many, low, and arbitrary limits on the win32 platform and the abysmal performance of winsockets, using a large number of sockets is not recommended (and not reasonable). If your program needs to use more than a hundred or so sockets, then likely it needs to use a totally different implementation for windows, as libev offers the POSIX readiness notification model, which cannot be implemented efficiently on windows -(microsoft monopoly games). +(Microsoft monopoly games). + +A typical way to use libev under windows is to embed it (see the embedding +section for details) and use the following F header file instead +of F: + + #define EV_STANDALONE /* keeps ev from requiring config.h */ + #define EV_SELECT_IS_WINSOCKET 1 /* configure libev for windows select */ + + #include "ev.h" + +And compile the following F file into your project (make sure +you do I compile the F or any other embedded soruce files!): + + #include "evwrap.h" + #include "ev.c" =over 4 =item The winsocket select function -The winsocket C function doesn't follow POSIX in that it +requires socket I and not socket I (it is +also extremely buggy). This makes select very inefficient, and also +requires a mapping from file descriptors to socket handles (the Microsoft +C runtime provides the function C<_open_osfhandle> for this). See the +discussion of the C, C and +C preprocessor symbols for more info. -The configuration for a "naked" win32 using the microsoft runtime +The configuration for a "naked" win32 using the Microsoft runtime libraries and raw winsocket select is: - #define EV_USE_SELECT 1 - #define EV_SELECT_IS_WINSOCKET 1 /* forces EV_SELECT_USE_FD_SET, too */ + #define EV_USE_SELECT 1 + #define EV_SELECT_IS_WINSOCKET 1 /* forces EV_SELECT_USE_FD_SET, too */ Note that winsockets handling of fd sets is O(n), so you can easily get a complexity in the O(n²) range when using win32. @@ -3288,7 +3452,7 @@ Early versions of winsocket's select only supported waiting for a maximum of C<64> handles (probably owning to the fact that all windows kernels -can only wait for C<64> things at the same time internally; microsoft +can only wait for C<64> things at the same time internally; Microsoft recommends spawning a chain of threads and wait for 63 handles and the previous thread in each. Great). @@ -3297,11 +3461,11 @@ call (which might be in libev or elsewhere, for example, perl does its own select emulation on windows). -Another limit is the number of file descriptors in the microsoft runtime +Another limit is the number of file descriptors in the Microsoft runtime libraries, which by default is C<64> (there must be a hidden I<64> fetish -or something like this inside microsoft). You can increase this by calling +or something like this inside Microsoft). You can increase this by calling C<_setmaxstdio>, which can increase this limit to C<2048> (another -arbitrary limit), but is broken in many versions of the microsoft runtime +arbitrary limit), but is broken in many versions of the Microsoft runtime libraries. This might get you to about C<512> or C<2048> sockets (depending on @@ -3319,6 +3483,15 @@ =over 4 +=item C must have compatible +calling conventions regardless of C. + +Libev assumes not only that all watcher pointers have the same internal +structure (guaranteed by POSIX but not by ISO C for example), but it also +assumes that the same (machine) code can be used to call any watcher +callback: The watcher callbacks have different type signatures, but libev +calls them using an C internally. + =item C must be thread-atomic as well The type C (or whatever is defined as @@ -3359,6 +3532,32 @@ If you know of other additional requirements drop me a note. +=head1 COMPILER WARNINGS + +Depending on your compiler and compiler settings, you might get no or a +lot of warnings when compiling libev code. Some people are apparently +scared by this. + +However, these are unavoidable for many reasons. For one, each compiler +has different warnings, and each user has different tastes regarding +warning options. "Warn-free" code therefore cannot be a goal except when +targeting a specific compiler and compiler-version. + +Another reason is that some compiler warnings require elaborate +workarounds, or other changes to the code that make it less clear and less +maintainable. + +And of course, some compiler warnings are just plain stupid, or simply +wrong (because they don't actually warn about the condition their message +seems to warn about). + +While libev is written to generate as few warnings as possible, +"warn-free" code is not a goal, and it is recommended not to build libev +with any compiler warnings enabled unless you are prepared to cope with +them (e.g. by ignoring them). Remember that warnings are just that: +warnings, not errors, or proof of bugs. + + =head1 VALGRIND Valgrind has a special section here because it is a popular tool that is @@ -3371,7 +3570,7 @@ ==2274== possibly lost: 0 bytes in 0 blocks. ==2274== still reachable: 256 bytes in 1 blocks. -then there is no memory leak. Similarly, under some circumstances, +Then there is no memory leak. Similarly, under some circumstances, valgrind might report kernel bugs as if it were a bug in libev, or it might be confused (it is a very good tool, but only a tool).