Last active
August 29, 2015 14:07
-
-
Save CatTail/677fb8348144ceabcc16 to your computer and use it in GitHub Desktop.
non-block reading
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 <stdio.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/uio.h> | |
int main(void) | |
{ | |
char buf[80]; | |
ssize_t size; | |
int fd = fileno(stdin); | |
// Non-blocking I/O; if no data is available to a read call, or if a write operation | |
// would block, the read or write call returns -1 with the error EAGAIN. | |
int flags = fcntl(fd, F_GETFL, 0); | |
fcntl(fd, F_SETFL, flags | O_NONBLOCK); | |
// manual poll | |
while (size = read(fd, buf, sizeof(buf))) { | |
printf("Current size %d\n", size); | |
if (size == -1) { | |
if (errno != EAGAIN) { | |
perror("read()"); | |
exit(EXIT_FAILURE); | |
} | |
// data not ready, wait and check again | |
perror(NULL); | |
sleep(3); | |
} | |
} | |
printf("%s", buf); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment