summaryrefslogtreecommitdiff
path: root/noblock.c
diff options
context:
space:
mode:
Diffstat (limited to 'noblock.c')
-rw-r--r--noblock.c38
1 files changed, 38 insertions, 0 deletions
diff --git a/noblock.c b/noblock.c
new file mode 100644
index 0000000..d46b736
--- /dev/null
+++ b/noblock.c
@@ -0,0 +1,38 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <sys/select.h>
+
+// utility to read non-blockingly from stdin.
+// returns exit code 1 on EOF. returns EXIT_FAILURE on error.
+// public domain
+
+int main(int argc, char *argv[]) {
+ long int max_chars = -1;
+ if (argc > 1) max_chars = atoi(argv[1]);
+
+ fd_set readset;
+ FD_ZERO(&readset);
+ FD_SET(STDIN_FILENO, &readset);
+ struct timeval timeout = {0,0};
+
+ int result;
+ size_t n = 0;
+ while ((result = select(1, &readset, NULL, NULL, &timeout)) != -1) {
+ if (result == 0) return 0; // there is nothing to read
+
+ int c = getc(stdin);
+ if (c == EOF) {
+ if (feof(stdin)) return 1;
+ else {
+ perror(argv[0]);
+ return EXIT_FAILURE;
+ }
+ } else putc(c, stdout);
+ if (++n == max_chars) return 0;
+ }
+
+ return 0;
+}