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
22 * It's designed to be as close to use to @libevent (without compromising
23 * modern C++ programming techniques) and efficient (since all implementation
24 * is trivial and inline, theoretically, it imposes no overhead at all) as
27 * Please, visit the @eventxx website for the latest version of this
30 * You can always get the <a
31 * href="http://www.llucax.com.ar/~luca/eventxx/releases/eventxx.tar.gz">current
32 * release</a> from the
33 * <a href="http://www.llucax.com.ar/~luca/eventxx/releases/">release
34 * directory</a> or grab the
35 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/">most up to date
36 * sources</a> from the <a href="http://www.darcs.net/">darcs</a> repository.
38 * You can also take a look the the <a
39 * href="http://auriga.wearlab.de/~alb/darcsweb/">darcsweb</a> interface to see
40 * the <a href="http://www.llucax.com.ar/~luca/repos/darcsweb/?r=eventxx">latest
41 * changes online</a> or subscribe to its
42 * <a href="http://www.llucax.com.ar/~luca/repos/darcsweb/?r=eventxx;a=rss">RSS
43 * feed</a> to follow the development.
48 * You probably should read @libevent documentation to get started or at least
49 * just for reference, although @eventxx is pretty simple so you can jump right
50 * into the \ref Example section (or the example list) and write a working
51 * program without much trouble.
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 simpler, so I hope nobody complains about it ;).
59 * See eventxx::dispatcher documentation for more details.
61 * You can use use the same plain functions callbacks @libevent use or the other
62 * kind of function objects (see @ref events section for details on event
65 * @eventxx uses @ref exceptions to report errors. All functions have exception
66 * specifications, so it's easy to find out what to expect. See @ref exceptions
67 * section for more detail.
69 * A @c timespec abstraction is provided as eventxx::time for convenient
70 * argument passing. Even more, it's a @c timespec itself, with some convenient
71 * methods for accessing the attributes with pritier names. And even more,
72 * @eventxx is such a direct mapping that all eventxx::event's are @libevent
73 * event structs too, so theoretically you can pass a eventxx::event to
74 * @libevent C functions without much trouble. eventxx::dispatcher is the only
75 * class that is not derived from @libevent struct (@c event_base) because this
76 * struct it's not 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 have
93 * eventxx::dispatcher& d;
95 * handler(eventxx::dispatcher& d): d(d), i(0) {}
96 * void operator() (int signum, eventxx::type event)
98 * if (i < 5) std::cout << "keep going...\n";
101 * std::cout << "done!\n";
107 * void sighandler(int signum, short event, void* data)
109 * int& i = *static_cast< int* >(data);
110 * std::cout << ++i << " interrupts, ";
115 * eventxx::dispatcher d;
117 * eventxx::csignal sigev(SIGINT, sighandler, &h.i);
118 * eventxx::signal< handler > e(SIGINT, h);
126 * You can see more examples on the test directory of the distribution or on the
127 * examples related page.
132 * This library has not been widely used yet, but it's used in some serious
133 * projects, so I think it's moderately stable now. The library has no support
134 * for buffered events yet, but patches are welcome. It doesn't support the
135 * HTTP stuff, and probably never will because that has nothing to do with
138 * @libevent had a memory leak before version 1.3b (before 1.2 it didn't even
139 * had a way free that memory, from version 1.2 to 1.3a, if you tried to free
140 * the memory the program @c abort() because a failed assertion). Because of
141 * that, there is a way to disable the @link eventxx::dispatcher::~dispatcher()
142 * dispatcher destructor @endlink (which calls the inexistent/broken
143 * @c event_base_free() function). So if you use a @libevent version previous
144 * to 1.3b, you have to compile your programs defining the
145 * @c EVENTXX_NO_EVENT_BASE_FREE macro.
147 * If something is broken it would be really easy to fix because @eventxx is
148 * just a simple wrapper around @libevent. So, please try it out, and if you
149 * have any problems, <a href="mailto:llucax+eventxx@gmail.com">drop me an
150 * e-mail</a> and and I'll fix it ASAP (or provide a patch and you will be my
153 * If you use this library, please drop me an e-mail with your thoughts, or
154 * simply saying "I use it", so I can keep track of how many people really use
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 details or read the
164 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/LICENSE">LICENSE</a>
165 * file itself, it's very short and it basically says it's Public Domain).
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 wrapped-functor-way.cpp
183 * This is a simple example illustrating the usage with an arbitrary member
184 * function as an event handler callbacks.
187 /** @example mixed-way.cpp
189 * This is a simple example illustrating the usage with a mix of C-like callbacks
190 * and function object callbacks.
193 /** @example bench.cpp
195 * This is a benchmark example, extracted from libevent and ported to eventxx.
198 /** @example prio-test.cpp
200 * This is a priority usage example.
203 /** @example test-time.cpp
205 * This is a timer usage example ported from libevent.
208 /** @example test-eof.cpp
210 * This is some kind of test of EOF ported from libevent.
213 /** @example test-weof.cpp
215 * Another test of EOF ported from libevent.
218 /** @example trivial.cpp
220 * This is the most trivial example.
224 * Namespace for all symbols libevent C++ wrapper defines.
230 // All libevent C API symbols and other internal stuff goes here.
237 /** @defgroup exceptions Exceptions
239 * eventxx makes a heavy use of exceptions. Each function has it's exceptions
240 * specified, so it's very easy to find out what exceptions to expect.
242 * Exceptions are mostly thrown when there is a programming error. So if you get
243 * an exception check your code.
249 * Base class for all libevent exceptions.
251 struct exception: public std::exception
257 * Invalid event exception.
259 * This exception is thrown when passing an invalid event to a function, the
260 * reason is given in the what() description but it usually means that the you
261 * are making some restricted operation with an active event.
263 * If you hit this exception, you probably got a programming error.
265 struct invalid_event: public std::invalid_argument, public exception
269 * Creates an invalid event exception with a reason.
271 * @param what Reason why the event is invalid).
273 explicit invalid_event(const std::string& what) throw():
274 std::invalid_argument(what)
278 }; // struct invalid_event
282 * Invalid priority exception.
284 * This exception is thrown when passing an invalid priority to a function. This
285 * usually means you don't have enough priority queues in your dispatcher, so
286 * you should have allocated more in the constructor.
288 * If you hit this exception, you probably got a programming error.
290 * @see dispatcher::dispatcher(int) to allocate more priority queues.
292 struct invalid_priority: public std::invalid_argument, public exception
296 * Creates an invalid priority exception with a reason.
298 * @param what Reason why the priority is invalid).
300 explicit invalid_priority(const std::string& what
301 = "invalid priority value") throw():
302 std::invalid_argument(what)
306 }; // struct invalid_priority
311 /// Miscellaneous constants
314 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
315 ONCE = EVLOOP_ONCE, ///< Loop just once.
316 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
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 * A member function wrapper functor (eventxx::mem_cb) is also included,
377 * so you can use any member function (method) as an event handler.
379 * Please note that C-like function callback take a short as the type of event,
380 * while functors (or member functions) use eventxx::type.
382 * All events derive from a plain class (not template) eventxx::basic_event, one
383 * of the main utilities of it (besides containing common code ;) is to be used
386 * Please see each class documentation for details and examples.
391 /// C function used as callback in the C API.
392 typedef void (*ccallback_type)(int, short, void*);
398 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
399 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
400 * flag, that tells eventxx that this event should live until dispatcher::del()
401 * is called. You can use, for example:
403 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
408 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
409 READ = EV_READ, ///< Read event.
410 WRITE = EV_WRITE, ///< Write event.
411 SIGNAL = EV_SIGNAL, ///< Signal event.
412 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
416 type operator| (const type& t1, const type& t2)
418 int r = static_cast< int >(t1) | static_cast< int >(t2);
419 return *reinterpret_cast< type* >(&r);
424 * Basic event from which all events derive.
426 * All events derive from this class, so it's useful for use in containers,
429 * std::list< eventxx::basic_event* > events;
432 struct basic_event: internal::event
436 * Checks if there is an event pending.
438 * @param ev Type of event to check.
440 * @return true if there is a pending event, false if not.
442 bool pending(type ev) const throw()
444 // HACK libevent don't use const
445 return event_pending(const_cast< basic_event* >(this), ev, 0);
449 * Timeout of the event.
451 * @return Timeout of the event.
453 time timeout() const throw()
456 // HACK libevent don't use const
457 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
462 * Sets the event's priority.
464 * @param priority New event priority.
466 * @pre The event must be added to some dispatcher.
468 * @see dispatcher::dispatcher(int)
470 void priority(int priority) const throw(invalid_event, invalid_priority)
472 if (ev_flags & EVLIST_ACTIVE)
473 throw invalid_event("can't change the priority of an "
475 // HACK libevent don't use const
476 if (event_priority_set(const_cast< basic_event* >(this),
478 throw invalid_priority();
482 * Event's file descriptor.
484 * @return Event's file descriptor.
486 int fd() const throw()
488 return EVENT_FD(this);
491 /// @note This is an abstract class, you can't instantiate it.
493 basic_event() throw() {}
494 basic_event(const basic_event&);
495 basic_event& operator= (const basic_event&);
497 }; // struct basic_event
501 * Generic event object.
503 * This object stores all the information about an event, including a callback
504 * functor, which is called when the event is fired. The template parameter
505 * must be a functor (callable object or function) that can take 2 parameters:
506 * an integer (the file descriptor of the fired event) and an event::type (the
507 * type of event being fired).
508 * There is a specialized version of this class which takes as the template
509 * parameter a C function with the eventxx::ccallback_type signature, just like
510 * C @libevent API does.
512 * @see eventxx::event< ccallback_type >
514 template < typename F >
515 struct event: basic_event
519 * Creates a new event.
521 * @param fd File descriptor to monitor for events.
522 * @param ev Type of events to monitor (see eventxx::type).
523 * @param handler Callback functor.
525 event(int fd, type ev, F& handler) throw()
527 event_set(this, fd, static_cast< short >(ev), &wrapper,
528 reinterpret_cast< void* >(&handler));
533 static void wrapper(int fd, short ev, void* h)
535 F& handler = *reinterpret_cast< F* >(h);
536 // Hackish, but this way the handler can get a clean
538 handler(fd, *reinterpret_cast< type* >(&ev));
541 }; // struct event< F >
545 * This is the specialization of eventxx::event for C-style callbacks.
547 * @see eventxx::event
550 struct event< ccallback_type >: basic_event
554 * Creates a new event.
556 * @param fd File descriptor to monitor for events.
557 * @param ev Type of events to monitor (see eventxx::type).
558 * @param handler C-style callback function.
559 * @param arg Arbitrary pointer to pass to the handler as argument.
561 event(int fd, type ev, ccallback_type handler, void* arg = 0) throw()
563 event_set(this, fd, static_cast< short >(ev), handler, arg);
569 }; // struct event< ccallback_type >
573 * Timer event object.
575 * This is just a special case of event that is fired only when a timeout is
576 * reached. It's just a shortcut to:
578 * event(-1, 0, handler);
581 * @note This event can't eventxx::PERSIST.
582 * @see timer< ccallback_type >
584 template < typename F >
585 struct timer: event< F >
589 * Creates a new timer event.
591 * @param handler Callback functor.
593 timer(F& handler) throw()
595 evtimer_set(this, &event< F >::wrapper,
596 reinterpret_cast< void* >(&handler));
599 }; // struct timer< F >
603 * This is the specialization of eventxx::timer for C-style callbacks.
605 * @note This event can't eventxx::PERSIST.
609 struct timer< ccallback_type >: event< ccallback_type >
613 * Creates a new timer event.
615 * @param handler C-style callback function.
616 * @param arg Arbitrary pointer to pass to the handler as argument.
618 timer(ccallback_type handler, void* arg = 0) throw()
620 evtimer_set(this, handler, arg);
623 }; // struct timer< ccallback_type >
627 * Signal event object.
629 * This is just a special case of event that is fired when a signal is raised
630 * (instead of a file descriptor being active). It's just a shortcut to:
632 * event(signum, eventxx::SIGNAL, handler);
635 * @note This event always eventxx::PERSIST.
636 * @see signal< ccallback_type >
638 template < typename F >
639 struct signal: event< F >
643 * Creates a new signal event.
645 * @param signum Signal number to monitor.
646 * @param handler Callback functor.
648 signal(int signum, F& handler) throw()
650 signal_set(this, signum, &event< F >::wrapper,
651 reinterpret_cast< void* >(&handler));
655 * Event's signal number.
657 * @return Event's signal number.
661 return EVENT_SIGNAL(this);
664 }; // struct signal<F>
668 * This is the specialization of eventxx::signal for C-style callbacks.
670 * @note This event always eventxx::PERSIST.
674 struct signal< ccallback_type >: event< ccallback_type >
678 * Creates a new signal event.
680 * @param signum Signal number to monitor.
681 * @param handler C-style callback function.
682 * @param arg Arbitrary pointer to pass to the handler as argument.
684 signal(int signum, ccallback_type handler, void* arg = 0) throw()
686 signal_set(this, signum, handler, arg);
690 * Event's signal number.
692 * @return Event's signal number.
696 return EVENT_SIGNAL(this);
699 }; // struct signal< ccallback_type >
702 /// Shortcut to C-style event.
703 typedef eventxx::event< ccallback_type > cevent;
705 /// Shortcut to C-style timer.
706 typedef eventxx::timer< ccallback_type > ctimer;
708 /// Shortcut to C-style signal handler.
709 typedef eventxx::signal< ccallback_type > csignal;
712 * Helper functor to use an arbitrary member function as an event handler.
714 * With this wrapper, you can use any object method, which accepts the right
715 * parameters (int, short) and returns void, as an event handler. This way you
716 * don't have to overload the operator() which can be confusing depending on the
719 * You can see an usage example in the Examples Section.
721 template < typename O, typename M >
726 * Member function callback constructor.
728 * It expects to receive a class as the first parameter (O), and a
729 * member function (of that class O) as the second parameter.
731 * When this instance is called with fd and ev as function arguments,
732 * object.method(fd, ev) will be called.
734 * @param object Object to be used.
735 * @param method Method to be called.
737 mem_cb(O& object, M method) throw():
738 _object(object), _method(method) {}
740 void operator() (int fd, type ev) { (_object.*_method)(fd, ev); }
753 * This class is the responsible for looping and dispatching events. Every time
754 * you need an event loop you should create an instance of this class.
756 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
757 * can @link dispatcher::del remove @endlink them later or you can @link
758 * dispatcher::add_once add events to be processed just once @endlink. You can
759 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
760 * can break that forever removing all the events or by @link dispatcher::exit
761 * exiting the loop @endlink).
767 * Creates a default dispatcher (with just 1 priority).
769 * @see dispatcher(int) if you want to create a dispatcher with more
774 _event_base = static_cast< internal::event_base* >(
775 internal::event_init());
779 * Creates a dispatcher with npriorities priorities.
781 * @param npriorities Number of priority queues to use.
783 dispatcher(int npriorities) throw(std::bad_alloc)
785 _event_base = static_cast< internal::event_base* >(
786 internal::event_init());
787 if (!_event_base) throw std::bad_alloc();
788 // Can't fail because there is no way that it has active events
789 internal::event_base_priority_init(_event_base, npriorities);
792 #ifndef EVENTXX_NO_EVENT_BASE_FREE
793 /// Free dispatcher resources, see @ref Status section for details.
794 ~dispatcher() throw() { event_base_free(_event_base); }
798 * Adds an event to the dispatcher.
800 * @param e Event to add.
801 * @param priority Priority of the event.
803 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
804 throw(invalid_priority)
806 internal::event_base_set(_event_base, &e);
807 if (priority != DEFAULT_PRIORITY
808 && internal::event_priority_set(&e, priority))
809 throw invalid_priority();
810 internal::event_add(&e, 0);
814 * Adds an event to the dispatcher with a timeout.
816 * The event is fired when there is activity on e or when to has elapsed,
817 * whatever come first.
819 * @param e Event to add.
821 * @param priority Priority of the event.
823 void add(basic_event& e, const time& to,
824 int priority = DEFAULT_PRIORITY)
825 throw(invalid_priority)
827 internal::event_base_set(_event_base, &e);
828 if (priority != DEFAULT_PRIORITY
829 && internal::event_priority_set(&e, priority))
830 throw invalid_priority();
831 // XXX HACK libevent don't use const
832 internal::event_add(&e, const_cast< time* >(&to));
836 * Adds a temporary event.
838 * Adds a temporary event, without the need of instantiating a new event
839 * object. Events added this way can't eventxx::PERSIST.
841 * @param fd File descriptor to monitor for events.
842 * @param ev Type of events to monitor.
843 * @param handler Callback function.
845 template < typename F >
846 void add_once(int fd, type ev, F& handler)
848 internal::event_once(fd, static_cast< short>(ev),
849 &dispatcher::wrapper< F >,
850 reinterpret_cast< void* >(&handler), 0);
854 * Adds a temporary event to with a C-style callback.
856 * Adds a temporary event, without the need of instantiating a new event
857 * object. Events added this way can't eventxx::PERSIST.
859 * @param fd File descriptor to monitor for events.
860 * @param ev Type of events to monitor.
861 * @param handler Callback function.
862 * @param arg Arbitrary pointer to pass to the handler as argument.
864 void add_once(int fd, type ev, ccallback_type handler, void* arg)
866 internal::event_once(fd, static_cast< short >(ev), handler,
871 * Adds a temporary event.
873 * Adds a temporary event, without the need of instantiating a new event
874 * object. Events added this way can't eventxx::PERSIST.
876 * @param fd File descriptor to monitor for events.
877 * @param ev Type of events to monitor.
878 * @param handler Callback function.
881 template < typename F >
882 void add_once(int fd, type ev, F& handler, const time& to)
884 internal::event_once(fd, static_cast< short >(ev),
885 &dispatcher::wrapper< F >,
886 reinterpret_cast< void* >(&handler),
887 // XXX HACK libevent don't use const
888 const_cast< time* >(&to));
892 * Adds a temporary event with a C-style callback.
894 * Adds a temporary event, without the need of instantiating a new event
895 * object. Events added this way can't eventxx::PERSIST.
897 * @param fd File descriptor to monitor for events.
898 * @param ev Type of events to monitor.
899 * @param handler Callback function.
900 * @param arg Arbitrary pointer to pass to the handler as argument.
903 void add_once(int fd, type ev, ccallback_type handler, void* arg,
906 internal::event_once(fd, static_cast< short >(ev), handler, arg,
907 // XXX HACK libevent don't use const
908 const_cast< time* >(&to));
912 * Adds a temporary timer.
914 * Adds a temporary timer, without the need of instantiating a new timer
917 * @param handler Callback function.
918 * @param to Timer's timeout.
920 template < typename F >
921 void add_once_timer(F& handler, const time& to)
923 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
924 reinterpret_cast< void* >(&handler),
925 // XXX HACK libevent don't use const
926 const_cast< time* >(&to));
930 * Adds a temporary timer with a C-style callback.
932 * Adds a temporary timer, without the need of instantiating a new timer
935 * @param handler Callback function.
936 * @param arg Arbitrary pointer to pass to the handler as argument.
937 * @param to Timer's timeout.
939 void add_once_timer(ccallback_type handler, void* arg, const time& to)
941 // XXX HACK libevent don't use const
942 internal::event_once(-1, EV_TIMEOUT, handler, arg,
943 const_cast< time* >(&to));
949 * The event e will be no longer monitored by this dispatcher.
951 * @param e Event to remove.
953 void del(basic_event& e) throw()
955 internal::event_del(&e);
959 * Main dispatcher loop.
961 * This function takes the control of the program, waiting for an event
962 * and calling its callbacks when it's fired. It only returns under
964 * - exit() was called.
965 * - All events were del()eted.
966 * - Another internal error.
967 * - eventxx::ONCE flag was set.
968 * - eventxx::NONBLOCK flag was set.
970 * @param flags If eventxx::ONCE is specified, then just one event is
971 * processed, if eventxx::NONBLOCK is specified, then this
972 * function returns even if there are no pending events.
974 * @return 0 if eventxx::NONBLOCK or eventxx::ONCE is set, 1 if there
975 * are no more events registered and EINTR if you use the
976 * @libevent's @c event_gotsig and return -1 in your
977 * @c event_sigcb callback.
979 int dispatch(int flags = 0) throw()
981 return internal::event_base_loop(_event_base, flags);
985 * Exit the dispatch() loop.
987 * @param to If a timeout is given, the loop exits after the specified
990 * @return Not very well specified by @libevent :-/ that's why it
991 * doesn't throw an exception either.
993 int exit(const time& to = time()) throw() // TODO throw(exception)
995 // XXX HACK libevent don't use const
996 return internal::event_base_loopexit(_event_base,
997 const_cast< time* >(&to));
1001 internal::event_base* _event_base;
1002 template < typename F >
1003 static void wrapper(int fd, short ev, void* h)
1005 F& handler = *reinterpret_cast< F* >(h);
1006 handler(fd, *reinterpret_cast< type* >(&ev));
1009 }; // struct dispatcher
1011 } // namespace eventxx
1013 #endif // _EVENTXX_HPP_
1015 // vim: set filetype=cpp :