summaryrefslogtreecommitdiff
path: root/noblock.c
blob: d46b736757de376418e967065ce7374bb58bf961 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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;
}