Created
February 3, 2017 23:15
-
-
Save ochaton/7a6ce7434b50d817a298547eeab72cf0 to your computer and use it in GitHub Desktop.
Read Example of libev in C
This file contains 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
#include <ev.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <fcntl.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <strings.h> | |
void on_error(struct ev_loop * loop, ev_io * w) { | |
fprintf(stderr, "Fatal error: %s\n", strerror(errno)); | |
ev_io_stop(loop, w); // stop ev-loop for this watcher | |
} | |
void on_read(struct ev_loop * loop, ev_io * w, int revents) { | |
fprintf(stderr, "on_read!!\n"); | |
char buf[128]; | |
int bytes = read (w->fd, buf, sizeof(buf) - 1); | |
if (bytes == -1) { | |
if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) { | |
// That's ok. EV-loop will call us again | |
return; | |
} else { | |
return on_error(loop, w); | |
} | |
} else if (bytes == 0) { | |
fprintf(stderr, "EOF catched on read\n"); | |
ev_io_stop(loop, w); | |
return; | |
} else { | |
buf[bytes] = 0; | |
fprintf(stderr, "Got %d bytes\n", bytes); | |
printf("%s\n", buf); | |
bzero(buf, sizeof(buf)); | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int fin = open("loop.c", O_RDONLY | O_NONBLOCK); | |
struct ev_loop * loop = ev_default_loop(0); | |
ev_io inw; // input-watcher | |
ev_init(&inw, on_read); | |
ev_io_set(&inw, fin, EV_READ); | |
ev_io_start(loop, &inw); | |
ev_loop(loop, 0); // start ev-loop | |
fprintf(stderr, "EV-Loop stoped\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment