maint: remove Local Variables: indent-tabs-mode: nil from all sources
[coreutils.git] / src / stdbuf.c
blob3ba5a516ea5e1bf6d674c3e8234a772a65572cec
1 /* stdbuf -- setup the standard streams for a command
2 Copyright (C) 2009 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 "posixver.h"
28 #include "quote.h"
29 #include "xstrtol.h"
30 #include "c-ctype.h"
32 /* The official name of this program (e.g., no `g' prefix). */
33 #define PROGRAM_NAME "stdbuf"
34 #define LIB_NAME "libstdbuf.so" /* FIXME: don't hardcode */
36 #define AUTHORS proper_name_utf8 ("Padraig Brady", "P\303\241draig Brady")
38 /* Internal error */
39 enum { EXIT_CANCELED = 125 };
41 static char *program_path;
43 extern char **environ;
45 static struct
47 size_t size;
48 int optc;
49 char *optarg;
50 } stdbuf[3];
52 static struct option const longopts[] =
54 {"input", required_argument, NULL, 'i'},
55 {"output", required_argument, NULL, 'o'},
56 {"error", required_argument, NULL, 'e'},
57 {GETOPT_HELP_OPTION_DECL},
58 {GETOPT_VERSION_OPTION_DECL},
59 {NULL, 0, NULL, 0}
62 /* Set size to the value of STR, interpreted as a decimal integer,
63 optionally multiplied by various values.
64 Return -1 on error, 0 on success.
66 This supports dd BLOCK size suffixes.
67 Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats. */
68 static int
69 parse_size (char const *str, size_t *size)
71 uintmax_t tmp_size;
72 enum strtol_error e = xstrtoumax (str, NULL, 10, &tmp_size, "EGkKMPTYZ0");
73 if (e == LONGINT_OK && tmp_size > SIZE_MAX)
74 e = LONGINT_OVERFLOW;
76 if (e == LONGINT_OK)
78 errno = 0;
79 *size = tmp_size;
80 return 0;
83 errno = (e == LONGINT_OVERFLOW ? EOVERFLOW : 0);
84 return -1;
87 void
88 usage (int status)
90 if (status != EXIT_SUCCESS)
91 fprintf (stderr, _("Try `%s --help' for more information.\n"),
92 program_name);
93 else
95 printf (_("Usage: %s OPTION... COMMAND\n"), program_name);
96 fputs (_("\
97 Run COMMAND, with modified buffering operations for its standard streams.\n\
98 \n\
99 "), stdout);
100 fputs (_("\
101 Mandatory arguments to long options are mandatory for short options too.\n\
102 "), stdout);
103 fputs (_("\
104 -i, --input=MODE Adjust standard input stream buffering\n\
105 -o, --output=MODE Adjust standard output stream buffering\n\
106 -e, --error=MODE Adjust standard error stream buffering\n\
107 "), stdout);
108 fputs (HELP_OPTION_DESCRIPTION, stdout);
109 fputs (VERSION_OPTION_DESCRIPTION, stdout);
110 fputs (_("\n\
111 If MODE is `L' then corresponding stream will be line buffered.\n\
112 This option is invalid with standard input.\n"), stdout);
113 fputs (_("\n\
114 If MODE is `0' then corresponding stream will be unbuffered.\n\
115 "), stdout);
116 fputs (_("\n\
117 Otherwise MODE is a number which may be followed by one of the following:\n\
118 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
119 In this case the corresponding stream will be fully buffered with the buffer\n\
120 size set to MODE bytes.\n\
121 "), stdout);
122 fputs (_("\n\
123 NOTE: If COMMAND adjusts the buffering of its standard streams (`tee' does\n\
124 for e.g.) then that will override corresponding settings changed by `stdbuf'.\n\
125 Also some filters (like `dd' and `cat' etc.) don't use streams for I/O,\n\
126 and are thus unaffected by `stdbuf' settings.\n\
127 "), stdout);
128 emit_bug_reporting_address ();
130 exit (status);
133 /* argv[0] can be anything really, but generally it contains
134 the path to the executable or just a name if it was executed
135 using $PATH. In the latter case to get the path we can:
136 search getenv("PATH"), readlink("/prof/self/exe"), getenv("_"),
137 dladdr(), pstat_getpathname(), etc. */
139 static void
140 set_program_path (const char *arg)
142 if (strchr (arg, '/')) /* Use absolute or relative paths directly. */
144 program_path = dir_name (arg);
146 else
148 char *path;
149 char tmppath[PATH_MAX + 1];
150 ssize_t len = readlink ("/proc/self/exe", tmppath, sizeof (tmppath) - 1);
151 if (len > 0)
153 tmppath[len] = '\0';
154 program_path = dir_name (tmppath);
156 else if ((path = getenv ("PATH")))
158 char *dir;
159 path = xstrdup (path);
160 for (dir = strtok (path, ":"); dir != NULL; dir = strtok (NULL, ":"))
162 int req = snprintf (tmppath, sizeof (tmppath), "%s/%s", dir, arg);
163 if (req >= sizeof (tmppath))
165 error (0, 0, _("path truncated when looking for %s"),
166 quote (arg));
168 else if (access (tmppath, X_OK) == 0)
170 program_path = dir_name (tmppath);
171 break;
174 free (path);
179 static int
180 optc_to_fileno (int c)
182 int ret = -1;
184 switch (c)
186 case 'e':
187 ret = STDERR_FILENO;
188 break;
189 case 'i':
190 ret = STDIN_FILENO;
191 break;
192 case 'o':
193 ret = STDOUT_FILENO;
194 break;
197 return ret;
200 static void
201 set_LD_PRELOAD (void)
203 int ret;
204 char *old_libs = getenv ("LD_PRELOAD");
205 char *LD_PRELOAD;
207 /* Note this would auto add the appropriate search path for "libstdbuf.so":
208 gcc stdbuf.c -Wl,-rpath,'$ORIGIN' -Wl,-rpath,$PKGLIBDIR
209 However we want the lookup done for the exec'd command not stdbuf.
211 Since we don't link against libstdbuf.so add it to LIBDIR rather than
212 LIBEXECDIR, as we'll search for it in the "sys default" case below. */
213 char const *const search_path[] = {
214 program_path,
215 PKGLIBDIR,
216 "", /* sys default */
217 NULL
220 char const *const *path = search_path;
221 char *libstdbuf;
225 struct stat sb;
227 if (!**path) /* system default */
229 libstdbuf = xstrdup (LIB_NAME);
230 break;
232 ret = asprintf (&libstdbuf, "%s/%s", *path, LIB_NAME);
233 if (ret < 0)
234 xalloc_die ();
235 if (stat (libstdbuf, &sb) == 0) /* file_exists */
236 break;
237 free (libstdbuf);
239 while (*++path);
241 /* FIXME: Do we need to support libstdbuf.dll, c:, '\' separators etc? */
243 if (old_libs)
244 ret = asprintf (&LD_PRELOAD, "LD_PRELOAD=%s:%s", old_libs, libstdbuf);
245 else
246 ret = asprintf (&LD_PRELOAD, "LD_PRELOAD=%s", libstdbuf);
248 if (ret < 0)
249 xalloc_die ();
251 free (libstdbuf);
253 ret = putenv (LD_PRELOAD);
255 if (ret != 0)
257 error (EXIT_CANCELED, errno,
258 _("failed to update the environment with %s"),
259 quote (LD_PRELOAD));
263 /* Populate environ with _STDBUF_I=$MODE _STDBUF_O=$MODE _STDBUF_E=$MODE */
265 static void
266 set_libstdbuf_options (void)
268 int i;
270 for (i = 0; i < ARRAY_CARDINALITY (stdbuf); i++)
272 if (stdbuf[i].optarg)
274 char *var;
275 int ret;
277 if (*stdbuf[i].optarg == 'L')
278 ret = asprintf (&var, "%s%c=L", "_STDBUF_",
279 toupper (stdbuf[i].optc));
280 else
281 ret = asprintf (&var, "%s%c=%" PRIuMAX, "_STDBUF_",
282 toupper (stdbuf[i].optc),
283 (uintmax_t) stdbuf[i].size);
284 if (ret < 0)
285 xalloc_die ();
287 if (putenv (var) != 0)
289 error (EXIT_CANCELED, errno,
290 _("failed to update the environment with %s"),
291 quote (var));
298 main (int argc, char **argv)
300 int c;
302 initialize_main (&argc, &argv);
303 set_program_name (argv[0]);
304 setlocale (LC_ALL, "");
305 bindtextdomain (PACKAGE, LOCALEDIR);
306 textdomain (PACKAGE);
308 initialize_exit_failure (EXIT_CANCELED);
309 atexit (close_stdout);
311 while ((c = getopt_long (argc, argv, "+i:o:e:", longopts, NULL)) != -1)
313 int opt_fileno;
315 switch (c)
317 /* Old McDonald had a farm ei... */
318 case 'e':
319 case 'i':
320 case 'o':
321 opt_fileno = optc_to_fileno (c);
322 assert (0 <= opt_fileno && opt_fileno < ARRAY_CARDINALITY (stdbuf));
323 stdbuf[opt_fileno].optc = c;
324 while (c_isspace (*optarg))
325 optarg++;
326 stdbuf[opt_fileno].optarg = optarg;
327 if (c == 'i' && *optarg == 'L')
329 /* -oL will be by far the most common use of this utility,
330 but one could easily think -iL might have the same affect,
331 so disallow it as it could be confusing. */
332 error (0, 0, _("line buffering stdin is meaningless"));
333 usage (EXIT_CANCELED);
336 if (!STREQ (optarg, "L")
337 && parse_size (optarg, &stdbuf[opt_fileno].size) == -1)
338 error (EXIT_CANCELED, errno, _("invalid mode %s"), quote (optarg));
340 break;
342 case_GETOPT_HELP_CHAR;
344 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
346 default:
347 usage (EXIT_CANCELED);
351 argv += optind;
352 argc -= optind;
354 /* must specify at least 1 command. */
355 if (argc < 1)
357 error (0, 0, _("missing operand"));
358 usage (EXIT_CANCELED);
361 /* FIXME: Should we mandate at least one option? */
363 set_libstdbuf_options ();
365 /* Try to preload libstdbuf first from the same path as
366 stdbuf is running from. */
367 set_program_path (argv[0]);
368 if (!program_path)
369 program_path = xstrdup (PKGLIBDIR); /* Need to init to non NULL. */
370 set_LD_PRELOAD ();
371 free (program_path);
373 execvp (*argv, argv);
376 int exit_status = (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
377 error (0, errno, _("failed to run command %s"), quote (argv[0]));
378 exit (exit_status);