4 #include <sys/types.h> // timeval
5 #include <stdexcept> // std::exception, std::invalid_argument,
6 // std::runtime_error, std::bad_alloc
10 * @section Introduction
12 * The <a href="http://monkey.org/~provos/libevent/">libevent</a> API provides
13 * a mechanism to execute a callback function when a specific event occurs on
14 * a file descriptor or after a timeout has been reached. Furthermore, libevent
15 * also support callbacks due to signals or regular timeouts.
17 * libevent is meant to replace the event loop found in event driven network
18 * servers. An application just needs to call dispatcher::dispatch() and then
19 * add or remove events dynamically without having to change the event loop.
21 * Currently, libevent supports /dev/poll, kqueue(2), select(2), poll(2) and
22 * epoll(4). It also has experimental support for real-time signals. The
23 * internal event mechanism is completely independent of the exposed event API,
24 * and a simple update of libevent can provide new functionality without having
25 * to redesign the applications. As a result, Libevent allows for portable
26 * application development and provides the most scalable event notification
27 * mechanism available on an operating system. Libevent should compile on Linux,
28 * *BSD, Mac OS X, Solaris and Windows.
30 * This is a simple, direct, one-header inline C++ wrapper for libevent. Yes,
31 * it's just one header file, so if you want to use it you can just copy the
32 * file to your project and you are set.
34 * It's designed to be as close to use to libevent (without compromising modern
35 * C++ programming techniques) and efficiency (since all implementation is
36 * trivial and inline, theoretically, it imposes no overhead at all).
38 * Please, visit the <a href="http://www.llucax.com.ar/~luca/eventxx/">eventxx
39 * website</a> for the latest documentation.
41 * You can always <a href="http://www.lluca.com.ar/~lucax/repos/eventxx/">get
42 * the most up to date sources</a> from the
43 * <a href="http://www.darcs.net/">darcs</a>.
45 * You can also take a look the the <a
46 * href="http://auriga.wearlab.de/~alb/darcsweb/">darcsweb</a> interface to see
47 * the <a href="http://www.llucax.com.ar/~luca/repos/darcsweb/?r=eventxx">latest
53 * This wrapper was designed to be used just like libevent, but with C++ style
54 * syntax sugar (or poison, depends on your point of view ;) and goodies. The
55 * main difference to libevent is you always have to instance a
56 * eventxx::dispatcher to get an event loop. There is no implicit global event
57 * loop. This adds just an extra line of code for single threaded applications
58 * and makes things much more simple. See eventxx::dispatcher documentation for
61 * You can use use the same plain functions callbacks or the other kind of
62 * function objects (see @link events @endlink section for details on event
65 * eventxx uses @link exceptions @endlink to report errors. All functions has
66 * exception specifications, so it's easy to find out what to expect. See
67 * exceptions section for more detail.
69 * A timespec abstraction is provided in eventxx::time for convenient argument
70 * passing. Even more, it's a timespec itself, with some convenient methods for
71 * accessing the timespec attributes in a more C++ way. And even more, eventxx
72 * is such a direct mapping that all eventxx::event's are libevent event structs
73 * too, so theoretically you can pass a eventxx::event to libevent C functions
74 * without much trouble. eventxx::dispatcher is the only class that is not
75 * derived from libevent struct (event_base) because this struct it's not
76 * defined on the libevent header (just declared).
78 * Maybe you shouldn't know this implementation details to keep the abstraction,
79 * but this is a basic design goal of this wrapper so there is not much chance
80 * that this changes in the future (but use this knowledge with care, you are
92 * eventxx::dispatcher& d;
94 * handler(eventxx::dispatcher& d): d(d), i(0) {}
95 * void operator() (int signum, short event)
97 * if (i < 5) std::cout << "keep going...\n";
100 * std::cout << "done!\n";
106 * void sighandler(int signum, short event, void* data)
108 * int& i = *static_cast< int* >(data);
109 * std::cout << ++i << " interrupts, ";
114 * eventxx::dispatcher d;
116 * eventxx::csignal sigev(SIGINT, sighandler, &h.i);
117 * eventxx::signal< handler > e(SIGINT, h);
125 * You can see some more examples on the test directory of the distribution or
126 * on the examples related page.
131 * This library was not widely used yet, it lack some testing. Because templates
132 * are not even compiled when they are used, you can't be surprised if you catch
133 * a piece of code that didn't got even compiled yet because the lack of
134 * testing. The library has no support for buffered events yet either. It
135 * doesn't support the http stuff, and probably never will because that has
136 * nothing to do with event handling.
138 * If you notice this lib leaks memory, don't blame me, blame libevent :)
139 * libevent has a known bug on event_base_free() that makes it assert always, so
140 * event_base_free() it's unusable, unless you patch your libevent (for example,
142 * href="http://monkeymail.org/archives/libevent-users/2006-April/000141.html">patch</a>
143 * written by Mark D. Anderson and who knows why it's not still applied. If you
144 * do so, you can compile your programs with -DEVENT_BASE_FREE_FIX so
145 * event_base_free() gets called.
147 * That said, I think it's pretty usable anyways. If something is broken it
148 * would be really easy to fix it because is just a simple wrapper around
149 * libevent. So, please try it out, and if you have any problems,
150 * <a href="mailto:llucax+eventxx@gmail.com">drop me an
151 * e-mail</a> and and I'll fix it ASAP (or provide a patch and you will be my
154 * Patches to support buffered events are welcome too.
157 * @author Leandro Lucarella <llucax+eventxx@gmail.com>
162 * This program is under the BOLA license (see
163 * http://auriga.wearlab.de/~alb/bola/ for more info or the
164 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/LICENSE">LICENSE</a>
169 /** @example c-way.cpp
171 * This is a simple example illustrating the usage with C-like callback
175 /** @example functor-way.cpp
177 * This is a simple example illustrating the usage with function object
181 /** @example mixed-way.cpp
183 * This is a simple example illustrating the usage with a mix of C-like callbacks
184 * and function object callbacks.
187 /** @example bench.cpp
189 * This is a benchmark example, extracted from libevent and ported to eventxx.
192 /** @example prio-test.cpp
194 * This is a priority usage example.
197 /** @example test-time.cpp
199 * This is a timer usage example ported from libevent.
202 /** @example test-eof.cpp
204 * This is some kind of test of EOF ported from libevent.
207 /** @example test-weof.cpp
209 * Another test of EOF ported from libevent.
212 /** @example trivial.cpp
214 * This is the most trivial example.
218 * Namespace for all symbols libevent C++ wrapper defines.
224 // All libevent C API symbols and other internal stuff goes here.
231 /** @defgroup exceptions Exceptions
233 * eventxx makes a heavy use of exceptions. Each function has it's exceptions
234 * specified, so it's very easy to find out what exceptions to expect.
236 * Exceptions are mostly thrown when there is a programming error. So if you get
237 * an exception check your code.
243 * Base class for all libevent exceptions.
245 struct exception: public std::exception
251 * Invalid event exception.
253 * This exception is thrown when passing an invalid event to a function, the
254 * reason is given in the what() description but it usually means that the you
255 * are making some restricted operation with an active event.
257 * If you hit this exception, you probably got a programming error.
259 struct invalid_event: public std::invalid_argument, public exception
263 * Creates an invalid event exception with a reason.
265 * @param what Reason why the event is invalid).
267 explicit invalid_event(const std::string& what) throw():
268 std::invalid_argument(what)
272 }; // struct invalid_event
276 * Invalid priority exception.
278 * This exception is thrown when passing an invalid priority to a function. This
279 * usually means you don't have enough priority queues in your dispatcher, so
280 * you should have allocated more in the constructor.
282 * If you hit this exception, you probably got a programming error.
284 * @see dispatcher::dispatcher(int) to allocate more priority queues.
286 struct invalid_priority: public std::invalid_argument, public exception
290 * Creates an invalid priority exception with a reason.
292 * @param what Reason why the priority is invalid).
294 explicit invalid_priority(const std::string& what
295 = "invalid priority value") throw():
296 std::invalid_argument(what)
300 }; // struct invalid_priority
305 /// Miscellaneous constants
308 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
309 ONCE = EVLOOP_ONCE, ///< Loop just once.
310 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
314 /// C function used as callback in the C API.
315 typedef void (*ccallback_type)(int, short, void*);
319 * Time used for timeout values.
321 * This timeout is compose of seconds and microseconds.
323 struct time: ::timeval
327 * Creates a new time with @p sec seconds and @p usec microseconds.
329 * @param sec Number of seconds.
330 * @param usec Number of microseconds.
332 time(long sec = 0l, long usec = 0l) throw()
333 { tv_sec = sec; tv_usec = usec; }
336 * Gets the number of seconds.
338 * @return Number of seconds.
340 long sec() const throw() { return tv_sec; };
343 * Gets the number of microseconds.
345 * @return Number of microseconds.
347 long usec() const throw() { return tv_usec; };
350 * Sets the number of seconds.
352 * @param s Number of seconds.
354 void sec(long s) throw() { tv_sec = s; };
357 * Sets the number of microseconds.
359 * @param u Number of microseconds.
361 void usec(long u) throw() { tv_usec = u; };
366 /** @defgroup events Events
368 * There are many ways to specify how to handle an event. You can use use the
369 * same plain functions callbacks (see eventxx::cevent, eventxx::ctimer and
370 * eventxx::csignal) like in C or the other kind of more advanced, stateful
371 * function objects (see eventxx::event, eventxx::timer and eventxx::signal
372 * templates). The former are just typedef'ed specialization of the later.
374 * All events derive from a plain class (not template) eventxx::basic_event, one
375 * of the main utilities of it (besides containing common code ;) is to be used
378 * Please see each class documentation for details and examples.
385 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
386 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
387 * flag, that tells eventxx that this event should live until dispatcher::del()
388 * is called. You can use, for example:
390 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
395 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
396 READ = EV_READ, ///< Read event.
397 WRITE = EV_WRITE, ///< Write event.
398 SIGNAL = EV_SIGNAL, ///< Signal event.
399 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
403 * Basic event from which all events derive.
405 * All events derive from this class, so it's useful for use in containers,
408 * std::list< eventxx::basic_event* > events;
411 struct basic_event: internal::event
415 * Checks if there is an event pending.
417 * @param ev Type of event to check.
419 * @return true if there is a pending event, false if not.
421 bool pending(type ev) const throw()
423 // HACK libevent don't use const
424 return event_pending(const_cast< basic_event* >(this), ev, 0);
428 * Timeout of the event.
430 * @return Timeout of the event.
432 time timeout() const throw()
435 // HACK libevent don't use const
436 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
441 * Sets the event's priority.
443 * @param priority New event priority.
445 * @pre The event must be added to some dispatcher.
447 * @see dispatcher::dispatcher(int)
449 void priority(int priority) const throw(invalid_event, invalid_priority)
451 if (ev_flags & EVLIST_ACTIVE)
452 throw invalid_event("can't change the priority of an "
454 // HACK libevent don't use const
455 if (event_priority_set(const_cast< basic_event* >(this),
457 throw invalid_priority();
461 * Event's file descriptor.
463 * @return Event's file descriptor.
465 int fd() const throw()
467 return EVENT_FD(this);
470 /// @note This is an abstract class, you can't instantiate it.
472 basic_event() throw() {}
473 basic_event(const basic_event&);
474 basic_event& operator= (const basic_event&);
476 }; // struct basic_event
480 * Generic event object.
482 * This object stores all the information about an event, including a callback
483 * functor, which is called when the event is fired. The template parameter
484 * must be a functor (callable object or function) that can take 2 parameters:
485 * an integer (the file descriptor of the fired event) and an event::type (the
486 * type of event being fired).
487 * There is a specialized version of this class which takes as the template
488 * parameter a C function with the ccallback_type signature, just like C
491 * @see eventxx::event< ccallback_type >
493 template < typename F >
494 struct event: basic_event
498 * Creates a new event.
500 * @param fd File descriptor to monitor for events.
501 * @param ev Type of events to monitor (see eventxx::type).
502 * @param handler Callback functor.
504 event(int fd, short ev, F& handler) throw()
506 event_set(this, fd, ev, &wrapper,
507 reinterpret_cast< void* >(&handler));
512 static void wrapper(int fd, short ev, void* h)
514 F& handler = *reinterpret_cast< F* >(h);
515 // Hackish, but this way the handler can get a clean
517 handler(fd, *reinterpret_cast< type* >(&ev));
520 }; // struct event< F >
524 * This is the specialization of eventxx::event for C-style callbacks.
526 * @see eventxx::event
529 struct event< ccallback_type >: basic_event
533 * Creates a new event.
535 * @param fd File descriptor to monitor for events.
536 * @param ev Type of events to monitor (see eventxx::type).
537 * @param handler C-style callback function.
538 * @param arg Arbitrary pointer to pass to the handler as argument.
540 event(int fd, short ev, ccallback_type handler, void* arg) throw()
542 event_set(this, fd, ev, handler, arg);
548 }; // struct event< ccallback_type >
552 * Timer event object.
554 * This is just a special case of event that is fired only when a timeout is
555 * reached. It's just a shortcut to:
557 * event(-1, 0, handler);
560 * @note This event can't eventxx::PERSIST.
561 * @see timer< ccallback_type >
563 template < typename F >
564 struct timer: event< F >
568 * Creates a new timer event.
570 * @param handler Callback functor.
572 timer(F& handler) throw()
574 evtimer_set(this, &event< F >::wrapper,
575 reinterpret_cast< void* >(&handler));
578 }; // struct timer< F >
582 * This is the specialization of eventxx::timer for C-style callbacks.
584 * @note This event can't eventxx::PERSIST.
588 struct timer< ccallback_type >: event< ccallback_type >
592 * Creates a new timer event.
594 * @param handler C-style callback function.
595 * @param arg Arbitrary pointer to pass to the handler as argument.
597 timer(ccallback_type handler, void* arg) throw()
599 evtimer_set(this, handler, arg);
602 }; // struct timer< ccallback_type >
606 * Signal event object.
608 * This is just a special case of event that is fired when a signal is raised
609 * (instead of a file descriptor being active). It's just a shortcut to:
611 * event(signum, eventxx::SIGNAL, handler);
614 * @note This event always eventxx::PERSIST.
615 * @see signal< ccallback_type >
617 template < typename F >
618 struct signal: event< F >
622 * Creates a new signal event.
624 * @param signum Signal number to monitor.
625 * @param handler Callback functor.
627 signal(int signum, F& handler) throw()
629 signal_set(this, signum, &event< F >::wrapper,
630 reinterpret_cast< void* >(&handler));
634 * Event's signal number.
636 * @return Event's signal number.
640 return EVENT_SIGNAL(this);
643 }; // struct signal<F>
647 * This is the specialization of eventxx::signal for C-style callbacks.
649 * @note This event always eventxx::PERSIST.
653 struct signal< ccallback_type >: event< ccallback_type >
657 * Creates a new signal event.
659 * @param signum Signal number to monitor.
660 * @param handler C-style callback function.
661 * @param arg Arbitrary pointer to pass to the handler as argument.
663 signal(int signum, ccallback_type handler, void* arg) throw()
665 signal_set(this, signum, handler, arg);
669 * Event's signal number.
671 * @return Event's signal number.
675 return EVENT_SIGNAL(this);
678 }; // struct signal< ccallback_type >
681 /// Shortcut to C-style event.
682 typedef eventxx::event< ccallback_type > cevent;
684 /// Shortcut to C-style timer.
685 typedef eventxx::timer< ccallback_type > ctimer;
687 /// Shortcut to C-style signal handler.
688 typedef eventxx::signal< ccallback_type > csignal;
697 * This class is the responsible for looping and dispatching events. Every time
698 * you need an event loop you should create an instance of this class.
700 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
701 * can @link dispatcher::del remove @endlink them later or you can @link
702 * dispatcher::add_once add events to be processed just once @endlink. You can
703 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
704 * can break that forever removing all the events or by @link dispatcher::exit
705 * exiting the loop @endlink).
711 * Creates a default dispatcher (with just 1 priority).
713 * @see dispatcher(int) if you want to create a dispatcher with more
718 _event_base = static_cast< internal::event_base* >(internal::event_init());
722 * Creates a dispatcher with npriorities priorities.
724 * @param npriorities Number of priority queues to use.
726 dispatcher(int npriorities) throw(std::bad_alloc)
728 _event_base = static_cast< internal::event_base* >(internal::event_init());
729 if (!_event_base) throw std::bad_alloc();
730 // Can't fail because there is no way that it has active events
731 internal::event_base_priority_init(_event_base, npriorities);
734 #ifdef EVENT_BASE_FREE_FIX
735 ~dispatcher() throw() { event_base_free(_event_base); }
737 #warning "The dispatcher class *will* leak memory because of a libevent bug, see http://www.mail-archive.com/libevent-users@monkey.org/msg00110.html for more info an a patch. If you already have this patch, please -DEVENT_BASE_FREE_FIX to your compiler to make this message disappear and really free the dispatcher memory using event_base_free()."
741 * Adds an event to the dispatcher.
743 * @param e Event to add.
744 * @param priority Priority of the event.
746 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
747 throw(invalid_priority)
749 internal::event_base_set(_event_base, &e);
750 if (priority != DEFAULT_PRIORITY
751 && internal::event_priority_set(&e, priority))
752 throw invalid_priority();
753 internal::event_add(&e, 0);
757 * Adds an event to the dispatcher with a timeout.
759 * The event is fired when there is activity on e or when to has elapsed,
760 * whatever come first.
762 * @param e Event to add.
764 * @param priority Priority of the event.
766 void add(basic_event& e, const time& to,
767 int priority = DEFAULT_PRIORITY)
768 throw(invalid_priority)
770 internal::event_base_set(_event_base, &e);
771 if (priority != DEFAULT_PRIORITY
772 && internal::event_priority_set(&e, priority))
773 throw invalid_priority();
774 internal::event_add(&e, const_cast< time* >(&to)); // XXX HACK libevent don't use const
778 * Adds a temporary event.
780 * Adds a temporary event, without the need of instantiating a new event
781 * object. Events added this way can't eventxx::PERSIST.
783 * @param fd File descriptor to monitor for events.
784 * @param ev Type of events to monitor.
785 * @param handler Callback function.
787 template < typename F >
788 void add_once(int fd, type ev, F& handler)
790 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
791 reinterpret_cast< void* >(&handler), 0);
795 * Adds a temporary event to with a C-style callback.
797 * Adds a temporary event, without the need of instantiating a new event
798 * object. Events added this way can't eventxx::PERSIST.
800 * @param fd File descriptor to monitor for events.
801 * @param ev Type of events to monitor.
802 * @param handler Callback function.
803 * @param arg Arbitrary pointer to pass to the handler as argument.
805 void add_once(int fd, type ev, ccallback_type handler, void* arg)
807 internal::event_once(fd, ev, handler, arg, 0);
811 * Adds a temporary event.
813 * Adds a temporary event, without the need of instantiating a new event
814 * object. Events added this way can't eventxx::PERSIST.
816 * @param fd File descriptor to monitor for events.
817 * @param ev Type of events to monitor.
818 * @param handler Callback function.
821 template < typename F >
822 void add_once(int fd, type ev, F& handler, const time& to)
824 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
825 reinterpret_cast< void* >(&handler),
826 const_cast< time* >(&to)); // XXX HACK libevent don't use const
830 * Adds a temporary event with a C-style callback.
832 * Adds a temporary event, without the need of instantiating a new event
833 * object. Events added this way can't eventxx::PERSIST.
835 * @param fd File descriptor to monitor for events.
836 * @param ev Type of events to monitor.
837 * @param handler Callback function.
838 * @param arg Arbitrary pointer to pass to the handler as argument.
841 void add_once(int fd, type ev, ccallback_type handler, void* arg, const time& to)
843 internal::event_once(fd, ev, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
847 * Adds a temporary timer.
849 * Adds a temporary timer, without the need of instantiating a new timer
852 * @param handler Callback function.
853 * @param to Timer's timeout.
855 template < typename F >
856 void add_once_timer(F& handler, const time& to)
858 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
859 reinterpret_cast< void* >(&handler),
860 const_cast< time* >(&to)); // XXX HACK libevent don't use const
864 * Adds a temporary timer with a C-style callback.
866 * Adds a temporary timer, without the need of instantiating a new timer
869 * @param handler Callback function.
870 * @param arg Arbitrary pointer to pass to the handler as argument.
871 * @param to Timer's timeout.
873 void add_once_timer(ccallback_type handler, void* arg, const time& to)
875 internal::event_once(-1, EV_TIMEOUT, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
881 * The event e will be no longer monitored by this dispatcher.
883 * @param e Event to remove.
885 void del(basic_event& e) throw()
887 internal::event_del(&e);
891 * Main dispatcher loop.
893 * This function takes the control of the program, waiting for an event
894 * and calling its callbacks when it's fired. It only returns under
896 * - exit() was called.
897 * - All events were del()eted.
898 * - Another internal error.
899 * - eventxx::ONCE flag was set.
900 * - eventxx::NONBLOCK flag was set.
902 * @param flags If eventxx::ONCE is specified, then just one event is
903 * processed, if eventxx::NONBLOCK is specified, then this
904 * function returns even if there are no pending events.
906 int dispatch(int flags = 0) // TODO throw(exception)
908 return internal::event_base_loop(_event_base, flags);
912 * Exit the dispatch() loop.
914 * @param to If a timeout is given, the loop exits after the specified
917 int exit(const time& to = time())
919 // XXX HACK libevent don't use const
920 return internal::event_base_loopexit(_event_base,
921 const_cast< time* >(&to));
925 internal::event_base* _event_base;
926 template < typename F >
927 static void wrapper(int fd, type ev, void* h)
929 F& handler = *reinterpret_cast< F* >(h);
930 handler(fd, *reinterpret_cast< type* >(&ev));
933 }; // struct dispatcher
938 #endif // _EVENTXX_HPP_
940 // vim: set filetype=cpp :