b8df35edbf8142a11eb8d6e13b841b4d7019abf4
[platform/upstream/coreutils.git] / src / tee.c
1 /* tee - read from standard input and write to standard output and files.
2    Copyright (C) 85,1990-2003 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Mike Parker, Richard M. Stallman, and David MacKenzie */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <signal.h>
24 #include <getopt.h>
25
26 #include "system.h"
27 #include "error.h"
28
29 /* The official name of this program (e.g., no `g' prefix).  */
30 #define PROGRAM_NAME "tee"
31
32 #define WRITTEN_BY _("Written by Mike Parker, Richard M. Stallman, and David MacKenzie.")
33
34 static int tee (int nfiles, const char **files);
35
36 /* If nonzero, append to output files rather than truncating them. */
37 static int append;
38
39 /* If nonzero, ignore interrupts. */
40 static int ignore_interrupts;
41
42 /* The name that this program was run with. */
43 char *program_name;
44
45 static struct option const long_options[] =
46 {
47   {"append", no_argument, NULL, 'a'},
48   {"ignore-interrupts", no_argument, NULL, 'i'},
49   {GETOPT_HELP_OPTION_DECL},
50   {GETOPT_VERSION_OPTION_DECL},
51   {NULL, 0, NULL, 0}
52 };
53
54 void
55 usage (int status)
56 {
57   if (status != 0)
58     fprintf (stderr, _("Try `%s --help' for more information.\n"),
59              program_name);
60   else
61     {
62       printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
63       fputs (_("\
64 Copy standard input to each FILE, and also to standard output.\n\
65 \n\
66   -a, --append              append to the given FILEs, do not overwrite\n\
67   -i, --ignore-interrupts   ignore interrupt signals\n\
68 "), stdout);
69       fputs (HELP_OPTION_DESCRIPTION, stdout);
70       fputs (VERSION_OPTION_DESCRIPTION, stdout);
71       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
72     }
73   exit (status);
74 }
75
76 int
77 main (int argc, char **argv)
78 {
79   int errs;
80   int optc;
81
82   initialize_main (&argc, &argv);
83   program_name = argv[0];
84   setlocale (LC_ALL, "");
85   bindtextdomain (PACKAGE, LOCALEDIR);
86   textdomain (PACKAGE);
87
88   atexit (close_stdout);
89
90   append = 0;
91   ignore_interrupts = 0;
92
93   while ((optc = getopt_long (argc, argv, "ai", long_options, NULL)) != -1)
94     {
95       switch (optc)
96         {
97         case 0:
98           break;
99
100         case 'a':
101           append = 1;
102           break;
103
104         case 'i':
105           ignore_interrupts = 1;
106           break;
107
108         case_GETOPT_HELP_CHAR;
109
110         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
111
112         default:
113           usage (EXIT_FAILURE);
114         }
115     }
116
117   if (ignore_interrupts)
118     {
119 #ifdef _POSIX_SOURCE
120       struct sigaction sigact;
121
122       sigact.sa_handler = SIG_IGN;
123       sigemptyset (&sigact.sa_mask);
124       sigact.sa_flags = 0;
125       sigaction (SIGINT, &sigact, NULL);
126 #else                           /* !_POSIX_SOURCE */
127       signal (SIGINT, SIG_IGN);
128 #endif                          /* _POSIX_SOURCE */
129     }
130
131   /* Don't let us be killed if one of the output files is a pipe that
132      doesn't consume all its input.  */
133 #ifdef _POSIX_SOURCE
134   {
135     struct sigaction sigact;
136
137     sigact.sa_handler = SIG_IGN;
138     sigemptyset (&sigact.sa_mask);
139     sigact.sa_flags = 0;
140     sigaction (SIGPIPE, &sigact, NULL);
141   }
142 #else
143   signal (SIGPIPE, SIG_IGN);
144 #endif
145
146   /* Do *not* warn if tee is given no file arguments.
147      POSIX requires that it work when given no arguments.  */
148
149   errs = tee (argc - optind, (const char **) &argv[optind]);
150   if (close (STDIN_FILENO) != 0)
151     error (EXIT_FAILURE, errno, _("standard input"));
152
153   exit (errs);
154 }
155
156 /* Copy the standard input into each of the NFILES files in FILES
157    and into the standard output.
158    Return 0 if successful, 1 if any errors occur. */
159
160 static int
161 tee (int nfiles, const char **files)
162 {
163   FILE **descriptors;
164   char buffer[BUFSIZ];
165   int bytes_read, i;
166   int ret = 0;
167   const char *mode_string = (append ? "a" : "w");
168
169   descriptors = xmalloc ((nfiles + 1) * sizeof (descriptors[0]));
170
171   /* Move all the names `up' one in the argv array to make room for
172      the entry for standard output.  This writes into argv[argc].  */
173   for (i = nfiles; i >= 1; i--)
174     files[i] = files[i - 1];
175
176   SET_BINARY2 (0, 1);
177
178   /* In the array of NFILES + 1 descriptors, make
179      the first one correspond to standard output.   */
180   descriptors[0] = stdout;
181   files[0] = _("standard output");
182   SETVBUF (stdout, NULL, _IONBF, 0);
183
184   for (i = 1; i <= nfiles; i++)
185     {
186       descriptors[i] = fopen (files[i], mode_string);
187       if (descriptors[i] == NULL)
188         {
189           error (0, errno, "%s", files[i]);
190           ret = 1;
191         }
192       else
193         {
194           SETVBUF (descriptors[i], NULL, _IONBF, 0);
195           SET_BINARY (fileno (descriptors[i]));
196         }
197     }
198
199   while (1)
200     {
201       bytes_read = read (0, buffer, sizeof buffer);
202 #ifdef EINTR
203       if (bytes_read < 0 && errno == EINTR)
204         continue;
205 #endif
206       if (bytes_read <= 0)
207         break;
208
209       /* Write to all NFILES + 1 descriptors.
210          Standard output is the first one.  */
211       for (i = 0; i <= nfiles; i++)
212         if (descriptors[i]
213             && fwrite (buffer, 1, bytes_read, descriptors[i]) != bytes_read)
214           {
215             error (0, errno, "%s", files[i]);
216             descriptors[i] = NULL;
217             ret = 1;
218           }
219     }
220
221   if (bytes_read == -1)
222     {
223       error (0, errno, _("read error"));
224       ret = 1;
225     }
226
227   /* Close the files, but not standard output.  */
228   for (i = 1; i <= nfiles; i++)
229     if (descriptors[i] && fclose (descriptors[i]) != 0)
230       {
231         error (0, errno, "%s", files[i]);
232         ret = 1;
233       }
234
235   free (descriptors);
236
237   return ret;
238 }