tests: stat-free-color: do not count stat calls before main
[coreutils.git] / src / stdbuf.c
blob6fd803c95595fb07773c300a7ce88edc4585d351
1 /* stdbuf -- setup the standard streams for a command
2 Copyright (C) 2009-2011 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Pádraig Brady. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <assert.h>
25 #include "system.h"
26 #include "error.h"
27 #include "filenamecat.h"
28 #include "quote.h"
29 #include "xreadlink.h"
30 #include "xstrtol.h"
31 #include "c-ctype.h"
33 /* The official name of this program (e.g., no `g' prefix). */
34 #define PROGRAM_NAME "stdbuf"
35 #define LIB_NAME "libstdbuf.so" /* FIXME: don't hardcode */
37 #define AUTHORS proper_name_utf8 ("Padraig Brady", "P\303\241draig Brady")
39 static char *program_path;
41 static struct
43 size_t size;
44 int optc;
45 char *optarg;
46 } stdbuf[3];
48 static struct option const longopts[] =
50 {"input", required_argument, NULL, 'i'},
51 {"output", required_argument, NULL, 'o'},
52 {"error", required_argument, NULL, 'e'},
53 {GETOPT_HELP_OPTION_DECL},
54 {GETOPT_VERSION_OPTION_DECL},
55 {NULL, 0, NULL, 0}
58 /* Set size to the value of STR, interpreted as a decimal integer,
59 optionally multiplied by various values.
60 Return -1 on error, 0 on success.
62 This supports dd BLOCK size suffixes.
63 Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats. */
64 static int
65 parse_size (char const *str, size_t *size)
67 uintmax_t tmp_size;
68 enum strtol_error e = xstrtoumax (str, NULL, 10, &tmp_size, "EGkKMPTYZ0");
69 if (e == LONGINT_OK && tmp_size > SIZE_MAX)
70 e = LONGINT_OVERFLOW;
72 if (e == LONGINT_OK)
74 errno = 0;
75 *size = tmp_size;
76 return 0;
79 errno = (e == LONGINT_OVERFLOW ? EOVERFLOW : 0);
80 return -1;
83 void
84 usage (int status)
86 if (status != EXIT_SUCCESS)
87 fprintf (stderr, _("Try `%s --help' for more information.\n"),
88 program_name);
89 else
91 printf (_("Usage: %s OPTION... COMMAND\n"), program_name);
92 fputs (_("\
93 Run COMMAND, with modified buffering operations for its standard streams.\n\
94 \n\
95 "), stdout);
96 fputs (_("\
97 Mandatory arguments to long options are mandatory for short options too.\n\
98 "), stdout);
99 fputs (_("\
100 -i, --input=MODE adjust standard input stream buffering\n\
101 -o, --output=MODE adjust standard output stream buffering\n\
102 -e, --error=MODE adjust standard error stream buffering\n\
103 "), stdout);
104 fputs (HELP_OPTION_DESCRIPTION, stdout);
105 fputs (VERSION_OPTION_DESCRIPTION, stdout);
106 fputs (_("\n\
107 If MODE is `L' the corresponding stream will be line buffered.\n\
108 This option is invalid with standard input.\n"), stdout);
109 fputs (_("\n\
110 If MODE is `0' the corresponding stream will be unbuffered.\n\
111 "), stdout);
112 fputs (_("\n\
113 Otherwise MODE is a number which may be followed by one of the following:\n\
114 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
115 In this case the corresponding stream will be fully buffered with the buffer\n\
116 size set to MODE bytes.\n\
117 "), stdout);
118 fputs (_("\n\
119 NOTE: If COMMAND adjusts the buffering of its standard streams (`tee' does\n\
120 for e.g.) then that will override corresponding settings changed by `stdbuf'.\n\
121 Also some filters (like `dd' and `cat' etc.) don't use streams for I/O,\n\
122 and are thus unaffected by `stdbuf' settings.\n\
123 "), stdout);
124 emit_ancillary_info ();
126 exit (status);
129 /* argv[0] can be anything really, but generally it contains
130 the path to the executable or just a name if it was executed
131 using $PATH. In the latter case to get the path we can:
132 search getenv("PATH"), readlink("/prof/self/exe"), getenv("_"),
133 dladdr(), pstat_getpathname(), etc. */
135 static void
136 set_program_path (const char *arg)
138 if (strchr (arg, '/')) /* Use absolute or relative paths directly. */
140 program_path = dir_name (arg);
142 else
144 char *path = xreadlink ("/proc/self/exe");
145 if (path)
146 program_path = dir_name (path);
147 else if ((path = getenv ("PATH")))
149 char *dir;
150 path = xstrdup (path);
151 for (dir = strtok (path, ":"); dir != NULL; dir = strtok (NULL, ":"))
153 char *candidate = file_name_concat (dir, arg, NULL);
154 if (access (candidate, X_OK) == 0)
156 program_path = dir_name (candidate);
157 free (candidate);
158 break;
160 free (candidate);
163 free (path);
167 static int
168 optc_to_fileno (int c)
170 int ret = -1;
172 switch (c)
174 case 'e':
175 ret = STDERR_FILENO;
176 break;
177 case 'i':
178 ret = STDIN_FILENO;
179 break;
180 case 'o':
181 ret = STDOUT_FILENO;
182 break;
185 return ret;
188 static void
189 set_LD_PRELOAD (void)
191 int ret;
192 char *old_libs = getenv ("LD_PRELOAD");
193 char *LD_PRELOAD;
195 /* Note this would auto add the appropriate search path for "libstdbuf.so":
196 gcc stdbuf.c -Wl,-rpath,'$ORIGIN' -Wl,-rpath,$PKGLIBEXECDIR
197 However we want the lookup done for the exec'd command not stdbuf.
199 Since we don't link against libstdbuf.so add it to PKGLIBEXECDIR
200 rather than to LIBDIR. */
201 char const *const search_path[] = {
202 program_path,
203 PKGLIBEXECDIR,
204 NULL
207 char const *const *path = search_path;
208 char *libstdbuf;
210 while (true)
212 struct stat sb;
214 if (!**path) /* system default */
216 libstdbuf = xstrdup (LIB_NAME);
217 break;
219 ret = asprintf (&libstdbuf, "%s/%s", *path, LIB_NAME);
220 if (ret < 0)
221 xalloc_die ();
222 if (stat (libstdbuf, &sb) == 0) /* file_exists */
223 break;
224 free (libstdbuf);
226 ++path;
227 if ( ! *path)
228 error (EXIT_CANCELED, 0, _("failed to find %s"), quote (LIB_NAME));
231 /* FIXME: Do we need to support libstdbuf.dll, c:, '\' separators etc? */
233 if (old_libs)
234 ret = asprintf (&LD_PRELOAD, "LD_PRELOAD=%s:%s", old_libs, libstdbuf);
235 else
236 ret = asprintf (&LD_PRELOAD, "LD_PRELOAD=%s", libstdbuf);
238 if (ret < 0)
239 xalloc_die ();
241 free (libstdbuf);
243 ret = putenv (LD_PRELOAD);
245 if (ret != 0)
247 error (EXIT_CANCELED, errno,
248 _("failed to update the environment with %s"),
249 quote (LD_PRELOAD));
253 /* Populate environ with _STDBUF_I=$MODE _STDBUF_O=$MODE _STDBUF_E=$MODE */
255 static void
256 set_libstdbuf_options (void)
258 unsigned int i;
260 for (i = 0; i < ARRAY_CARDINALITY (stdbuf); i++)
262 if (stdbuf[i].optarg)
264 char *var;
265 int ret;
267 if (*stdbuf[i].optarg == 'L')
268 ret = asprintf (&var, "%s%c=L", "_STDBUF_",
269 toupper (stdbuf[i].optc));
270 else
271 ret = asprintf (&var, "%s%c=%" PRIuMAX, "_STDBUF_",
272 toupper (stdbuf[i].optc),
273 (uintmax_t) stdbuf[i].size);
274 if (ret < 0)
275 xalloc_die ();
277 if (putenv (var) != 0)
279 error (EXIT_CANCELED, errno,
280 _("failed to update the environment with %s"),
281 quote (var));
288 main (int argc, char **argv)
290 int c;
292 initialize_main (&argc, &argv);
293 set_program_name (argv[0]);
294 setlocale (LC_ALL, "");
295 bindtextdomain (PACKAGE, LOCALEDIR);
296 textdomain (PACKAGE);
298 initialize_exit_failure (EXIT_CANCELED);
299 atexit (close_stdout);
301 while ((c = getopt_long (argc, argv, "+i:o:e:", longopts, NULL)) != -1)
303 int opt_fileno;
305 switch (c)
307 /* Old McDonald had a farm ei... */
308 case 'e':
309 case 'i':
310 case 'o':
311 opt_fileno = optc_to_fileno (c);
312 assert (0 <= opt_fileno && opt_fileno < ARRAY_CARDINALITY (stdbuf));
313 stdbuf[opt_fileno].optc = c;
314 while (c_isspace (*optarg))
315 optarg++;
316 stdbuf[opt_fileno].optarg = optarg;
317 if (c == 'i' && *optarg == 'L')
319 /* -oL will be by far the most common use of this utility,
320 but one could easily think -iL might have the same affect,
321 so disallow it as it could be confusing. */
322 error (0, 0, _("line buffering stdin is meaningless"));
323 usage (EXIT_CANCELED);
326 if (!STREQ (optarg, "L")
327 && parse_size (optarg, &stdbuf[opt_fileno].size) == -1)
328 error (EXIT_CANCELED, errno, _("invalid mode %s"), quote (optarg));
330 break;
332 case_GETOPT_HELP_CHAR;
334 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
336 default:
337 usage (EXIT_CANCELED);
341 argv += optind;
342 argc -= optind;
344 /* must specify at least 1 command. */
345 if (argc < 1)
347 error (0, 0, _("missing operand"));
348 usage (EXIT_CANCELED);
351 /* FIXME: Should we mandate at least one option? */
353 set_libstdbuf_options ();
355 /* Try to preload libstdbuf first from the same path as
356 stdbuf is running from. */
357 set_program_path (argv[0]);
358 if (!program_path)
359 program_path = xstrdup (PKGLIBDIR); /* Need to init to non NULL. */
360 set_LD_PRELOAD ();
361 free (program_path);
363 execvp (*argv, argv);
366 int exit_status = (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
367 error (0, errno, _("failed to run command %s"), quote (argv[0]));
368 exit (exit_status);