Lines Matching refs:to
33 // this causes all nested ev_run's to stop iterating
42 // this causes the innermost ev_run to stop iterating
53 // this one will watch for stdin to become readable
62 // now wait for events to arrive
74 web page you might find easier to navigate when reading it for the first
77 While this document tries to be as complete as possible in documenting
87 This manual tries to be very detailed, but unfortunately, this also makes
88 it very long. If you just want to know the basics of libev, I suggest
105 details of the event, and then hand it over to libev by I<starting> the
123 L<benchmark|http://libev.schmorp.de/bench.html> comparing it to libevent
142 too. It usually aliases to the C<double> type in C. When you need to do
155 set via C<ev_set_syserr_cb>, which is supposed to fix the problem or
156 abort. The default is to print a diagnostic message and to call C<abort
162 the libev caller and need to be fixed there.
180 you actually want to know. Also interesting is the combination of
192 The range of the C<interval> is limited - libev only guarantees to work
193 with sleep times of up to one day (C<< interval <= 86400 >>).
205 These version numbers refer to the ABI version of the library, not the
208 Usually, it's a good idea to terminate if the major versions mismatch,
210 compatible to older versions, so a larger minor version alone is usually
249 the current system, you would need to look at C<ev_embeddable_backends ()
256 Sets the allocation function to use (the prototype is similar - the
257 semantics are identical to the C<realloc> C89/SuS/POSIX function). It is
258 used to allocate and free memory (no surprises here). If it returns zero
259 when memory needs to be allocated (C<size != 0>), the library might abort
262 Since some systems (at least OpenBSD and Darwin) fail to implement
266 You could override this function in high-availability programs to, say,
267 free some memory if it cannot allocate memory, to use a special allocator,
268 or even to sleep a while and retry until some memory is available.
292 Set the callback function to call on a retryable system call error (such
295 callback is set, then libev will expect it to remedy the situation, no
314 This function can be used to "simulate" a signal receive. It is completely
315 safe to call this function at any time, from any context, including signal
318 Its main use is to customise signal handling in your process, especially
322 mechanism to wait for signals, then "deliver" them to libev by calling
352 If you don't know what event loop to use, use the one returned from this
355 Note that this function is I<not> thread-safe, so if you want to use it
356 from multiple threads, you have to employ some kind of mutex (note also
361 and to do this, it always registers a handler for C<SIGCHLD>. If this is
371 Example: Restrict libev to the select and poll backends, and do not allow
372 environment settings to be taken into account:
381 This function is thread-safe, and one common way to use libev with
382 threads is indeed to create one loop per thread, and using the default
385 The flags argument can be used to specify special behaviour or specific
386 backends to use, and is usually specified as C<0> (or C<EVFLAG_AUTO>).
403 useful to try out specific backends to test their performance, to work
404 around bugs, or to make libev threadsafe (accessing environment variables
421 forget about forgetting to tell libev about forking, although you still
422 have to ignore C<SIGPIPE>) when you use this flag.
429 When this flag is specified, then libev will not attempt to use the
431 testing, this flag can be useful to conserve inotify file descriptors, as
436 When this flag is specified, then libev will attempt to use the
439 it possible to get the queued signal data. It can also simplify signal
449 When this flag is specified, then libev will avoid to modify the signal
450 mask. Specifically, this means you have to make sure signals are unblocked
451 when you want to receive them.
453 This behaviour is useful when you want to do your own signal handling, or
454 want to handle signals only in specific threads and want to avoid libev
465 libev tries to roll its own fd_set with no limits on the number of fds,
472 writing a server, you should C<accept ()> in a loop to accept as many
473 connections as possible during one iteration. You might also want to have
474 a look at C<ev_set_io_collect_interval ()> to increase the amount of
477 This backend maps C<EV_READ> to the C<readfds> set and C<EV_WRITE> to the
478 C<writefds> set (and to work around Microsoft Windows bugs, also onto the
486 considerably with a lot of inactive fds). It scales similarly to select,
490 This backend maps C<EV_READ> to C<POLLIN | POLLERR | POLLHUP>, and
491 C<EV_WRITE> to C<POLLOUT | POLLERR | POLLHUP>.
510 forks then I<both> parent and child process have to recreate the epoll
512 and is of course hard to detect.
515 but of course I<doesn't>, and epoll just loves to report events for
518 (especially on SMP systems). Libev tries to counter these spurious
520 that against the events to filter out spurious ones, recreating the set
522 no way to know when and by how much, so sometimes you have to busy-wait
524 not least, it also refuses to work with some file descriptors which work
528 cobbled together in a hurry, no thought to design or interaction with
533 incident (because the same I<file descriptor> could point to a different
534 I<file description> now), so its best to avoid that. Also, C<dup ()>'ed
543 as in libev having to destroy and recreate the epoll object, which can
547 faster than epoll for maybe up to a hundred file descriptors, depending on
563 without API changes to existing programs. For this reason it's not being
565 C<EVBACKEND_KQUEUE>) or libev was compiled on a known-to-be-good (-enough)
572 It scales in the same way as the epoll backend, but the interface to the
575 cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to
577 might have to leak fd's on fork, but it's more sane than epoll) and it
578 drops fds silently in similarly hard-to-detect cases.
583 everywhere, so you might need to test for this. And since it is broken
596 implementation). According to reports, C</dev/poll> only supports sockets
610 On the positive side, this backend actually performed fully to
617 function sometimes returns events to the caller even though an error
620 absolutely have to know whether an event occurred or not because you have
621 to re-arm the watcher.
623 Fortunately libev seems to be able to work around these idiocies.
634 It is definitely not recommended to use this flag, use whatever
640 Not a backend at all, but a mask to select all backend bits from a
641 C<flags> value, in case you want to mask out any backends from a flags
651 Example: Try to create a event loop that uses epoll and nothing else.
657 Example: Use whatever libev has to offer, but make sure that kqueue is
667 responsibility to either stop all watchers cleanly yourself I<before>
674 as signal and child watchers) would need to be stopped manually.
680 Note that it is not advisable to call this function on the default loop
681 except in the rare occasion where you really need to free its resources.
682 If you need dynamically allocated loops it is better to use C<ev_loop_new>
688 to reinitialise the kernel state for backends that have one. Despite
689 the name, you can call it anytime you are allowed to start or stop
694 In addition, if you want to reuse a loop (via this function or
695 C<EVFLAG_FORKCHECK>), you I<also> have to ignore C<SIGPIPE>.
697 Again, you I<have> to call it on I<any> loop that you want to re-use after
698 a fork, I<even if you do not plan to use the loop in the parent>. This is
702 On the other hand, you only need to call this function in the child
703 process if and only if you want to use the event loop in the child. If
704 you just fork+exec or create a new loop in the child, you don't have to
709 The function itself is quite fast and it's usually not a problem to call
732 to the number of times libev did poll for new events. It starts at C<0>
751 as a hint to avoid such ungentleman-like behaviour unless it's really
787 the user presses C<^Z> to suspend the game and resumes it an hour later it
788 would be best to handle timeouts as if no time had actually passed while
791 C<ev_resume> directly afterwards to resume timer processing.
800 without a previous call to C<ev_suspend>.
808 after you have initialised all your watchers and you want to start
822 relying on all watchers to be stopped when deciding when a program has
824 that automatically loops as long as it has to and no longer by virtue
836 iteration of the loop. This is sometimes useful to poll and handle new
837 events while doing lengthy calculations, to keep the program responsive.
842 be an event internal to libev itself, so there is no guarantee that a
864 as to not disturb the other process.
867 - Calculate for how long to sleep or block, if at all
894 ... as they still have work to do (even an idle watcher will do..)
900 Can be used to make a call to C<ev_run> return early (but only after it
905 This "break state" will be cleared on the next call to C<ev_run>.
907 It is safe to call C<ev_break> from outside any C<ev_run> calls, too, in
914 Ref/unref can be used to add or remove a reference count on the event
918 This is useful when you have a watcher that you never intend to
924 is not visible to the libev user and should not keep C<ev_run> from
926 excellent way to do this for generic recurring timers or from within
927 third-party libraries. Just remember to I<unref after start> and I<ref
930 (e.g. non-repeating timers) in which case you have to C<ev_ref>
952 will try to invoke timer/periodic callbacks and I/O callbacks with minimum
955 Setting these to a higher value (the C<interval> I<must> be >= C<0>)
956 allows libev to delay invocation of I/O and timer/periodic callbacks
957 to increase efficiency of loop iterations (or to increase power-saving
960 The idea is that sometimes your program runs just fast enough to handle
962 program responsive, it also wastes a lot of CPU time to poll for new
966 By setting a higher I<io collect interval> you allow libev to spend more
969 C<ev_timer>) will not be affected. Setting this to a non-null value will
976 to spend more time collecting timeouts, at the expense of increased
978 later). C<ev_io> watchers will not be affected. Setting this to a non-null
982 interval to a value near C<0.1> or so, which is often enough for
984 usually doesn't make much sense to set it to a lower value than C<0.01>,
988 need to poll once per transaction and the I/O collect interval is 0.01,
994 times the process sleeps and wakes up again. Another useful technique to
995 reduce iterations/wake-ups is to use C<ev_periodic> watchers and make sure
998 Example: we only need 0.1s timeout granularity, and we wish not to poll
1010 when you want to do some lengthy calculation and want to pass further
1011 event handling to another thread (you still have to make sure only one
1023 this callback instead. This is useful, for example, when you want to
1026 If you want to reset the callback, use C<ev_invoke_pending> as new
1031 Sometimes you want to share the same loop between multiple threads. This
1033 each call to a libev function.
1036 to wait for it to return. One way around this is to wake up the event
1037 loop via C<ev_break> and C<ev_async_send>, another way is to set these
1051 waited. Use an C<ev_async> watcher to wake up C<ev_run> when you want it
1052 to take note of any changes you made.
1068 These two functions can be used to associate arbitrary data with a loop,
1076 compiled in, which is the default for non-minimal builds. It tries to go
1078 is found to be inconsistent, it will print an error message to standard
1081 This can be used to catch bugs inside libev itself: under normal
1094 A watcher is an opaque structure that you allocate and register to record
1096 to wait for STDIN to become readable, you would create an C<ev_io> watcher
1116 watcher structures (and it is I<usually> a bad idea to do this on the
1122 Each watcher structure must be initialised by a call to C<ev_init (watcher
1123 *, callback)>, which expects a callback to be provided. This callback is
1129 macro to configure it, with arguments specific to the watcher type. There
1130 is also a macro to combine initialisation and setting in one call: C<<
1133 To make the watcher actually watch out for events, you have to start it
1181 The C<ev_idle> watcher has determined that you have nothing better to do.
1187 All C<ev_prepare> watchers are invoked just I<before> C<ev_run> starts to
1197 C<ev_prepare> watcher might start an idle watcher to keep C<ev_run> from
1211 The event loop is about to be destroyed (see C<ev_cleanup>).
1220 by libev users to signal watchers (e.g. via C<ev_feed_event>).
1226 ran out of memory, a file descriptor was found to be closed or any other
1251 the generic parts of the watcher are initialised, you I<need> to call
1252 the type-specific C<ev_TYPE_set> macro afterwards to initialise the
1270 This macro initialises the type-specific parts of a watcher. You need to
1274 difference to the C<ev_init> macro).
1277 (e.g. C<ev_prepare>) you still need to call its C<set> macro.
1284 calls into a single call. This is the most convenient method to initialise
1309 pending. If you want to free or reuse the memory used by the watcher it is
1310 therefore a good idea to always call its C<ev_TYPE_stop> function.
1324 make sure the watcher is available to libev (e.g. you cannot C<free ()>
1346 If you need to suppress invocation when higher priority events are pending
1347 you need to look at C<ev_idle> watchers, which provide this functionality.
1352 Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is
1354 or might not have been clamped to the valid range.
1357 always C<0>, which is supposed to not be too high and not be too low :).
1365 C<loop> nor C<revents> need to be valid as long as the watcher callback
1366 can deal with that fact, as both are simply passed through to the
1375 Sometimes it can be useful to "poll" a watcher instead of waiting for its
1376 callback to be invoked, which can be accomplished with this function.
1381 had happened for the specified watcher (which must be a pointer to an
1400 active, pending and so on. In this section these states and the rules to
1408 Before a watcher can be registered with the event loop it has to be
1409 initialised. This can be done with a call to C<ev_TYPE_init>, or calls to
1419 Once a watcher has been started with a call to C<ev_TYPE_start> it becomes
1422 freed or anything else - the only legal thing is to keep a pointer to it,
1423 and call libev functions on it that are documented to work on active watchers.
1430 about to be invoked, so it is not normally pending inside the watcher
1440 It is also possible to feed an event on a watcher that is not active (e.g.
1454 you wish (but when you trash the memory block, you need to C<ev_TYPE_init>
1476 The less common only-for-ordering model uses priorities solely to order
1493 C<ev_io> watcher to receive data, and an associated C<ev_timer> to handle
1503 received events, they can be used to implement the "lock-out" model when
1506 For example, to emulate how many other event libraries handle priorities,
1507 you can associate an C<ev_idle> watcher to each such watcher, and in
1509 processing is done in the idle watcher callback. This causes libev to
1511 the lock-out case is known to be rare (which in turn is rare :), this is
1515 miserably under the type of load it was designed to handle. In that case,
1516 it might be preferable to stop the real watcher before starting the
1517 idle watcher, so the kernel will not have to process the event in case
1531 // are not yet ready to handle it.
1534 // start the idle watcher to handle the actual event.
1546 // have to start the I/O watcher again, as
1556 In the "real" world, it might also be beneficial to start a timer, so that
1558 enables your program to keep a lower latency for important connections
1567 functions and members specific to the watcher type are explained.
1572 watcher is stopped to your hearts content), or I<[read-write]>, which
1573 means you can expect it to have some sensible content while the watcher
1583 would not block the process and writing would at least be able to write
1586 the watcher if you don't want to act on the event and neither want to
1591 descriptors to non-blocking mode is also usually a good idea (but not
1594 Another thing you have to watch out for is that it is quite easy to
1597 because there is no data. It is very easy to get into this situation even
1598 with a relatively standard program structure. Thus it is best to always
1600 preferable to a program hanging until some data arrives.
1603 not play around with an Xlib connection), then you have to separately
1604 re-test whether a file descriptor is really ready with a known-to-be good
1606 this on its own, so its quite safe to use). Some people additionally
1607 use C<SIGALRM> and an interval timer, just to be sure you won't block
1614 Some backends (e.g. kqueue, epoll) need to be told about closing a file
1615 descriptor (either due to calling C<close> explicitly or any other means,
1619 registered with libev, there is no efficient way to see that this is, in
1622 To avoid having to explicitly tell libev about such cases, libev follows
1626 you I<have> to call C<ev_io_set> (or C<ev_io_init>) when you change the
1631 optimisations to libev.
1641 for potentially C<dup ()>'ed file descriptors, or to resort to
1646 Many people try to use C<select> (or libev) on file descriptors
1647 representing files, and expect it to become ready when their program
1656 Another way to view it is that in the case of sockets, pipes, character
1660 wish to read - you would first have to request some data.
1663 mechanism, libev tries hard to emulate POSIX behaviour with respect
1664 to files, even though you should not use it. The reason for this is
1665 convenience: sometimes you want to watch STDIN or STDOUT, which is
1672 So avoid file descriptors pointing to files when you know it (e.g. use
1674 when you rarely read from a file instead of from a socket, and want to
1680 useless behaviour. Libev fully supports fork, but needs to be told about
1681 it in the child if you want to continue to use it in the child.
1683 To support fork in your child processes, you have to call C<ev_loop_fork
1684 ()> after a fork in the child, enable C<EVFLAG_FORKCHECK>, or resort to
1689 While not really specific to libev, it is easy to forget about C<SIGPIPE>:
1690 when writing to a pipe whose other end has been closed, your program gets
1705 of resource limits), causing C<accept> to fail with C<ENFILE> but not
1706 rejecting the connection, leading to libev signalling readiness on
1708 typically causing the program to loop at 100% CPU usage.
1711 operating systems, there is usually little the app can do to remedy the
1712 situation, and no known thread-safe method of removing the connection to
1713 cope with overload is known (to me).
1715 One of the easiest ways to handle this situation is to just ignore it
1718 event-based way to handle this situation, so it's the best one can do.
1720 A better way to handle the situation is to log any errors other than
1721 C<EAGAIN> and C<EWOULDBLOCK>, making sure not to flood the log with such
1733 The last way to handle it is to simply log the error and C<exit>, as
1745 Configures an C<ev_io> watcher. The C<fd> is the file descriptor to
1747 C<EV_READ | EV_WRITE>, to express the desire to receive the given events.
1763 attempt to read a whole line in the callback.
1786 times out after an hour and you reset your system clock to January last
1791 The callback is guaranteed to be invoked only I<after> its timeout has
1803 you want to raise some error after a while.
1805 What follows are some ways to handle this problem, from obvious and
1806 inefficient to smart and efficient.
1809 gets reset to 60 seconds each time there is activity (e.g. each time some
1829 This is relatively simple to implement, but means that each time there is
1830 some activity, libev will first have to remove the timer from its internal
1831 data structure and then add it again. Libev tries to be fast, but it's
1842 you do not expect data to travel on the socket, you can C<ev_timer_stop>
1846 C<after> argument to C<ev_timer_set>, and only ever use the C<repeat>
1859 It is even possible to change the time-out on the fly, regardless of
1866 you want to modify its timeout value, as libev does not have to completely
1869 It is, however, even simpler than the "obvious" way to do it.
1874 relatively long compared to the intervals between other activity - in
1878 In this case, it would be more efficient to leave the C<ev_timer> alone,
1900 // activity. simply restart the timer to time out
1914 timed out, and need to do whatever is needed in this case.
1920 the timeout occurred. If not, it will simply reschedule itself to check
1924 minus half the average time between activity), but virtually no calls to
1925 libev to change the timeout.
1928 C<last_activity> to the current time (meaning there was some activity just
1951 time-out is unlikely to be triggered, much more efficient.
1962 Then use an C<ev_timer> to fire when the timeout at the I<beginning> of
1963 the list is expected to fire (for example, using the technique #3).
1966 the timeout, append it to the end of the list again, and make sure to
1971 complication, and having to use a constant timeout. The constant timeout
1990 If you ask a timer to call your callback after three seconds, then
1991 you expect it to be invoked after three seconds - but of course, this
1992 cannot be guaranteed to infinite precision. Less obviously, it cannot be
1993 guaranteed to any precision by libev - imagine somebody suspending the
1996 So, libev tries to invoke your callback as soon as possible I<after> the
2001 this can cause your callback to be invoked much earlier than you would
2007 event loop will schedule your timeout to elapse at a system time of 500
2008 (500.9 truncated to the resolution) + 1, or 501.
2033 The relative timeouts are calculated relative to the C<ev_now ()>
2034 time. This is usually the right thing as this timestamp refers to the time
2036 you suspect event processing to be delayed and you I<need> to base the
2037 timeout on the current time, use something like the following to adjust
2050 "wall clock" clock and, if available, the monotonic clock (to avoid time
2056 a call to C<gettimeofday> might return a second count that is one higher
2057 than a directly following call to C<time>.
2059 The moral of this is to only compare libev-related timestamps with
2063 One more problem arises due to this lack of synchronisation: if libev uses
2070 I<measured according to the real time>, not the system clock.
2076 If you want to compare wall clock/system timestamps to your timers, then
2077 you need to use C<ev_periodic>s, as these are based on the wall clock
2082 When you leave the server world it is quite customary to hit machines that
2083 can suspend/hibernate - what happens to the clocks during such a suspend?
2087 to run until the system is suspended, but they will not advance while the
2095 I would not be surprised to see different behaviour in different between
2101 then you can expect C<ev_timer>s to expire as the full suspension time
2105 It might be beneficial for this latter case to call C<ev_suspend>
2106 and C<ev_resume> in code that handles C<SIGTSTP>, to at least get
2118 Configure the timer to trigger after C<after> seconds. If C<repeat>
2121 configured to trigger again C<repeat> seconds later, again, and again,
2125 you configure a timer to trigger every 10 seconds, then it will normally
2127 keep up with the timer (because it takes longer than those 10 seconds to
2134 timeout to the C<repeat> value and calling C<ev_timer_start>.
2137 applied to the watcher:
2157 then this time is relative to the current event loop time, otherwise it's
2203 // reset the timeout to start ticking again at 10 seconds
2207 =head2 C<ev_periodic> - to cron or not to cron?
2219 You can tell a periodic watcher to trigger after some specific point
2220 in time: for example, if you tell a periodic watcher to trigger "in 10
2222 not a delay) and then reset your system clock to January of the previous
2223 year, then it will take a year or more to trigger the event (unlike an
2227 C<ev_periodic> watchers can also be used to implement vastly more complex
2230 those cannot react to time jumps.
2232 As with timers, the callback is guaranteed to be invoked only when the
2233 point in time where it is supposed to trigger has passed. If multiple
2247 operation, and we will explain them from simplest to most complex:
2255 time jump occurs, that is, if it is to be run at January 1st 2011 then it
2261 In this mode the watcher will always be scheduled to time out at the next
2266 This can be used to create timers that do not drift with respect to the
2268 hour, on the hour (with respect to UTC):
2277 Another way to think about it (for the mathematically inclined) is that
2278 C<ev_periodic> will try to run the callback in this mode at the next possible
2288 Note also that there is an upper limit to how often a timer can fire (CPU
2290 will of course deteriorate. Libev itself tries to be exact to be about one
2304 If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop
2306 only event loop modification you are allowed to do).
2317 It must return the next time to trigger, based on the passed time value
2318 (that is, the lowest time value larger than to the second argument). It
2323 equal to the passed C<now> value >>.
2325 This can be used to create very complex timers, such as a timer that
2328 you do this is, again, up to you (but it is not trivial, which is the main
2343 to trigger next. This is not the same as the C<offset> argument to
2350 absolute point in time (the C<offset> value passed to C<ev_periodic_set>,
2386 Example: The same as above, but use a reschedule callback to do it:
2410 will try its best to deliver signals synchronously, i.e. as part of the
2413 If you want signals to be delivered truly asynchronously, just use
2415 the signal. You can even use C<ev_async> from a signal handler to
2422 the moment, C<SIGCHLD> is permanently tied to the default loop.
2443 sets signals to C<SIG_IGN>, so handlers will be reset to C<SIG_DFL> on
2445 certain signals to be blocked.
2448 the signal mask to whatever "default" you expect (all clear is a good
2451 The simplest way to ensure that the signal mask is reset in the child is
2452 to install a fork handler with C<pthread_atfork> that resets it. That will
2458 I<has> to modify the signal mask, at least temporarily.
2461 you expect it to be empty, you have a race condition in your code>. This
2468 threads in a process block signals, which is hard to achieve.
2470 When you want to use sigwait (or mix libev signal handling with your own
2486 Configures the watcher to trigger on the given signal number (usually one
2497 Example: Try to exit cleanly on SIGINT.
2512 Child watchers trigger when your process receives a SIGCHLD in response to
2514 exits). It is permissible to install a child watcher I<after> the child
2524 Due to some design glitches inside libev, child watchers will always be
2525 handled at maximum priority (their priority is set to C<EV_MAXPRI> by
2531 initialised. This is necessary to guarantee proper behaviour even if the
2543 default loop never gets destroyed. You are encouraged, however, to use an
2544 event-based approach to child reaping and thus use libev's support for
2550 child terminates, so normally one needs to stop the watcher in the
2563 Configures the watcher to wait for status changes of process C<pid> (or
2565 at the C<rstatus> member of the C<ev_child> watcher structure to see
2589 Example: C<fork()> a new process and install a child handler to wait for
2621 and sees if it changed compared to the last time, invoking the callback
2625 The path does not need to exist: changing from "path exists" to "path does
2628 C<st_nlink> field being zero (which is otherwise always forced to be at
2638 to see if it changed somehow. You can specify a recommended polling
2641 (which you can expect to be around five seconds, although this might
2659 structure. When using the library from programs that change the ABI to
2660 use 64 bit file offsets the programs will fail. In that case you have to
2661 compile libev with the same flags to get binary compatibility. This is
2665 The solution for this is to lobby your distribution maker to make large
2668 to exchange stat structures with application programs compiled using the
2674 runtime, it will be used to speed up change detection where possible. The
2679 except that changes might be detected earlier, and in some cases, to avoid
2681 there are many cases where libev has to resort to regular C<stat> polling,
2687 There is no support for kqueue, as apparently it cannot be used to
2688 implement this functionality, due to the requirement of having a file
2704 time due to network issues, and even under good conditions, a stat call
2707 Therefore, it is best to avoid using C<ev_stat> watchers on networked
2719 within the same second, C<ev_stat> will be unable to detect unless the
2722 The solution to this is to delay acting on a change for slightly more
2727 The C<.02> offset is added to work around small timing inconsistencies
2729 might be be delayed. One such system is the Linux kernel, where a call to
2731 a subsequent C<time> call - if the equivalent of C<time ()> is used to
2733 the previous second to update file times but libev might already execute
2744 Configures the watcher to wait for status changes of the given
2745 C<path>. The C<interval> is a hint on how quickly a change is expected to
2746 be detected and should normally be specified as C<0> to let libev choose
2747 a suitable value. The memory pointed to by C<path> must point to the same
2751 relative to the attributes at the time the watcher was started (or the
2757 watched path in your callback, you could call this function to avoid
2759 the only one changing the path). Can also be useful simply to find out the
2767 members to be present. If the C<st_nlink> member is C<0>, then there was
2842 =head2 C<ev_idle> - when you've got nothing better to do...
2859 effect on its own sometimes), idle watchers are a good place to do
2860 "pseudo-background processing", or delay processing stuff to after the
2867 For this to work, the idle watcher doesn't need to be invoked at all - the
2871 to do something on each event loop iteration - for example to balance load
2903 // now do something you wanted to do when the program has
2904 // no longer anything immediate to do.
2921 however. The rationale behind this is that you do not need to check
2926 Their main purpose is to integrate other event mechanisms into libev and
2927 their use is somewhat advanced. They could be used, for example, to track
2930 you cache some data and want to flush it before blocking (for example,
2931 in X programs you might want to do an C<XFlush ()> in an C<ev_prepare>
2935 need to be watched by the other library, registering C<ev_io> watchers
2943 As another example, the Perl Coro module uses these hooks to integrate
2944 coroutines into libev programs, by yielding to other active coroutines
2946 are ready to run (it's actually more complicated: it only runs coroutines
2947 with priority higher than or equal to the event loop and one coroutine
2948 of lower priority, but only once, using idle watchers to keep the event
2950 low-priority coroutines to idle/background tasks).
2952 When used for this purpose, it is recommended to give C<ev_check> watchers
2953 highest (C<EV_MAXPRI>) priority, to ensure that they are being run before
2960 C<ev_check> watchers are often used to embed other (non-libev) event
2962 C<ev_check> watcher ran (always remind yourself to coexist peacefully with
2969 example, if you want to handle a large number of connections fairly, you
2971 is more work to do, you wait for the next event loop iteration, so other
3001 There are a number of principal ways to embed other event loops or modules
3002 into libev. Here are some ideas on how to include libadns into libev
3010 is pseudo-code only of course. This requires you to either use a low
3028 // actual code will need to loop here and realloc etc.
3072 Method 3: If the module to be embedded supports explicit event
3098 want to embed is not flexible enough to support it. Instead, you can
3120 ev_timer_stop (EV_A_ &to);
3142 still want to make use of it because you have many sockets and it scales
3145 will be a bit slower because first libev has to call C<poll> and then
3147 best: C<kqueue> for scalable sockets and C<poll> if you want it to work :)
3150 some fds have to be watched and handled very quickly (with low latency),
3157 must then call C<ev_embed_sweep (mainloop, watcher)> to make a single
3158 sweep and invoke their callbacks (the callback doesn't need to invoke the
3160 to give the embedded loop strictly lower priority for example).
3162 You can also set the callback to C<0>, in which case the embed watcher
3174 So when you want to use this feature you will always have to be prepared
3175 that you cannot get an embeddable loop. The recommended way to get around
3176 this is to have a separate variables for your embeddable loop, try to
3182 automatically be applied to the embedded loop as well, so no special
3184 however, it is still the task of the libev user to call C<ev_loop_fork ()>
3195 Configures the watcher to embed the given loop, which must be
3198 to invoke it (it will continue to be called until the sweep has been done,
3199 if you do not want that, you need to temporarily stop the embed watcher).
3204 similarly to C<ev_run (embedded_loop, EVRUN_NOWAIT)>, but in the most
3215 Example: Try to get an embeddable event loop and embed it into the default
3231 // if we got one, then embed it, otherwise default to loop_hi
3262 =head2 C<ev_fork> - the audacity to resume the event loop after a fork
3265 whoever is a good citizen cared to tell libev about it by calling
3274 Most uses of C<fork ()> consist of forking, then some simple calls to set
3275 up/change the process environment, followed by a call to C<exec()>. This
3278 This changes when the application actually wants to do event handling
3282 The default mode of operation (for libev, with application help to detect
3283 forks) is to duplicate all the state in the child, as would be expected
3286 When both processes want to continue using libev, then this is usually the
3288 supposed to continue with all watchers in place as before, while the other
3289 process typically wants to start fresh, i.e. without any active watchers.
3291 The cleanest and most efficient way to achieve that with libev is to
3295 disadvantage of having to use multiple event loops (which do not support
3298 When this is not possible, or you want to use the default loop for
3299 other reasons, then in the process that wants to start "fresh", call
3302 watchers, so you have to be careful not to execute code that modifies
3303 those watchers. Note also that in that case, you have to re-register any
3322 by a call to C<ev_loop_destroy>.
3325 watchers provide a convenient method to install cleanup hooks for your
3326 program, worker threads and so on - you just to make sure to destroy the
3327 loop when you want them to be invoked.
3330 all other watchers, they do not keep a reference to the event loop (which
3346 Example: Register an atexit handler to destroy the default loop, so any
3359 =head2 C<ev_async> - how to wake up an event loop
3362 asynchronous sources such as signal handlers (as opposed to multiple event
3363 loops - those are of course safe to use in different threads).
3365 Sometimes, however, you need to wake up an event loop you do not control,
3366 for example because it belongs to another thread. This is what C<ev_async>
3370 This functionality is very similar to C<ev_signal> watchers, as signals,
3375 signal, and C<ev_feed_signal> to signal this watcher from another thread,
3386 That means that if you want to queue data, you have to provide your own
3387 queue. But at least I can tell you how to implement locking around your
3394 To implement race-free queueing, you simply add to the queue in the signal
3427 (Note: pthreads in theory requires you to use C<pthread_setmask>
3434 threads but you can easily preempt them, so to queue safely you need to
3443 // only need to lock the actual queueing operation
3481 Unlike C<ev_feed_event>, this call is safe to do from other threads,
3486 compressed into a single callback invocation (another way to look at
3493 repeated calls are basically free (there is no need to avoid calls for
3504 the loop iterates next and checks for the watcher to have become active,
3505 it will reset the flag again. C<ev_async_pending> can be used to very
3509 only whether it has been requested to make this watcher pending: there
3526 watchers. This is useful if you want to wait for a single event on an fd
3527 or timeout without having to allocate/configure/start/stop/free one or
3541 value passed to C<ev_once>. Note that it is possible to receive I<both>
3545 Example: wait up to ten seconds for data to appear on STDIN_FILENO.
3580 to associate arbitrary data with your watcher. If you need more data and
3581 don't want to allocate memory separately and store a pointer to it in that
3597 And since your callback will be called with a pointer to the watcher, you
3598 can cast it back to your own type:
3611 Another common scenario is to use some data structure with multiple
3622 In this case getting the pointer to C<my_biggy> is a bit more
3625 to use some pointer arithmetic using C<offsetof> inside your watchers (for
3655 The intent is to start some "lengthy" operation. The C<request> could be
3656 used to cancel the operation, or do other things with it.
3658 It's not uncommon to have code paths in C<start_new_request> that
3659 immediately invoke the callback, for example, to report errors. Or you add
3666 Even if you pass the request by some safer means to the callback, you
3667 might want to do something to the request after starting it, such as
3671 A common way around all these issues is to make sure that
3690 This brings the problem of exiting - a callback might want to finish the
3696 The solution is to maintain "break this loop" variable for each C<ev_run>
3725 Here is a fictitious example of how to run an event loop in a different
3733 The example uses a pthread mutex to protect the loop data, a condition
3734 variable to wait for callback invocations, an async watcher to notify the
3735 event loop thread and an unspecified mechanism to wake up the main thread.
3737 First, you need to associate some data with the event loop:
3767 solely to wake up the event loop so it takes notice of any new watchers
3828 Now, whenever the main thread gets told to invoke pending watchers, it
3830 thread to continue:
3843 Whenever you want to start/stop a watcher or do other modifications to an
3844 event loop, you will now have to lock:
3865 kind of threads or coroutines, you might want to customise libev so that
3868 Imagine you have coroutines that you can switch to using a function
3870 and that due to some magic, the currently active coroutine is stored in a
3879 coroutine to switch to in each watcher, and instead of having libev call
3880 your callback, you instead have it switch to that coroutine.
3883 C<wait_for_event>. (the watcher needs to be started, as always, but it doesn't
3895 continues the libev coroutine, which, when appropriate, switches back to
3900 switching to a coroutine, you push the watcher onto the queue and notify
3903 To embed libev, see L</EMBEDDING>, but in short, it's easiest to create two
3950 =item * The libev emulation is I<not> ABI compatible to libevent, you need
3951 to use the libev header file and library.
3963 Proper exception specifications might have to be added to callbacks passed
3964 to libev: exceptions may be thrown only from watcher callbacks, all
3967 ()> specification. If you have code that needs to be compiled as both C
3991 you to use some convenience methods to start/stop watchers and also change
3992 the callback model to a model using method callbacks on objects.
4003 Care has been taken to keep the overhead low. The only data member the C++
4004 classes add (compared to plain C-style watchers) is the event loop pointer
4010 to add as long as they only need one additional pointer for context. If
4014 For all this to work, your C++ compiler either has to use the same calling
4016 to embed libev and compile libev itself as C++.
4029 Aliases to the same types/functions as with the C<ev_> prefix.
4035 which is called C<ev::sig> to avoid clashes with the C<signal> macro
4048 The constructor (optionally) takes an event loop to associate the watcher
4051 The constructor calls C<ev_init> for you, which means you have to call the
4054 It will not set a callback, however: You have to call the templated C<set>
4055 method to set a callback before you can start the watcher.
4057 (The reason why you have to use a method is a limitation in C++ which does
4064 This method sets the callback method to call. The method has to have a
4069 This method synthesizes efficient thunking code to call your method from
4071 callback (i.e. it is visible to it at the place of the C<set> call and
4088 This is a variation of a method callback - leaving out the method to call
4089 will default the method to C<operator ()>, which makes it possible to use
4090 functor objects without having to manually specify the C<operator ()> all
4118 C<data> member and is free for you to use.
4142 For C<ev::embed> watchers this method is called C<set_embed>, to avoid
4153 convenient to wrap them in one call. Uses the same type of arguments as
4204 any interesting language binding in addition to the ones listed here, drop
4211 The EV module implements the full libev API and is actually used to test
4214 to C<libadns> (C<EV::ADNS>, but C<AnyEvent::DNS> is preferred nowadays),
4224 seems to be quite complete and well-documented.
4228 Tony Arcieri has written a ruby extension that offers access to a subset
4238 A haskell binding to libev is available at
4243 Leandro Lucarella has written a D language binding (F<ev.d>) for libev, to
4248 Erkki Seppala has written Ocaml bindings for libev, to be found at
4253 Brian Maher has written a partial interface to libev for lua (at the
4254 time of this writing, only C<ev_io> and C<ev_timer>), to be found at
4274 To make it easier to write programs that cope with either variant, the
4309 Similar to the other two macros, this gives you the value of the default
4314 to initialise the loop somewhere.
4318 Usage identical to C<EV_DEFAULT> and C<EV_DEFAULT_>, but requires that the
4323 It is often prudent to use C<EV_DEFAULT> when initialising the first
4350 The goal is to enable you to just copy the necessary files into your
4351 source directory without having to change even a single line in them, so
4357 Depending on what features you need you need to include one or more sets of files
4369 single C source file only to provide the function implementations. To use
4370 it, do the same for F<ev.h> in all files wishing to use this API (best
4398 to compile this single file.
4410 in the files that want to use the libevent API. This also includes F<ev.h>.
4430 Libev can be configured via a variety of preprocessor symbols you have to
4436 to redefine them before including F<ev.h> without breaking compatibility
4437 to a compiled library. All other symbols change the ABI, which means all
4449 You can disable these wrappers (to test compatibility with future
4450 versions) by defining C<EV_COMPAT3> to C<0> when compiling your
4467 In standalone mode, libev will still try to automatically deduce the
4468 configuration, but has to be more conservative.
4472 If defined to be C<1>, libev will use the C<floor ()> function for its
4474 portable (slower) implementation. If you enable this, you usually have to
4476 function is not available will fail, so the safe default is to not enable
4481 If defined to be C<1>, libev will try to detect the availability of the
4484 you usually have to link against librt or something similar. Enabling it
4486 to make sure you link against any libraries where the C<clock_gettime>
4491 If defined to be C<1>, libev will try to detect the availability of the
4497 C<EV_USE_MONOTONIC>, though. Defaults to the opposite value of
4502 If defined to be C<1>, libev will try to use a direct syscall instead
4508 the pthread dependency. Defaults to C<1> on GNU/Linux with glibc 2.x or
4513 If defined to be C<1>, libev will assume that C<nanosleep ()> is available
4518 If defined to be C<1>, then libev will assume that C<eventfd ()> is
4526 If undefined or defined to be C<1>, libev will compile in support for the
4533 If defined to C<1>, then the select backend will use the system C<fd_set>
4534 structure. This is useful if libev doesn't compile due to a missing
4536 on exotic systems. This usually limits the range of file descriptors to
4543 When defined to C<1>, the select backend will assume that
4545 wants osf handles on win32 (this is the case when the select to
4547 C<_get_osfhandle> on the fd to convert it to an OS handle. Otherwise,
4553 If C<EV_SELECT_IS_WINSOCKET> is enabled, then libev needs a way to map
4554 file descriptors to socket handles. When not defining this symbol (the
4557 in which case they can provide this function to map fds to socket handles.
4561 If C<EV_SELECT_IS_WINSOCKET> then libev maps handles to file descriptors
4563 their own fd to handle mapping, overwriting this function makes it easier
4564 to do so. This can be done by defining this macro to an appropriate value.
4568 If programs implement their own fd to handle mapping on win32, then this
4569 macro can be used to override the C<close> function, useful to unregister
4570 file descriptors again. Note that the replacement function has to close
4575 If defined to be C<1>, libev will use C<WSASocket> to create its internal
4582 If defined to be C<1>, libev will compile in support for the C<poll>(2)
4588 If defined to be C<1>, libev will compile in support for the Linux
4596 If defined to be C<1>, libev will compile in support for the BSD style
4602 not be used unless explicitly requested. The best way to use it is to find
4608 If defined to be C<1>, libev will compile in support for the Solaris
4619 If defined to be C<1>, libev will compile in support for the Linux inotify
4620 interface to speed up C<ev_stat> watchers. Its actual availability will
4626 If defined to be C<1>, libev will assume that memory is always coherent
4633 If defined to be C<1>, libev will assume that it will never be called from
4641 access is atomic with respect to other threads or signal contexts. No
4652 The name of the F<ev.h> header file used to include it. The default if
4654 used to virtually rename the F<ev.h> header file in case of conflicts.
4658 If C<EV_STANDALONE> isn't C<1>, this variable can be used to override
4659 F<ev.c>'s idea of where to find the F<config.h> file, similarly to
4664 Similarly to C<EV_H>, this macro can be used to override F<event.c>'s idea
4669 If defined to be C<0>, then F<ev.h> will not define any function
4671 occasionally useful if you want to provide your own wrapper functions
4676 If undefined or defined to C<1>, then all event-loop-specific functions
4683 default loop when multiplicity is switched off - you always have to
4690 The range of allowed priorities. C<EV_MINPRI> must be smaller or equal to
4693 to be C<-2> and C<2>, respectively).
4695 When doing priority-based operations, libev usually has to linearly search
4701 both to C<0> will save some memory and CPU.
4707 If undefined or defined to be C<1> (and the platform supports it), then
4708 the respective watcher type is supported. If defined to be C<0>, then it
4713 If you need to shave off some kilobytes of code at the expense of some
4714 speed (but with the full API), you can define this symbol to request
4715 certain subsets of functionality. The default is to enable all features
4718 A typical way to use this symbol is to define it to C<0> (or to a bitset
4737 Use larger code to speed up some operations.
4739 Currently this is used to override some inlining decisions (enlarging the
4772 Enables all optional watcher types. If you want to selectively enable
4775 C<EV_watchertype_ENABLE> to C<1> instead.
4779 This enables all backends - without this feature, you need to enable at
4790 reduces the compiled size of libev from 24.7Kb code/2.8Kb data to 6.5Kb
4804 when you embed libev, only want to use libev functions in a single file,
4805 and do not want its identifiers to be visible.
4808 wants to use libev.
4815 If this is set to C<1> at compiletime, then libev will avoid using stdio
4827 signals): Normally, libev tries to deduce the maximum number of signals
4835 C<ev_child> watchers use a small hash table to distribute workload by
4837 usually more than enough. If you need to manage thousands of children you
4838 might want to increase this value (I<must> be a power of two).
4842 C<ev_stat> watchers use a small hash table to distribute workload by
4844 disabled), usually more than enough. If you need to manage thousands of
4845 C<ev_stat> watchers you might want to increase this value (I<must> be a
4852 to C<1>. The 4-heap uses more complicated (longer) code but has noticeably
4862 the heap structure (selected by defining C<EV_HEAP_CACHE_AT> to C<1>),
4873 be done: If set to C<0>, no internal verification code will be compiled
4874 in. If set to C<1>, then verification code will be compiled in, but not
4875 called. If set to C<2>, then the internal verification code will be
4876 called once per loop, which can slow down libev. If set to C<3>, then the
4886 this macro to something else you can include more and other types of
4887 members. You have to define it each time you include one of the files,
4902 Can be used to change the callback member declaration in each watcher,
4903 and the way callbacks are invoked and set. Must expand to a struct member
4905 their default definitions. One possible use for overriding these is to
4906 avoid the C<struct ev_loop *> as first argument in all cases, or to use
4913 If you need to re-export the API (e.g. via a DLL) and you need a list of
4920 This can also be used to rename all public symbols to avoid clashes with
4922 itself, but sometimes it is inconvenient to avoid this).
4924 A sed command like this will create wrapper C<#define>'s that you need to
4979 Or to put it differently: calls with different loop parameters can be done
4985 Specifically to support threads (and signal handlers), libev implements
4990 If you want to know which design (one loop, locking, or multiple loops
5013 =item * often you need to talk to some other thread which blocks in the
5016 C<ev_async> watchers can be used to wake them up from other threads safely
5019 An example use would be to communicate signals or other events that only
5030 Libev is very accommodating to coroutines ("cooperative threads"):
5031 libev fully supports nesting calls to its functions from different
5037 Care has been taken to ensure that libev does not keep local state inside
5053 workarounds, or other changes to the code that make it less clear and less
5058 seems to warn about). For example, certain older gcc versions had some
5063 While libev is written to generate as few warnings as possible,
5064 "warn-free" code is not a goal, and it is recommended not to build libev
5065 with any compiler warnings enabled unless you are prepared to cope with
5073 highly useful. Unfortunately, valgrind reports are very hard to interpret.
5082 Then there is no memory leak, just as memory accounted to global variables
5093 If you are unsure about something, feel free to contact the mailing list
5097 of learning how to interpret valgrind properly.
5113 Unfortunately, many programs try to work around this GNU/Linux issue
5118 suddenly make it incompatible to the default compile time environment,
5132 Libev tries to work around this by not using C<kqueue> by default on this
5135 probably going to work well.
5143 Libev tries to work around this by not using C<poll> by default on
5149 All that's left is C<select>, and of course Apple found a way to fuck this
5151 descriptors you can pass in to 1024 - your program suddenly crashes when
5155 C<_DARWIN_UNLIMITED_SELECT>, which libev tries to use, so select I<should>
5167 If you want to use libev in threaded environments you have to make sure
5177 are multiple ones to apply, and afterwards, event ports actually work
5180 If you can't get it to work, you can try running the program by setting
5181 the environment variable C<LIBEV_FLAGS=3> to only allow C<poll> and
5187 this by trying to avoid the poll backend altogether (i.e. it's not even
5200 e.g. cygwin. Actually, it only applies to the microsofts own compilers,
5207 also that glib is the slowest event library known to man).
5222 Due to the many, low, and arbitrary limits on the win32 platform and
5224 is not recommended (and not reasonable). If your program needs to use
5225 more than a hundred or so sockets, then likely it needs to use a totally
5228 (due to Microsoft monopoly games).
5230 A typical way to use libev under windows is to embed it (see the embedding
5250 requires a mapping from file descriptors to socket handles (the Microsoft
5269 of C<64> handles (probably owning to the fact that all windows kernels
5274 Newer versions support more handles, but you need to define C<FD_SETSIZE>
5275 to some high number (e.g. C<2048>) before compiling the winsocket select
5282 by calling C<_setmaxstdio>, which can increase this limit to C<2048>
5284 runtime libraries. This might get you to about C<512> or C<2048> sockets
5286 you need to wrap all I/O functions and provide your own fd management, but
5291 In addition to a working ISO-C implementation and of course the
5301 assumes that the same (machine) code can be used to call any watcher
5313 C<EV_ATOMIC_T>) must be atomic with respect to accesses from different
5315 believed to be sufficiently portable.
5319 Libev uses C<sigprocmask> to temporarily block signals. This is not
5320 allowed in a threaded program (C<pthread_sigmask> has to be used). Typical
5326 The most portable way to handle signals is to block signals in all threads
5340 The type C<double> is used to represent timestamps. It is required to
5348 is either obsolete or somebody patched it to use C<long double> or
5362 All of the following are about amortised time: If an array needs to be
5363 extended, libev needs to realloc and move the whole array, but this
5374 have to skip roughly seven (C<ld 100>) of these watchers.
5379 as only the relative motion in the event queue has to be paid for.
5389 These watchers are stored in lists, so they need to be walked to find the
5390 correct watcher to remove. The lists are usually short (you don't usually
5402 libev to recalculate its status (and possibly tell the kernel, depending
5410 priority. When doing priority-based operations, libev usually has to
5412 watchers becomes O(1) with respect to priority handling.
5430 The major version 4 introduced some incompatible changes to the API.
5434 layer might be removed in later versions of libev, so better update to the
5473 associated constants have been renamed to not collide with the C<struct
5535 The model used to describe how an event loop handles and processes
5556 to be started (attached to an event loop) before they can receive events.