Created
June 7, 2013 19:13
-
-
Save bodokaiser/5731639 to your computer and use it in GitHub Desktop.
kqueue file read stream
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
#include <stdio.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
#include <sys/time.h> | |
#include <sys/event.h> | |
#define PATH "some.tmp" | |
int kq; | |
int fd; | |
int nev; | |
int off = 0; | |
FILE * file; | |
struct kevent event; | |
struct kevent change; | |
void read_cb(); | |
int main(int argc, const char ** argv) { | |
kq = kqueue(); | |
if (kq == -1) { | |
perror("Error on creating kqueue.\n"); | |
exit(EXIT_FAILURE); | |
} | |
fd = open(PATH, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); | |
if (fd == -1) { | |
perror("Error on opening temp file.\n"); | |
exit(EXIT_FAILURE); | |
} | |
file = fdopen(fd, "r"); | |
EV_SET(&change, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT, | |
NOTE_EXTEND, 0, 0); | |
for (;;) { | |
nev = kevent(kq, &change, 1, &event, 1, NULL); | |
if (nev == -1) { | |
perror("Error on receiving events.\n"); | |
exit(EXIT_FAILURE); | |
} | |
if (nev == 1) { | |
read_cb(); | |
} | |
} | |
return EXIT_SUCCESS; | |
} | |
void read_cb() { | |
fseek(file, 0, SEEK_END); | |
int size = (ftell (file)) - off; | |
fseek(file, off, SEEK_SET); | |
char * buf = (char *) malloc(size); | |
fread(buf, size, 1, file); | |
printf("%s\n", buf); | |
off += size; | |
free(buf); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment