Skip to content

Instantly share code, notes, and snippets.



Created Mar 12, 2015
What would you like to do?
Example: Integrating readline with libev eventloop.
// g++ -o readline_ev -g readline_ev.cpp -g -lreadline -lev
#include <stdlib.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <ev.h>
#include <fcntl.h>
// The function that'll get passed each line of input
void my_rlhandler(char* line) {
if (line==NULL) {
// Ctrl-D will allow us to exit nicely
} else {
if (*line!=0) {
// If line wasn't empty, store it so that uparrow retrieves it
printf("Your input was:\n%s\n", line);
// all watcher callbacks have a similar signature
// this callback is called when data is readable on stdin
static void stdin_cb(EV_P_ ev_io *w, int revents)
if (revents & EV_READ) {
ev_timer timeout_watcher;
static void timeout_cb(EV_P_ struct ev_timer* w, int revents)
int main(int argc, char **argv)
fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
const char *prompt = "WOOP> ";
// Install the handler
rl_callback_handler_install(prompt, (rl_vcpfunc_t*) &my_rlhandler);
// setup libev
struct ev_loop *loop = EV_DEFAULT;
ev_io stdin_watcher;
ev_io_init(&stdin_watcher, stdin_cb, fileno(stdin), EV_READ);
// initialize an timer watcher
// the timeout event will occur after 1sec, and repeat every 2sec
ev_timer_init(&timeout_watcher, timeout_cb, 1, 2);
ev_timer_start(loop, &timeout_watcher);
ev_io_start(loop, &stdin_watcher);
// start libev
ev_loop(loop, 0);
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment