From 21b865498f0198d5f484adc912ec291dead1145b Mon Sep 17 00:00:00 2001 From: the lemons Date: Tue, 8 Mar 2022 14:15:09 -0600 Subject: block/noblock commands --- block.c | 20 ++++++++++++++++++++ noblock.c | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 block.c create mode 100644 noblock.c diff --git a/block.c b/block.c new file mode 100644 index 0000000..40178d8 --- /dev/null +++ b/block.c @@ -0,0 +1,20 @@ +#include +#include +#include +#include +#include + +// utility to block until stdin has input +// public domain + +int main(int argc, char *argv[]) { + fd_set readset; + FD_ZERO(&readset); + FD_SET(STDIN_FILENO, &readset); + if (select(1, &readset, NULL, NULL, NULL) == -1) { + perror(argv[0]); + return EXIT_FAILURE; + } + + return 0; +} 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 +#include +#include +#include +#include +#include + +// 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; +} -- cgit v1.2.3