4 #include <sys/types.h> // timeval
5 #include <stdexcept> // std::exception, std::invalid_argument,
6 // std::runtime_error, std::bad_alloc
10 * @section Introduction
12 * The <a href="http://monkey.org/~provos/libevent/">libevent</a> API provides
13 * a mechanism to execute a callback function when a specific event occurs on
14 * a file descriptor or after a timeout has been reached. Furthermore, libevent
15 * also support callbacks due to signals or regular timeouts.
17 * libevent is meant to replace the event loop found in event driven network
18 * servers. An application just needs to call dispatcher::dispatch() and then
19 * add or remove events dynamically without having to change the event loop.
21 * Currently, libevent supports /dev/poll, kqueue(2), select(2), poll(2) and
22 * epoll(4). It also has experimental support for real-time signals. The
23 * internal event mechanism is completely independent of the exposed event API,
24 * and a simple update of libevent can provide new functionality without having
25 * to redesign the applications. As a result, Libevent allows for portable
26 * application development and provides the most scalable event notification
27 * mechanism available on an operating system. Libevent should compile on Linux,
28 * *BSD, Mac OS X, Solaris and Windows.
30 * This is a simple, direct, one-header inline C++ wrapper for libevent. Yes,
31 * it's just one header file, so if you want to use it you can just copy the
32 * file to your project and you are set.
34 * It's designed to be as close to use to libevent (without compromising modern
35 * C++ programming techniques) and efficiency (since all implementation is
36 * trivial and inline, theoretically, it imposes no overhead at all).
38 * Please, visit the <a href="http://www.llucax.com.ar/~luca/eventxx/">eventxx
39 * website</a> for the latest documentation.
41 * You can always get the
42 * <a href="http://www.llucax.com.ar/~luca/eventxx/releases/current.tar.gz">current
43 * release</a> from the
44 * <a href="http://www.llucax.com.ar/~luca/eventxx/releases/">release
45 * directory</a> or grab the
46 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/">most up to date
47 * sources</a> from the <a href="http://www.darcs.net/">darcs</a> repository.
49 * You can also take a look the the <a
50 * href="http://auriga.wearlab.de/~alb/darcsweb/">darcsweb</a> interface to see
51 * the <a href="http://www.llucax.com.ar/~luca/repos/darcsweb/?r=eventxx">latest
57 * This wrapper was designed to be used just like libevent, but with C++ style
58 * syntax sugar (or poison, depends on your point of view ;) and goodies. The
59 * main difference to libevent is you always have to instance a
60 * eventxx::dispatcher to get an event loop. There is no implicit global event
61 * loop. This adds just an extra line of code for single threaded applications
62 * and makes things much more simple. See eventxx::dispatcher documentation for
65 * You can use use the same plain functions callbacks or the other kind of
66 * function objects (see @link events @endlink section for details on event
69 * eventxx uses @link exceptions @endlink to report errors. All functions has
70 * exception specifications, so it's easy to find out what to expect. See
71 * exceptions section for more detail.
73 * A timespec abstraction is provided in eventxx::time for convenient argument
74 * passing. Even more, it's a timespec itself, with some convenient methods for
75 * accessing the timespec attributes in a more C++ way. And even more, eventxx
76 * is such a direct mapping that all eventxx::event's are libevent event structs
77 * too, so theoretically you can pass a eventxx::event to libevent C functions
78 * without much trouble. eventxx::dispatcher is the only class that is not
79 * derived from libevent struct (event_base) because this struct it's not
80 * defined on the libevent header (just declared).
82 * Maybe you shouldn't know this implementation details to keep the abstraction,
83 * but this is a basic design goal of this wrapper so there is not much chance
84 * that this changes in the future (but use this knowledge with care, you are
96 * eventxx::dispatcher& d;
98 * handler(eventxx::dispatcher& d): d(d), i(0) {}
99 * void operator() (int signum, short event)
101 * if (i < 5) std::cout << "keep going...\n";
104 * std::cout << "done!\n";
110 * void sighandler(int signum, short event, void* data)
112 * int& i = *static_cast< int* >(data);
113 * std::cout << ++i << " interrupts, ";
118 * eventxx::dispatcher d;
120 * eventxx::csignal sigev(SIGINT, sighandler, &h.i);
121 * eventxx::signal< handler > e(SIGINT, h);
129 * You can see some more examples on the test directory of the distribution or
130 * on the examples related page.
135 * This library was not widely used yet, it lack some testing. Because templates
136 * are not even compiled when they are used, you can't be surprised if you catch
137 * a piece of code that didn't got even compiled yet because the lack of
138 * testing. The library has no support for buffered events yet either. It
139 * doesn't support the http stuff, and probably never will because that has
140 * nothing to do with event handling.
142 * If you notice this lib leaks memory, don't blame me, blame libevent :)
143 * libevent has a known bug on event_base_free() that makes it assert always, so
144 * event_base_free() it's unusable, unless you patch your libevent (for example,
146 * href="http://monkeymail.org/archives/libevent-users/2006-April/000141.html">patch</a>
147 * written by Mark D. Anderson and who knows why it's not still applied. If you
148 * do so, you can compile your programs with -DEVENT_BASE_FREE_FIX so
149 * event_base_free() gets called.
151 * That said, I think it's pretty usable anyways. If something is broken it
152 * would be really easy to fix it because is just a simple wrapper around
153 * libevent. So, please try it out, and if you have any problems,
154 * <a href="mailto:llucax+eventxx@gmail.com">drop me an
155 * e-mail</a> and and I'll fix it ASAP (or provide a patch and you will be my
158 * Patches to support buffered events are welcome too.
161 * @author Leandro Lucarella <llucax+eventxx@gmail.com>
166 * This program is under the BOLA license (see
167 * http://auriga.wearlab.de/~alb/bola/ for more info or the
168 * <a href="http://www.llucax.com.ar/~luca/repos/eventxx/LICENSE">LICENSE</a>
173 /** @example c-way.cpp
175 * This is a simple example illustrating the usage with C-like callback
179 /** @example functor-way.cpp
181 * This is a simple example illustrating the usage with function object
185 /** @example mixed-way.cpp
187 * This is a simple example illustrating the usage with a mix of C-like callbacks
188 * and function object callbacks.
191 /** @example bench.cpp
193 * This is a benchmark example, extracted from libevent and ported to eventxx.
196 /** @example prio-test.cpp
198 * This is a priority usage example.
201 /** @example test-time.cpp
203 * This is a timer usage example ported from libevent.
206 /** @example test-eof.cpp
208 * This is some kind of test of EOF ported from libevent.
211 /** @example test-weof.cpp
213 * Another test of EOF ported from libevent.
216 /** @example trivial.cpp
218 * This is the most trivial example.
222 * Namespace for all symbols libevent C++ wrapper defines.
228 // All libevent C API symbols and other internal stuff goes here.
235 /** @defgroup exceptions Exceptions
237 * eventxx makes a heavy use of exceptions. Each function has it's exceptions
238 * specified, so it's very easy to find out what exceptions to expect.
240 * Exceptions are mostly thrown when there is a programming error. So if you get
241 * an exception check your code.
247 * Base class for all libevent exceptions.
249 struct exception: public std::exception
255 * Invalid event exception.
257 * This exception is thrown when passing an invalid event to a function, the
258 * reason is given in the what() description but it usually means that the you
259 * are making some restricted operation with an active event.
261 * If you hit this exception, you probably got a programming error.
263 struct invalid_event: public std::invalid_argument, public exception
267 * Creates an invalid event exception with a reason.
269 * @param what Reason why the event is invalid).
271 explicit invalid_event(const std::string& what) throw():
272 std::invalid_argument(what)
276 }; // struct invalid_event
280 * Invalid priority exception.
282 * This exception is thrown when passing an invalid priority to a function. This
283 * usually means you don't have enough priority queues in your dispatcher, so
284 * you should have allocated more in the constructor.
286 * If you hit this exception, you probably got a programming error.
288 * @see dispatcher::dispatcher(int) to allocate more priority queues.
290 struct invalid_priority: public std::invalid_argument, public exception
294 * Creates an invalid priority exception with a reason.
296 * @param what Reason why the priority is invalid).
298 explicit invalid_priority(const std::string& what
299 = "invalid priority value") throw():
300 std::invalid_argument(what)
304 }; // struct invalid_priority
309 /// Miscellaneous constants
312 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
313 ONCE = EVLOOP_ONCE, ///< Loop just once.
314 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
318 /// C function used as callback in the C API.
319 typedef void (*ccallback_type)(int, short, void*);
323 * Time used for timeout values.
325 * This timeout is compose of seconds and microseconds.
327 struct time: ::timeval
331 * Creates a new time with @p sec seconds and @p usec microseconds.
333 * @param sec Number of seconds.
334 * @param usec Number of microseconds.
336 time(long sec = 0l, long usec = 0l) throw()
337 { tv_sec = sec; tv_usec = usec; }
340 * Gets the number of seconds.
342 * @return Number of seconds.
344 long sec() const throw() { return tv_sec; };
347 * Gets the number of microseconds.
349 * @return Number of microseconds.
351 long usec() const throw() { return tv_usec; };
354 * Sets the number of seconds.
356 * @param s Number of seconds.
358 void sec(long s) throw() { tv_sec = s; };
361 * Sets the number of microseconds.
363 * @param u Number of microseconds.
365 void usec(long u) throw() { tv_usec = u; };
370 /** @defgroup events Events
372 * There are many ways to specify how to handle an event. You can use use the
373 * same plain functions callbacks (see eventxx::cevent, eventxx::ctimer and
374 * eventxx::csignal) like in C or the other kind of more advanced, stateful
375 * function objects (see eventxx::event, eventxx::timer and eventxx::signal
376 * templates). The former are just typedef'ed specialization of the later.
378 * All events derive from a plain class (not template) eventxx::basic_event, one
379 * of the main utilities of it (besides containing common code ;) is to be used
382 * Please see each class documentation for details and examples.
389 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
390 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
391 * flag, that tells eventxx that this event should live until dispatcher::del()
392 * is called. You can use, for example:
394 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
399 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
400 READ = EV_READ, ///< Read event.
401 WRITE = EV_WRITE, ///< Write event.
402 SIGNAL = EV_SIGNAL, ///< Signal event.
403 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
407 * Basic event from which all events derive.
409 * All events derive from this class, so it's useful for use in containers,
412 * std::list< eventxx::basic_event* > events;
415 struct basic_event: internal::event
419 * Checks if there is an event pending.
421 * @param ev Type of event to check.
423 * @return true if there is a pending event, false if not.
425 bool pending(type ev) const throw()
427 // HACK libevent don't use const
428 return event_pending(const_cast< basic_event* >(this), ev, 0);
432 * Timeout of the event.
434 * @return Timeout of the event.
436 time timeout() const throw()
439 // HACK libevent don't use const
440 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
445 * Sets the event's priority.
447 * @param priority New event priority.
449 * @pre The event must be added to some dispatcher.
451 * @see dispatcher::dispatcher(int)
453 void priority(int priority) const throw(invalid_event, invalid_priority)
455 if (ev_flags & EVLIST_ACTIVE)
456 throw invalid_event("can't change the priority of an "
458 // HACK libevent don't use const
459 if (event_priority_set(const_cast< basic_event* >(this),
461 throw invalid_priority();
465 * Event's file descriptor.
467 * @return Event's file descriptor.
469 int fd() const throw()
471 return EVENT_FD(this);
474 /// @note This is an abstract class, you can't instantiate it.
476 basic_event() throw() {}
477 basic_event(const basic_event&);
478 basic_event& operator= (const basic_event&);
480 }; // struct basic_event
484 * Generic event object.
486 * This object stores all the information about an event, including a callback
487 * functor, which is called when the event is fired. The template parameter
488 * must be a functor (callable object or function) that can take 2 parameters:
489 * an integer (the file descriptor of the fired event) and an event::type (the
490 * type of event being fired).
491 * There is a specialized version of this class which takes as the template
492 * parameter a C function with the ccallback_type signature, just like C
495 * @see eventxx::event< ccallback_type >
497 template < typename F >
498 struct event: basic_event
502 * Creates a new event.
504 * @param fd File descriptor to monitor for events.
505 * @param ev Type of events to monitor (see eventxx::type).
506 * @param handler Callback functor.
508 event(int fd, short ev, F& handler) throw()
510 event_set(this, fd, ev, &wrapper,
511 reinterpret_cast< void* >(&handler));
516 static void wrapper(int fd, short ev, void* h)
518 F& handler = *reinterpret_cast< F* >(h);
519 // Hackish, but this way the handler can get a clean
521 handler(fd, *reinterpret_cast< type* >(&ev));
524 }; // struct event< F >
528 * This is the specialization of eventxx::event for C-style callbacks.
530 * @see eventxx::event
533 struct event< ccallback_type >: basic_event
537 * Creates a new event.
539 * @param fd File descriptor to monitor for events.
540 * @param ev Type of events to monitor (see eventxx::type).
541 * @param handler C-style callback function.
542 * @param arg Arbitrary pointer to pass to the handler as argument.
544 event(int fd, short ev, ccallback_type handler, void* arg) throw()
546 event_set(this, fd, ev, handler, arg);
552 }; // struct event< ccallback_type >
556 * Timer event object.
558 * This is just a special case of event that is fired only when a timeout is
559 * reached. It's just a shortcut to:
561 * event(-1, 0, handler);
564 * @note This event can't eventxx::PERSIST.
565 * @see timer< ccallback_type >
567 template < typename F >
568 struct timer: event< F >
572 * Creates a new timer event.
574 * @param handler Callback functor.
576 timer(F& handler) throw()
578 evtimer_set(this, &event< F >::wrapper,
579 reinterpret_cast< void* >(&handler));
582 }; // struct timer< F >
586 * This is the specialization of eventxx::timer for C-style callbacks.
588 * @note This event can't eventxx::PERSIST.
592 struct timer< ccallback_type >: event< ccallback_type >
596 * Creates a new timer event.
598 * @param handler C-style callback function.
599 * @param arg Arbitrary pointer to pass to the handler as argument.
601 timer(ccallback_type handler, void* arg) throw()
603 evtimer_set(this, handler, arg);
606 }; // struct timer< ccallback_type >
610 * Signal event object.
612 * This is just a special case of event that is fired when a signal is raised
613 * (instead of a file descriptor being active). It's just a shortcut to:
615 * event(signum, eventxx::SIGNAL, handler);
618 * @note This event always eventxx::PERSIST.
619 * @see signal< ccallback_type >
621 template < typename F >
622 struct signal: event< F >
626 * Creates a new signal event.
628 * @param signum Signal number to monitor.
629 * @param handler Callback functor.
631 signal(int signum, F& handler) throw()
633 signal_set(this, signum, &event< F >::wrapper,
634 reinterpret_cast< void* >(&handler));
638 * Event's signal number.
640 * @return Event's signal number.
644 return EVENT_SIGNAL(this);
647 }; // struct signal<F>
651 * This is the specialization of eventxx::signal for C-style callbacks.
653 * @note This event always eventxx::PERSIST.
657 struct signal< ccallback_type >: event< ccallback_type >
661 * Creates a new signal event.
663 * @param signum Signal number to monitor.
664 * @param handler C-style callback function.
665 * @param arg Arbitrary pointer to pass to the handler as argument.
667 signal(int signum, ccallback_type handler, void* arg) throw()
669 signal_set(this, signum, handler, arg);
673 * Event's signal number.
675 * @return Event's signal number.
679 return EVENT_SIGNAL(this);
682 }; // struct signal< ccallback_type >
685 /// Shortcut to C-style event.
686 typedef eventxx::event< ccallback_type > cevent;
688 /// Shortcut to C-style timer.
689 typedef eventxx::timer< ccallback_type > ctimer;
691 /// Shortcut to C-style signal handler.
692 typedef eventxx::signal< ccallback_type > csignal;
701 * This class is the responsible for looping and dispatching events. Every time
702 * you need an event loop you should create an instance of this class.
704 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
705 * can @link dispatcher::del remove @endlink them later or you can @link
706 * dispatcher::add_once add events to be processed just once @endlink. You can
707 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
708 * can break that forever removing all the events or by @link dispatcher::exit
709 * exiting the loop @endlink).
715 * Creates a default dispatcher (with just 1 priority).
717 * @see dispatcher(int) if you want to create a dispatcher with more
722 _event_base = static_cast< internal::event_base* >(internal::event_init());
726 * Creates a dispatcher with npriorities priorities.
728 * @param npriorities Number of priority queues to use.
730 dispatcher(int npriorities) throw(std::bad_alloc)
732 _event_base = static_cast< internal::event_base* >(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 ~dispatcher() throw() { event_base_free(_event_base); }
741 #warning "The dispatcher class *will* leak memory because of a libevent bug, see http://www.mail-archive.com/libevent-users@monkey.org/msg00110.html for more info an a patch. If you already have this patch, please -DEVENT_BASE_FREE_FIX to your compiler to make this message disappear and really free the dispatcher memory using event_base_free()."
745 * Adds an event to the dispatcher.
747 * @param e Event to add.
748 * @param priority Priority of the event.
750 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
751 throw(invalid_priority)
753 internal::event_base_set(_event_base, &e);
754 if (priority != DEFAULT_PRIORITY
755 && internal::event_priority_set(&e, priority))
756 throw invalid_priority();
757 internal::event_add(&e, 0);
761 * Adds an event to the dispatcher with a timeout.
763 * The event is fired when there is activity on e or when to has elapsed,
764 * whatever come first.
766 * @param e Event to add.
768 * @param priority Priority of the event.
770 void add(basic_event& e, const time& to,
771 int priority = DEFAULT_PRIORITY)
772 throw(invalid_priority)
774 internal::event_base_set(_event_base, &e);
775 if (priority != DEFAULT_PRIORITY
776 && internal::event_priority_set(&e, priority))
777 throw invalid_priority();
778 internal::event_add(&e, const_cast< time* >(&to)); // XXX HACK libevent don't use const
782 * Adds a temporary event.
784 * Adds a temporary event, without the need of instantiating a new event
785 * object. Events added this way can't eventxx::PERSIST.
787 * @param fd File descriptor to monitor for events.
788 * @param ev Type of events to monitor.
789 * @param handler Callback function.
791 template < typename F >
792 void add_once(int fd, type ev, F& handler)
794 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
795 reinterpret_cast< void* >(&handler), 0);
799 * Adds a temporary event to with a C-style callback.
801 * Adds a temporary event, without the need of instantiating a new event
802 * object. Events added this way can't eventxx::PERSIST.
804 * @param fd File descriptor to monitor for events.
805 * @param ev Type of events to monitor.
806 * @param handler Callback function.
807 * @param arg Arbitrary pointer to pass to the handler as argument.
809 void add_once(int fd, type ev, ccallback_type handler, void* arg)
811 internal::event_once(fd, ev, handler, arg, 0);
815 * Adds a temporary event.
817 * Adds a temporary event, without the need of instantiating a new event
818 * object. Events added this way can't eventxx::PERSIST.
820 * @param fd File descriptor to monitor for events.
821 * @param ev Type of events to monitor.
822 * @param handler Callback function.
825 template < typename F >
826 void add_once(int fd, type ev, F& handler, const time& to)
828 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
829 reinterpret_cast< void* >(&handler),
830 const_cast< time* >(&to)); // XXX HACK libevent don't use const
834 * Adds a temporary event with a C-style callback.
836 * Adds a temporary event, without the need of instantiating a new event
837 * object. Events added this way can't eventxx::PERSIST.
839 * @param fd File descriptor to monitor for events.
840 * @param ev Type of events to monitor.
841 * @param handler Callback function.
842 * @param arg Arbitrary pointer to pass to the handler as argument.
845 void add_once(int fd, type ev, ccallback_type handler, void* arg, const time& to)
847 internal::event_once(fd, ev, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
851 * Adds a temporary timer.
853 * Adds a temporary timer, without the need of instantiating a new timer
856 * @param handler Callback function.
857 * @param to Timer's timeout.
859 template < typename F >
860 void add_once_timer(F& handler, const time& to)
862 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
863 reinterpret_cast< void* >(&handler),
864 const_cast< time* >(&to)); // XXX HACK libevent don't use const
868 * Adds a temporary timer with a C-style callback.
870 * Adds a temporary timer, without the need of instantiating a new timer
873 * @param handler Callback function.
874 * @param arg Arbitrary pointer to pass to the handler as argument.
875 * @param to Timer's timeout.
877 void add_once_timer(ccallback_type handler, void* arg, const time& to)
879 internal::event_once(-1, EV_TIMEOUT, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
885 * The event e will be no longer monitored by this dispatcher.
887 * @param e Event to remove.
889 void del(basic_event& e) throw()
891 internal::event_del(&e);
895 * Main dispatcher loop.
897 * This function takes the control of the program, waiting for an event
898 * and calling its callbacks when it's fired. It only returns under
900 * - exit() was called.
901 * - All events were del()eted.
902 * - Another internal error.
903 * - eventxx::ONCE flag was set.
904 * - eventxx::NONBLOCK flag was set.
906 * @param flags If eventxx::ONCE is specified, then just one event is
907 * processed, if eventxx::NONBLOCK is specified, then this
908 * function returns even if there are no pending events.
910 int dispatch(int flags = 0) // TODO throw(exception)
912 return internal::event_base_loop(_event_base, flags);
916 * Exit the dispatch() loop.
918 * @param to If a timeout is given, the loop exits after the specified
921 int exit(const time& to = time())
923 // XXX HACK libevent don't use const
924 return internal::event_base_loopexit(_event_base,
925 const_cast< time* >(&to));
929 internal::event_base* _event_base;
930 template < typename F >
931 static void wrapper(int fd, type ev, void* h)
933 F& handler = *reinterpret_cast< F* >(h);
934 handler(fd, *reinterpret_cast< type* >(&ev));
937 }; // struct dispatcher
942 #endif // _EVENTXX_HPP_
944 // vim: set filetype=cpp :