4 #include <sys/types.h> // timeval (hack -> event.h don't include it)
5 #include <stdexcept> // std::exception, std::invalid_argument,
6 // std::runtime_error, std::bad_alloc
10 * @section Introduction
12 * The libevent API provides a mechanism to execute a callback function when a
13 * specific event occurs on a file descriptor or after a timeout has been
14 * reached. Furthermore, libevent also support callbacks due to signals or
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.
31 * It's designed to be as close to use to libevent without compromising modern
32 * C++ programming techniques and efficiency (since all implementation is
33 * trivial and inline, theoretically, it imposes no overhead at all).
38 * The best way to explain how this works is by examples. TODO
40 * @author Leandro Lucarella <llucarella@integratech.com.ar>
43 * This program is under the BOLA license (see
44 * http://auriga.wearlab.de/~alb/bola/)
50 * Namespace for all symbols libevent C++ wrapper defines.
56 // All libevent C API symbols and other internal stuff goes here.
63 /// @defgroup exceptions Exceptions
68 * Base class for all libevent exceptions.
70 struct exception: public std::exception
76 * Invalid event exception.
78 * This exception is thrown when passing an invalid event to a function, the
79 * reason is given in the what() description but it usually means that the you
80 * are making some restricted operation with an active event.
82 * If you hit this exception, you probably got a programming error.
84 struct invalid_event: public std::invalid_argument, public exception
88 * Creates an invalid event exception with a reason.
90 * @param what Reason why the event is invalid).
92 explicit invalid_event(const std::string& what) throw():
93 std::invalid_argument(what)
97 }; // struct invalid_event
101 * Invalid priority exception.
103 * This exception is thrown when passing an invalid priority to a function. This
104 * usually means you don't have enought priority queues in your dispatcher, so
105 * you should have allocated more in the constructor.
107 * If you hit this exception, you probably got a programming error.
109 * @see dispatcher::dispatcher(int) to allocate more priority queues.
111 struct invalid_priority: public std::invalid_argument, public exception
115 * Creates an invalid priority exception with a reason.
117 * @param what Reason why the priority is invalid).
119 explicit invalid_priority(const std::string& what
120 = "invalid priority value") throw():
121 std::invalid_argument(what)
125 }; // struct invalid_priority
130 /// Miscelaneous constants
133 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
134 ONCE = EVLOOP_ONCE, ///< Loop just once.
135 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
139 /// C function used as callback in the C API.
140 typedef void (*ccallback_type)(int, short, void*);
144 * Time used for timeout values.
146 * This timeout is compose of seconds and microseconds.
148 struct time: ::timeval
152 * Creates a new time with @p sec seconds and @p usec microseconds.
154 * @param sec Number of seconds.
155 * @param usec Number of microseconds.
157 time(long sec = 0l, long usec = 0l) throw()
158 { tv_sec = sec; tv_usec = usec; }
161 * Gets the number of seconds.
163 * @return Number of seconds.
165 long sec() const throw() { return tv_sec; };
168 * Gets the number of microseconds.
170 * @return Number of microseconds.
172 long usec() const throw() { return tv_usec; };
175 * Sets the number of seconds.
177 * @param s Number of seconds.
179 void sec(long s) throw() { tv_sec = s; };
182 * Sets the number of microseconds.
184 * @param u Number of microseconds.
186 void usec(long u) throw() { tv_usec = u; };
191 /// @defgroup events Events
197 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
198 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
199 * flag, that tells eventxx that this event should live until dispatcher::del()
200 * is called. You can use, for example:
202 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
207 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
208 READ = EV_READ, ///< Read event.
209 WRITE = EV_WRITE, ///< Write event.
210 SIGNAL = EV_SIGNAL, ///< Signal event.
211 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
215 * Basic event from which all events derive.
217 * All events derive from this class, so it's useful for use in containers,
220 * std::list< eventxx::basic_event* > events;
223 struct basic_event: internal::event
227 * Checks if there is an event pending.
229 * @param ev Type of event to check.
231 * @return true if there is a pending event, false if not.
233 bool pending(type ev) const throw()
235 // HACK libevent don't use const
236 return event_pending(const_cast< basic_event* >(this), ev, 0);
240 * Timeout of the event.
242 * @return Timeout of the event.
244 time timeout() const throw()
247 // HACK libevent don't use const
248 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
253 * Sets the event's priority.
255 * @param priority New event priority.
257 * @pre The event must be added to some dispatcher.
259 * @see dispatcher::dispatcher(int)
261 void priority(int priority) const throw(invalid_event, invalid_priority)
263 if (ev_flags & EVLIST_ACTIVE)
264 throw invalid_event("can't change the priority of an "
266 // HACK libevent don't use const
267 if (event_priority_set(const_cast< basic_event* >(this),
269 throw invalid_priority();
273 * Event's file descriptor.
275 * @return Event's file descriptor.
277 int fd() const throw()
279 return EVENT_FD(this);
282 /// @note This is an abstract class, you can't instantiate it.
284 basic_event() throw() {}
285 basic_event(const basic_event&);
286 basic_event& operator= (const basic_event&);
288 }; // struct basic_event
292 * Generic event object.
294 * This object stores all the information about an event, incluiding a callback
295 * functor, which is called when the event is fired. The template parameter
296 * must be a functor (callable object or function) that can take 2 parameters:
297 * an integer (the file descriptor of the fired event) and an event::type (the
298 * type of event being fired).
299 * There is a specialized version of this class which takes as the template
300 * parameter a C function with the ccallback_type signature, just like C
303 * @see eventxx::event< ccallback_type >
305 template < typename F >
306 struct event: basic_event
310 * Creates a new event.
312 * @param fd File descriptor to monitor for events.
313 * @param ev Type of events to monitor (see eventxx::type).
314 * @param handler Callback functor.
316 event(int fd, short ev, F& handler) throw()
318 event_set(this, fd, ev, &wrapper,
319 reinterpret_cast< void* >(&handler));
324 static void wrapper(int fd, short ev, void* h)
326 F& handler = *reinterpret_cast< F* >(h);
327 // Hackish, but this way the handler can get a clean
329 handler(fd, *reinterpret_cast< type* >(&ev));
332 }; // struct event< F >
336 * This is the specialization of eventxx::event for C-style callbacks.
338 * @see eventxx::event
341 struct event< ccallback_type >: basic_event
345 * Creates a new event.
347 * @param fd File descriptor to monitor for events.
348 * @param ev Type of events to monitor (see eventxx::type).
349 * @param handler C-style callback function.
350 * @param arg Arbitrary pointer to pass to the handler as argument.
352 event(int fd, short ev, ccallback_type handler, void* arg) throw()
354 event_set(this, fd, ev, handler, arg);
360 }; // struct event< ccallback_type >
364 * Timer event object.
366 * This is just a special case of event that is fired only when a timeout is
367 * reached. It's just a shortcut to:
369 * event(-1, 0, handler);
372 * @note This event can't eventxx::PERSIST.
373 * @see timer< ccallback_type >
375 template < typename F >
376 struct timer: event< F >
380 * Creates a new timer event.
382 * @param handler Callback functor.
384 timer(F& handler) throw()
386 evtimer_set(this, &event< F >::wrapper,
387 reinterpret_cast< void* >(&handler));
390 }; // struct timer< F >
394 * This is the specialization of eventxx::timer for C-style callbacks.
396 * @note This event can't eventxx::PERSIST.
400 struct timer< ccallback_type >: event< ccallback_type >
404 * Creates a new timer event.
406 * @param handler C-style callback function.
407 * @param arg Arbitrary pointer to pass to the handler as argument.
409 timer(ccallback_type handler, void* arg) throw()
411 evtimer_set(this, handler, arg);
414 }; // struct timer< ccallback_type >
418 * Signal event object.
420 * This is just a special case of event that is fired when a signal is raised
421 * (instead of a file descriptor being active). It's just a shortcut to:
423 * event(signum, eventxx::SIGNAL, handler);
426 * @note This event always eventxx::PERSIST.
427 * @see signal< ccallback_type >
429 template < typename F >
430 struct signal: event< F >
434 * Creates a new singal event.
436 * @param signum Signal number to monitor.
437 * @param handler Callback functor.
439 signal(int signum, F& handler) throw()
441 signal_set(this, signum, &event< F >::wrapper,
442 reinterpret_cast< void* >(&handler));
446 * Event's signal number.
448 * @return Event's signal number.
452 return EVENT_SIGNAL(this);
455 }; // struct signal<F>
459 * This is the specialization of eventxx::signal for C-style callbacks.
461 * @note This event always eventxx::PERSIST.
465 struct signal< ccallback_type >: event< ccallback_type >
469 * Creates a new signal event.
471 * @param signum Signal number to monitor.
472 * @param handler C-style callback function.
473 * @param arg Arbitrary pointer to pass to the handler as argument.
475 signal(int signum, ccallback_type handler, void* arg) throw()
477 signal_set(this, signum, handler, arg);
481 * Event's signal number.
483 * @return Event's signal number.
487 return EVENT_SIGNAL(this);
490 }; // struct signal< ccallback_type >
493 /// Shortcut to C-style event.
494 typedef eventxx::event< ccallback_type > cevent;
496 /// Shortcut to C-style timer.
497 typedef eventxx::timer< ccallback_type > ctimer;
499 /// Shortcut to C-style signal handler.
500 typedef eventxx::signal< ccallback_type > csignal;
509 * This class is the responsable for looping and dispatching events.
515 * Creates a default dispatcher (with just 1 priority).
517 * @see dispatcher(int) if you want to create a dispatcher with more
522 _event_base = static_cast< internal::event_base* >(internal::event_init());
526 * Creates a dispatcher with npriorities priorities.
528 * @param npriorities Number of priority queues to use.
530 dispatcher(int npriorities) throw(std::bad_alloc)
532 _event_base = static_cast< internal::event_base* >(internal::event_init());
533 if (!_event_base) throw std::bad_alloc();
534 // Can't fail because there is no way that it has active events
535 internal::event_base_priority_init(_event_base, npriorities);
538 #ifdef EVENT_BASE_FREE_FIX
539 ~dispatcher() throw() { event_base_free(_event_base); }
541 #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()."
545 * Adds an event to the dispatcher.
547 * @param e Event to add.
548 * @param priority Priority of the event.
550 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
551 throw(invalid_priority)
553 internal::event_base_set(_event_base, &e);
554 if (priority != DEFAULT_PRIORITY
555 && internal::event_priority_set(&e, priority))
556 throw invalid_priority();
557 internal::event_add(&e, 0);
561 * Adds an event to the dispatcher with a timeout.
563 * The event is fired when there is activity on e or when to has elapsed,
564 * whatever come first.
566 * @param e Event to add.
568 * @param priority Priority of the event.
570 void add(basic_event& e, const time& to,
571 int priority = DEFAULT_PRIORITY)
572 throw(invalid_priority)
574 internal::event_base_set(_event_base, &e);
575 if (priority != DEFAULT_PRIORITY
576 && internal::event_priority_set(&e, priority))
577 throw invalid_priority();
578 internal::event_add(&e, const_cast< time* >(&to)); // XXX HACK libevent don't use const
582 * Adds a temporary event.
584 * Adds a temporary event, without the need of instantiating a new event
585 * object. Events added this way can't eventxx::PERSIST.
587 * @param fd File descriptor to monitor for events.
588 * @param ev Type of events to monitor.
589 * @param handler Callback function.
591 template < typename F >
592 void add_once(int fd, type ev, F& handler)
594 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
595 reinterpret_cast< void* >(&handler), 0);
599 * Adds a temporary event to with a C-style callback.
601 * Adds a temporary event, without the need of instantiating a new event
602 * object. Events added this way can't eventxx::PERSIST.
604 * @param fd File descriptor to monitor for events.
605 * @param ev Type of events to monitor.
606 * @param handler Callback function.
607 * @param arg Arbitrary pointer to pass to the handler as argument.
609 void add_once(int fd, type ev, ccallback_type handler, void* arg)
611 internal::event_once(fd, ev, handler, arg, 0);
615 * Adds a temporary event.
617 * Adds a temporary event, without the need of instantiating a new event
618 * object. Events added this way can't eventxx::PERSIST.
620 * @param fd File descriptor to monitor for events.
621 * @param ev Type of events to monitor.
622 * @param handler Callback function.
625 template < typename F >
626 void add_once(int fd, type ev, F& handler, const time& to)
628 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
629 reinterpret_cast< void* >(&handler),
630 const_cast< time* >(&to)); // XXX HACK libevent don't use const
634 * Adds a temporary event with a C-style callback.
636 * Adds a temporary event, without the need of instantiating a new event
637 * object. Events added this way can't eventxx::PERSIST.
639 * @param fd File descriptor to monitor for events.
640 * @param ev Type of events to monitor.
641 * @param handler Callback function.
642 * @param arg Arbitrary pointer to pass to the handler as argument.
645 void add_once(int fd, type ev, ccallback_type handler, void* arg, const time& to)
647 internal::event_once(fd, ev, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
651 * Adds a temporary timer.
653 * Adds a temporary timer, without the need of instantiating a new timer
656 * @param handler Callback function.
657 * @param to Timer's timeout.
659 template < typename F >
660 void add_once_timer(F& handler, const time& to)
662 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
663 reinterpret_cast< void* >(&handler),
664 const_cast< time* >(&to)); // XXX HACK libevent don't use const
668 * Adds a temporary timer with a C-style callback.
670 * Adds a temporary timer, without the need of instantiating a new timer
673 * @param handler Callback function.
674 * @param arg Arbitrary pointer to pass to the handler as argument.
675 * @param to Timer's timeout.
677 void add_once_timer(ccallback_type handler, void* arg, const time& to)
679 internal::event_once(-1, EV_TIMEOUT, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
685 * The event e will be no longer monitored by this dispatcher.
687 * @param e Event to remove.
689 void del(basic_event& e) throw()
691 internal::event_del(&e);
695 * Main dispatcher loop.
697 * This function takes the control of the program, waiting for an event
698 * and calling its callbacks when it's fired. It only returns under
700 * - exit() was called.
701 * - All events were del()eted.
702 * - Another internal error.
703 * - eventxx::ONCE flag was set.
704 * - eventxx::NONBLOCK flag was set.
706 * @param flags If eventxx::ONCE is specified, then just one event is
707 * processed, if eventxx::NONBLOCK is specified, then this
708 * function returns even if there are no pending events.
710 int dispatch(int flags = 0) // TODO throw(exception)
712 return internal::event_base_loop(_event_base, flags);
716 * Exit the dispatch() loop.
718 * @param to If a timeout is given, the loop exits after the specified
721 int exit(const time& to = time())
723 // XXX HACK libevent don't use const
724 return internal::event_base_loopexit(_event_base,
725 const_cast< time* >(&to));
729 internal::event_base* _event_base;
730 template < typename F >
731 static void wrapper(int fd, type ev, void* h)
733 F& handler = *reinterpret_cast< F* >(h);
734 handler(fd, *reinterpret_cast< type* >(&ev));
737 }; // struct dispatcher
742 #endif // _EVENTXX_HPP_
744 // vim: set filetype=cpp :