freebsd patch from Enrico Tassi
[moreutils.git] / pee.c
blob6ba38f78da10b61c8670b1c450fa769248ef84c4
1 #include <stdlib.h>
2 #include <stdio.h>
4 /* Licensed under the GPL
5 * Copyright (c) Miek Gieben, 2006
6 */
8 /* like tee(1), but then connect to other programs using
9 * pipes _and_ output to standard output
12 void
13 close_pipes(FILE **p, size_t i)
15 size_t j;
16 for (j = 0; j < i; j++)
17 pclose(p[j]);
20 int
21 main(int argc, char **argv) {
22 size_t i, r;
23 FILE **pipes;
24 char buf[BUFSIZ];
26 pipes = malloc(((argc - 1) * sizeof *pipes));
27 if (!pipes)
28 exit(EXIT_FAILURE);
30 for (i = 1; i < argc; i++) {
31 pipes[i - 1] = popen(argv[i], "w");
32 if (!pipes[i - 1]) {
33 fprintf(stderr, "Can not open pipe to '%s\'\n", argv[i]);
34 close_pipes(pipes, i);
36 exit(EXIT_FAILURE);
39 argc--;
41 while(!feof(stdin) && (!ferror(stdin))) {
42 r = fread(buf, sizeof(char), BUFSIZ, stdin);
43 for(i = 0; i < argc; i++) {
44 if (fwrite(buf, sizeof(char), r, pipes[i]) != r) {
45 fprintf(stderr, "Write error to `%s\'\n", argv[i + 1]);
46 close_pipes(pipes, i);
47 exit(EXIT_FAILURE);
51 close_pipes(pipes, argc);
53 exit(EXIT_SUCCESS);