* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef EVENT2_EVENT_H_INCLUDED_
#define EVENT2_EVENT_H_INCLUDED_
@section intro Introduction
Libevent is an event notification library for developing scalable network
servers. The Libevent API provides a mechanism to execute a callback
function when a specific event occurs on a file descriptor or after a
timeout has been reached. Furthermore, Libevent also support callbacks due
to signals or regular timeouts.
Libevent is meant to replace the event loop found in event driven network
servers. An application just needs to call event_base_dispatch() and then add or
remove events dynamically without having to change the event loop.
Currently, Libevent supports /dev/poll, kqueue(2), select(2), poll(2),
epoll(4), and evports. The internal event mechanism is completely
independent of the exposed event API, and a simple update of Libevent can
provide new functionality without having to redesign the applications. As a
result, Libevent allows for portable application development and provides
the most scalable event notification mechanism available on an operating
system. Libevent can also be used for multithreaded programs. Libevent
should compile on Linux, *BSD, Mac OS X, Solaris and, Windows.
@section usage Standard usage
Every program that uses Libevent must include the <event2/event.h>
header, and pass the -levent flag to the linker. (You can instead link
-levent_core if you only want the main event and buffered IO-based code,
and don't want to link any protocol code.)
@section setup Library setup
Before you call any other Libevent functions, you need to set up the
library. If you're going to use Libevent from multiple threads in a
multithreaded application, you need to initialize thread support --
typically by using evthread_use_pthreads() or
evthread_use_windows_threads(). See <event2/thread.h> for more
This is also the point where you can replace Libevent's memory
management functions with event_set_mem_functions, and enable debug mode
with event_enable_debug_mode().
@section base Creating an event base
Next, you need to create an event_base structure, using event_base_new()
or event_base_new_with_config(). The event_base is responsible for
keeping track of which events are "pending" (that is to say, being
watched to see if they become active) and which events are "active".
Every event is associated with a single event_base.
@section event Event notification
For each file descriptor that you wish to monitor, you must create an
event structure with event_new(). (You may also declare an event
structure and call event_assign() to initialize the members of the
structure.) To enable notification, you add the structure to the list
of monitored events by calling event_add(). The event structure must
remain allocated as long as it is active, so it should generally be
@section loop Dispatching events.
Finally, you call event_base_dispatch() to loop and dispatch events.
You can also use event_base_loop() for more fine-grained control.
Currently, only one thread can be dispatching a given event_base at a
time. If you want to run events in multiple threads at once, you can
either have a single event_base whose events add work to a work queue,
or you can create multiple event_base objects.
@section bufferevent I/O Buffers
Libevent provides a buffered I/O abstraction on top of the regular event
callbacks. This abstraction is called a bufferevent. A bufferevent
provides input and output buffers that get filled and drained
automatically. The user of a buffered event no longer deals directly
with the I/O, but instead is reading from input and writing to output
Once initialized via bufferevent_socket_new(), the bufferevent structure
can be used repeatedly with bufferevent_enable() and
bufferevent_disable(). Instead of reading and writing directly to a
socket, you would call bufferevent_read() and bufferevent_write().
When read enabled the bufferevent will try to read from the file descriptor
and call the read callback. The write callback is executed whenever the
output buffer is drained below the write low watermark, which is 0 by
See <event2/bufferevent*.h> for more information.
Libevent can also be used to create timers that invoke a callback after a
certain amount of time has expired. The evtimer_new() macro returns
an event struct to use as a timer. To activate the timer, call
evtimer_add(). Timers can be deactivated by calling evtimer_del().
(These macros are thin wrappers around event_new(), event_add(),
and event_del(); you can also use those instead.)
@section evdns Asynchronous DNS resolution
Libevent provides an asynchronous DNS resolver that should be used instead
of the standard DNS resolver functions. See the <event2/dns.h>
functions for more detail.
@section evhttp Event-driven HTTP servers
Libevent provides a very simple event-driven HTTP server that can be
embedded in your program and used to service HTTP requests.
To use this capability, you need to include the <event2/http.h> header in your
program. See that header for more information.
@section evrpc A framework for RPC servers and clients
Libevent provides a framework for creating RPC servers and clients. It
takes care of marshaling and unmarshaling all data structures.
@section api API Reference
To browse the complete documentation of the libevent API, click on any of
The primary libevent header
Functions for use by multithreaded programs
event2/buffer.h and event2/bufferevent.h
Buffer management for network reading and writing
Utility functions for portable nonblocking network code
Asynchronous DNS resolution
An embedded libevent-based HTTP server
A framework for creating RPC servers and clients
Core functions for waiting for and receiving events, and using event bases.
#include <event2/visibility.h>
#include <event2/event-config.h>
#ifdef EVENT__HAVE_SYS_TYPES_H
#ifdef EVENT__HAVE_SYS_TIME_H
* Structure to hold information and state for a Libevent dispatch loop.
* The event_base lies at the center of Libevent; every application will
* have one. It keeps track of all pending and active events, and
* notifies your application of the active ones.
* This is an opaque structure; you can allocate one using
* event_base_new() or event_base_new_with_config().
* @see event_base_new(), event_base_free(), event_base_loop(),
* event_base_new_with_config()
{/*Empty body so that doxygen will generate documentation here.*/}
* Structure to represent a single event.
* An event can have some underlying condition it represents: a socket
* becoming readable or writeable (or both), or a signal becoming raised.
* (An event that represents no underlying condition is still useful: you
* can use one to implement a timer, or to communicate between threads.)
* Generally, you can create events with event_new(), then make them
* pending with event_add(). As your event_base runs, it will run the
* callbacks of an events whose conditions are triggered. When you
* longer want the event, free it with event_free().
* An event may be "pending" (one whose condition we are watching),
* "active" (one whose condition has triggered and whose callback is about
* to run), neither, or both. Events come into existence via
* event_assign() or event_new(), and are then neither active nor pending.
* To make an event pending, pass it to event_add(). When doing so, you
* can also set a timeout for the event.
* Events become active during an event_base_loop() call when either their
* condition has triggered, or when their timeout has elapsed. You can
* also activate an event manually using event_active(). The even_base
* loop will run the callbacks of active events; after it has done so, it
* marks them as no longer active.
* You can make an event non-pending by passing it to event_del(). This
* also makes the event non-active.
* Events can be "persistent" or "non-persistent". A non-persistent event
* becomes non-pending as soon as it is triggered: thus, it only runs at
* most once per call to event_add(). A persistent event remains pending
* even when it becomes active: you'll need to event_del() it manually in
* order to make it non-pending. When a persistent event with a timeout
* becomes active, its timeout is reset: this means you can use persistent
* events to implement periodic timeouts.
* This should be treated as an opaque structure; you should never read or
* write any of its fields directly. For backward compatibility with old
* code, it is defined in the event2/event_struct.h header; including this
* header may make your code incompatible with other versions of Libevent.
* @see event_new(), event_free(), event_assign(), event_get_assignment(),
* event_add(), event_del(), event_active(), event_pending(),
* event_get_fd(), event_get_base(), event_get_events(),
* event_get_callback(), event_get_callback_arg(),
{/*Empty body so that doxygen will generate documentation here.*/}
* Configuration for an event_base.
* There are many options that can be used to alter the behavior and
* implementation of an event_base. To avoid having to pass them all in a
* complex many-argument constructor, we provide an abstract data type
* wrhere you set up configation information before passing it to
* event_base_new_with_config().
* @see event_config_new(), event_config_free(), event_base_new_with_config(),
* event_config_avoid_method(), event_config_require_features(),
* event_config_set_flag(), event_config_set_num_cpus_hint()
{/*Empty body so that doxygen will generate documentation here.*/}
* Enable some relatively expensive debugging checks in Libevent that
* would normally be turned off. Generally, these checks cause code that
* would otherwise crash mysteriously to fail earlier with an assertion
* failure. Note that this method MUST be called before any events or
* event_bases have been created.
* Debug mode can currently catch the following errors:
* An event is re-assigned while it is added
* Any function is called on a non-assigned event
* Note that debugging mode uses memory to track every event that has been
* initialized (via event_assign, event_set, or event_new) but not yet
* released (via event_free or event_debug_unassign). If you want to use
* debug mode, and you find yourself running out of memory, you will need
* to use event_debug_unassign to explicitly stop tracking events that
* are no longer considered set-up.
* @see event_debug_unassign()
void event_enable_debug_mode(void);
* When debugging mode is enabled, informs Libevent that an event should no
* longer be considered as assigned. When debugging mode is not enabled, does
* This function must only be called on a non-added event.
* @see event_enable_debug_mode()
void event_debug_unassign(struct event *);
* Create and return a new event_base to use with the rest of Libevent.
* @return a new event_base on success, or NULL on failure.
* @see event_base_free(), event_base_new_with_config()
struct event_base *event_base_new(void);
Reinitialize the event base after a fork
Some event mechanisms do not survive across fork. The event base needs
to be reinitialized with the event_reinit() function.
@param base the event base that needs to be re-initialized
@return 0 if successful, or -1 if some events could not be re-added.
int event_reinit(struct event_base *base);
This loop will run the event base until either there are no more pending or
active, or until something calls event_base_loopbreak() or
@param base the event_base structure returned by event_base_new() or
event_base_new_with_config()
@return 0 if successful, -1 if an error occurred, or 1 if we exited because
no events were pending or active.
int event_base_dispatch(struct event_base *);
Get the kernel event notification mechanism used by Libevent.
@param eb the event_base structure returned by event_base_new()
@return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
const char *event_base_get_method(const struct event_base *);
Gets all event notification mechanisms supported by Libevent.
This functions returns the event mechanism in order preferred by
Libevent. Note that this list will include all backends that
Libevent has compiled-in support for, and will not necessarily check
your OS to see whether it has the required resources.
@return an array with pointers to the names of support methods.
The end of the array is indicated by a NULL pointer. If an
error is encountered NULL is returned.
const char **event_get_supported_methods(void);
/** Query the current monotonic time from a the timer for a struct
int event_gettime_monotonic(struct event_base *base, struct timeval *tp);
Flags to pass to event_base_get_num_events() to specify the kinds of events
we want to aggregate counts for
/** count the number of active events, which have been triggered.*/
#define EVENT_BASE_COUNT_ACTIVE 1U
/** count the number of virtual events, which is used to represent an internal
* condition, other than a pending event, that keeps the loop from exiting. */
#define EVENT_BASE_COUNT_VIRTUAL 2U
/** count the number of events which have been added to event base, including
#define EVENT_BASE_COUNT_ADDED 4U
Gets the number of events in event_base, as specified in the flags.
Since event base has some internal events added to make some of its
functionalities work, EVENT_BASE_COUNT_ADDED may return more than the
number of events you added using event_add().
If you pass EVENT_BASE_COUNT_ACTIVE and EVENT_BASE_COUNT_ADDED together, an
active event will be counted twice. However, this might not be the case in
future libevent versions. The return value is an indication of the work
load, but the user shouldn't rely on the exact value as this may change in
@param eb the event_base structure returned by event_base_new()
@param flags a bitwise combination of the kinds of events to aggregate
@return the number of events specified in the flags
int event_base_get_num_events(struct event_base *, unsigned int);
Get the maximum number of events in a given event_base as specified in the
@param eb the event_base structure returned by event_base_new()
@param flags a bitwise combination of the kinds of events to aggregate
@param clear option used to reset the maximum count.
@return the number of events specified in the flags
int event_base_get_max_events(struct event_base *, unsigned int, int);
Allocates a new event configuration object.
The event configuration object can be used to change the behavior of
@return an event_config object that can be used to store configuration, or
NULL if an error is encountered.
@see event_base_new_with_config(), event_config_free(), event_config
struct event_config *event_config_new(void);
Deallocates all memory associated with an event configuration object
@param cfg the event configuration object to be freed.
void event_config_free(struct event_config *cfg);
Enters an event method that should be avoided into the configuration.
This can be used to avoid event mechanisms that do not support certain
file descriptor types, or for debugging to avoid certain event
mechanisms. An application can make use of multiple event bases to
accommodate incompatible file descriptor types.
@param cfg the event configuration object
@param method the name of the event method to avoid
@return 0 on success, -1 on failure.
int event_config_avoid_method(struct event_config *cfg, const char *method);
A flag used to describe which features an event_base (must) provide.
Because of OS limitations, not every Libevent backend supports every
possible feature. You can use this type with
event_config_require_features() to tell Libevent to only proceed if your
event_base implements a given feature, and you can receive this type from
event_base_get_features() to see which features are available.