diff options
author | the lemons <citrons@mondecitronne.com> | 2022-03-08 14:15:09 -0600 |
---|---|---|
committer | the lemons <citrons@mondecitronne.com> | 2022-03-08 14:15:19 -0600 |
commit | 21b865498f0198d5f484adc912ec291dead1145b (patch) | |
tree | d8c14321f7b5eae17a4bb09283f77394d6b54db7 | |
parent | 169152db5bfc993cd3a8bee12e2c28d010e4c91a (diff) |
block/noblock commands
-rw-r--r-- | block.c | 20 | ||||
-rw-r--r-- | noblock.c | 38 |
2 files changed, 58 insertions, 0 deletions
@@ -0,0 +1,20 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <errno.h> +#include <sys/select.h> + +// 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 <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; +} |