Created
March 12, 2015 09:12
-
-
Save aero/bb135b42e266ea57500e to your computer and use it in GitHub Desktop.
Example: Integrating readline with libev eventloop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
printf("\nNULLBURGER\n"); | |
} else { | |
if (*line!=0) { | |
// If line wasn't empty, store it so that uparrow retrieves it | |
add_history(line); | |
} | |
printf("Your input was:\n%s\n", line); | |
free(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) { | |
rl_callback_read_char(); | |
} | |
} | |
ev_timer timeout_watcher; | |
static void timeout_cb(EV_P_ struct ev_timer* w, int revents) | |
{ | |
puts("."); | |
} | |
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); | |
rl_callback_handler_remove(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment