ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/libev/ev.pod
Revision: 1.34
Committed: Fri Nov 23 16:17:12 2007 UTC (16 years, 5 months ago) by root
Branch: MAIN
Changes since 1.33: +203 -5 lines
Log Message:
add lots of theoretical examples

File Contents

# Content
1 =head1 NAME
2
3 libev - a high performance full-featured event loop written in C
4
5 =head1 SYNOPSIS
6
7 #include <ev.h>
8
9 =head1 DESCRIPTION
10
11 Libev is an event loop: you register interest in certain events (such as a
12 file descriptor being readable or a timeout occuring), and it will manage
13 these event sources and provide your program with events.
14
15 To do this, it must take more or less complete control over your process
16 (or thread) by executing the I<event loop> handler, and will then
17 communicate events via a callback mechanism.
18
19 You register interest in certain events by registering so-called I<event
20 watchers>, which are relatively small C structures you initialise with the
21 details of the event, and then hand it over to libev by I<starting> the
22 watcher.
23
24 =head1 FEATURES
25
26 Libev supports select, poll, the linux-specific epoll and the bsd-specific
27 kqueue mechanisms for file descriptor events, relative timers, absolute
28 timers with customised rescheduling, signal events, process status change
29 events (related to SIGCHLD), and event watchers dealing with the event
30 loop mechanism itself (idle, prepare and check watchers). It also is quite
31 fast (see this L<benchmark|http://libev.schmorp.de/bench.html> comparing
32 it to libevent for example).
33
34 =head1 CONVENTIONS
35
36 Libev is very configurable. In this manual the default configuration
37 will be described, which supports multiple event loops. For more info
38 about various configuration options please have a look at the file
39 F<README.embed> in the libev distribution. If libev was configured without
40 support for multiple event loops, then all functions taking an initial
41 argument of name C<loop> (which is always of type C<struct ev_loop *>)
42 will not have this argument.
43
44 =head1 TIME REPRESENTATION
45
46 Libev represents time as a single floating point number, representing the
47 (fractional) number of seconds since the (POSIX) epoch (somewhere near
48 the beginning of 1970, details are complicated, don't ask). This type is
49 called C<ev_tstamp>, which is what you should use too. It usually aliases
50 to the C<double> type in C, and when you need to do any calculations on
51 it, you should treat it as such.
52
53
54 =head1 GLOBAL FUNCTIONS
55
56 These functions can be called anytime, even before initialising the
57 library in any way.
58
59 =over 4
60
61 =item ev_tstamp ev_time ()
62
63 Returns the current time as libev would use it. Please note that the
64 C<ev_now> function is usually faster and also often returns the timestamp
65 you actually want to know.
66
67 =item int ev_version_major ()
68
69 =item int ev_version_minor ()
70
71 You can find out the major and minor version numbers of the library
72 you linked against by calling the functions C<ev_version_major> and
73 C<ev_version_minor>. If you want, you can compare against the global
74 symbols C<EV_VERSION_MAJOR> and C<EV_VERSION_MINOR>, which specify the
75 version of the library your program was compiled against.
76
77 Usually, it's a good idea to terminate if the major versions mismatch,
78 as this indicates an incompatible change. Minor versions are usually
79 compatible to older versions, so a larger minor version alone is usually
80 not a problem.
81
82 Example: make sure we haven't accidentally been linked against the wrong
83 version:
84
85 assert (("libev version mismatch",
86 ev_version_major () == EV_VERSION_MAJOR
87 && ev_version_minor () >= EV_VERSION_MINOR));
88
89 =item unsigned int ev_supported_backends ()
90
91 Return the set of all backends (i.e. their corresponding C<EV_BACKEND_*>
92 value) compiled into this binary of libev (independent of their
93 availability on the system you are running on). See C<ev_default_loop> for
94 a description of the set values.
95
96 Example: make sure we have the epoll method, because yeah this is cool and
97 a must have and can we have a torrent of it please!!!11
98
99 assert (("sorry, no epoll, no sex",
100 ev_supported_backends () & EVBACKEND_EPOLL));
101
102 =item unsigned int ev_recommended_backends ()
103
104 Return the set of all backends compiled into this binary of libev and also
105 recommended for this platform. This set is often smaller than the one
106 returned by C<ev_supported_backends>, as for example kqueue is broken on
107 most BSDs and will not be autodetected unless you explicitly request it
108 (assuming you know what you are doing). This is the set of backends that
109 libev will probe for if you specify no backends explicitly.
110
111 =item ev_set_allocator (void *(*cb)(void *ptr, long size))
112
113 Sets the allocation function to use (the prototype is similar to the
114 realloc C function, the semantics are identical). It is used to allocate
115 and free memory (no surprises here). If it returns zero when memory
116 needs to be allocated, the library might abort or take some potentially
117 destructive action. The default is your system realloc function.
118
119 You could override this function in high-availability programs to, say,
120 free some memory if it cannot allocate memory, to use a special allocator,
121 or even to sleep a while and retry until some memory is available.
122
123 Example: replace the libev allocator with one that waits a bit and then
124 retries: better than mine).
125
126 static void *
127 persistent_realloc (void *ptr, long size)
128 {
129 for (;;)
130 {
131 void *newptr = realloc (ptr, size);
132
133 if (newptr)
134 return newptr;
135
136 sleep (60);
137 }
138 }
139
140 ...
141 ev_set_allocator (persistent_realloc);
142
143 =item ev_set_syserr_cb (void (*cb)(const char *msg));
144
145 Set the callback function to call on a retryable syscall error (such
146 as failed select, poll, epoll_wait). The message is a printable string
147 indicating the system call or subsystem causing the problem. If this
148 callback is set, then libev will expect it to remedy the sitution, no
149 matter what, when it returns. That is, libev will generally retry the
150 requested operation, or, if the condition doesn't go away, do bad stuff
151 (such as abort).
152
153 Example: do the same thing as libev does internally:
154
155 static void
156 fatal_error (const char *msg)
157 {
158 perror (msg);
159 abort ();
160 }
161
162 ...
163 ev_set_syserr_cb (fatal_error);
164
165 =back
166
167 =head1 FUNCTIONS CONTROLLING THE EVENT LOOP
168
169 An event loop is described by a C<struct ev_loop *>. The library knows two
170 types of such loops, the I<default> loop, which supports signals and child
171 events, and dynamically created loops which do not.
172
173 If you use threads, a common model is to run the default event loop
174 in your main thread (or in a separate thread) and for each thread you
175 create, you also create another event loop. Libev itself does no locking
176 whatsoever, so if you mix calls to the same event loop in different
177 threads, make sure you lock (this is usually a bad idea, though, even if
178 done correctly, because it's hideous and inefficient).
179
180 =over 4
181
182 =item struct ev_loop *ev_default_loop (unsigned int flags)
183
184 This will initialise the default event loop if it hasn't been initialised
185 yet and return it. If the default loop could not be initialised, returns
186 false. If it already was initialised it simply returns it (and ignores the
187 flags. If that is troubling you, check C<ev_backend ()> afterwards).
188
189 If you don't know what event loop to use, use the one returned from this
190 function.
191
192 The flags argument can be used to specify special behaviour or specific
193 backends to use, and is usually specified as C<0> (or C<EVFLAG_AUTO>).
194
195 The following flags are supported:
196
197 =over 4
198
199 =item C<EVFLAG_AUTO>
200
201 The default flags value. Use this if you have no clue (it's the right
202 thing, believe me).
203
204 =item C<EVFLAG_NOENV>
205
206 If this flag bit is ored into the flag value (or the program runs setuid
207 or setgid) then libev will I<not> look at the environment variable
208 C<LIBEV_FLAGS>. Otherwise (the default), this environment variable will
209 override the flags completely if it is found in the environment. This is
210 useful to try out specific backends to test their performance, or to work
211 around bugs.
212
213 =item C<EVBACKEND_SELECT> (value 1, portable select backend)
214
215 This is your standard select(2) backend. Not I<completely> standard, as
216 libev tries to roll its own fd_set with no limits on the number of fds,
217 but if that fails, expect a fairly low limit on the number of fds when
218 using this backend. It doesn't scale too well (O(highest_fd)), but its usually
219 the fastest backend for a low number of fds.
220
221 =item C<EVBACKEND_POLL> (value 2, poll backend, available everywhere except on windows)
222
223 And this is your standard poll(2) backend. It's more complicated than
224 select, but handles sparse fds better and has no artificial limit on the
225 number of fds you can use (except it will slow down considerably with a
226 lot of inactive fds). It scales similarly to select, i.e. O(total_fds).
227
228 =item C<EVBACKEND_EPOLL> (value 4, Linux)
229
230 For few fds, this backend is a bit little slower than poll and select,
231 but it scales phenomenally better. While poll and select usually scale like
232 O(total_fds) where n is the total number of fds (or the highest fd), epoll scales
233 either O(1) or O(active_fds).
234
235 While stopping and starting an I/O watcher in the same iteration will
236 result in some caching, there is still a syscall per such incident
237 (because the fd could point to a different file description now), so its
238 best to avoid that. Also, dup()ed file descriptors might not work very
239 well if you register events for both fds.
240
241 Please note that epoll sometimes generates spurious notifications, so you
242 need to use non-blocking I/O or other means to avoid blocking when no data
243 (or space) is available.
244
245 =item C<EVBACKEND_KQUEUE> (value 8, most BSD clones)
246
247 Kqueue deserves special mention, as at the time of this writing, it
248 was broken on all BSDs except NetBSD (usually it doesn't work with
249 anything but sockets and pipes, except on Darwin, where of course its
250 completely useless). For this reason its not being "autodetected"
251 unless you explicitly specify it explicitly in the flags (i.e. using
252 C<EVBACKEND_KQUEUE>).
253
254 It scales in the same way as the epoll backend, but the interface to the
255 kernel is more efficient (which says nothing about its actual speed, of
256 course). While starting and stopping an I/O watcher does not cause an
257 extra syscall as with epoll, it still adds up to four event changes per
258 incident, so its best to avoid that.
259
260 =item C<EVBACKEND_DEVPOLL> (value 16, Solaris 8)
261
262 This is not implemented yet (and might never be).
263
264 =item C<EVBACKEND_PORT> (value 32, Solaris 10)
265
266 This uses the Solaris 10 port mechanism. As with everything on Solaris,
267 it's really slow, but it still scales very well (O(active_fds)).
268
269 Please note that solaris ports can result in a lot of spurious
270 notifications, so you need to use non-blocking I/O or other means to avoid
271 blocking when no data (or space) is available.
272
273 =item C<EVBACKEND_ALL>
274
275 Try all backends (even potentially broken ones that wouldn't be tried
276 with C<EVFLAG_AUTO>). Since this is a mask, you can do stuff such as
277 C<EVBACKEND_ALL & ~EVBACKEND_KQUEUE>.
278
279 =back
280
281 If one or more of these are ored into the flags value, then only these
282 backends will be tried (in the reverse order as given here). If none are
283 specified, most compiled-in backend will be tried, usually in reverse
284 order of their flag values :)
285
286 The most typical usage is like this:
287
288 if (!ev_default_loop (0))
289 fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?");
290
291 Restrict libev to the select and poll backends, and do not allow
292 environment settings to be taken into account:
293
294 ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV);
295
296 Use whatever libev has to offer, but make sure that kqueue is used if
297 available (warning, breaks stuff, best use only with your own private
298 event loop and only if you know the OS supports your types of fds):
299
300 ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE);
301
302 =item struct ev_loop *ev_loop_new (unsigned int flags)
303
304 Similar to C<ev_default_loop>, but always creates a new event loop that is
305 always distinct from the default loop. Unlike the default loop, it cannot
306 handle signal and child watchers, and attempts to do so will be greeted by
307 undefined behaviour (or a failed assertion if assertions are enabled).
308
309 Example: try to create a event loop that uses epoll and nothing else.
310
311 struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV);
312 if (!epoller)
313 fatal ("no epoll found here, maybe it hides under your chair");
314
315 =item ev_default_destroy ()
316
317 Destroys the default loop again (frees all memory and kernel state
318 etc.). This stops all registered event watchers (by not touching them in
319 any way whatsoever, although you cannot rely on this :).
320
321 =item ev_loop_destroy (loop)
322
323 Like C<ev_default_destroy>, but destroys an event loop created by an
324 earlier call to C<ev_loop_new>.
325
326 =item ev_default_fork ()
327
328 This function reinitialises the kernel state for backends that have
329 one. Despite the name, you can call it anytime, but it makes most sense
330 after forking, in either the parent or child process (or both, but that
331 again makes little sense).
332
333 You I<must> call this function in the child process after forking if and
334 only if you want to use the event library in both processes. If you just
335 fork+exec, you don't have to call it.
336
337 The function itself is quite fast and it's usually not a problem to call
338 it just in case after a fork. To make this easy, the function will fit in
339 quite nicely into a call to C<pthread_atfork>:
340
341 pthread_atfork (0, 0, ev_default_fork);
342
343 At the moment, C<EVBACKEND_SELECT> and C<EVBACKEND_POLL> are safe to use
344 without calling this function, so if you force one of those backends you
345 do not need to care.
346
347 =item ev_loop_fork (loop)
348
349 Like C<ev_default_fork>, but acts on an event loop created by
350 C<ev_loop_new>. Yes, you have to call this on every allocated event loop
351 after fork, and how you do this is entirely your own problem.
352
353 =item unsigned int ev_backend (loop)
354
355 Returns one of the C<EVBACKEND_*> flags indicating the event backend in
356 use.
357
358 =item ev_tstamp ev_now (loop)
359
360 Returns the current "event loop time", which is the time the event loop
361 received events and started processing them. This timestamp does not
362 change as long as callbacks are being processed, and this is also the base
363 time used for relative timers. You can treat it as the timestamp of the
364 event occuring (or more correctly, libev finding out about it).
365
366 =item ev_loop (loop, int flags)
367
368 Finally, this is it, the event handler. This function usually is called
369 after you initialised all your watchers and you want to start handling
370 events.
371
372 If the flags argument is specified as C<0>, it will not return until
373 either no event watchers are active anymore or C<ev_unloop> was called.
374
375 Please note that an explicit C<ev_unloop> is usually better than
376 relying on all watchers to be stopped when deciding when a program has
377 finished (especially in interactive programs), but having a program that
378 automatically loops as long as it has to and no longer by virtue of
379 relying on its watchers stopping correctly is a thing of beauty.
380
381 A flags value of C<EVLOOP_NONBLOCK> will look for new events, will handle
382 those events and any outstanding ones, but will not block your process in
383 case there are no events and will return after one iteration of the loop.
384
385 A flags value of C<EVLOOP_ONESHOT> will look for new events (waiting if
386 neccessary) and will handle those and any outstanding ones. It will block
387 your process until at least one new event arrives, and will return after
388 one iteration of the loop. This is useful if you are waiting for some
389 external event in conjunction with something not expressible using other
390 libev watchers. However, a pair of C<ev_prepare>/C<ev_check> watchers is
391 usually a better approach for this kind of thing.
392
393 Here are the gory details of what C<ev_loop> does:
394
395 * If there are no active watchers (reference count is zero), return.
396 - Queue prepare watchers and then call all outstanding watchers.
397 - If we have been forked, recreate the kernel state.
398 - Update the kernel state with all outstanding changes.
399 - Update the "event loop time".
400 - Calculate for how long to block.
401 - Block the process, waiting for any events.
402 - Queue all outstanding I/O (fd) events.
403 - Update the "event loop time" and do time jump handling.
404 - Queue all outstanding timers.
405 - Queue all outstanding periodics.
406 - If no events are pending now, queue all idle watchers.
407 - Queue all check watchers.
408 - Call all queued watchers in reverse order (i.e. check watchers first).
409 Signals and child watchers are implemented as I/O watchers, and will
410 be handled here by queueing them when their watcher gets executed.
411 - If ev_unloop has been called or EVLOOP_ONESHOT or EVLOOP_NONBLOCK
412 were used, return, otherwise continue with step *.
413
414 Example: queue some jobs and then loop until no events are outsanding
415 anymore.
416
417 ... queue jobs here, make sure they register event watchers as long
418 ... as they still have work to do (even an idle watcher will do..)
419 ev_loop (my_loop, 0);
420 ... jobs done. yeah!
421
422 =item ev_unloop (loop, how)
423
424 Can be used to make a call to C<ev_loop> return early (but only after it
425 has processed all outstanding events). The C<how> argument must be either
426 C<EVUNLOOP_ONE>, which will make the innermost C<ev_loop> call return, or
427 C<EVUNLOOP_ALL>, which will make all nested C<ev_loop> calls return.
428
429 =item ev_ref (loop)
430
431 =item ev_unref (loop)
432
433 Ref/unref can be used to add or remove a reference count on the event
434 loop: Every watcher keeps one reference, and as long as the reference
435 count is nonzero, C<ev_loop> will not return on its own. If you have
436 a watcher you never unregister that should not keep C<ev_loop> from
437 returning, ev_unref() after starting, and ev_ref() before stopping it. For
438 example, libev itself uses this for its internal signal pipe: It is not
439 visible to the libev user and should not keep C<ev_loop> from exiting if
440 no event watchers registered by it are active. It is also an excellent
441 way to do this for generic recurring timers or from within third-party
442 libraries. Just remember to I<unref after start> and I<ref before stop>.
443
444 Example: create a signal watcher, but keep it from keeping C<ev_loop>
445 running when nothing else is active.
446
447 struct dv_signal exitsig;
448 ev_signal_init (&exitsig, sig_cb, SIGINT);
449 ev_signal_start (myloop, &exitsig);
450 evf_unref (myloop);
451
452 Example: for some weird reason, unregister the above signal handler again.
453
454 ev_ref (myloop);
455 ev_signal_stop (myloop, &exitsig);
456
457 =back
458
459 =head1 ANATOMY OF A WATCHER
460
461 A watcher is a structure that you create and register to record your
462 interest in some event. For instance, if you want to wait for STDIN to
463 become readable, you would create an C<ev_io> watcher for that:
464
465 static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents)
466 {
467 ev_io_stop (w);
468 ev_unloop (loop, EVUNLOOP_ALL);
469 }
470
471 struct ev_loop *loop = ev_default_loop (0);
472 struct ev_io stdin_watcher;
473 ev_init (&stdin_watcher, my_cb);
474 ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ);
475 ev_io_start (loop, &stdin_watcher);
476 ev_loop (loop, 0);
477
478 As you can see, you are responsible for allocating the memory for your
479 watcher structures (and it is usually a bad idea to do this on the stack,
480 although this can sometimes be quite valid).
481
482 Each watcher structure must be initialised by a call to C<ev_init
483 (watcher *, callback)>, which expects a callback to be provided. This
484 callback gets invoked each time the event occurs (or, in the case of io
485 watchers, each time the event loop detects that the file descriptor given
486 is readable and/or writable).
487
488 Each watcher type has its own C<< ev_<type>_set (watcher *, ...) >> macro
489 with arguments specific to this watcher type. There is also a macro
490 to combine initialisation and setting in one call: C<< ev_<type>_init
491 (watcher *, callback, ...) >>.
492
493 To make the watcher actually watch out for events, you have to start it
494 with a watcher-specific start function (C<< ev_<type>_start (loop, watcher
495 *) >>), and you can stop watching for events at any time by calling the
496 corresponding stop function (C<< ev_<type>_stop (loop, watcher *) >>.
497
498 As long as your watcher is active (has been started but not stopped) you
499 must not touch the values stored in it. Most specifically you must never
500 reinitialise it or call its set macro.
501
502 You can check whether an event is active by calling the C<ev_is_active
503 (watcher *)> macro. To see whether an event is outstanding (but the
504 callback for it has not been called yet) you can use the C<ev_is_pending
505 (watcher *)> macro.
506
507 Each and every callback receives the event loop pointer as first, the
508 registered watcher structure as second, and a bitset of received events as
509 third argument.
510
511 The received events usually include a single bit per event type received
512 (you can receive multiple events at the same time). The possible bit masks
513 are:
514
515 =over 4
516
517 =item C<EV_READ>
518
519 =item C<EV_WRITE>
520
521 The file descriptor in the C<ev_io> watcher has become readable and/or
522 writable.
523
524 =item C<EV_TIMEOUT>
525
526 The C<ev_timer> watcher has timed out.
527
528 =item C<EV_PERIODIC>
529
530 The C<ev_periodic> watcher has timed out.
531
532 =item C<EV_SIGNAL>
533
534 The signal specified in the C<ev_signal> watcher has been received by a thread.
535
536 =item C<EV_CHILD>
537
538 The pid specified in the C<ev_child> watcher has received a status change.
539
540 =item C<EV_IDLE>
541
542 The C<ev_idle> watcher has determined that you have nothing better to do.
543
544 =item C<EV_PREPARE>
545
546 =item C<EV_CHECK>
547
548 All C<ev_prepare> watchers are invoked just I<before> C<ev_loop> starts
549 to gather new events, and all C<ev_check> watchers are invoked just after
550 C<ev_loop> has gathered them, but before it invokes any callbacks for any
551 received events. Callbacks of both watcher types can start and stop as
552 many watchers as they want, and all of them will be taken into account
553 (for example, a C<ev_prepare> watcher might start an idle watcher to keep
554 C<ev_loop> from blocking).
555
556 =item C<EV_ERROR>
557
558 An unspecified error has occured, the watcher has been stopped. This might
559 happen because the watcher could not be properly started because libev
560 ran out of memory, a file descriptor was found to be closed or any other
561 problem. You best act on it by reporting the problem and somehow coping
562 with the watcher being stopped.
563
564 Libev will usually signal a few "dummy" events together with an error,
565 for example it might indicate that a fd is readable or writable, and if
566 your callbacks is well-written it can just attempt the operation and cope
567 with the error from read() or write(). This will not work in multithreaded
568 programs, though, so beware.
569
570 =back
571
572 =head2 ASSOCIATING CUSTOM DATA WITH A WATCHER
573
574 Each watcher has, by default, a member C<void *data> that you can change
575 and read at any time, libev will completely ignore it. This can be used
576 to associate arbitrary data with your watcher. If you need more data and
577 don't want to allocate memory and store a pointer to it in that data
578 member, you can also "subclass" the watcher type and provide your own
579 data:
580
581 struct my_io
582 {
583 struct ev_io io;
584 int otherfd;
585 void *somedata;
586 struct whatever *mostinteresting;
587 }
588
589 And since your callback will be called with a pointer to the watcher, you
590 can cast it back to your own type:
591
592 static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents)
593 {
594 struct my_io *w = (struct my_io *)w_;
595 ...
596 }
597
598 More interesting and less C-conformant ways of catsing your callback type
599 have been omitted....
600
601
602 =head1 WATCHER TYPES
603
604 This section describes each watcher in detail, but will not repeat
605 information given in the last section.
606
607
608 =head2 C<ev_io> - is this file descriptor readable or writable
609
610 I/O watchers check whether a file descriptor is readable or writable
611 in each iteration of the event loop (This behaviour is called
612 level-triggering because you keep receiving events as long as the
613 condition persists. Remember you can stop the watcher if you don't want to
614 act on the event and neither want to receive future events).
615
616 In general you can register as many read and/or write event watchers per
617 fd as you want (as long as you don't confuse yourself). Setting all file
618 descriptors to non-blocking mode is also usually a good idea (but not
619 required if you know what you are doing).
620
621 You have to be careful with dup'ed file descriptors, though. Some backends
622 (the linux epoll backend is a notable example) cannot handle dup'ed file
623 descriptors correctly if you register interest in two or more fds pointing
624 to the same underlying file/socket etc. description (that is, they share
625 the same underlying "file open").
626
627 If you must do this, then force the use of a known-to-be-good backend
628 (at the time of this writing, this includes only C<EVBACKEND_SELECT> and
629 C<EVBACKEND_POLL>).
630
631 =over 4
632
633 =item ev_io_init (ev_io *, callback, int fd, int events)
634
635 =item ev_io_set (ev_io *, int fd, int events)
636
637 Configures an C<ev_io> watcher. The fd is the file descriptor to rceeive
638 events for and events is either C<EV_READ>, C<EV_WRITE> or C<EV_READ |
639 EV_WRITE> to receive the given events.
640
641 Please note that most of the more scalable backend mechanisms (for example
642 epoll and solaris ports) can result in spurious readyness notifications
643 for file descriptors, so you practically need to use non-blocking I/O (and
644 treat callback invocation as hint only), or retest separately with a safe
645 interface before doing I/O (XLib can do this), or force the use of either
646 C<EVBACKEND_SELECT> or C<EVBACKEND_POLL>, which don't suffer from this
647 problem. Also note that it is quite easy to have your callback invoked
648 when the readyness condition is no longer valid even when employing
649 typical ways of handling events, so its a good idea to use non-blocking
650 I/O unconditionally.
651
652 =back
653
654 Example: call C<stdin_readable_cb> when STDIN_FILENO has become, well
655 readable, but only once. Since it is likely line-buffered, you could
656 attempt to read a whole line in the callback:
657
658 static void
659 stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents)
660 {
661 ev_io_stop (loop, w);
662 .. read from stdin here (or from w->fd) and haqndle any I/O errors
663 }
664
665 ...
666 struct ev_loop *loop = ev_default_init (0);
667 struct ev_io stdin_readable;
668 ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ);
669 ev_io_start (loop, &stdin_readable);
670 ev_loop (loop, 0);
671
672
673 =head2 C<ev_timer> - relative and optionally recurring timeouts
674
675 Timer watchers are simple relative timers that generate an event after a
676 given time, and optionally repeating in regular intervals after that.
677
678 The timers are based on real time, that is, if you register an event that
679 times out after an hour and you reset your system clock to last years
680 time, it will still time out after (roughly) and hour. "Roughly" because
681 detecting time jumps is hard, and some inaccuracies are unavoidable (the
682 monotonic clock option helps a lot here).
683
684 The relative timeouts are calculated relative to the C<ev_now ()>
685 time. This is usually the right thing as this timestamp refers to the time
686 of the event triggering whatever timeout you are modifying/starting. If
687 you suspect event processing to be delayed and you I<need> to base the timeout
688 on the current time, use something like this to adjust for this:
689
690 ev_timer_set (&timer, after + ev_now () - ev_time (), 0.);
691
692 The callback is guarenteed to be invoked only when its timeout has passed,
693 but if multiple timers become ready during the same loop iteration then
694 order of execution is undefined.
695
696 =over 4
697
698 =item ev_timer_init (ev_timer *, callback, ev_tstamp after, ev_tstamp repeat)
699
700 =item ev_timer_set (ev_timer *, ev_tstamp after, ev_tstamp repeat)
701
702 Configure the timer to trigger after C<after> seconds. If C<repeat> is
703 C<0.>, then it will automatically be stopped. If it is positive, then the
704 timer will automatically be configured to trigger again C<repeat> seconds
705 later, again, and again, until stopped manually.
706
707 The timer itself will do a best-effort at avoiding drift, that is, if you
708 configure a timer to trigger every 10 seconds, then it will trigger at
709 exactly 10 second intervals. If, however, your program cannot keep up with
710 the timer (because it takes longer than those 10 seconds to do stuff) the
711 timer will not fire more than once per event loop iteration.
712
713 =item ev_timer_again (loop)
714
715 This will act as if the timer timed out and restart it again if it is
716 repeating. The exact semantics are:
717
718 If the timer is started but nonrepeating, stop it.
719
720 If the timer is repeating, either start it if necessary (with the repeat
721 value), or reset the running timer to the repeat value.
722
723 This sounds a bit complicated, but here is a useful and typical
724 example: Imagine you have a tcp connection and you want a so-called idle
725 timeout, that is, you want to be called when there have been, say, 60
726 seconds of inactivity on the socket. The easiest way to do this is to
727 configure an C<ev_timer> with after=repeat=60 and calling ev_timer_again each
728 time you successfully read or write some data. If you go into an idle
729 state where you do not expect data to travel on the socket, you can stop
730 the timer, and again will automatically restart it if need be.
731
732 =back
733
734 Example: create a timer that fires after 60 seconds.
735
736 static void
737 one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents)
738 {
739 .. one minute over, w is actually stopped right here
740 }
741
742 struct ev_timer mytimer;
743 ev_timer_init (&mytimer, one_minute_cb, 60., 0.);
744 ev_timer_start (loop, &mytimer);
745
746 Example: create a timeout timer that times out after 10 seconds of
747 inactivity.
748
749 static void
750 timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents)
751 {
752 .. ten seconds without any activity
753 }
754
755 struct ev_timer mytimer;
756 ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */
757 ev_timer_again (&mytimer); /* start timer */
758 ev_loop (loop, 0);
759
760 // and in some piece of code that gets executed on any "activity":
761 // reset the timeout to start ticking again at 10 seconds
762 ev_timer_again (&mytimer);
763
764
765 =head2 C<ev_periodic> - to cron or not to cron
766
767 Periodic watchers are also timers of a kind, but they are very versatile
768 (and unfortunately a bit complex).
769
770 Unlike C<ev_timer>'s, they are not based on real time (or relative time)
771 but on wallclock time (absolute time). You can tell a periodic watcher
772 to trigger "at" some specific point in time. For example, if you tell a
773 periodic watcher to trigger in 10 seconds (by specifiying e.g. c<ev_now ()
774 + 10.>) and then reset your system clock to the last year, then it will
775 take a year to trigger the event (unlike an C<ev_timer>, which would trigger
776 roughly 10 seconds later and of course not if you reset your system time
777 again).
778
779 They can also be used to implement vastly more complex timers, such as
780 triggering an event on eahc midnight, local time.
781
782 As with timers, the callback is guarenteed to be invoked only when the
783 time (C<at>) has been passed, but if multiple periodic timers become ready
784 during the same loop iteration then order of execution is undefined.
785
786 =over 4
787
788 =item ev_periodic_init (ev_periodic *, callback, ev_tstamp at, ev_tstamp interval, reschedule_cb)
789
790 =item ev_periodic_set (ev_periodic *, ev_tstamp after, ev_tstamp repeat, reschedule_cb)
791
792 Lots of arguments, lets sort it out... There are basically three modes of
793 operation, and we will explain them from simplest to complex:
794
795 =over 4
796
797 =item * absolute timer (interval = reschedule_cb = 0)
798
799 In this configuration the watcher triggers an event at the wallclock time
800 C<at> and doesn't repeat. It will not adjust when a time jump occurs,
801 that is, if it is to be run at January 1st 2011 then it will run when the
802 system time reaches or surpasses this time.
803
804 =item * non-repeating interval timer (interval > 0, reschedule_cb = 0)
805
806 In this mode the watcher will always be scheduled to time out at the next
807 C<at + N * interval> time (for some integer N) and then repeat, regardless
808 of any time jumps.
809
810 This can be used to create timers that do not drift with respect to system
811 time:
812
813 ev_periodic_set (&periodic, 0., 3600., 0);
814
815 This doesn't mean there will always be 3600 seconds in between triggers,
816 but only that the the callback will be called when the system time shows a
817 full hour (UTC), or more correctly, when the system time is evenly divisible
818 by 3600.
819
820 Another way to think about it (for the mathematically inclined) is that
821 C<ev_periodic> will try to run the callback in this mode at the next possible
822 time where C<time = at (mod interval)>, regardless of any time jumps.
823
824 =item * manual reschedule mode (reschedule_cb = callback)
825
826 In this mode the values for C<interval> and C<at> are both being
827 ignored. Instead, each time the periodic watcher gets scheduled, the
828 reschedule callback will be called with the watcher as first, and the
829 current time as second argument.
830
831 NOTE: I<This callback MUST NOT stop or destroy any periodic watcher,
832 ever, or make any event loop modifications>. If you need to stop it,
833 return C<now + 1e30> (or so, fudge fudge) and stop it afterwards (e.g. by
834 starting a prepare watcher).
835
836 Its prototype is C<ev_tstamp (*reschedule_cb)(struct ev_periodic *w,
837 ev_tstamp now)>, e.g.:
838
839 static ev_tstamp my_rescheduler (struct ev_periodic *w, ev_tstamp now)
840 {
841 return now + 60.;
842 }
843
844 It must return the next time to trigger, based on the passed time value
845 (that is, the lowest time value larger than to the second argument). It
846 will usually be called just before the callback will be triggered, but
847 might be called at other times, too.
848
849 NOTE: I<< This callback must always return a time that is later than the
850 passed C<now> value >>. Not even C<now> itself will do, it I<must> be larger.
851
852 This can be used to create very complex timers, such as a timer that
853 triggers on each midnight, local time. To do this, you would calculate the
854 next midnight after C<now> and return the timestamp value for this. How
855 you do this is, again, up to you (but it is not trivial, which is the main
856 reason I omitted it as an example).
857
858 =back
859
860 =item ev_periodic_again (loop, ev_periodic *)
861
862 Simply stops and restarts the periodic watcher again. This is only useful
863 when you changed some parameters or the reschedule callback would return
864 a different time than the last time it was called (e.g. in a crond like
865 program when the crontabs have changed).
866
867 =back
868
869 Example: call a callback every hour, or, more precisely, whenever the
870 system clock is divisible by 3600. The callback invocation times have
871 potentially a lot of jittering, but good long-term stability.
872
873 static void
874 clock_cb (struct ev_loop *loop, struct ev_io *w, int revents)
875 {
876 ... its now a full hour (UTC, or TAI or whatever your clock follows)
877 }
878
879 struct ev_periodic hourly_tick;
880 ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0);
881 ev_periodic_start (loop, &hourly_tick);
882
883 Example: the same as above, but use a reschedule callback to do it:
884
885 #include <math.h>
886
887 static ev_tstamp
888 my_scheduler_cb (struct ev_periodic *w, ev_tstamp now)
889 {
890 return fmod (now, 3600.) + 3600.;
891 }
892
893 ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb);
894
895 Example: call a callback every hour, starting now:
896
897 struct ev_periodic hourly_tick;
898 ev_periodic_init (&hourly_tick, clock_cb,
899 fmod (ev_now (loop), 3600.), 3600., 0);
900 ev_periodic_start (loop, &hourly_tick);
901
902
903 =head2 C<ev_signal> - signal me when a signal gets signalled
904
905 Signal watchers will trigger an event when the process receives a specific
906 signal one or more times. Even though signals are very asynchronous, libev
907 will try it's best to deliver signals synchronously, i.e. as part of the
908 normal event processing, like any other event.
909
910 You can configure as many watchers as you like per signal. Only when the
911 first watcher gets started will libev actually register a signal watcher
912 with the kernel (thus it coexists with your own signal handlers as long
913 as you don't register any with libev). Similarly, when the last signal
914 watcher for a signal is stopped libev will reset the signal handler to
915 SIG_DFL (regardless of what it was set to before).
916
917 =over 4
918
919 =item ev_signal_init (ev_signal *, callback, int signum)
920
921 =item ev_signal_set (ev_signal *, int signum)
922
923 Configures the watcher to trigger on the given signal number (usually one
924 of the C<SIGxxx> constants).
925
926 =back
927
928 =head2 C<ev_child> - wait for pid status changes
929
930 Child watchers trigger when your process receives a SIGCHLD in response to
931 some child status changes (most typically when a child of yours dies).
932
933 =over 4
934
935 =item ev_child_init (ev_child *, callback, int pid)
936
937 =item ev_child_set (ev_child *, int pid)
938
939 Configures the watcher to wait for status changes of process C<pid> (or
940 I<any> process if C<pid> is specified as C<0>). The callback can look
941 at the C<rstatus> member of the C<ev_child> watcher structure to see
942 the status word (use the macros from C<sys/wait.h> and see your systems
943 C<waitpid> documentation). The C<rpid> member contains the pid of the
944 process causing the status change.
945
946 =back
947
948 Example: try to exit cleanly on SIGINT and SIGTERM.
949
950 static void
951 sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents)
952 {
953 ev_unloop (loop, EVUNLOOP_ALL);
954 }
955
956 struct ev_signal signal_watcher;
957 ev_signal_init (&signal_watcher, sigint_cb, SIGINT);
958 ev_signal_start (loop, &sigint_cb);
959
960
961 =head2 C<ev_idle> - when you've got nothing better to do
962
963 Idle watchers trigger events when there are no other events are pending
964 (prepare, check and other idle watchers do not count). That is, as long
965 as your process is busy handling sockets or timeouts (or even signals,
966 imagine) it will not be triggered. But when your process is idle all idle
967 watchers are being called again and again, once per event loop iteration -
968 until stopped, that is, or your process receives more events and becomes
969 busy.
970
971 The most noteworthy effect is that as long as any idle watchers are
972 active, the process will not block when waiting for new events.
973
974 Apart from keeping your process non-blocking (which is a useful
975 effect on its own sometimes), idle watchers are a good place to do
976 "pseudo-background processing", or delay processing stuff to after the
977 event loop has handled all outstanding events.
978
979 =over 4
980
981 =item ev_idle_init (ev_signal *, callback)
982
983 Initialises and configures the idle watcher - it has no parameters of any
984 kind. There is a C<ev_idle_set> macro, but using it is utterly pointless,
985 believe me.
986
987 =back
988
989 Example: dynamically allocate an C<ev_idle>, start it, and in the
990 callback, free it. Alos, use no error checking, as usual.
991
992 static void
993 idle_cb (struct ev_loop *loop, struct ev_idle *w, int revents)
994 {
995 free (w);
996 // now do something you wanted to do when the program has
997 // no longer asnything immediate to do.
998 }
999
1000 struct ev_idle *idle_watcher = malloc (sizeof (struct ev_idle));
1001 ev_idle_init (idle_watcher, idle_cb);
1002 ev_idle_start (loop, idle_cb);
1003
1004
1005 =head2 C<ev_prepare> and C<ev_check> - customise your event loop
1006
1007 Prepare and check watchers are usually (but not always) used in tandem:
1008 prepare watchers get invoked before the process blocks and check watchers
1009 afterwards.
1010
1011 Their main purpose is to integrate other event mechanisms into libev. This
1012 could be used, for example, to track variable changes, implement your own
1013 watchers, integrate net-snmp or a coroutine library and lots more.
1014
1015 This is done by examining in each prepare call which file descriptors need
1016 to be watched by the other library, registering C<ev_io> watchers for
1017 them and starting an C<ev_timer> watcher for any timeouts (many libraries
1018 provide just this functionality). Then, in the check watcher you check for
1019 any events that occured (by checking the pending status of all watchers
1020 and stopping them) and call back into the library. The I/O and timer
1021 callbacks will never actually be called (but must be valid nevertheless,
1022 because you never know, you know?).
1023
1024 As another example, the Perl Coro module uses these hooks to integrate
1025 coroutines into libev programs, by yielding to other active coroutines
1026 during each prepare and only letting the process block if no coroutines
1027 are ready to run (it's actually more complicated: it only runs coroutines
1028 with priority higher than or equal to the event loop and one coroutine
1029 of lower priority, but only once, using idle watchers to keep the event
1030 loop from blocking if lower-priority coroutines are active, thus mapping
1031 low-priority coroutines to idle/background tasks).
1032
1033 =over 4
1034
1035 =item ev_prepare_init (ev_prepare *, callback)
1036
1037 =item ev_check_init (ev_check *, callback)
1038
1039 Initialises and configures the prepare or check watcher - they have no
1040 parameters of any kind. There are C<ev_prepare_set> and C<ev_check_set>
1041 macros, but using them is utterly, utterly and completely pointless.
1042
1043 =back
1044
1045 Example: *TODO*.
1046
1047
1048 =head1 OTHER FUNCTIONS
1049
1050 There are some other functions of possible interest. Described. Here. Now.
1051
1052 =over 4
1053
1054 =item ev_once (loop, int fd, int events, ev_tstamp timeout, callback)
1055
1056 This function combines a simple timer and an I/O watcher, calls your
1057 callback on whichever event happens first and automatically stop both
1058 watchers. This is useful if you want to wait for a single event on an fd
1059 or timeout without having to allocate/configure/start/stop/free one or
1060 more watchers yourself.
1061
1062 If C<fd> is less than 0, then no I/O watcher will be started and events
1063 is being ignored. Otherwise, an C<ev_io> watcher for the given C<fd> and
1064 C<events> set will be craeted and started.
1065
1066 If C<timeout> is less than 0, then no timeout watcher will be
1067 started. Otherwise an C<ev_timer> watcher with after = C<timeout> (and
1068 repeat = 0) will be started. While C<0> is a valid timeout, it is of
1069 dubious value.
1070
1071 The callback has the type C<void (*cb)(int revents, void *arg)> and gets
1072 passed an C<revents> set like normal event callbacks (a combination of
1073 C<EV_ERROR>, C<EV_READ>, C<EV_WRITE> or C<EV_TIMEOUT>) and the C<arg>
1074 value passed to C<ev_once>:
1075
1076 static void stdin_ready (int revents, void *arg)
1077 {
1078 if (revents & EV_TIMEOUT)
1079 /* doh, nothing entered */;
1080 else if (revents & EV_READ)
1081 /* stdin might have data for us, joy! */;
1082 }
1083
1084 ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);
1085
1086 =item ev_feed_event (loop, watcher, int events)
1087
1088 Feeds the given event set into the event loop, as if the specified event
1089 had happened for the specified watcher (which must be a pointer to an
1090 initialised but not necessarily started event watcher).
1091
1092 =item ev_feed_fd_event (loop, int fd, int revents)
1093
1094 Feed an event on the given fd, as if a file descriptor backend detected
1095 the given events it.
1096
1097 =item ev_feed_signal_event (loop, int signum)
1098
1099 Feed an event as if the given signal occured (loop must be the default loop!).
1100
1101 =back
1102
1103
1104 =head1 LIBEVENT EMULATION
1105
1106 Libev offers a compatibility emulation layer for libevent. It cannot
1107 emulate the internals of libevent, so here are some usage hints:
1108
1109 =over 4
1110
1111 =item * Use it by including <event.h>, as usual.
1112
1113 =item * The following members are fully supported: ev_base, ev_callback,
1114 ev_arg, ev_fd, ev_res, ev_events.
1115
1116 =item * Avoid using ev_flags and the EVLIST_*-macros, while it is
1117 maintained by libev, it does not work exactly the same way as in libevent (consider
1118 it a private API).
1119
1120 =item * Priorities are not currently supported. Initialising priorities
1121 will fail and all watchers will have the same priority, even though there
1122 is an ev_pri field.
1123
1124 =item * Other members are not supported.
1125
1126 =item * The libev emulation is I<not> ABI compatible to libevent, you need
1127 to use the libev header file and library.
1128
1129 =back
1130
1131 =head1 C++ SUPPORT
1132
1133 TBD.
1134
1135 =head1 AUTHOR
1136
1137 Marc Lehmann <libev@schmorp.de>.
1138