Mirror of :pserver:anonymous@cvs.schmorp.de/schmorpforge libev http://software.schmorp.de/pkg/libev.html
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3509 lines
131 KiB

13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
13 years ago
13 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
13 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
  1. =head1 NAME
  2. libev - a high performance full-featured event loop written in C
  3. =head1 SYNOPSIS
  4. #include <ev.h>
  6. // a single header file is required
  7. #include <ev.h>
  8. // every watcher type has its own typedef'd struct
  9. // with the name ev_<type>
  10. ev_io stdin_watcher;
  11. ev_timer timeout_watcher;
  12. // all watcher callbacks have a similar signature
  13. // this callback is called when data is readable on stdin
  14. static void
  15. stdin_cb (EV_P_ struct ev_io *w, int revents)
  16. {
  17. puts ("stdin ready");
  18. // for one-shot events, one must manually stop the watcher
  19. // with its corresponding stop function.
  20. ev_io_stop (EV_A_ w);
  21. // this causes all nested ev_loop's to stop iterating
  22. ev_unloop (EV_A_ EVUNLOOP_ALL);
  23. }
  24. // another callback, this time for a time-out
  25. static void
  26. timeout_cb (EV_P_ struct ev_timer *w, int revents)
  27. {
  28. puts ("timeout");
  29. // this causes the innermost ev_loop to stop iterating
  30. ev_unloop (EV_A_ EVUNLOOP_ONE);
  31. }
  32. int
  33. main (void)
  34. {
  35. // use the default event loop unless you have special needs
  36. struct ev_loop *loop = ev_default_loop (0);
  37. // initialise an io watcher, then start it
  38. // this one will watch for stdin to become readable
  39. ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
  40. ev_io_start (loop, &stdin_watcher);
  41. // initialise a timer watcher, then start it
  42. // simple non-repeating 5.5 second timeout
  43. ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
  44. ev_timer_start (loop, &timeout_watcher);
  45. // now wait for events to arrive
  46. ev_loop (loop, 0);
  47. // unloop was called, so exit
  48. return 0;
  49. }
  50. =head1 DESCRIPTION
  51. The newest version of this document is also available as an html-formatted
  52. web page you might find easier to navigate when reading it for the first
  53. time: L<http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod>.
  54. Libev is an event loop: you register interest in certain events (such as a
  55. file descriptor being readable or a timeout occurring), and it will manage
  56. these event sources and provide your program with events.
  57. To do this, it must take more or less complete control over your process
  58. (or thread) by executing the I<event loop> handler, and will then
  59. communicate events via a callback mechanism.
  60. You register interest in certain events by registering so-called I<event
  61. watchers>, which are relatively small C structures you initialise with the
  62. details of the event, and then hand it over to libev by I<starting> the
  63. watcher.
  64. =head2 FEATURES
  65. Libev supports C<select>, C<poll>, the Linux-specific C<epoll>, the
  66. BSD-specific C<kqueue> and the Solaris-specific event port mechanisms
  67. for file descriptor events (C<ev_io>), the Linux C<inotify> interface
  68. (for C<ev_stat>), relative timers (C<ev_timer>), absolute timers
  69. with customised rescheduling (C<ev_periodic>), synchronous signals
  70. (C<ev_signal>), process status change events (C<ev_child>), and event
  71. watchers dealing with the event loop mechanism itself (C<ev_idle>,
  72. C<ev_embed>, C<ev_prepare> and C<ev_check> watchers) as well as
  73. file watchers (C<ev_stat>) and even limited support for fork events
  74. (C<ev_fork>).
  75. It also is quite fast (see this
  76. L<benchmark|http://libev.schmorp.de/bench.html> comparing it to libevent
  77. for example).
  78. =head2 CONVENTIONS
  79. Libev is very configurable. In this manual the default (and most common)
  80. configuration will be described, which supports multiple event loops. For
  81. more info about various configuration options please have a look at
  82. B<EMBED> section in this manual. If libev was configured without support
  83. for multiple event loops, then all functions taking an initial argument of
  84. name C<loop> (which is always of type C<struct ev_loop *>) will not have
  85. this argument.
  87. Libev represents time as a single floating point number, representing the
  88. (fractional) number of seconds since the (POSIX) epoch (somewhere near
  89. the beginning of 1970, details are complicated, don't ask). This type is
  90. called C<ev_tstamp>, which is what you should use too. It usually aliases
  91. to the C<double> type in C, and when you need to do any calculations on
  92. it, you should treat it as some floating point value. Unlike the name
  93. component C<stamp> might indicate, it is also used for time differences
  94. throughout libev.
  95. =head1 ERROR HANDLING
  96. Libev knows three classes of errors: operating system errors, usage errors
  97. and internal errors (bugs).
  98. When libev catches an operating system error it cannot handle (for example
  99. a system call indicating a condition libev cannot fix), it calls the callback
  100. set via C<ev_set_syserr_cb>, which is supposed to fix the problem or
  101. abort. The default is to print a diagnostic message and to call C<abort
  102. ()>.
  103. When libev detects a usage error such as a negative timer interval, then
  104. it will print a diagnostic message and abort (via the C<assert> mechanism,
  105. so C<NDEBUG> will disable this checking): these are programming errors in
  106. the libev caller and need to be fixed there.
  107. Libev also has a few internal error-checking C<assert>ions, and also has
  108. extensive consistency checking code. These do not trigger under normal
  109. circumstances, as they indicate either a bug in libev or worse.
  110. =head1 GLOBAL FUNCTIONS
  111. These functions can be called anytime, even before initialising the
  112. library in any way.
  113. =over 4
  114. =item ev_tstamp ev_time ()
  115. Returns the current time as libev would use it. Please note that the
  116. C<ev_now> function is usually faster and also often returns the timestamp
  117. you actually want to know.
  118. =item ev_sleep (ev_tstamp interval)
  119. Sleep for the given interval: The current thread will be blocked until
  120. either it is interrupted or the given time interval has passed. Basically
  121. this is a sub-second-resolution C<sleep ()>.
  122. =item int ev_version_major ()
  123. =item int ev_version_minor ()
  124. You can find out the major and minor ABI version numbers of the library
  125. you linked against by calling the functions C<ev_version_major> and
  126. C<ev_version_minor>. If you want, you can compare against the global
  127. symbols C<EV_VERSION_MAJOR> and C<EV_VERSION_MINOR>, which specify the
  128. version of the library your program was compiled against.
  129. These version numbers refer to the ABI version of the library, not the
  130. release version.
  131. Usually, it's a good idea to terminate if the major versions mismatch,
  132. as this indicates an incompatible change. Minor versions are usually
  133. compatible to older versions, so a larger minor version alone is usually
  134. not a problem.
  135. Example: Make sure we haven't accidentally been linked against the wrong
  136. version.
  137. assert (("libev version mismatch",
  138. ev_version_major () == EV_VERSION_MAJOR
  139. && ev_version_minor () >= EV_VERSION_MINOR));
  140. =item unsigned int ev_supported_backends ()
  141. Return the set of all backends (i.e. their corresponding C<EV_BACKEND_*>
  142. value) compiled into this binary of libev (independent of their
  143. availability on the system you are running on). See C<ev_default_loop> for
  144. a description of the set values.
  145. Example: make sure we have the epoll method, because yeah this is cool and
  146. a must have and can we have a torrent of it please!!!11
  147. assert (("sorry, no epoll, no sex",
  148. ev_supported_backends () & EVBACKEND_EPOLL));
  149. =item unsigned int ev_recommended_backends ()
  150. Return the set of all backends compiled into this binary of libev and also
  151. recommended for this platform. This set is often smaller than the one
  152. returned by C<ev_supported_backends>, as for example kqueue is broken on
  153. most BSDs and will not be auto-detected unless you explicitly request it
  154. (assuming you know what you are doing). This is the set of backends that
  155. libev will probe for if you specify no backends explicitly.
  156. =item unsigned int ev_embeddable_backends ()
  157. Returns the set of backends that are embeddable in other event loops. This
  158. is the theoretical, all-platform, value. To find which backends
  159. might be supported on the current system, you would need to look at
  160. C<ev_embeddable_backends () & ev_supported_backends ()>, likewise for
  161. recommended ones.
  162. See the description of C<ev_embed> watchers for more info.
  163. =item ev_set_allocator (void *(*cb)(void *ptr, long size))
  164. Sets the allocation function to use (the prototype is similar - the
  165. semantics are identical to the C<realloc> C89/SuS/POSIX function). It is
  166. used to allocate and free memory (no surprises here). If it returns zero
  167. when memory needs to be allocated (C<size != 0>), the library might abort
  168. or take some potentially destructive action.
  169. Since some systems (at least OpenBSD and Darwin) fail to implement
  170. correct C<realloc> semantics, libev will use a wrapper around the system
  171. C<realloc> and C<free> functions by default.
  172. You could override this function in high-availability programs to, say,
  173. free some memory if it cannot allocate memory, to use a special allocator,
  174. or even to sleep a while and retry until some memory is available.
  175. Example: Replace the libev allocator with one that waits a bit and then
  176. retries (example requires a standards-compliant C<realloc>).
  177. static void *
  178. persistent_realloc (void *ptr, size_t size)
  179. {
  180. for (;;)
  181. {
  182. void *newptr = realloc (ptr, size);
  183. if (newptr)
  184. return newptr;
  185. sleep (60);
  186. }
  187. }
  188. ...
  189. ev_set_allocator (persistent_realloc);
  190. =item ev_set_syserr_cb (void (*cb)(const char *msg));
  191. Set the callback function to call on a retryable system call error (such
  192. as failed select, poll, epoll_wait). The message is a printable string
  193. indicating the system call or subsystem causing the problem. If this
  194. callback is set, then libev will expect it to remedy the situation, no
  195. matter what, when it returns. That is, libev will generally retry the
  196. requested operation, or, if the condition doesn't go away, do bad stuff
  197. (such as abort).
  198. Example: This is basically the same thing that libev does internally, too.
  199. static void
  200. fatal_error (const char *msg)
  201. {
  202. perror (msg);
  203. abort ();
  204. }
  205. ...
  206. ev_set_syserr_cb (fatal_error);
  207. =back
  209. An event loop is described by a C<struct ev_loop *>. The library knows two
  210. types of such loops, the I<default> loop, which supports signals and child
  211. events, and dynamically created loops which do not.
  212. =over 4
  213. =item struct ev_loop *ev_default_loop (unsigned int flags)
  214. This will initialise the default event loop if it hasn't been initialised
  215. yet and return it. If the default loop could not be initialised, returns
  216. false. If it already was initialised it simply returns it (and ignores the
  217. flags. If that is troubling you, check C<ev_backend ()> afterwards).
  218. If you don't know what event loop to use, use the one returned from this
  219. function.
  220. Note that this function is I<not> thread-safe, so if you want to use it
  221. from multiple threads, you have to lock (note also that this is unlikely,
  222. as loops cannot bes hared easily between threads anyway).
  223. The default loop is the only loop that can handle C<ev_signal> and
  224. C<ev_child> watchers, and to do this, it always registers a handler
  225. for C<SIGCHLD>. If this is a problem for your application you can either
  226. create a dynamic loop with C<ev_loop_new> that doesn't do that, or you
  227. can simply overwrite the C<SIGCHLD> signal handler I<after> calling
  228. C<ev_default_init>.
  229. The flags argument can be used to specify special behaviour or specific
  230. backends to use, and is usually specified as C<0> (or C<EVFLAG_AUTO>).
  231. The following flags are supported:
  232. =over 4
  233. =item C<EVFLAG_AUTO>
  234. The default flags value. Use this if you have no clue (it's the right
  235. thing, believe me).
  236. =item C<EVFLAG_NOENV>
  237. If this flag bit is or'ed into the flag value (or the program runs setuid
  238. or setgid) then libev will I<not> look at the environment variable
  239. C<LIBEV_FLAGS>. Otherwise (the default), this environment variable will
  240. override the flags completely if it is found in the environment. This is
  241. useful to try out specific backends to test their performance, or to work
  242. around bugs.
  243. =item C<EVFLAG_FORKCHECK>
  244. Instead of calling C<ev_default_fork> or C<ev_loop_fork> manually after
  245. a fork, you can also make libev check for a fork in each iteration by
  246. enabling this flag.
  247. This works by calling C<getpid ()> on every iteration of the loop,
  248. and thus this might slow down your event loop if you do a lot of loop
  249. iterations and little real work, but is usually not noticeable (on my
  250. GNU/Linux system for example, C<getpid> is actually a simple 5-insn sequence
  251. without a system call and thus I<very> fast, but my GNU/Linux system also has
  252. C<pthread_atfork> which is even faster).
  253. The big advantage of this flag is that you can forget about fork (and
  254. forget about forgetting to tell libev about forking) when you use this
  255. flag.
  256. This flag setting cannot be overridden or specified in the C<LIBEV_FLAGS>
  257. environment variable.
  258. =item C<EVBACKEND_SELECT> (value 1, portable select backend)
  259. This is your standard select(2) backend. Not I<completely> standard, as
  260. libev tries to roll its own fd_set with no limits on the number of fds,
  261. but if that fails, expect a fairly low limit on the number of fds when
  262. using this backend. It doesn't scale too well (O(highest_fd)), but its
  263. usually the fastest backend for a low number of (low-numbered :) fds.
  264. To get good performance out of this backend you need a high amount of
  265. parallelism (most of the file descriptors should be busy). If you are
  266. writing a server, you should C<accept ()> in a loop to accept as many
  267. connections as possible during one iteration. You might also want to have
  268. a look at C<ev_set_io_collect_interval ()> to increase the amount of
  269. readiness notifications you get per iteration.
  270. =item C<EVBACKEND_POLL> (value 2, poll backend, available everywhere except on windows)
  271. And this is your standard poll(2) backend. It's more complicated
  272. than select, but handles sparse fds better and has no artificial
  273. limit on the number of fds you can use (except it will slow down
  274. considerably with a lot of inactive fds). It scales similarly to select,
  275. i.e. O(total_fds). See the entry for C<EVBACKEND_SELECT>, above, for
  276. performance tips.
  277. =item C<EVBACKEND_EPOLL> (value 4, Linux)
  278. For few fds, this backend is a bit little slower than poll and select,
  279. but it scales phenomenally better. While poll and select usually scale
  280. like O(total_fds) where n is the total number of fds (or the highest fd),
  281. epoll scales either O(1) or O(active_fds). The epoll design has a number
  282. of shortcomings, such as silently dropping events in some hard-to-detect
  283. cases and requiring a system call per fd change, no fork support and bad
  284. support for dup.
  285. While stopping, setting and starting an I/O watcher in the same iteration
  286. will result in some caching, there is still a system call per such incident
  287. (because the fd could point to a different file description now), so its
  288. best to avoid that. Also, C<dup ()>'ed file descriptors might not work
  289. very well if you register events for both fds.
  290. Please note that epoll sometimes generates spurious notifications, so you
  291. need to use non-blocking I/O or other means to avoid blocking when no data
  292. (or space) is available.
  293. Best performance from this backend is achieved by not unregistering all
  294. watchers for a file descriptor until it has been closed, if possible, i.e.
  295. keep at least one watcher active per fd at all times.
  296. While nominally embeddable in other event loops, this feature is broken in
  297. all kernel versions tested so far.
  298. =item C<EVBACKEND_KQUEUE> (value 8, most BSD clones)
  299. Kqueue deserves special mention, as at the time of this writing, it
  300. was broken on all BSDs except NetBSD (usually it doesn't work reliably
  301. with anything but sockets and pipes, except on Darwin, where of course
  302. it's completely useless). For this reason it's not being "auto-detected"
  303. unless you explicitly specify it explicitly in the flags (i.e. using
  304. C<EVBACKEND_KQUEUE>) or libev was compiled on a known-to-be-good (-enough)
  305. system like NetBSD.
  306. You still can embed kqueue into a normal poll or select backend and use it
  307. only for sockets (after having made sure that sockets work with kqueue on
  308. the target platform). See C<ev_embed> watchers for more info.
  309. It scales in the same way as the epoll backend, but the interface to the
  310. kernel is more efficient (which says nothing about its actual speed, of
  311. course). While stopping, setting and starting an I/O watcher does never
  312. cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to
  313. two event changes per incident, support for C<fork ()> is very bad and it
  314. drops fds silently in similarly hard-to-detect cases.
  315. This backend usually performs well under most conditions.
  316. While nominally embeddable in other event loops, this doesn't work
  317. everywhere, so you might need to test for this. And since it is broken
  318. almost everywhere, you should only use it when you have a lot of sockets
  319. (for which it usually works), by embedding it into another event loop
  320. (e.g. C<EVBACKEND_SELECT> or C<EVBACKEND_POLL>) and using it only for
  321. sockets.
  322. =item C<EVBACKEND_DEVPOLL> (value 16, Solaris 8)
  323. This is not implemented yet (and might never be, unless you send me an
  324. implementation). According to reports, C</dev/poll> only supports sockets
  325. and is not embeddable, which would limit the usefulness of this backend
  326. immensely.
  327. =item C<EVBACKEND_PORT> (value 32, Solaris 10)
  328. This uses the Solaris 10 event port mechanism. As with everything on Solaris,
  329. it's really slow, but it still scales very well (O(active_fds)).
  330. Please note that Solaris event ports can deliver a lot of spurious
  331. notifications, so you need to use non-blocking I/O or other means to avoid
  332. blocking when no data (or space) is available.
  333. While this backend scales well, it requires one system call per active
  334. file descriptor per loop iteration. For small and medium numbers of file
  335. descriptors a "slow" C<EVBACKEND_SELECT> or C<EVBACKEND_POLL> backend
  336. might perform better.
  337. On the positive side, ignoring the spurious readiness notifications, this
  338. backend actually performed to specification in all tests and is fully
  339. embeddable, which is a rare feat among the OS-specific backends.
  340. =item C<EVBACKEND_ALL>
  341. Try all backends (even potentially broken ones that wouldn't be tried
  342. with C<EVFLAG_AUTO>). Since this is a mask, you can do stuff such as
  344. It is definitely not recommended to use this flag.
  345. =back
  346. If one or more of these are or'ed into the flags value, then only these
  347. backends will be tried (in the reverse order as listed here). If none are
  348. specified, all backends in C<ev_recommended_backends ()> will be tried.
  349. The most typical usage is like this:
  350. if (!ev_default_loop (0))
  351. fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?");
  352. Restrict libev to the select and poll backends, and do not allow
  353. environment settings to be taken into account:
  355. Use whatever libev has to offer, but make sure that kqueue is used if
  356. available (warning, breaks stuff, best use only with your own private
  357. event loop and only if you know the OS supports your types of fds):
  358. ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE);
  359. =item struct ev_loop *ev_loop_new (unsigned int flags)
  360. Similar to C<ev_default_loop>, but always creates a new event loop that is
  361. always distinct from the default loop. Unlike the default loop, it cannot
  362. handle signal and child watchers, and attempts to do so will be greeted by
  363. undefined behaviour (or a failed assertion if assertions are enabled).
  364. Note that this function I<is> thread-safe, and the recommended way to use
  365. libev with threads is indeed to create one loop per thread, and using the
  366. default loop in the "main" or "initial" thread.
  367. Example: Try to create a event loop that uses epoll and nothing else.
  368. struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV);
  369. if (!epoller)
  370. fatal ("no epoll found here, maybe it hides under your chair");
  371. =item ev_default_destroy ()
  372. Destroys the default loop again (frees all memory and kernel state
  373. etc.). None of the active event watchers will be stopped in the normal
  374. sense, so e.g. C<ev_is_active> might still return true. It is your
  375. responsibility to either stop all watchers cleanly yourself I<before>
  376. calling this function, or cope with the fact afterwards (which is usually
  377. the easiest thing, you can just ignore the watchers and/or C<free ()> them
  378. for example).
  379. Note that certain global state, such as signal state, will not be freed by
  380. this function, and related watchers (such as signal and child watchers)
  381. would need to be stopped manually.
  382. In general it is not advisable to call this function except in the
  383. rare occasion where you really need to free e.g. the signal handling
  384. pipe fds. If you need dynamically allocated loops it is better to use
  385. C<ev_loop_new> and C<ev_loop_destroy>).
  386. =item ev_loop_destroy (loop)
  387. Like C<ev_default_destroy>, but destroys an event loop created by an
  388. earlier call to C<ev_loop_new>.
  389. =item ev_default_fork ()
  390. This function sets a flag that causes subsequent C<ev_loop> iterations
  391. to reinitialise the kernel state for backends that have one. Despite the
  392. name, you can call it anytime, but it makes most sense after forking, in
  393. the child process (or both child and parent, but that again makes little
  394. sense). You I<must> call it in the child before using any of the libev
  395. functions, and it will only take effect at the next C<ev_loop> iteration.
  396. On the other hand, you only need to call this function in the child
  397. process if and only if you want to use the event library in the child. If
  398. you just fork+exec, you don't have to call it at all.
  399. The function itself is quite fast and it's usually not a problem to call
  400. it just in case after a fork. To make this easy, the function will fit in
  401. quite nicely into a call to C<pthread_atfork>:
  402. pthread_atfork (0, 0, ev_default_fork);
  403. =item ev_loop_fork (loop)
  404. Like C<ev_default_fork>, but acts on an event loop created by
  405. C<ev_loop_new>. Yes, you have to call this on every allocated event loop
  406. after fork, and how you do this is entirely your own problem.
  407. =item int ev_is_default_loop (loop)
  408. Returns true when the given loop actually is the default loop, false otherwise.
  409. =item unsigned int ev_loop_count (loop)
  410. Returns the count of loop iterations for the loop, which is identical to
  411. the number of times libev did poll for new events. It starts at C<0> and
  412. happily wraps around with enough iterations.
  413. This value can sometimes be useful as a generation counter of sorts (it
  414. "ticks" the number of loop iterations), as it roughly corresponds with
  415. C<ev_prepare> and C<ev_check> calls.
  416. =item unsigned int ev_backend (loop)
  417. Returns one of the C<EVBACKEND_*> flags indicating the event backend in
  418. use.
  419. =item ev_tstamp ev_now (loop)
  420. Returns the current "event loop time", which is the time the event loop
  421. received events and started processing them. This timestamp does not
  422. change as long as callbacks are being processed, and this is also the base
  423. time used for relative timers. You can treat it as the timestamp of the
  424. event occurring (or more correctly, libev finding out about it).
  425. =item ev_loop (loop, int flags)
  426. Finally, this is it, the event handler. This function usually is called
  427. after you initialised all your watchers and you want to start handling
  428. events.
  429. If the flags argument is specified as C<0>, it will not return until
  430. either no event watchers are active anymore or C<ev_unloop> was called.
  431. Please note that an explicit C<ev_unloop> is usually better than
  432. relying on all watchers to be stopped when deciding when a program has
  433. finished (especially in interactive programs), but having a program that
  434. automatically loops as long as it has to and no longer by virtue of
  435. relying on its watchers stopping correctly is a thing of beauty.
  436. A flags value of C<EVLOOP_NONBLOCK> will look for new events, will handle
  437. those events and any outstanding ones, but will not block your process in
  438. case there are no events and will return after one iteration of the loop.
  439. A flags value of C<EVLOOP_ONESHOT> will look for new events (waiting if
  440. necessary) and will handle those and any outstanding ones. It will block
  441. your process until at least one new event arrives, and will return after
  442. one iteration of the loop. This is useful if you are waiting for some
  443. external event in conjunction with something not expressible using other
  444. libev watchers. However, a pair of C<ev_prepare>/C<ev_check> watchers is
  445. usually a better approach for this kind of thing.
  446. Here are the gory details of what C<ev_loop> does:
  447. - Before the first iteration, call any pending watchers.
  448. * If EVFLAG_FORKCHECK was used, check for a fork.
  449. - If a fork was detected, queue and call all fork watchers.
  450. - Queue and call all prepare watchers.
  451. - If we have been forked, recreate the kernel state.
  452. - Update the kernel state with all outstanding changes.
  453. - Update the "event loop time".
  454. - Calculate for how long to sleep or block, if at all
  455. (active idle watchers, EVLOOP_NONBLOCK or not having
  456. any active watchers at all will result in not sleeping).
  457. - Sleep if the I/O and timer collect interval say so.
  458. - Block the process, waiting for any events.
  459. - Queue all outstanding I/O (fd) events.
  460. - Update the "event loop time" and do time jump handling.
  461. - Queue all outstanding timers.
  462. - Queue all outstanding periodics.
  463. - If no events are pending now, queue all idle watchers.
  464. - Queue all check watchers.
  465. - Call all queued watchers in reverse order (i.e. check watchers first).
  466. Signals and child watchers are implemented as I/O watchers, and will
  467. be handled here by queueing them when their watcher gets executed.
  468. - If ev_unloop has been called, or EVLOOP_ONESHOT or EVLOOP_NONBLOCK
  469. were used, or there are no active watchers, return, otherwise
  470. continue with step *.
  471. Example: Queue some jobs and then loop until no events are outstanding
  472. anymore.
  473. ... queue jobs here, make sure they register event watchers as long
  474. ... as they still have work to do (even an idle watcher will do..)
  475. ev_loop (my_loop, 0);
  476. ... jobs done. yeah!
  477. =item ev_unloop (loop, how)
  478. Can be used to make a call to C<ev_loop> return early (but only after it
  479. has processed all outstanding events). The C<how> argument must be either
  480. C<EVUNLOOP_ONE>, which will make the innermost C<ev_loop> call return, or
  481. C<EVUNLOOP_ALL>, which will make all nested C<ev_loop> calls return.
  482. This "unloop state" will be cleared when entering C<ev_loop> again.
  483. =item ev_ref (loop)
  484. =item ev_unref (loop)
  485. Ref/unref can be used to add or remove a reference count on the event
  486. loop: Every watcher keeps one reference, and as long as the reference
  487. count is nonzero, C<ev_loop> will not return on its own. If you have
  488. a watcher you never unregister that should not keep C<ev_loop> from
  489. returning, ev_unref() after starting, and ev_ref() before stopping it. For
  490. example, libev itself uses this for its internal signal pipe: It is not
  491. visible to the libev user and should not keep C<ev_loop> from exiting if
  492. no event watchers registered by it are active. It is also an excellent
  493. way to do this for generic recurring timers or from within third-party
  494. libraries. Just remember to I<unref after start> and I<ref before stop>
  495. (but only if the watcher wasn't active before, or was active before,
  496. respectively).
  497. Example: Create a signal watcher, but keep it from keeping C<ev_loop>
  498. running when nothing else is active.
  499. struct ev_signal exitsig;
  500. ev_signal_init (&exitsig, sig_cb, SIGINT);
  501. ev_signal_start (loop, &exitsig);
  502. evf_unref (loop);
  503. Example: For some weird reason, unregister the above signal handler again.
  504. ev_ref (loop);
  505. ev_signal_stop (loop, &exitsig);
  506. =item ev_set_io_collect_interval (loop, ev_tstamp interval)
  507. =item ev_set_timeout_collect_interval (loop, ev_tstamp interval)
  508. These advanced functions influence the time that libev will spend waiting
  509. for events. Both are by default C<0>, meaning that libev will try to
  510. invoke timer/periodic callbacks and I/O callbacks with minimum latency.
  511. Setting these to a higher value (the C<interval> I<must> be >= C<0>)
  512. allows libev to delay invocation of I/O and timer/periodic callbacks to
  513. increase efficiency of loop iterations.
  514. The background is that sometimes your program runs just fast enough to
  515. handle one (or very few) event(s) per loop iteration. While this makes
  516. the program responsive, it also wastes a lot of CPU time to poll for new
  517. events, especially with backends like C<select ()> which have a high
  518. overhead for the actual polling but can deliver many events at once.
  519. By setting a higher I<io collect interval> you allow libev to spend more
  520. time collecting I/O events, so you can handle more events per iteration,
  521. at the cost of increasing latency. Timeouts (both C<ev_periodic> and
  522. C<ev_timer>) will be not affected. Setting this to a non-null value will
  523. introduce an additional C<ev_sleep ()> call into most loop iterations.
  524. Likewise, by setting a higher I<timeout collect interval> you allow libev
  525. to spend more time collecting timeouts, at the expense of increased
  526. latency (the watcher callback will be called later). C<ev_io> watchers
  527. will not be affected. Setting this to a non-null value will not introduce
  528. any overhead in libev.
  529. Many (busy) programs can usually benefit by setting the I/O collect
  530. interval to a value near C<0.1> or so, which is often enough for
  531. interactive servers (of course not for games), likewise for timeouts. It
  532. usually doesn't make much sense to set it to a lower value than C<0.01>,
  533. as this approaches the timing granularity of most systems.
  534. =item ev_loop_verify (loop)
  535. This function only does something when C<EV_VERIFY> support has been
  536. compiled in. It tries to go through all internal structures and checks
  537. them for validity. If anything is found to be inconsistent, it will print
  538. an error message to standard error and call C<abort ()>.
  539. This can be used to catch bugs inside libev itself: under normal
  540. circumstances, this function will never abort as of course libev keeps its
  541. data structures consistent.
  542. =back
  543. =head1 ANATOMY OF A WATCHER
  544. A watcher is a structure that you create and register to record your
  545. interest in some event. For instance, if you want to wait for STDIN to
  546. become readable, you would create an C<ev_io> watcher for that:
  547. static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents)
  548. {
  549. ev_io_stop (w);
  550. ev_unloop (loop, EVUNLOOP_ALL);
  551. }
  552. struct ev_loop *loop = ev_default_loop (0);
  553. struct ev_io stdin_watcher;
  554. ev_init (&stdin_watcher, my_cb);
  555. ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ);
  556. ev_io_start (loop, &stdin_watcher);
  557. ev_loop (loop, 0);
  558. As you can see, you are responsible for allocating the memory for your
  559. watcher structures (and it is usually a bad idea to do this on the stack,
  560. although this can sometimes be quite valid).
  561. Each watcher structure must be initialised by a call to C<ev_init
  562. (watcher *, callback)>, which expects a callback to be provided. This
  563. callback gets invoked each time the event occurs (or, in the case of I/O
  564. watchers, each time the event loop detects that the file descriptor given
  565. is readable and/or writable).
  566. Each watcher type has its own C<< ev_<type>_set (watcher *, ...) >> macro
  567. with arguments specific to this watcher type. There is also a macro
  568. to combine initialisation and setting in one call: C<< ev_<type>_init
  569. (watcher *, callback, ...) >>.
  570. To make the watcher actually watch out for events, you have to start it
  571. with a watcher-specific start function (C<< ev_<type>_start (loop, watcher
  572. *) >>), and you can stop watching for events at any time by calling the
  573. corresponding stop function (C<< ev_<type>_stop (loop, watcher *) >>.
  574. As long as your watcher is active (has been started but not stopped) you
  575. must not touch the values stored in it. Most specifically you must never
  576. reinitialise it or call its C<set> macro.
  577. Each and every callback receives the event loop pointer as first, the
  578. registered watcher structure as second, and a bitset of received events as
  579. third argument.
  580. The received events usually include a single bit per event type received
  581. (you can receive multiple events at the same time). The possible bit masks
  582. are:
  583. =over 4
  584. =item C<EV_READ>
  585. =item C<EV_WRITE>
  586. The file descriptor in the C<ev_io> watcher has become readable and/or
  587. writable.
  588. =item C<EV_TIMEOUT>
  589. The C<ev_timer> watcher has timed out.
  590. =item C<EV_PERIODIC>
  591. The C<ev_periodic> watcher has timed out.
  592. =item C<EV_SIGNAL>
  593. The signal specified in the C<ev_signal> watcher has been received by a thread.
  594. =item C<EV_CHILD>
  595. The pid specified in the C<ev_child> watcher has received a status change.
  596. =item C<EV_STAT>
  597. The path specified in the C<ev_stat> watcher changed its attributes somehow.
  598. =item C<EV_IDLE>
  599. The C<ev_idle> watcher has determined that you have nothing better to do.
  600. =item C<EV_PREPARE>
  601. =item C<EV_CHECK>
  602. All C<ev_prepare> watchers are invoked just I<before> C<ev_loop> starts
  603. to gather new events, and all C<ev_check> watchers are invoked just after
  604. C<ev_loop> has gathered them, but before it invokes any callbacks for any
  605. received events. Callbacks of both watcher types can start and stop as
  606. many watchers as they want, and all of them will be taken into account
  607. (for example, a C<ev_prepare> watcher might start an idle watcher to keep
  608. C<ev_loop> from blocking).
  609. =item C<EV_EMBED>
  610. The embedded event loop specified in the C<ev_embed> watcher needs attention.
  611. =item C<EV_FORK>
  612. The event loop has been resumed in the child process after fork (see
  613. C<ev_fork>).
  614. =item C<EV_ASYNC>
  615. The given async watcher has been asynchronously notified (see C<ev_async>).
  616. =item C<EV_ERROR>
  617. An unspecified error has occurred, the watcher has been stopped. This might
  618. happen because the watcher could not be properly started because libev
  619. ran out of memory, a file descriptor was found to be closed or any other
  620. problem. You best act on it by reporting the problem and somehow coping
  621. with the watcher being stopped.
  622. Libev will usually signal a few "dummy" events together with an error,
  623. for example it might indicate that a fd is readable or writable, and if
  624. your callbacks is well-written it can just attempt the operation and cope
  625. with the error from read() or write(). This will not work in multi-threaded
  626. programs, though, so beware.
  627. =back
  629. In the following description, C<TYPE> stands for the watcher type,
  630. e.g. C<timer> for C<ev_timer> watchers and C<io> for C<ev_io> watchers.
  631. =over 4
  632. =item C<ev_init> (ev_TYPE *watcher, callback)
  633. This macro initialises the generic portion of a watcher. The contents
  634. of the watcher object can be arbitrary (so C<malloc> will do). Only
  635. the generic parts of the watcher are initialised, you I<need> to call
  636. the type-specific C<ev_TYPE_set> macro afterwards to initialise the
  637. type-specific parts. For each type there is also a C<ev_TYPE_init> macro
  638. which rolls both calls into one.
  639. You can reinitialise a watcher at any time as long as it has been stopped
  640. (or never started) and there are no pending events outstanding.
  641. The callback is always of type C<void (*)(ev_loop *loop, ev_TYPE *watcher,
  642. int revents)>.
  643. =item C<ev_TYPE_set> (ev_TYPE *, [args])
  644. This macro initialises the type-specific parts of a watcher. You need to
  645. call C<ev_init> at least once before you call this macro, but you can
  646. call C<ev_TYPE_set> any number of times. You must not, however, call this
  647. macro on a watcher that is active (it can be pending, however, which is a
  648. difference to the C<ev_init> macro).
  649. Although some watcher types do not have type-specific arguments
  650. (e.g. C<ev_prepare>) you still need to call its C<set> macro.
  651. =item C<ev_TYPE_init> (ev_TYPE *watcher, callback, [args])
  652. This convenience macro rolls both C<ev_init> and C<ev_TYPE_set> macro
  653. calls into a single call. This is the most convenient method to initialise
  654. a watcher. The same limitations apply, of course.
  655. =item C<ev_TYPE_start> (loop *, ev_TYPE *watcher)
  656. Starts (activates) the given watcher. Only active watchers will receive
  657. events. If the watcher is already active nothing will happen.
  658. =item C<ev_TYPE_stop> (loop *, ev_TYPE *watcher)
  659. Stops the given watcher again (if active) and clears the pending
  660. status. It is possible that stopped watchers are pending (for example,
  661. non-repeating timers are being stopped when they become pending), but
  662. C<ev_TYPE_stop> ensures that the watcher is neither active nor pending. If
  663. you want to free or reuse the memory used by the watcher it is therefore a
  664. good idea to always call its C<ev_TYPE_stop> function.
  665. =item bool ev_is_active (ev_TYPE *watcher)
  666. Returns a true value iff the watcher is active (i.e. it has been started
  667. and not yet been stopped). As long as a watcher is active you must not modify
  668. it.
  669. =item bool ev_is_pending (ev_TYPE *watcher)
  670. Returns a true value iff the watcher is pending, (i.e. it has outstanding
  671. events but its callback has not yet been invoked). As long as a watcher
  672. is pending (but not active) you must not call an init function on it (but
  673. C<ev_TYPE_set> is safe), you must not change its priority, and you must
  674. make sure the watcher is available to libev (e.g. you cannot C<free ()>
  675. it).
  676. =item callback ev_cb (ev_TYPE *watcher)
  677. Returns the callback currently set on the watcher.
  678. =item ev_cb_set (ev_TYPE *watcher, callback)
  679. Change the callback. You can change the callback at virtually any time
  680. (modulo threads).
  681. =item ev_set_priority (ev_TYPE *watcher, priority)
  682. =item int ev_priority (ev_TYPE *watcher)
  683. Set and query the priority of the watcher. The priority is a small
  684. integer between C<EV_MAXPRI> (default: C<2>) and C<EV_MINPRI>
  685. (default: C<-2>). Pending watchers with higher priority will be invoked
  686. before watchers with lower priority, but priority will not keep watchers
  687. from being executed (except for C<ev_idle> watchers).
  688. This means that priorities are I<only> used for ordering callback
  689. invocation after new events have been received. This is useful, for
  690. example, to reduce latency after idling, or more often, to bind two
  691. watchers on the same event and make sure one is called first.
  692. If you need to suppress invocation when higher priority events are pending
  693. you need to look at C<ev_idle> watchers, which provide this functionality.
  694. You I<must not> change the priority of a watcher as long as it is active or
  695. pending.
  696. The default priority used by watchers when no priority has been set is
  697. always C<0>, which is supposed to not be too high and not be too low :).
  698. Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is
  699. fine, as long as you do not mind that the priority value you query might
  700. or might not have been adjusted to be within valid range.
  701. =item ev_invoke (loop, ev_TYPE *watcher, int revents)
  702. Invoke the C<watcher> with the given C<loop> and C<revents>. Neither
  703. C<loop> nor C<revents> need to be valid as long as the watcher callback
  704. can deal with that fact.
  705. =item int ev_clear_pending (loop, ev_TYPE *watcher)
  706. If the watcher is pending, this function returns clears its pending status
  707. and returns its C<revents> bitset (as if its callback was invoked). If the
  708. watcher isn't pending it does nothing and returns C<0>.
  709. =back
  711. Each watcher has, by default, a member C<void *data> that you can change
  712. and read at any time, libev will completely ignore it. This can be used
  713. to associate arbitrary data with your watcher. If you need more data and
  714. don't want to allocate memory and store a pointer to it in that data
  715. member, you can also "subclass" the watcher type and provide your own
  716. data:
  717. struct my_io
  718. {
  719. struct ev_io io;
  720. int otherfd;
  721. void *somedata;
  722. struct whatever *mostinteresting;
  723. }
  724. And since your callback will be called with a pointer to the watcher, you
  725. can cast it back to your own type:
  726. static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents)
  727. {
  728. struct my_io *w = (struct my_io *)w_;
  729. ...
  730. }
  731. More interesting and less C-conformant ways of casting your callback type
  732. instead have been omitted.
  733. Another common scenario is having some data structure with multiple
  734. watchers:
  735. struct my_biggy
  736. {
  737. int some_data;
  738. ev_timer t1;
  739. ev_timer t2;
  740. }
  741. In this case getting the pointer to C<my_biggy> is a bit more complicated,
  742. you need to use C<offsetof>:
  743. #include <stddef.h>
  744. static void
  745. t1_cb (EV_P_ struct ev_timer *w, int revents)
  746. {
  747. struct my_biggy big = (struct my_biggy *
  748. (((char *)w) - offsetof (struct my_biggy, t1));
  749. }
  750. static void
  751. t2_cb (EV_P_ struct ev_timer *w, int revents)
  752. {
  753. struct my_biggy big = (struct my_biggy *
  754. (((char *)w) - offsetof (struct my_biggy, t2));
  755. }
  756. =head1 WATCHER TYPES
  757. This section describes each watcher in detail, but will not repeat
  758. information given in the last section. Any initialisation/set macros,
  759. functions and members specific to the watcher type are explained.
  760. Members are additionally marked with either I<[read-only]>, meaning that,
  761. while the watcher is active, you can look at the member and expect some
  762. sensible content, but you must not modify it (you can modify it while the
  763. watcher is stopped to your hearts content), or I<[read-write]>, which
  764. means you can expect it to have some sensible content while the watcher
  765. is active, but you can also modify it. Modifying it may not do something
  766. sensible or take immediate effect (or do anything at all), but libev will
  767. not crash or malfunction in any way.
  768. =head2 C<ev_io> - is this file descriptor readable or writable?
  769. I/O watchers check whether a file descriptor is readable or writable
  770. in each iteration of the event loop, or, more precisely, when reading
  771. would not block the process and writing would at least be able to write
  772. some data. This behaviour is called level-triggering because you keep
  773. receiving events as long as the condition persists. Remember you can stop
  774. the watcher if you don't want to act on the event and neither want to
  775. receive future events.
  776. In general you can register as many read and/or write event watchers per
  777. fd as you want (as long as you don't confuse yourself). Setting all file
  778. descriptors to non-blocking mode is also usually a good idea (but not
  779. required if you know what you are doing).
  780. If you must do this, then force the use of a known-to-be-good backend
  781. (at the time of this writing, this includes only C<EVBACKEND_SELECT> and
  783. Another thing you have to watch out for is that it is quite easy to
  784. receive "spurious" readiness notifications, that is your callback might
  785. be called with C<EV_READ> but a subsequent C<read>(2) will actually block
  786. because there is no data. Not only are some backends known to create a
  787. lot of those (for example Solaris ports), it is very easy to get into
  788. this situation even with a relatively standard program structure. Thus
  789. it is best to always use non-blocking I/O: An extra C<read>(2) returning
  790. C<EAGAIN> is far preferable to a program hanging until some data arrives.
  791. If you cannot run the fd in non-blocking mode (for example you should not
  792. play around with an Xlib connection), then you have to separately re-test
  793. whether a file descriptor is really ready with a known-to-be good interface
  794. such as poll (fortunately in our Xlib example, Xlib already does this on
  795. its own, so its quite safe to use).
  796. =head3 The special problem of disappearing file descriptors
  797. Some backends (e.g. kqueue, epoll) need to be told about closing a file
  798. descriptor (either by calling C<close> explicitly or by any other means,
  799. such as C<dup>). The reason is that you register interest in some file
  800. descriptor, but when it goes away, the operating system will silently drop
  801. this interest. If another file descriptor with the same number then is
  802. registered with libev, there is no efficient way to see that this is, in
  803. fact, a different file descriptor.
  804. To avoid having to explicitly tell libev about such cases, libev follows
  805. the following policy: Each time C<ev_io_set> is being called, libev
  806. will assume that this is potentially a new file descriptor, otherwise
  807. it is assumed that the file descriptor stays the same. That means that
  808. you I<have> to call C<ev_io_set> (or C<ev_io_init>) when you change the
  809. descriptor even if the file descriptor number itself did not change.
  810. This is how one would do it normally anyway, the important point is that
  811. the libev application should not optimise around libev but should leave
  812. optimisations to libev.
  813. =head3 The special problem of dup'ed file descriptors
  814. Some backends (e.g. epoll), cannot register events for file descriptors,
  815. but only events for the underlying file descriptions. That means when you
  816. have C<dup ()>'ed file descriptors or weirder constellations, and register
  817. events for them, only one file descriptor might actually receive events.
  818. There is no workaround possible except not registering events
  819. for potentially C<dup ()>'ed file descriptors, or to resort to
  821. =head3 The special problem of fork
  822. Some backends (epoll, kqueue) do not support C<fork ()> at all or exhibit
  823. useless behaviour. Libev fully supports fork, but needs to be told about
  824. it in the child.
  825. To support fork in your programs, you either have to call
  826. C<ev_default_fork ()> or C<ev_loop_fork ()> after a fork in the child,
  827. enable C<EVFLAG_FORKCHECK>, or resort to C<EVBACKEND_SELECT> or
  829. =head3 The special problem of SIGPIPE
  830. While not really specific to libev, it is easy to forget about SIGPIPE:
  831. when reading from a pipe whose other end has been closed, your program
  832. gets send a SIGPIPE, which, by default, aborts your program. For most
  833. programs this is sensible behaviour, for daemons, this is usually
  834. undesirable.
  835. So when you encounter spurious, unexplained daemon exits, make sure you
  836. ignore SIGPIPE (and maybe make sure you log the exit status of your daemon
  837. somewhere, as that would have given you a big clue).
  838. =head3 Watcher-Specific Functions
  839. =over 4
  840. =item ev_io_init (ev_io *, callback, int fd, int events)
  841. =item ev_io_set (ev_io *, int fd, int events)
  842. Configures an C<ev_io> watcher. The C<fd> is the file descriptor to
  843. receive events for and events is either C<EV_READ>, C<EV_WRITE> or
  844. C<EV_READ | EV_WRITE> to receive the given events.
  845. =item int fd [read-only]
  846. The file descriptor being watched.
  847. =item int events [read-only]
  848. The events being watched.
  849. =back
  850. =head3 Examples
  851. Example: Call C<stdin_readable_cb> when STDIN_FILENO has become, well
  852. readable, but only once. Since it is likely line-buffered, you could
  853. attempt to read a whole line in the callback.
  854. static void
  855. stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents)
  856. {
  857. ev_io_stop (loop, w);
  858. .. read from stdin here (or from w->fd) and haqndle any I/O errors
  859. }
  860. ...
  861. struct ev_loop *loop = ev_default_init (0);
  862. struct ev_io stdin_readable;
  863. ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ);
  864. ev_io_start (loop, &stdin_readable);
  865. ev_loop (loop, 0);
  866. =head2 C<ev_timer> - relative and optionally repeating timeouts
  867. Timer watchers are simple relative timers that generate an event after a
  868. given time, and optionally repeating in regular intervals after that.
  869. The timers are based on real time, that is, if you register an event that
  870. times out after an hour and you reset your system clock to January last
  871. year, it will still time out after (roughly) and hour. "Roughly" because
  872. detecting time jumps is hard, and some inaccuracies are unavoidable (the
  873. monotonic clock option helps a lot here).
  874. The relative timeouts are calculated relative to the C<ev_now ()>
  875. time. This is usually the right thing as this timestamp refers to the time
  876. of the event triggering whatever timeout you are modifying/starting. If
  877. you suspect event processing to be delayed and you I<need> to base the timeout
  878. on the current time, use something like this to adjust for this:
  879. ev_timer_set (&timer, after + ev_now () - ev_time (), 0.);
  880. The callback is guaranteed to be invoked only after its timeout has passed,
  881. but if multiple timers become ready during the same loop iteration then
  882. order of execution is undefined.
  883. =head3 Watcher-Specific Functions and Data Members
  884. =over 4
  885. =item ev_timer_init (ev_timer *, callback, ev_tstamp after, ev_tstamp repeat)
  886. =item ev_timer_set (ev_timer *, ev_tstamp after, ev_tstamp repeat)
  887. Configure the timer to trigger after C<after> seconds. If C<repeat>
  888. is C<0.>, then it will automatically be stopped once the timeout is
  889. reached. If it is positive, then the timer will automatically be
  890. configured to trigger again C<repeat> seconds later, again, and again,
  891. until stopped manually.
  892. The timer itself will do a best-effort at avoiding drift, that is, if
  893. you configure a timer to trigger every 10 seconds, then it will normally
  894. trigger at exactly 10 second intervals. If, however, your program cannot
  895. keep up with the timer (because it takes longer than those 10 seconds to
  896. do stuff) the timer will not fire more than once per event loop iteration.
  897. =item ev_timer_again (loop, ev_timer *)
  898. This will act as if the timer timed out and restart it again if it is
  899. repeating. The exact semantics are:
  900. If the timer is pending, its pending status is cleared.
  901. If the timer is started but non-repeating, stop it (as if it timed out).
  902. If the timer is repeating, either start it if necessary (with the
  903. C<repeat> value), or reset the running timer to the C<repeat> value.
  904. This sounds a bit complicated, but here is a useful and typical
  905. example: Imagine you have a TCP connection and you want a so-called idle
  906. timeout, that is, you want to be called when there have been, say, 60
  907. seconds of inactivity on the socket. The easiest way to do this is to
  908. configure an C<ev_timer> with a C<repeat> value of C<60> and then call
  909. C<ev_timer_again> each time you successfully read or write some data. If
  910. you go into an idle state where you do not expect data to travel on the
  911. socket, you can C<ev_timer_stop> the timer, and C<ev_timer_again> will
  912. automatically restart it if need be.
  913. That means you can ignore the C<after> value and C<ev_timer_start>
  914. altogether and only ever use the C<repeat> value and C<ev_timer_again>:
  915. ev_timer_init (timer, callback, 0., 5.);
  916. ev_timer_again (loop, timer);
  917. ...
  918. timer->again = 17.;
  919. ev_timer_again (loop, timer);
  920. ...
  921. timer->again = 10.;
  922. ev_timer_again (loop, timer);
  923. This is more slightly efficient then stopping/starting the timer each time
  924. you want to modify its timeout value.
  925. =item ev_tstamp repeat [read-write]
  926. The current C<repeat> value. Will be used each time the watcher times out
  927. or C<ev_timer_again> is called and determines the next timeout (if any),
  928. which is also when any modifications are taken into account.
  929. =back
  930. =head3 Examples
  931. Example: Create a timer that fires after 60 seconds.
  932. static void
  933. one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents)
  934. {
  935. .. one minute over, w is actually stopped right here
  936. }
  937. struct ev_timer mytimer;
  938. ev_timer_init (&mytimer, one_minute_cb, 60., 0.);
  939. ev_timer_start (loop, &mytimer);
  940. Example: Create a timeout timer that times out after 10 seconds of
  941. inactivity.
  942. static void
  943. timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents)
  944. {
  945. .. ten seconds without any activity
  946. }
  947. struct ev_timer mytimer;
  948. ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */
  949. ev_timer_again (&mytimer); /* start timer */
  950. ev_loop (loop, 0);
  951. // and in some piece of code that gets executed on any "activity":
  952. // reset the timeout to start ticking again at 10 seconds
  953. ev_timer_again (&mytimer);
  954. =head2 C<ev_periodic> - to cron or not to cron?
  955. Periodic watchers are also timers of a kind, but they are very versatile
  956. (and unfortunately a bit complex).
  957. Unlike C<ev_timer>'s, they are not based on real time (or relative time)
  958. but on wall clock time (absolute time). You can tell a periodic watcher
  959. to trigger after some specific point in time. For example, if you tell a
  960. periodic watcher to trigger in 10 seconds (by specifying e.g. C<ev_now ()
  961. + 10.>, that is, an absolute time not a delay) and then reset your system
  962. clock to January of the previous year, then it will take more than year
  963. to trigger the event (unlike an C<ev_timer>, which would still trigger
  964. roughly 10 seconds later as it uses a relative timeout).
  965. C<ev_periodic>s can also be used to implement vastly more complex timers,
  966. such as triggering an event on each "midnight, local time", or other
  967. complicated, rules.
  968. As with timers, the callback is guaranteed to be invoked only when the
  969. time (C<at>) has passed, but if multiple periodic timers become ready
  970. during the same loop iteration then order of execution is undefined.
  971. =head3 Watcher-Specific Functions and Data Members
  972. =over 4
  973. =item ev_periodic_init (ev_periodic *, callback, ev_tstamp at, ev_tstamp interval, reschedule_cb)
  974. =item ev_periodic_set (ev_periodic *, ev_tstamp after, ev_tstamp repeat, reschedule_cb)
  975. Lots of arguments, lets sort it out... There are basically three modes of
  976. operation, and we will explain them from simplest to complex:
  977. =over 4
  978. =item * absolute timer (at = time, interval = reschedule_cb = 0)
  979. In this configuration the watcher triggers an event after the wall clock
  980. time C<at> has passed and doesn't repeat. It will not adjust when a time
  981. jump occurs, that is, if it is to be run at January 1st 2011 then it will
  982. run when the system time reaches or surpasses this time.
  983. =item * repeating interval timer (at = offset, interval > 0, reschedule_cb = 0)
  984. In this mode the watcher will always be scheduled to time out at the next
  985. C<at + N * interval> time (for some integer N, which can also be negative)
  986. and then repeat, regardless of any time jumps.
  987. This can be used to create timers that do not drift with respect to system
  988. time, for example, here is a C<ev_periodic> that triggers each hour, on
  989. the hour:
  990. ev_periodic_set (&periodic, 0., 3600., 0);
  991. This doesn't mean there will always be 3600 seconds in between triggers,
  992. but only that the callback will be called when the system time shows a
  993. full hour (UTC), or more correctly, when the system time is evenly divisible
  994. by 3600.
  995. Another way to think about it (for the mathematically inclined) is that
  996. C<ev_periodic> will try to run the callback in this mode at the next possible
  997. time where C<time = at (mod interval)>, regardless of any time jumps.
  998. For numerical stability it is preferable that the C<at> value is near
  999. C<ev_now ()> (the current time), but there is no range requirement for
  1000. this value, and in fact is often specified as zero.
  1001. Note also that there is an upper limit to how often a timer can fire (CPU
  1002. speed for example), so if C<interval> is very small then timing stability
  1003. will of course deteriorate. Libev itself tries to be exact to be about one
  1004. millisecond (if the OS supports it and the machine is fast enough).
  1005. =item * manual reschedule mode (at and interval ignored, reschedule_cb = callback)
  1006. In this mode the values for C<interval> and C<at> are both being
  1007. ignored. Instead, each time the periodic watcher gets scheduled, the
  1008. reschedule callback will be called with the watcher as first, and the
  1009. current time as second argument.
  1010. NOTE: I<This callback MUST NOT stop or destroy any periodic watcher,
  1011. ever, or make ANY event loop modifications whatsoever>.
  1012. If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop
  1013. it afterwards (e.g. by starting an C<ev_prepare> watcher, which is the
  1014. only event loop modification you are allowed to do).
  1015. The callback prototype is C<ev_tstamp (*reschedule_cb)(struct ev_periodic
  1016. *w, ev_tstamp now)>, e.g.:
  1017. static ev_tstamp my_rescheduler (struct ev_periodic *w, ev_tstamp now)
  1018. {
  1019. return now + 60.;
  1020. }
  1021. It must return the next time to trigger, based on the passed time value
  1022. (that is, the lowest time value larger than to the second argument). It
  1023. will usually be called just before the callback will be triggered, but
  1024. might be called at other times, too.
  1025. NOTE: I<< This callback must always return a time that is higher than or
  1026. equal to the passed C<now> value >>.
  1027. This can be used to create very complex timers, such as a timer that
  1028. triggers on "next midnight, local time". To do this, you would calculate the
  1029. next midnight after C<now> and return the timestamp value for this. How
  1030. you do this is, again, up to you (but it is not trivial, which is the main
  1031. reason I omitted it as an example).
  1032. =back
  1033. =item ev_periodic_again (loop, ev_periodic *)
  1034. Simply stops and restarts the periodic watcher again. This is only useful
  1035. when you changed some parameters or the reschedule callback would return
  1036. a different time than the last time it was called (e.g. in a crond like
  1037. program when the crontabs have changed).
  1038. =item ev_tstamp ev_periodic_at (ev_periodic *)
  1039. When active, returns the absolute time that the watcher is supposed to
  1040. trigger next.
  1041. =item ev_tstamp offset [read-write]
  1042. When repeating, this contains the offset value, otherwise this is the
  1043. absolute point in time (the C<at> value passed to C<ev_periodic_set>).
  1044. Can be modified any time, but changes only take effect when the periodic
  1045. timer fires or C<ev_periodic_again> is being called.
  1046. =item ev_tstamp interval [read-write]
  1047. The current interval value. Can be modified any time, but changes only
  1048. take effect when the periodic timer fires or C<ev_periodic_again> is being
  1049. called.
  1050. =item ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now) [read-write]
  1051. The current reschedule callback, or C<0>, if this functionality is
  1052. switched off. Can be changed any time, but changes only take effect when
  1053. the periodic timer fires or C<ev_periodic_again> is being called.
  1054. =back
  1055. =head3 Examples
  1056. Example: Call a callback every hour, or, more precisely, whenever the
  1057. system clock is divisible by 3600. The callback invocation times have
  1058. potentially a lot of jitter, but good long-term stability.
  1059. static void
  1060. clock_cb (struct ev_loop *loop, struct ev_io *w, int revents)
  1061. {
  1062. ... its now a full hour (UTC, or TAI or whatever your clock follows)
  1063. }
  1064. struct ev_periodic hourly_tick;
  1065. ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0);
  1066. ev_periodic_start (loop, &hourly_tick);
  1067. Example: The same as above, but use a reschedule callback to do it:
  1068. #include <math.h>
  1069. static ev_tstamp
  1070. my_scheduler_cb (struct ev_periodic *w, ev_tstamp now)
  1071. {
  1072. return fmod (now, 3600.) + 3600.;
  1073. }
  1074. ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb);
  1075. Example: Call a callback every hour, starting now:
  1076. struct ev_periodic hourly_tick;
  1077. ev_periodic_init (&hourly_tick, clock_cb,
  1078. fmod (ev_now (loop), 3600.), 3600., 0);
  1079. ev_periodic_start (loop, &hourly_tick);
  1080. =head2 C<ev_signal> - signal me when a signal gets signalled!
  1081. Signal watchers will trigger an event when the process receives a specific
  1082. signal one or more times. Even though signals are very asynchronous, libev
  1083. will try it's best to deliver signals synchronously, i.e. as part of the
  1084. normal event processing, like any other event.
  1085. You can configure as many watchers as you like per signal. Only when the
  1086. first watcher gets started will libev actually register a signal watcher
  1087. with the kernel (thus it coexists with your own signal handlers as long
  1088. as you don't register any with libev). Similarly, when the last signal
  1089. watcher for a signal is stopped libev will reset the signal handler to
  1090. SIG_DFL (regardless of what it was set to before).
  1091. If possible and supported, libev will install its handlers with
  1092. C<SA_RESTART> behaviour enabled, so system calls should not be unduly
  1093. interrupted. If you have a problem with system calls getting interrupted by
  1094. signals you can block all signals in an C<ev_check> watcher and unblock
  1095. them in an C<ev_prepare> watcher.
  1096. =head3 Watcher-Specific Functions and Data Members
  1097. =over 4
  1098. =item ev_signal_init (ev_signal *, callback, int signum)
  1099. =item ev_signal_set (ev_signal *, int signum)
  1100. Configures the watcher to trigger on the given signal number (usually one
  1101. of the C<SIGxxx> constants).
  1102. =item int signum [read-only]
  1103. The signal the watcher watches out for.
  1104. =back
  1105. =head3 Examples
  1106. Example: Try to exit cleanly on SIGINT and SIGTERM.
  1107. static void
  1108. sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents)
  1109. {
  1110. ev_unloop (loop, EVUNLOOP_ALL);
  1111. }
  1112. struct ev_signal signal_watcher;
  1113. ev_signal_init (&signal_watcher, sigint_cb, SIGINT);
  1114. ev_signal_start (loop, &sigint_cb);
  1115. =head2 C<ev_child> - watch out for process status changes
  1116. Child watchers trigger when your process receives a SIGCHLD in response to
  1117. some child status changes (most typically when a child of yours dies). It
  1118. is permissible to install a child watcher I<after> the child has been
  1119. forked (which implies it might have already exited), as long as the event
  1120. loop isn't entered (or is continued from a watcher).
  1121. Only the default event loop is capable of handling signals, and therefore
  1122. you can only register child watchers in the default event loop.
  1123. =head3 Process Interaction
  1124. Libev grabs C<SIGCHLD> as soon as the default event loop is
  1125. initialised. This is necessary to guarantee proper behaviour even if
  1126. the first child watcher is started after the child exits. The occurrence
  1127. of C<SIGCHLD> is recorded asynchronously, but child reaping is done
  1128. synchronously as part of the event loop processing. Libev always reaps all
  1129. children, even ones not watched.
  1130. =head3 Overriding the Built-In Processing
  1131. Libev offers no special support for overriding the built-in child
  1132. processing, but if your application collides with libev's default child
  1133. handler, you can override it easily by installing your own handler for
  1134. C<SIGCHLD> after initialising the default loop, and making sure the
  1135. default loop never gets destroyed. You are encouraged, however, to use an
  1136. event-based approach to child reaping and thus use libev's support for
  1137. that, so other libev users can use C<ev_child> watchers freely.
  1138. =head3 Watcher-Specific Functions and Data Members
  1139. =over 4
  1140. =item ev_child_init (ev_child *, callback, int pid, int trace)
  1141. =item ev_child_set (ev_child *, int pid, int trace)
  1142. Configures the watcher to wait for status changes of process C<pid> (or
  1143. I<any> process if C<pid> is specified as C<0>). The callback can look
  1144. at the C<rstatus> member of the C<ev_child> watcher structure to see
  1145. the status word (use the macros from C<sys/wait.h> and see your systems
  1146. C<waitpid> documentation). The C<rpid> member contains the pid of the
  1147. process causing the status change. C<trace> must be either C<0> (only
  1148. activate the watcher when the process terminates) or C<1> (additionally
  1149. activate the watcher when the process is stopped or continued).
  1150. =item int pid [read-only]
  1151. The process id this watcher watches out for, or C<0>, meaning any process id.
  1152. =item int rpid [read-write]
  1153. The process id that detected a status change.
  1154. =item int rstatus [read-write]
  1155. The process exit/trace status caused by C<rpid> (see your systems
  1156. C<waitpid> and C<sys/wait.h> documentation for details).
  1157. =back
  1158. =head3 Examples
  1159. Example: C<fork()> a new process and install a child handler to wait for
  1160. its completion.
  1161. ev_child cw;
  1162. static void
  1163. child_cb (EV_P_ struct ev_child *w, int revents)
  1164. {
  1165. ev_child_stop (EV_A_ w);
  1166. printf ("process %d exited with status %x\n", w->rpid, w->rstatus);
  1167. }
  1168. pid_t pid = fork ();
  1169. if (pid < 0)
  1170. // error
  1171. else if (pid == 0)
  1172. {
  1173. // the forked child executes here
  1174. exit (1);
  1175. }
  1176. else
  1177. {
  1178. ev_child_init (&cw, child_cb, pid, 0);
  1179. ev_child_start (EV_DEFAULT_ &cw);
  1180. }
  1181. =head2 C<ev_stat> - did the file attributes just change?
  1182. This watches a file system path for attribute changes. That is, it calls
  1183. C<stat> regularly (or when the OS says it changed) and sees if it changed
  1184. compared to the last time, invoking the callback if it did.
  1185. The path does not need to exist: changing from "path exists" to "path does
  1186. not exist" is a status change like any other. The condition "path does
  1187. not exist" is signified by the C<st_nlink> field being zero (which is
  1188. otherwise always forced to be at least one) and all the other fields of
  1189. the stat buffer having unspecified contents.
  1190. The path I<should> be absolute and I<must not> end in a slash. If it is
  1191. relative and your working directory changes, the behaviour is undefined.
  1192. Since there is no standard to do this, the portable implementation simply