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, eventxx::type 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, but it's used in some serious
134 * projects, so I think it's moderately stable now. The library has no support
135 * for buffered events yet, but patches are welcome. It doesn't support the
136 * HTTP stuff, and probably never will because that has nothing to do with
139 * @libevent had a memory leak before version 1.3b (before 1.2 it didn't even
140 * had a way free that memory, from version 1.2 to 1.3a, if you tried to free the
141 * memory the program abort() because a failed assertion). Because of that,
142 * there is a way to disable the @link eventxx::dispatcher::~dispatcher()
143 * destructor @endlink (which calls the inexistent/broken @c event_base_free()
144 * function). So if you use a @libevent version previous to 1.3b, you have to
145 * compile your programs defining the 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
154 * @author Leandro Lucarella <llucax+eventxx@gmail.com>
159 * This program is under the BOLA license (see
160 * http://auriga.wearlab.de/~alb/bola/ for more details or read the
161 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/LICENSE">LICENSE</a>
162 * file itself, it's very short and it basically says it's Public Domain).
166 /** @example c-way.cpp
168 * This is a simple example illustrating the usage with C-like callback
172 /** @example functor-way.cpp
174 * This is a simple example illustrating the usage with function object
178 /** @example wrapped-functor-way.cpp
180 * This is a simple example illustrating the usage with an arbitrary member
181 * function as an event handler callbacks.
184 /** @example mixed-way.cpp
186 * This is a simple example illustrating the usage with a mix of C-like callbacks
187 * and function object callbacks.
190 /** @example bench.cpp
192 * This is a benchmark example, extracted from libevent and ported to eventxx.
195 /** @example prio-test.cpp
197 * This is a priority usage example.
200 /** @example test-time.cpp
202 * This is a timer usage example ported from libevent.
205 /** @example test-eof.cpp
207 * This is some kind of test of EOF ported from libevent.
210 /** @example test-weof.cpp
212 * Another test of EOF ported from libevent.
215 /** @example trivial.cpp
217 * This is the most trivial example.
221 * Namespace for all symbols libevent C++ wrapper defines.
227 // All libevent C API symbols and other internal stuff goes here.
234 /** @defgroup exceptions Exceptions
236 * eventxx makes a heavy use of exceptions. Each function has it's exceptions
237 * specified, so it's very easy to find out what exceptions to expect.
239 * Exceptions are mostly thrown when there is a programming error. So if you get
240 * an exception check your code.
246 * Base class for all libevent exceptions.
248 struct exception: public std::exception
254 * Invalid event exception.
256 * This exception is thrown when passing an invalid event to a function, the
257 * reason is given in the what() description but it usually means that the you
258 * are making some restricted operation with an active event.
260 * If you hit this exception, you probably got a programming error.
262 struct invalid_event: public std::invalid_argument, public exception
266 * Creates an invalid event exception with a reason.
268 * @param what Reason why the event is invalid).
270 explicit invalid_event(const std::string& what) throw():
271 std::invalid_argument(what)
275 }; // struct invalid_event
279 * Invalid priority exception.
281 * This exception is thrown when passing an invalid priority to a function. This
282 * usually means you don't have enough priority queues in your dispatcher, so
283 * you should have allocated more in the constructor.
285 * If you hit this exception, you probably got a programming error.
287 * @see dispatcher::dispatcher(int) to allocate more priority queues.
289 struct invalid_priority: public std::invalid_argument, public exception
293 * Creates an invalid priority exception with a reason.
295 * @param what Reason why the priority is invalid).
297 explicit invalid_priority(const std::string& what
298 = "invalid priority value") throw():
299 std::invalid_argument(what)
303 }; // struct invalid_priority
308 /// Miscellaneous constants
311 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
312 ONCE = EVLOOP_ONCE, ///< Loop just once.
313 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
318 * Time used for timeout values.
320 * This timeout is compose of seconds and microseconds.
322 struct time: ::timeval
326 * Creates a new time with @p sec seconds and @p usec microseconds.
328 * @param sec Number of seconds.
329 * @param usec Number of microseconds.
331 time(long sec = 0l, long usec = 0l) throw()
332 { tv_sec = sec; tv_usec = usec; }
335 * Gets the number of seconds.
337 * @return Number of seconds.
339 long sec() const throw() { return tv_sec; };
342 * Gets the number of microseconds.
344 * @return Number of microseconds.
346 long usec() const throw() { return tv_usec; };
349 * Sets the number of seconds.
351 * @param s Number of seconds.
353 void sec(long s) throw() { tv_sec = s; };
356 * Sets the number of microseconds.
358 * @param u Number of microseconds.
360 void usec(long u) throw() { tv_usec = u; };
365 /** @defgroup events Events
367 * There are many ways to specify how to handle an event. You can use use the
368 * same plain functions callbacks (see eventxx::cevent, eventxx::ctimer and
369 * eventxx::csignal) like in C or the other kind of more advanced, stateful
370 * function objects (see eventxx::event, eventxx::timer and eventxx::signal
371 * templates). The former are just typedef'ed specialization of the later.
373 * A member function wrapper functor (eventxx::mem_cb) is also included,
374 * so you can use any member function (method) as an event handler.
376 * Please note that C-like function callback take a short as the type of event,
377 * while functors (or member functions) use eventxx::type.
379 * All events derive from a plain class (not template) eventxx::basic_event, one
380 * of the main utilities of it (besides containing common code ;) is to be used
383 * Please see each class documentation for details and examples.
388 /// C function used as callback in the C API.
389 typedef void (*ccallback_type)(int, short, void*);
395 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
396 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
397 * flag, that tells eventxx that this event should live until dispatcher::del()
398 * is called. You can use, for example:
400 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
405 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
406 READ = EV_READ, ///< Read event.
407 WRITE = EV_WRITE, ///< Write event.
408 SIGNAL = EV_SIGNAL, ///< Signal event.
409 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
413 type operator| (const type& t1, const type& t2)
415 int r = static_cast< int >(t1) | static_cast< int >(t2);
416 return *reinterpret_cast< type* >(&r);
421 * Basic event from which all events derive.
423 * All events derive from this class, so it's useful for use in containers,
426 * std::list< eventxx::basic_event* > events;
429 struct basic_event: internal::event
433 * Checks if there is an event pending.
435 * @param ev Type of event to check.
437 * @return true if there is a pending event, false if not.
439 bool pending(type ev) const throw()
441 // HACK libevent don't use const
442 return event_pending(const_cast< basic_event* >(this), ev, 0);
446 * Timeout of the event.
448 * @return Timeout of the event.
450 time timeout() const throw()
453 // HACK libevent don't use const
454 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
459 * Sets the event's priority.
461 * @param priority New event priority.
463 * @pre The event must be added to some dispatcher.
465 * @see dispatcher::dispatcher(int)
467 void priority(int priority) const throw(invalid_event, invalid_priority)
469 if (ev_flags & EVLIST_ACTIVE)
470 throw invalid_event("can't change the priority of an "
472 // HACK libevent don't use const
473 if (event_priority_set(const_cast< basic_event* >(this),
475 throw invalid_priority();
479 * Event's file descriptor.
481 * @return Event's file descriptor.
483 int fd() const throw()
485 return EVENT_FD(this);
488 /// @note This is an abstract class, you can't instantiate it.
490 basic_event() throw() {}
491 basic_event(const basic_event&);
492 basic_event& operator= (const basic_event&);
494 }; // struct basic_event
498 * Generic event object.
500 * This object stores all the information about an event, including a callback
501 * functor, which is called when the event is fired. The template parameter
502 * must be a functor (callable object or function) that can take 2 parameters:
503 * an integer (the file descriptor of the fired event) and an event::type (the
504 * type of event being fired).
505 * There is a specialized version of this class which takes as the template
506 * parameter a C function with the eventxx::ccallback_type signature, just like
507 * C @libevent API does.
509 * @see eventxx::event< ccallback_type >
511 template < typename F >
512 struct event: basic_event
516 * Creates a new event.
518 * @param fd File descriptor to monitor for events.
519 * @param ev Type of events to monitor (see eventxx::type).
520 * @param handler Callback functor.
522 event(int fd, type ev, F& handler) throw()
524 event_set(this, fd, static_cast< short >(ev), &wrapper,
525 reinterpret_cast< void* >(&handler));
530 static void wrapper(int fd, short ev, void* h)
532 F& handler = *reinterpret_cast< F* >(h);
533 // Hackish, but this way the handler can get a clean
535 handler(fd, *reinterpret_cast< type* >(&ev));
538 }; // struct event< F >
542 * This is the specialization of eventxx::event for C-style callbacks.
544 * @see eventxx::event
547 struct event< ccallback_type >: basic_event
551 * Creates a new event.
553 * @param fd File descriptor to monitor for events.
554 * @param ev Type of events to monitor (see eventxx::type).
555 * @param handler C-style callback function.
556 * @param arg Arbitrary pointer to pass to the handler as argument.
558 event(int fd, type ev, ccallback_type handler, void* arg = 0) throw()
560 event_set(this, fd, static_cast< short >(ev), handler, arg);
566 }; // struct event< ccallback_type >
570 * Timer event object.
572 * This is just a special case of event that is fired only when a timeout is
573 * reached. It's just a shortcut to:
575 * event(-1, 0, handler);
578 * @note This event can't eventxx::PERSIST.
579 * @see timer< ccallback_type >
581 template < typename F >
582 struct timer: event< F >
586 * Creates a new timer event.
588 * @param handler Callback functor.
590 timer(F& handler) throw()
592 evtimer_set(this, &event< F >::wrapper,
593 reinterpret_cast< void* >(&handler));
596 }; // struct timer< F >
600 * This is the specialization of eventxx::timer for C-style callbacks.
602 * @note This event can't eventxx::PERSIST.
606 struct timer< ccallback_type >: event< ccallback_type >
610 * Creates a new timer event.
612 * @param handler C-style callback function.
613 * @param arg Arbitrary pointer to pass to the handler as argument.
615 timer(ccallback_type handler, void* arg = 0) throw()
617 evtimer_set(this, handler, arg);
620 }; // struct timer< ccallback_type >
624 * Signal event object.
626 * This is just a special case of event that is fired when a signal is raised
627 * (instead of a file descriptor being active). It's just a shortcut to:
629 * event(signum, eventxx::SIGNAL, handler);
632 * @note This event always eventxx::PERSIST.
633 * @see signal< ccallback_type >
635 template < typename F >
636 struct signal: event< F >
640 * Creates a new signal event.
642 * @param signum Signal number to monitor.
643 * @param handler Callback functor.
645 signal(int signum, F& handler) throw()
647 signal_set(this, signum, &event< F >::wrapper,
648 reinterpret_cast< void* >(&handler));
652 * Event's signal number.
654 * @return Event's signal number.
658 return EVENT_SIGNAL(this);
661 }; // struct signal<F>
665 * This is the specialization of eventxx::signal for C-style callbacks.
667 * @note This event always eventxx::PERSIST.
671 struct signal< ccallback_type >: event< ccallback_type >
675 * Creates a new signal event.
677 * @param signum Signal number to monitor.
678 * @param handler C-style callback function.
679 * @param arg Arbitrary pointer to pass to the handler as argument.
681 signal(int signum, ccallback_type handler, void* arg = 0) throw()
683 signal_set(this, signum, handler, arg);
687 * Event's signal number.
689 * @return Event's signal number.
693 return EVENT_SIGNAL(this);
696 }; // struct signal< ccallback_type >
699 /// Shortcut to C-style event.
700 typedef eventxx::event< ccallback_type > cevent;
702 /// Shortcut to C-style timer.
703 typedef eventxx::timer< ccallback_type > ctimer;
705 /// Shortcut to C-style signal handler.
706 typedef eventxx::signal< ccallback_type > csignal;
709 * Helper functor to use an arbitrary member function as an event handler.
711 * With this wrapper, you can use any object method, which accepts the right
712 * parameters (int, short) and returns void, as an event handler. This way you
713 * don't have to overload the operator() which can be confusing depending on the
716 * You can see an usage example in the Examples Section.
718 template < typename O, typename M >
723 * Member function callback constructor.
725 * It expects to receive a class as the first parameter (O), and a
726 * member function (of that class O) as the second parameter.
728 * When this instance is called with fd and ev as function arguments,
729 * object.method(fd, ev) will be called.
731 * @param object Object to be used.
732 * @param method Method to be called.
734 mem_cb(O& object, M method) throw():
735 _object(object), _method(method) {}
737 void operator() (int fd, type ev) { (_object.*_method)(fd, ev); }
750 * This class is the responsible for looping and dispatching events. Every time
751 * you need an event loop you should create an instance of this class.
753 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
754 * can @link dispatcher::del remove @endlink them later or you can @link
755 * dispatcher::add_once add events to be processed just once @endlink. You can
756 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
757 * can break that forever removing all the events or by @link dispatcher::exit
758 * exiting the loop @endlink).
764 * Creates a default dispatcher (with just 1 priority).
766 * @see dispatcher(int) if you want to create a dispatcher with more
771 _event_base = static_cast< internal::event_base* >(
772 internal::event_init());
776 * Creates a dispatcher with npriorities priorities.
778 * @param npriorities Number of priority queues to use.
780 dispatcher(int npriorities) throw(std::bad_alloc)
782 _event_base = static_cast< internal::event_base* >(
783 internal::event_init());
784 if (!_event_base) throw std::bad_alloc();
785 // Can't fail because there is no way that it has active events
786 internal::event_base_priority_init(_event_base, npriorities);
789 #ifndef EVENTXX_NO_EVENT_BASE_FREE
790 /// Free dispatcher resources, see @ref Status section for details.
791 ~dispatcher() throw() { event_base_free(_event_base); }
795 * Adds an event to the dispatcher.
797 * @param e Event to add.
798 * @param priority Priority of the event.
800 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
801 throw(invalid_priority)
803 internal::event_base_set(_event_base, &e);
804 if (priority != DEFAULT_PRIORITY
805 && internal::event_priority_set(&e, priority))
806 throw invalid_priority();
807 internal::event_add(&e, 0);
811 * Adds an event to the dispatcher with a timeout.
813 * The event is fired when there is activity on e or when to has elapsed,
814 * whatever come first.
816 * @param e Event to add.
818 * @param priority Priority of the event.
820 void add(basic_event& e, const time& to,
821 int priority = DEFAULT_PRIORITY)
822 throw(invalid_priority)
824 internal::event_base_set(_event_base, &e);
825 if (priority != DEFAULT_PRIORITY
826 && internal::event_priority_set(&e, priority))
827 throw invalid_priority();
828 // XXX HACK libevent don't use const
829 internal::event_add(&e, const_cast< time* >(&to));
833 * Adds a temporary event.
835 * Adds a temporary event, without the need of instantiating a new event
836 * object. Events added this way can't eventxx::PERSIST.
838 * @param fd File descriptor to monitor for events.
839 * @param ev Type of events to monitor.
840 * @param handler Callback function.
842 template < typename F >
843 void add_once(int fd, type ev, F& handler)
845 internal::event_once(fd, static_cast< short>(ev),
846 &dispatcher::wrapper< F >,
847 reinterpret_cast< void* >(&handler), 0);
851 * Adds a temporary event to with a C-style callback.
853 * Adds a temporary event, without the need of instantiating a new event
854 * object. Events added this way can't eventxx::PERSIST.
856 * @param fd File descriptor to monitor for events.
857 * @param ev Type of events to monitor.
858 * @param handler Callback function.
859 * @param arg Arbitrary pointer to pass to the handler as argument.
861 void add_once(int fd, type ev, ccallback_type handler, void* arg)
863 internal::event_once(fd, static_cast< short >(ev), handler,
868 * Adds a temporary event.
870 * Adds a temporary event, without the need of instantiating a new event
871 * object. Events added this way can't eventxx::PERSIST.
873 * @param fd File descriptor to monitor for events.
874 * @param ev Type of events to monitor.
875 * @param handler Callback function.
878 template < typename F >
879 void add_once(int fd, type ev, F& handler, const time& to)
881 internal::event_once(fd, static_cast< short >(ev),
882 &dispatcher::wrapper< F >,
883 reinterpret_cast< void* >(&handler),
884 // XXX HACK libevent don't use const
885 const_cast< time* >(&to));
889 * Adds a temporary event with a C-style callback.
891 * Adds a temporary event, without the need of instantiating a new event
892 * object. Events added this way can't eventxx::PERSIST.
894 * @param fd File descriptor to monitor for events.
895 * @param ev Type of events to monitor.
896 * @param handler Callback function.
897 * @param arg Arbitrary pointer to pass to the handler as argument.
900 void add_once(int fd, type ev, ccallback_type handler, void* arg,
903 internal::event_once(fd, static_cast< short >(ev), handler, arg,
904 // XXX HACK libevent don't use const
905 const_cast< time* >(&to));
909 * Adds a temporary timer.
911 * Adds a temporary timer, without the need of instantiating a new timer
914 * @param handler Callback function.
915 * @param to Timer's timeout.
917 template < typename F >
918 void add_once_timer(F& handler, const time& to)
920 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
921 reinterpret_cast< void* >(&handler),
922 // XXX HACK libevent don't use const
923 const_cast< time* >(&to));
927 * Adds a temporary timer with a C-style callback.
929 * Adds a temporary timer, without the need of instantiating a new timer
932 * @param handler Callback function.
933 * @param arg Arbitrary pointer to pass to the handler as argument.
934 * @param to Timer's timeout.
936 void add_once_timer(ccallback_type handler, void* arg, const time& to)
938 // XXX HACK libevent don't use const
939 internal::event_once(-1, EV_TIMEOUT, handler, arg,
940 const_cast< time* >(&to));
946 * The event e will be no longer monitored by this dispatcher.
948 * @param e Event to remove.
950 void del(basic_event& e) throw()
952 internal::event_del(&e);
956 * Main dispatcher loop.
958 * This function takes the control of the program, waiting for an event
959 * and calling its callbacks when it's fired. It only returns under
961 * - exit() was called.
962 * - All events were del()eted.
963 * - Another internal error.
964 * - eventxx::ONCE flag was set.
965 * - eventxx::NONBLOCK flag was set.
967 * @param flags If eventxx::ONCE is specified, then just one event is
968 * processed, if eventxx::NONBLOCK is specified, then this
969 * function returns even if there are no pending events.
971 * @return 0 if eventxx::NONBLOCK or eventxx::ONCE is set, 1 if there
972 * are no more events registered and EINTR if you use the
973 * @libevent's @c event_gotsig and return -1 in your
974 * @c event_sigcb callback.
976 int dispatch(int flags = 0) throw()
978 return internal::event_base_loop(_event_base, flags);
982 * Exit the dispatch() loop.
984 * @param to If a timeout is given, the loop exits after the specified
987 * @return Not very well specified by @libevent :-/ that's why it
988 * doesn't throw an exception either.
990 int exit(const time& to = time()) throw() // TODO throw(exception)
992 // XXX HACK libevent don't use const
993 return internal::event_base_loopexit(_event_base,
994 const_cast< time* >(&to));
998 internal::event_base* _event_base;
999 template < typename F >
1000 static void wrapper(int fd, short ev, void* h)
1002 F& handler = *reinterpret_cast< F* >(h);
1003 handler(fd, *reinterpret_cast< type* >(&ev));
1006 }; // struct dispatcher
1008 } // namespace eventxx
1010 #endif // _EVENTXX_HPP_
1012 // vim: set filetype=cpp :