]> err.no Git - moreutils/blob - pee.c
Update name one more place
[moreutils] / pee.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <sys/wait.h>
5
6 /* Licensed under the GPL
7  * Copyright (c) Miek Gieben, 2006
8  */
9
10 /* like tee(1), but then connect to other programs using
11  * pipes _and_ output to standard output
12  */
13
14 int
15 close_pipes(FILE **p, size_t i) 
16 {
17         int ret=EXIT_SUCCESS;
18         size_t j;
19         for (j = 0; j < i; j++) {
20                 int r = pclose(p[j]);
21                 if (WIFEXITED(r))
22                         ret |= WEXITSTATUS(r);
23                 else
24                         ret |= 1;
25         }
26         return ret;
27 }
28
29 int
30 main(int argc, char **argv) {
31         size_t i, r;
32         FILE **pipes;
33         char buf[BUFSIZ];
34
35         pipes = malloc(((argc - 1) * sizeof *pipes));
36         if (!pipes) 
37                 exit(EXIT_FAILURE);
38
39         for (i = 1; i < argc; i++) {
40                 pipes[i - 1] = popen(argv[i], "w");
41                 if (!pipes[i - 1]) {
42                         fprintf(stderr, "Can not open pipe to '%s\'\n", argv[i]);
43                         close_pipes(pipes, argc);
44
45                         exit(EXIT_FAILURE);
46                 }
47         }
48         argc--;
49         
50         while(!feof(stdin) && (!ferror(stdin))) {
51                 r = fread(buf, sizeof(char), BUFSIZ, stdin);
52                 for(i = 0; i < argc; i++) {
53                         if (fwrite(buf, sizeof(char), r, pipes[i]) != r) {
54                                 fprintf(stderr, "Write error to `%s\'\n", argv[i + 1]);
55                                 close_pipes(pipes, argc);
56                                 exit(EXIT_FAILURE);
57                         }
58                 }
59         }
60         exit(close_pipes(pipes, argc));
61 }