summaryrefslogtreecommitdiff
path: root/pee.c
blob: 6ba38f78da10b61c8670b1c450fa769248ef84c4 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdlib.h>
#include <stdio.h>

/* Licensed under the GPL
 * Copyright (c) Miek Gieben, 2006
 */

/* like tee(1), but then connect to other programs using
 * pipes _and_ output to standard output
 */

void
close_pipes(FILE **p, size_t i) 
{
	size_t j;
	for (j = 0; j < i; j++) 
		pclose(p[j]);
}

int
main(int argc, char **argv) {
	size_t i, r;
	FILE **pipes;
	char buf[BUFSIZ];

	pipes = malloc(((argc - 1) * sizeof *pipes));
	if (!pipes) 
		exit(EXIT_FAILURE);

	for (i = 1; i < argc; i++) {
		pipes[i - 1] = popen(argv[i], "w");
		if (!pipes[i - 1]) {
			fprintf(stderr, "Can not open pipe to '%s\'\n", argv[i]);
			close_pipes(pipes, i);

			exit(EXIT_FAILURE);
		}
	}
	argc--;
	
	while(!feof(stdin) && (!ferror(stdin))) {
		r = fread(buf, sizeof(char), BUFSIZ, stdin);
		for(i = 0; i < argc; i++) {
			if (fwrite(buf, sizeof(char), r, pipes[i]) != r) {
				fprintf(stderr, "Write error to `%s\'\n", argv[i + 1]);
				close_pipes(pipes, i);
				exit(EXIT_FAILURE);
			}
		}
	}
	close_pipes(pipes, argc);

	exit(EXIT_SUCCESS);
}