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 * @libevent is a popular API that provides a mechanism to execute a callback
13 * function when a specific event occurs on a file descriptor or after a
14 * timeout has been reached. Furthermore, @libevent also support callbacks due
15 * to signals or regular timeouts.
17 * @eventxx is a simple, direct, one-header inline C++ wrapper for @libevent.
18 * Yes, it's just one header file, so if you want to use it you can just copy
19 * the file to your project and you are set (well, you'll need to link to
20 * @libevent too ;). I know @eventxx will work with @libevent 1.1 and 1.2 if you
21 * use the @c event_base_free() fix (see \ref Status section for more details).
23 * It's designed to be as close to use to @libevent (without compromising
24 * modern C++ programming techniques) and efficient (since all implementation
25 * is trivial and inline, theoretically, it imposes no overhead at all) as
28 * Please, visit the @eventxx website for the latest version of this
31 * You can always get the <a
32 * href="http://www.llucax.com.ar/~luca/eventxx/releases/eventxx.tar.gz">current
33 * release</a> from the
34 * <a href="http://www.llucax.com.ar/~luca/eventxx/releases/">release
35 * directory</a> or grab the
36 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/">most up to date
37 * sources</a> from the <a href="http://www.darcs.net/">darcs</a> repository.
39 * You can also take a look the the <a
40 * href="http://auriga.wearlab.de/~alb/darcsweb/">darcsweb</a> interface to see
41 * the <a href="http://www.llucax.com.ar/~luca/repos/darcsweb/?r=eventxx">latest
42 * changes online</a> or subscribe to its
43 * <a href="http://www.llucax.com.ar/~luca/repos/darcsweb/?r=eventxx;a=rss">RSS
44 * feed</a> to follow the development.
49 * You probably should read @libevent documentation to get started or at least
50 * just for reference, although @eventxx is pretty simple so you can jump right
51 * into the \ref Example section (or the example list) and write a working
52 * program without much trouble.
54 * This wrapper was designed to be used just like @libevent, but with C++ style
55 * syntax sugar (or poison, depends on your point of view ;) and goodies. The
56 * main difference to libevent is you always have to instance a
57 * eventxx::dispatcher to get an event loop. There is no implicit global event
58 * loop. This adds just an extra line of code for single threaded applications
59 * and makes things much more simpler, so I hope nobody complains about it ;).
60 * See eventxx::dispatcher documentation for more details.
62 * You can use use the same plain functions callbacks @libevent use or the other
63 * kind of function objects (see @ref events section for details on event
66 * @eventxx uses @ref exceptions to report errors. All functions have exception
67 * specifications, so it's easy to find out what to expect. See @ref exceptions
68 * section for more detail.
70 * A @c timespec abstraction is provided as eventxx::time for convenient
71 * argument passing. Even more, it's a @c timespec itself, with some convenient
72 * methods for accessing the attributes with pritier names. And even more,
73 * @eventxx is such a direct mapping that all eventxx::event's are @libevent
74 * event structs too, so theoretically you can pass a eventxx::event to
75 * @libevent C functions without much trouble. eventxx::dispatcher is the only
76 * class that is not derived from @libevent struct (@c event_base) because this
77 * struct it's not defined on the libevent header (just declared).
79 * Maybe you shouldn't know this implementation details to keep the abstraction,
80 * but this is a basic design goal of this wrapper so there is not much chance
81 * that this changes in the future (but use this knowledge with care, you have
94 * eventxx::dispatcher& d;
96 * handler(eventxx::dispatcher& d): d(d), i(0) {}
97 * void operator() (int signum, short event)
99 * if (i < 5) std::cout << "keep going...\n";
102 * std::cout << "done!\n";
108 * void sighandler(int signum, short event, void* data)
110 * int& i = *static_cast< int* >(data);
111 * std::cout << ++i << " interrupts, ";
116 * eventxx::dispatcher d;
118 * eventxx::csignal sigev(SIGINT, sighandler, &h.i);
119 * eventxx::signal< handler > e(SIGINT, h);
127 * You can see more examples on the test directory of the distribution or on the
128 * examples related page.
133 * This library has not been widely used yet, so it lacks proper testing.
134 * Because templates are not even compiled when they are not used, don't have to
135 * be surprised if you catch a piece of code that doesn't compile. The library
136 * has no support for buffered events yet. It doesn't support the HTTP stuff,
137 * and probably never will because that has nothing to do with event handling.
139 * If you notice that when using @eventxx your program leaks some memory, don't
140 * blame me, blame @libevent :) @libevent has a known bug on @c event_base_free()
141 * that makes it assert always, so @c event_base_free() is unusable, unless you
142 * patch your libevent (for example, using this <a
143 * href="http://monkeymail.org/archives/libevent-users/2006-April/000141.html">patch</a>
144 * written by Mark D. Anderson, and who knows why it's not still applied). If
145 * you do so, you can compile your programs with @c -DEVENT_BASE_FREE_FIX so
146 * @c event_base_free() gets called in the eventxx::dispatcher @link
147 * eventxx::dispatcher::~dispatcher() destructor @endlink.
149 * That said, I think it's still pretty usable anyways. If something is broken
150 * it would be really easy to fix because @eventxx is just a simple wrapper
151 * around @libevent. So, please try it out, and if you have any problems,
152 * <a href="mailto:llucax+eventxx@gmail.com">drop me an
153 * e-mail</a> and and I'll fix it ASAP (or provide a patch and you will be my
156 * Patches to support buffered events are welcome too.
159 * @author Leandro Lucarella <llucax+eventxx@gmail.com>
164 * This program is under the BOLA license (see
165 * http://auriga.wearlab.de/~alb/bola/ for more details or read the
166 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/LICENSE">LICENSE</a>
167 * file itself, it's very short and it basically says it's Public Domain).
171 /** @example c-way.cpp
173 * This is a simple example illustrating the usage with C-like callback
177 /** @example functor-way.cpp
179 * This is a simple example illustrating the usage with function object
183 /** @example mixed-way.cpp
185 * This is a simple example illustrating the usage with a mix of C-like callbacks
186 * and function object callbacks.
189 /** @example bench.cpp
191 * This is a benchmark example, extracted from libevent and ported to eventxx.
194 /** @example prio-test.cpp
196 * This is a priority usage example.
199 /** @example test-time.cpp
201 * This is a timer usage example ported from libevent.
204 /** @example test-eof.cpp
206 * This is some kind of test of EOF ported from libevent.
209 /** @example test-weof.cpp
211 * Another test of EOF ported from libevent.
214 /** @example trivial.cpp
216 * This is the most trivial example.
220 * Namespace for all symbols libevent C++ wrapper defines.
226 // All libevent C API symbols and other internal stuff goes here.
233 /** @defgroup exceptions Exceptions
235 * eventxx makes a heavy use of exceptions. Each function has it's exceptions
236 * specified, so it's very easy to find out what exceptions to expect.
238 * Exceptions are mostly thrown when there is a programming error. So if you get
239 * an exception check your code.
245 * Base class for all libevent exceptions.
247 struct exception: public std::exception
253 * Invalid event exception.
255 * This exception is thrown when passing an invalid event to a function, the
256 * reason is given in the what() description but it usually means that the you
257 * are making some restricted operation with an active event.
259 * If you hit this exception, you probably got a programming error.
261 struct invalid_event: public std::invalid_argument, public exception
265 * Creates an invalid event exception with a reason.
267 * @param what Reason why the event is invalid).
269 explicit invalid_event(const std::string& what) throw():
270 std::invalid_argument(what)
274 }; // struct invalid_event
278 * Invalid priority exception.
280 * This exception is thrown when passing an invalid priority to a function. This
281 * usually means you don't have enough priority queues in your dispatcher, so
282 * you should have allocated more in the constructor.
284 * If you hit this exception, you probably got a programming error.
286 * @see dispatcher::dispatcher(int) to allocate more priority queues.
288 struct invalid_priority: public std::invalid_argument, public exception
292 * Creates an invalid priority exception with a reason.
294 * @param what Reason why the priority is invalid).
296 explicit invalid_priority(const std::string& what
297 = "invalid priority value") throw():
298 std::invalid_argument(what)
302 }; // struct invalid_priority
307 /// Miscellaneous constants
310 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
311 ONCE = EVLOOP_ONCE, ///< Loop just once.
312 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
316 /// C function used as callback in the C API.
317 typedef void (*ccallback_type)(int, short, void*);
321 * Time used for timeout values.
323 * This timeout is compose of seconds and microseconds.
325 struct time: ::timeval
329 * Creates a new time with @p sec seconds and @p usec microseconds.
331 * @param sec Number of seconds.
332 * @param usec Number of microseconds.
334 time(long sec = 0l, long usec = 0l) throw()
335 { tv_sec = sec; tv_usec = usec; }
338 * Gets the number of seconds.
340 * @return Number of seconds.
342 long sec() const throw() { return tv_sec; };
345 * Gets the number of microseconds.
347 * @return Number of microseconds.
349 long usec() const throw() { return tv_usec; };
352 * Sets the number of seconds.
354 * @param s Number of seconds.
356 void sec(long s) throw() { tv_sec = s; };
359 * Sets the number of microseconds.
361 * @param u Number of microseconds.
363 void usec(long u) throw() { tv_usec = u; };
368 /** @defgroup events Events
370 * There are many ways to specify how to handle an event. You can use use the
371 * same plain functions callbacks (see eventxx::cevent, eventxx::ctimer and
372 * eventxx::csignal) like in C or the other kind of more advanced, stateful
373 * function objects (see eventxx::event, eventxx::timer and eventxx::signal
374 * templates). The former are just typedef'ed specialization of the later.
376 * All events derive from a plain class (not template) eventxx::basic_event, one
377 * of the main utilities of it (besides containing common code ;) is to be used
380 * Please see each class documentation for details and examples.
387 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
388 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
389 * flag, that tells eventxx that this event should live until dispatcher::del()
390 * is called. You can use, for example:
392 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
397 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
398 READ = EV_READ, ///< Read event.
399 WRITE = EV_WRITE, ///< Write event.
400 SIGNAL = EV_SIGNAL, ///< Signal event.
401 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
405 * Basic event from which all events derive.
407 * All events derive from this class, so it's useful for use in containers,
410 * std::list< eventxx::basic_event* > events;
413 struct basic_event: internal::event
417 * Checks if there is an event pending.
419 * @param ev Type of event to check.
421 * @return true if there is a pending event, false if not.
423 bool pending(type ev) const throw()
425 // HACK libevent don't use const
426 return event_pending(const_cast< basic_event* >(this), ev, 0);
430 * Timeout of the event.
432 * @return Timeout of the event.
434 time timeout() const throw()
437 // HACK libevent don't use const
438 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
443 * Sets the event's priority.
445 * @param priority New event priority.
447 * @pre The event must be added to some dispatcher.
449 * @see dispatcher::dispatcher(int)
451 void priority(int priority) const throw(invalid_event, invalid_priority)
453 if (ev_flags & EVLIST_ACTIVE)
454 throw invalid_event("can't change the priority of an "
456 // HACK libevent don't use const
457 if (event_priority_set(const_cast< basic_event* >(this),
459 throw invalid_priority();
463 * Event's file descriptor.
465 * @return Event's file descriptor.
467 int fd() const throw()
469 return EVENT_FD(this);
472 /// @note This is an abstract class, you can't instantiate it.
474 basic_event() throw() {}
475 basic_event(const basic_event&);
476 basic_event& operator= (const basic_event&);
478 }; // struct basic_event
482 * Generic event object.
484 * This object stores all the information about an event, including a callback
485 * functor, which is called when the event is fired. The template parameter
486 * must be a functor (callable object or function) that can take 2 parameters:
487 * an integer (the file descriptor of the fired event) and an event::type (the
488 * type of event being fired).
489 * There is a specialized version of this class which takes as the template
490 * parameter a C function with the eventxx::ccallback_type signature, just like
491 * C @libevent API does.
493 * @see eventxx::event< ccallback_type >
495 template < typename F >
496 struct event: basic_event
500 * Creates a new event.
502 * @param fd File descriptor to monitor for events.
503 * @param ev Type of events to monitor (see eventxx::type).
504 * @param handler Callback functor.
506 event(int fd, short ev, F& handler) throw()
508 event_set(this, fd, ev, &wrapper,
509 reinterpret_cast< void* >(&handler));
514 static void wrapper(int fd, short ev, void* h)
516 F& handler = *reinterpret_cast< F* >(h);
517 // Hackish, but this way the handler can get a clean
519 handler(fd, *reinterpret_cast< type* >(&ev));
522 }; // struct event< F >
526 * This is the specialization of eventxx::event for C-style callbacks.
528 * @see eventxx::event
531 struct event< ccallback_type >: basic_event
535 * Creates a new event.
537 * @param fd File descriptor to monitor for events.
538 * @param ev Type of events to monitor (see eventxx::type).
539 * @param handler C-style callback function.
540 * @param arg Arbitrary pointer to pass to the handler as argument.
542 event(int fd, short ev, ccallback_type handler, void* arg = 0) throw()
544 event_set(this, fd, ev, handler, arg);
550 }; // struct event< ccallback_type >
554 * Timer event object.
556 * This is just a special case of event that is fired only when a timeout is
557 * reached. It's just a shortcut to:
559 * event(-1, 0, handler);
562 * @note This event can't eventxx::PERSIST.
563 * @see timer< ccallback_type >
565 template < typename F >
566 struct timer: event< F >
570 * Creates a new timer event.
572 * @param handler Callback functor.
574 timer(F& handler) throw()
576 evtimer_set(this, &event< F >::wrapper,
577 reinterpret_cast< void* >(&handler));
580 }; // struct timer< F >
584 * This is the specialization of eventxx::timer for C-style callbacks.
586 * @note This event can't eventxx::PERSIST.
590 struct timer< ccallback_type >: event< ccallback_type >
594 * Creates a new timer event.
596 * @param handler C-style callback function.
597 * @param arg Arbitrary pointer to pass to the handler as argument.
599 timer(ccallback_type handler, void* arg = 0) throw()
601 evtimer_set(this, handler, arg);
604 }; // struct timer< ccallback_type >
608 * Signal event object.
610 * This is just a special case of event that is fired when a signal is raised
611 * (instead of a file descriptor being active). It's just a shortcut to:
613 * event(signum, eventxx::SIGNAL, handler);
616 * @note This event always eventxx::PERSIST.
617 * @see signal< ccallback_type >
619 template < typename F >
620 struct signal: event< F >
624 * Creates a new signal event.
626 * @param signum Signal number to monitor.
627 * @param handler Callback functor.
629 signal(int signum, F& handler) throw()
631 signal_set(this, signum, &event< F >::wrapper,
632 reinterpret_cast< void* >(&handler));
636 * Event's signal number.
638 * @return Event's signal number.
642 return EVENT_SIGNAL(this);
645 }; // struct signal<F>
649 * This is the specialization of eventxx::signal for C-style callbacks.
651 * @note This event always eventxx::PERSIST.
655 struct signal< ccallback_type >: event< ccallback_type >
659 * Creates a new signal event.
661 * @param signum Signal number to monitor.
662 * @param handler C-style callback function.
663 * @param arg Arbitrary pointer to pass to the handler as argument.
665 signal(int signum, ccallback_type handler, void* arg = 0) throw()
667 signal_set(this, signum, handler, arg);
671 * Event's signal number.
673 * @return Event's signal number.
677 return EVENT_SIGNAL(this);
680 }; // struct signal< ccallback_type >
683 /// Shortcut to C-style event.
684 typedef eventxx::event< ccallback_type > cevent;
686 /// Shortcut to C-style timer.
687 typedef eventxx::timer< ccallback_type > ctimer;
689 /// Shortcut to C-style signal handler.
690 typedef eventxx::signal< ccallback_type > csignal;
699 * This class is the responsible for looping and dispatching events. Every time
700 * you need an event loop you should create an instance of this class.
702 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
703 * can @link dispatcher::del remove @endlink them later or you can @link
704 * dispatcher::add_once add events to be processed just once @endlink. You can
705 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
706 * can break that forever removing all the events or by @link dispatcher::exit
707 * exiting the loop @endlink).
713 * Creates a default dispatcher (with just 1 priority).
715 * @see dispatcher(int) if you want to create a dispatcher with more
720 _event_base = static_cast< internal::event_base* >(
721 internal::event_init());
725 * Creates a dispatcher with npriorities priorities.
727 * @param npriorities Number of priority queues to use.
729 dispatcher(int npriorities) throw(std::bad_alloc)
731 _event_base = static_cast< internal::event_base* >(
732 internal::event_init());
733 if (!_event_base) throw std::bad_alloc();
734 // Can't fail because there is no way that it has active events
735 internal::event_base_priority_init(_event_base, npriorities);
738 #ifdef EVENT_BASE_FREE_FIX
739 /// Free dispatcher resources, see @ref Status section for details.
740 ~dispatcher() throw() { event_base_free(_event_base); }
742 #warning "The dispatcher class *will* leak memory because of a libevent bug, " \
743 "see http://www.mail-archive.com/libevent-users@monkey.org/msg00110.html " \
744 "for more info an a patch. If you already have this patch, please " \
745 "-DEVENT_BASE_FREE_FIX to your compiler to make this message disappear " \
746 "and really free the dispatcher memory using event_base_free()."
750 * Adds an event to the dispatcher.
752 * @param e Event to add.
753 * @param priority Priority of the event.
755 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
756 throw(invalid_priority)
758 internal::event_base_set(_event_base, &e);
759 if (priority != DEFAULT_PRIORITY
760 && internal::event_priority_set(&e, priority))
761 throw invalid_priority();
762 internal::event_add(&e, 0);
766 * Adds an event to the dispatcher with a timeout.
768 * The event is fired when there is activity on e or when to has elapsed,
769 * whatever come first.
771 * @param e Event to add.
773 * @param priority Priority of the event.
775 void add(basic_event& e, const time& to,
776 int priority = DEFAULT_PRIORITY)
777 throw(invalid_priority)
779 internal::event_base_set(_event_base, &e);
780 if (priority != DEFAULT_PRIORITY
781 && internal::event_priority_set(&e, priority))
782 throw invalid_priority();
783 // XXX HACK libevent don't use const
784 internal::event_add(&e, const_cast< time* >(&to));
788 * Adds a temporary event.
790 * Adds a temporary event, without the need of instantiating a new event
791 * object. Events added this way can't eventxx::PERSIST.
793 * @param fd File descriptor to monitor for events.
794 * @param ev Type of events to monitor.
795 * @param handler Callback function.
797 template < typename F >
798 void add_once(int fd, type ev, F& handler)
800 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
801 reinterpret_cast< void* >(&handler), 0);
805 * Adds a temporary event to with a C-style callback.
807 * Adds a temporary event, without the need of instantiating a new event
808 * object. Events added this way can't eventxx::PERSIST.
810 * @param fd File descriptor to monitor for events.
811 * @param ev Type of events to monitor.
812 * @param handler Callback function.
813 * @param arg Arbitrary pointer to pass to the handler as argument.
815 void add_once(int fd, type ev, ccallback_type handler, void* arg)
817 internal::event_once(fd, ev, handler, arg, 0);
821 * Adds a temporary event.
823 * Adds a temporary event, without the need of instantiating a new event
824 * object. Events added this way can't eventxx::PERSIST.
826 * @param fd File descriptor to monitor for events.
827 * @param ev Type of events to monitor.
828 * @param handler Callback function.
831 template < typename F >
832 void add_once(int fd, type ev, F& handler, const time& to)
834 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
835 reinterpret_cast< void* >(&handler),
836 // XXX HACK libevent don't use const
837 const_cast< time* >(&to));
841 * Adds a temporary event with a C-style callback.
843 * Adds a temporary event, without the need of instantiating a new event
844 * object. Events added this way can't eventxx::PERSIST.
846 * @param fd File descriptor to monitor for events.
847 * @param ev Type of events to monitor.
848 * @param handler Callback function.
849 * @param arg Arbitrary pointer to pass to the handler as argument.
852 void add_once(int fd, type ev, ccallback_type handler, void* arg,
855 internal::event_once(fd, ev, handler, arg,
856 // XXX HACK libevent don't use const
857 const_cast< time* >(&to));
861 * Adds a temporary timer.
863 * Adds a temporary timer, without the need of instantiating a new timer
866 * @param handler Callback function.
867 * @param to Timer's timeout.
869 template < typename F >
870 void add_once_timer(F& handler, const time& to)
872 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
873 reinterpret_cast< void* >(&handler),
874 // XXX HACK libevent don't use const
875 const_cast< time* >(&to));
879 * Adds a temporary timer with a C-style callback.
881 * Adds a temporary timer, without the need of instantiating a new timer
884 * @param handler Callback function.
885 * @param arg Arbitrary pointer to pass to the handler as argument.
886 * @param to Timer's timeout.
888 void add_once_timer(ccallback_type handler, void* arg, const time& to)
890 // XXX HACK libevent don't use const
891 internal::event_once(-1, EV_TIMEOUT, handler, arg,
892 const_cast< time* >(&to));
898 * The event e will be no longer monitored by this dispatcher.
900 * @param e Event to remove.
902 void del(basic_event& e) throw()
904 internal::event_del(&e);
908 * Main dispatcher loop.
910 * This function takes the control of the program, waiting for an event
911 * and calling its callbacks when it's fired. It only returns under
913 * - exit() was called.
914 * - All events were del()eted.
915 * - Another internal error.
916 * - eventxx::ONCE flag was set.
917 * - eventxx::NONBLOCK flag was set.
919 * @param flags If eventxx::ONCE is specified, then just one event is
920 * processed, if eventxx::NONBLOCK is specified, then this
921 * function returns even if there are no pending events.
923 * @return Not very well specified by @libevent :-/ that's why it
924 * doesn't throw an exception either.
926 int dispatch(int flags = 0) throw() // TODO throw(exception)
928 return internal::event_base_loop(_event_base, flags);
932 * Exit the dispatch() loop.
934 * @param to If a timeout is given, the loop exits after the specified
937 * @return Not very well specified by @libevent :-/ that's why it
938 * doesn't throw an exception either.
940 int exit(const time& to = time()) throw() // TODO throw(exception)
942 // XXX HACK libevent don't use const
943 return internal::event_base_loopexit(_event_base,
944 const_cast< time* >(&to));
948 internal::event_base* _event_base;
949 template < typename F >
950 static void wrapper(int fd, type ev, void* h)
952 F& handler = *reinterpret_cast< F* >(h);
953 handler(fd, *reinterpret_cast< type* >(&ev));
956 }; // struct dispatcher
961 #endif // _EVENTXX_HPP_
963 // vim: set filetype=cpp :