Skip to content

Instantly share code, notes, and snippets.

@mlc
Created December 6, 2012 07:46
Show Gist options
  • Save mlc/4222605 to your computer and use it in GitHub Desktop.
Save mlc/4222605 to your computer and use it in GitHub Desktop.
event-driven 10 PRINT program using libev
#include <ev.h>
#include <locale.h>
#include <stdio.h>
#include <wchar.h>
#include <termios.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
static ev_timer timer_watcher;
static ev_io stdin_watcher;
static ev_signal sigint_watcher;
static unsigned int seed;
void set_single_char(int fd, struct termios *stored_termios) {
struct termios *st = malloc(sizeof(struct termios));
tcgetattr(fd, st);
memcpy(stored_termios, st, sizeof(*st));
st->c_iflag &= ~(INLCR | IGNCR | ICRNL | IXON);
st->c_lflag &= ~(ECHO | ECHONL | ICANON);
st->c_cflag &= ~CSIZE;
st->c_cflag |= CS8;
tcsetattr(fd, TCSANOW, st);
free(st);
}
static void stop(struct ev_loop *loop) {
ev_io_stop(loop, &stdin_watcher);
ev_timer_stop(loop, &timer_watcher);
ev_signal_stop(loop, &sigint_watcher);
}
static void stdin_cb(struct ev_loop *loop, ev_io *w, int revents) {
char buf[256];
if (revents & EV_READ) {
read(STDIN_FILENO, buf, 255);
}
stop(loop);
}
static void sigint_cb(struct ev_loop *loop, ev_signal *w, int revents) {
stop(loop);
}
static void timer_cb(struct ev_loop *loop, ev_timer *w, int revents) {
putwchar(0x2571 + (rand_r(&seed) & 1));
fflush(stdout);
}
int main(int argc, char** argv) {
struct ev_loop *loop = ev_default_loop(EVFLAG_SIGNALFD | EVBACKEND_SELECT);
struct termios *stored_termios = malloc(sizeof(struct termios));
setlocale(LC_ALL, "");
set_single_char(STDIN_FILENO, stored_termios);
seed = time(NULL);
ev_io_init(&stdin_watcher, stdin_cb, STDIN_FILENO, EV_READ);
ev_io_start(loop, &stdin_watcher);
ev_signal_init(&sigint_watcher, sigint_cb, SIGINT);
ev_signal_start(loop, &sigint_watcher);
ev_timer_init(&timer_watcher, timer_cb, 0.0, 0.025);
ev_timer_start(loop, &timer_watcher);
ev_run(loop, 0);
putwchar(L'\n');
tcsetattr(STDIN_FILENO, TCSANOW, stored_termios);
free(stored_termios);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment