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 the
140 * memory the program abort() because a failed assertion). Because of that,
141 * there is a way to disable the @link eventxx::dispatcher::~dispatcher()
142 * destructor @endlink (which calls the inexistent/broken @c event_base_free()
143 * function). So if you use a @libevent version previous to 1.3b, you have to
144 * compile your programs defining the EVENTXX_NO_EVENT_BASE_FREE macro.
146 * If something is broken it would be really easy to fix because @eventxx is
147 * just a simple wrapper around @libevent. So, please try it out, and if you
148 * have any problems, <a href="mailto:llucax+eventxx@gmail.com">drop me an
149 * e-mail</a> and and I'll fix it ASAP (or provide a patch and you will be my
152 * If you use this library, please drop me an e-mail with your thoughts, or
153 * simply saying "I use it", so I can keep track of how many people really use
156 * @author Leandro Lucarella <llucax+eventxx@gmail.com>
161 * This program is under the BOLA license (see
162 * http://auriga.wearlab.de/~alb/bola/ for more details or read the
163 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/LICENSE">LICENSE</a>
164 * file itself, it's very short and it basically says it's Public Domain).
168 /** @example c-way.cpp
170 * This is a simple example illustrating the usage with C-like callback
174 /** @example functor-way.cpp
176 * This is a simple example illustrating the usage with function object
180 /** @example wrapped-functor-way.cpp
182 * This is a simple example illustrating the usage with an arbitrary member
183 * function as an event handler callbacks.
186 /** @example mixed-way.cpp
188 * This is a simple example illustrating the usage with a mix of C-like callbacks
189 * and function object callbacks.
192 /** @example bench.cpp
194 * This is a benchmark example, extracted from libevent and ported to eventxx.
197 /** @example prio-test.cpp
199 * This is a priority usage example.
202 /** @example test-time.cpp
204 * This is a timer usage example ported from libevent.
207 /** @example test-eof.cpp
209 * This is some kind of test of EOF ported from libevent.
212 /** @example test-weof.cpp
214 * Another test of EOF ported from libevent.
217 /** @example trivial.cpp
219 * This is the most trivial example.
223 * Namespace for all symbols libevent C++ wrapper defines.
229 // All libevent C API symbols and other internal stuff goes here.
236 /** @defgroup exceptions Exceptions
238 * eventxx makes a heavy use of exceptions. Each function has it's exceptions
239 * specified, so it's very easy to find out what exceptions to expect.
241 * Exceptions are mostly thrown when there is a programming error. So if you get
242 * an exception check your code.
248 * Base class for all libevent exceptions.
250 struct exception: public std::exception
256 * Invalid event exception.
258 * This exception is thrown when passing an invalid event to a function, the
259 * reason is given in the what() description but it usually means that the you
260 * are making some restricted operation with an active event.
262 * If you hit this exception, you probably got a programming error.
264 struct invalid_event: public std::invalid_argument, public exception
268 * Creates an invalid event exception with a reason.
270 * @param what Reason why the event is invalid).
272 explicit invalid_event(const std::string& what) throw():
273 std::invalid_argument(what)
277 }; // struct invalid_event
281 * Invalid priority exception.
283 * This exception is thrown when passing an invalid priority to a function. This
284 * usually means you don't have enough priority queues in your dispatcher, so
285 * you should have allocated more in the constructor.
287 * If you hit this exception, you probably got a programming error.
289 * @see dispatcher::dispatcher(int) to allocate more priority queues.
291 struct invalid_priority: public std::invalid_argument, public exception
295 * Creates an invalid priority exception with a reason.
297 * @param what Reason why the priority is invalid).
299 explicit invalid_priority(const std::string& what
300 = "invalid priority value") throw():
301 std::invalid_argument(what)
305 }; // struct invalid_priority
310 /// Miscellaneous constants
313 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
314 ONCE = EVLOOP_ONCE, ///< Loop just once.
315 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
320 * Time used for timeout values.
322 * This timeout is compose of seconds and microseconds.
324 struct time: ::timeval
328 * Creates a new time with @p sec seconds and @p usec microseconds.
330 * @param sec Number of seconds.
331 * @param usec Number of microseconds.
333 time(long sec = 0l, long usec = 0l) throw()
334 { tv_sec = sec; tv_usec = usec; }
337 * Gets the number of seconds.
339 * @return Number of seconds.
341 long sec() const throw() { return tv_sec; };
344 * Gets the number of microseconds.
346 * @return Number of microseconds.
348 long usec() const throw() { return tv_usec; };
351 * Sets the number of seconds.
353 * @param s Number of seconds.
355 void sec(long s) throw() { tv_sec = s; };
358 * Sets the number of microseconds.
360 * @param u Number of microseconds.
362 void usec(long u) throw() { tv_usec = u; };
367 /** @defgroup events Events
369 * There are many ways to specify how to handle an event. You can use use the
370 * same plain functions callbacks (see eventxx::cevent, eventxx::ctimer and
371 * eventxx::csignal) like in C or the other kind of more advanced, stateful
372 * function objects (see eventxx::event, eventxx::timer and eventxx::signal
373 * templates). The former are just typedef'ed specialization of the later.
375 * A member function wrapper functor (eventxx::mem_cb) is also included,
376 * so you can use any member function (method) as an event handler.
378 * Please note that C-like function callback take a short as the type of event,
379 * while functors (or member functions) use eventxx::type.
381 * All events derive from a plain class (not template) eventxx::basic_event, one
382 * of the main utilities of it (besides containing common code ;) is to be used
385 * Please see each class documentation for details and examples.
390 /// C function used as callback in the C API.
391 typedef void (*ccallback_type)(int, short, void*);
397 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
398 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
399 * flag, that tells eventxx that this event should live until dispatcher::del()
400 * is called. You can use, for example:
402 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
407 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
408 READ = EV_READ, ///< Read event.
409 WRITE = EV_WRITE, ///< Write event.
410 SIGNAL = EV_SIGNAL, ///< Signal event.
411 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
415 type operator| (const type& t1, const type& t2)
417 int r = static_cast< int >(t1) | static_cast< int >(t2);
418 return *reinterpret_cast< type* >(&r);
423 * Basic event from which all events derive.
425 * All events derive from this class, so it's useful for use in containers,
428 * std::list< eventxx::basic_event* > events;
431 struct basic_event: internal::event
435 * Checks if there is an event pending.
437 * @param ev Type of event to check.
439 * @return true if there is a pending event, false if not.
441 bool pending(type ev) const throw()
443 // HACK libevent don't use const
444 return event_pending(const_cast< basic_event* >(this), ev, 0);
448 * Timeout of the event.
450 * @return Timeout of the event.
452 time timeout() const throw()
455 // HACK libevent don't use const
456 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
461 * Sets the event's priority.
463 * @param priority New event priority.
465 * @pre The event must be added to some dispatcher.
467 * @see dispatcher::dispatcher(int)
469 void priority(int priority) const throw(invalid_event, invalid_priority)
471 if (ev_flags & EVLIST_ACTIVE)
472 throw invalid_event("can't change the priority of an "
474 // HACK libevent don't use const
475 if (event_priority_set(const_cast< basic_event* >(this),
477 throw invalid_priority();
481 * Event's file descriptor.
483 * @return Event's file descriptor.
485 int fd() const throw()
487 return EVENT_FD(this);
490 /// @note This is an abstract class, you can't instantiate it.
492 basic_event() throw() {}
493 basic_event(const basic_event&);
494 basic_event& operator= (const basic_event&);
496 }; // struct basic_event
500 * Generic event object.
502 * This object stores all the information about an event, including a callback
503 * functor, which is called when the event is fired. The template parameter
504 * must be a functor (callable object or function) that can take 2 parameters:
505 * an integer (the file descriptor of the fired event) and an event::type (the
506 * type of event being fired).
507 * There is a specialized version of this class which takes as the template
508 * parameter a C function with the eventxx::ccallback_type signature, just like
509 * C @libevent API does.
511 * @see eventxx::event< ccallback_type >
513 template < typename F >
514 struct event: basic_event
518 * Creates a new event.
520 * @param fd File descriptor to monitor for events.
521 * @param ev Type of events to monitor (see eventxx::type).
522 * @param handler Callback functor.
524 event(int fd, type ev, F& handler) throw()
526 event_set(this, fd, static_cast< short >(ev), &wrapper,
527 reinterpret_cast< void* >(&handler));
532 static void wrapper(int fd, short ev, void* h)
534 F& handler = *reinterpret_cast< F* >(h);
535 // Hackish, but this way the handler can get a clean
537 handler(fd, *reinterpret_cast< type* >(&ev));
540 }; // struct event< F >
544 * This is the specialization of eventxx::event for C-style callbacks.
546 * @see eventxx::event
549 struct event< ccallback_type >: basic_event
553 * Creates a new event.
555 * @param fd File descriptor to monitor for events.
556 * @param ev Type of events to monitor (see eventxx::type).
557 * @param handler C-style callback function.
558 * @param arg Arbitrary pointer to pass to the handler as argument.
560 event(int fd, type ev, ccallback_type handler, void* arg = 0) throw()
562 event_set(this, fd, static_cast< short >(ev), handler, arg);
568 }; // struct event< ccallback_type >
572 * Timer event object.
574 * This is just a special case of event that is fired only when a timeout is
575 * reached. It's just a shortcut to:
577 * event(-1, 0, handler);
580 * @note This event can't eventxx::PERSIST.
581 * @see timer< ccallback_type >
583 template < typename F >
584 struct timer: event< F >
588 * Creates a new timer event.
590 * @param handler Callback functor.
592 timer(F& handler) throw()
594 evtimer_set(this, &event< F >::wrapper,
595 reinterpret_cast< void* >(&handler));
598 }; // struct timer< F >
602 * This is the specialization of eventxx::timer for C-style callbacks.
604 * @note This event can't eventxx::PERSIST.
608 struct timer< ccallback_type >: event< ccallback_type >
612 * Creates a new timer event.
614 * @param handler C-style callback function.
615 * @param arg Arbitrary pointer to pass to the handler as argument.
617 timer(ccallback_type handler, void* arg = 0) throw()
619 evtimer_set(this, handler, arg);
622 }; // struct timer< ccallback_type >
626 * Signal event object.
628 * This is just a special case of event that is fired when a signal is raised
629 * (instead of a file descriptor being active). It's just a shortcut to:
631 * event(signum, eventxx::SIGNAL, handler);
634 * @note This event always eventxx::PERSIST.
635 * @see signal< ccallback_type >
637 template < typename F >
638 struct signal: event< F >
642 * Creates a new signal event.
644 * @param signum Signal number to monitor.
645 * @param handler Callback functor.
647 signal(int signum, F& handler) throw()
649 signal_set(this, signum, &event< F >::wrapper,
650 reinterpret_cast< void* >(&handler));
654 * Event's signal number.
656 * @return Event's signal number.
660 return EVENT_SIGNAL(this);
663 }; // struct signal<F>
667 * This is the specialization of eventxx::signal for C-style callbacks.
669 * @note This event always eventxx::PERSIST.
673 struct signal< ccallback_type >: event< ccallback_type >
677 * Creates a new signal event.
679 * @param signum Signal number to monitor.
680 * @param handler C-style callback function.
681 * @param arg Arbitrary pointer to pass to the handler as argument.
683 signal(int signum, ccallback_type handler, void* arg = 0) throw()
685 signal_set(this, signum, handler, arg);
689 * Event's signal number.
691 * @return Event's signal number.
695 return EVENT_SIGNAL(this);
698 }; // struct signal< ccallback_type >
701 /// Shortcut to C-style event.
702 typedef eventxx::event< ccallback_type > cevent;
704 /// Shortcut to C-style timer.
705 typedef eventxx::timer< ccallback_type > ctimer;
707 /// Shortcut to C-style signal handler.
708 typedef eventxx::signal< ccallback_type > csignal;
711 * Helper functor to use an arbitrary member function as an event handler.
713 * With this wrapper, you can use any object method, which accepts the right
714 * parameters (int, short) and returns void, as an event handler. This way you
715 * don't have to overload the operator() which can be confusing depending on the
718 * You can see an usage example in the Examples Section.
720 template < typename O, typename M >
725 * Member function callback constructor.
727 * It expects to receive a class as the first parameter (O), and a
728 * member function (of that class O) as the second parameter.
730 * When this instance is called with fd and ev as function arguments,
731 * object.method(fd, ev) will be called.
733 * @param object Object to be used.
734 * @param method Method to be called.
736 mem_cb(O& object, M method) throw():
737 _object(object), _method(method) {}
739 void operator() (int fd, type ev) { (_object.*_method)(fd, ev); }
752 * This class is the responsible for looping and dispatching events. Every time
753 * you need an event loop you should create an instance of this class.
755 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
756 * can @link dispatcher::del remove @endlink them later or you can @link
757 * dispatcher::add_once add events to be processed just once @endlink. You can
758 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
759 * can break that forever removing all the events or by @link dispatcher::exit
760 * exiting the loop @endlink).
766 * Creates a default dispatcher (with just 1 priority).
768 * @see dispatcher(int) if you want to create a dispatcher with more
773 _event_base = static_cast< internal::event_base* >(
774 internal::event_init());
778 * Creates a dispatcher with npriorities priorities.
780 * @param npriorities Number of priority queues to use.
782 dispatcher(int npriorities) throw(std::bad_alloc)
784 _event_base = static_cast< internal::event_base* >(
785 internal::event_init());
786 if (!_event_base) throw std::bad_alloc();
787 // Can't fail because there is no way that it has active events
788 internal::event_base_priority_init(_event_base, npriorities);
791 #ifndef EVENTXX_NO_EVENT_BASE_FREE
792 /// Free dispatcher resources, see @ref Status section for details.
793 ~dispatcher() throw() { event_base_free(_event_base); }
797 * Adds an event to the dispatcher.
799 * @param e Event to add.
800 * @param priority Priority of the event.
802 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
803 throw(invalid_priority)
805 internal::event_base_set(_event_base, &e);
806 if (priority != DEFAULT_PRIORITY
807 && internal::event_priority_set(&e, priority))
808 throw invalid_priority();
809 internal::event_add(&e, 0);
813 * Adds an event to the dispatcher with a timeout.
815 * The event is fired when there is activity on e or when to has elapsed,
816 * whatever come first.
818 * @param e Event to add.
820 * @param priority Priority of the event.
822 void add(basic_event& e, const time& to,
823 int priority = DEFAULT_PRIORITY)
824 throw(invalid_priority)
826 internal::event_base_set(_event_base, &e);
827 if (priority != DEFAULT_PRIORITY
828 && internal::event_priority_set(&e, priority))
829 throw invalid_priority();
830 // XXX HACK libevent don't use const
831 internal::event_add(&e, const_cast< time* >(&to));
835 * Adds a temporary event.
837 * Adds a temporary event, without the need of instantiating a new event
838 * object. Events added this way can't eventxx::PERSIST.
840 * @param fd File descriptor to monitor for events.
841 * @param ev Type of events to monitor.
842 * @param handler Callback function.
844 template < typename F >
845 void add_once(int fd, type ev, F& handler)
847 internal::event_once(fd, static_cast< short>(ev),
848 &dispatcher::wrapper< F >,
849 reinterpret_cast< void* >(&handler), 0);
853 * Adds a temporary event to with a C-style callback.
855 * Adds a temporary event, without the need of instantiating a new event
856 * object. Events added this way can't eventxx::PERSIST.
858 * @param fd File descriptor to monitor for events.
859 * @param ev Type of events to monitor.
860 * @param handler Callback function.
861 * @param arg Arbitrary pointer to pass to the handler as argument.
863 void add_once(int fd, type ev, ccallback_type handler, void* arg)
865 internal::event_once(fd, static_cast< short >(ev), handler,
870 * Adds a temporary event.
872 * Adds a temporary event, without the need of instantiating a new event
873 * object. Events added this way can't eventxx::PERSIST.
875 * @param fd File descriptor to monitor for events.
876 * @param ev Type of events to monitor.
877 * @param handler Callback function.
880 template < typename F >
881 void add_once(int fd, type ev, F& handler, const time& to)
883 internal::event_once(fd, static_cast< short >(ev),
884 &dispatcher::wrapper< F >,
885 reinterpret_cast< void* >(&handler),
886 // XXX HACK libevent don't use const
887 const_cast< time* >(&to));
891 * Adds a temporary event with a C-style callback.
893 * Adds a temporary event, without the need of instantiating a new event
894 * object. Events added this way can't eventxx::PERSIST.
896 * @param fd File descriptor to monitor for events.
897 * @param ev Type of events to monitor.
898 * @param handler Callback function.
899 * @param arg Arbitrary pointer to pass to the handler as argument.
902 void add_once(int fd, type ev, ccallback_type handler, void* arg,
905 internal::event_once(fd, static_cast< short >(ev), handler, arg,
906 // XXX HACK libevent don't use const
907 const_cast< time* >(&to));
911 * Adds a temporary timer.
913 * Adds a temporary timer, without the need of instantiating a new timer
916 * @param handler Callback function.
917 * @param to Timer's timeout.
919 template < typename F >
920 void add_once_timer(F& handler, const time& to)
922 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
923 reinterpret_cast< void* >(&handler),
924 // XXX HACK libevent don't use const
925 const_cast< time* >(&to));
929 * Adds a temporary timer with a C-style callback.
931 * Adds a temporary timer, without the need of instantiating a new timer
934 * @param handler Callback function.
935 * @param arg Arbitrary pointer to pass to the handler as argument.
936 * @param to Timer's timeout.
938 void add_once_timer(ccallback_type handler, void* arg, const time& to)
940 // XXX HACK libevent don't use const
941 internal::event_once(-1, EV_TIMEOUT, handler, arg,
942 const_cast< time* >(&to));
948 * The event e will be no longer monitored by this dispatcher.
950 * @param e Event to remove.
952 void del(basic_event& e) throw()
954 internal::event_del(&e);
958 * Main dispatcher loop.
960 * This function takes the control of the program, waiting for an event
961 * and calling its callbacks when it's fired. It only returns under
963 * - exit() was called.
964 * - All events were del()eted.
965 * - Another internal error.
966 * - eventxx::ONCE flag was set.
967 * - eventxx::NONBLOCK flag was set.
969 * @param flags If eventxx::ONCE is specified, then just one event is
970 * processed, if eventxx::NONBLOCK is specified, then this
971 * function returns even if there are no pending events.
973 * @return 0 if eventxx::NONBLOCK or eventxx::ONCE is set, 1 if there
974 * are no more events registered and EINTR if you use the
975 * @libevent's @c event_gotsig and return -1 in your
976 * @c event_sigcb callback.
978 int dispatch(int flags = 0) throw()
980 return internal::event_base_loop(_event_base, flags);
984 * Exit the dispatch() loop.
986 * @param to If a timeout is given, the loop exits after the specified
989 * @return Not very well specified by @libevent :-/ that's why it
990 * doesn't throw an exception either.
992 int exit(const time& to = time()) throw() // TODO throw(exception)
994 // XXX HACK libevent don't use const
995 return internal::event_base_loopexit(_event_base,
996 const_cast< time* >(&to));
1000 internal::event_base* _event_base;
1001 template < typename F >
1002 static void wrapper(int fd, short ev, void* h)
1004 F& handler = *reinterpret_cast< F* >(h);
1005 handler(fd, *reinterpret_cast< type* >(&ev));
1008 }; // struct dispatcher
1010 } // namespace eventxx
1012 #endif // _EVENTXX_HPP_
1014 // vim: set filetype=cpp :