1 /* stdbuf -- setup the standard streams for a command
2 Copyright (C) 2009-2012 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. */
22 #include <sys/types.h>
27 #include "filenamecat.h"
29 #include "xreadlink.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
;
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
},
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. */
65 parse_size (char const *str
, size_t *size
)
68 enum strtol_error e
= xstrtoumax (str
, NULL
, 10, &tmp_size
, "EGkKMPTYZ0");
69 if (e
== LONGINT_OK
&& tmp_size
> SIZE_MAX
)
79 errno
= (e
== LONGINT_OVERFLOW
? EOVERFLOW
: 0);
86 if (status
!= EXIT_SUCCESS
)
90 printf (_("Usage: %s OPTION... COMMAND\n"), program_name
);
92 Run COMMAND, with modified buffering operations for its standard streams.\n\
96 Mandatory arguments to long options are mandatory for short options too.\n\
99 -i, --input=MODE adjust standard input stream buffering\n\
100 -o, --output=MODE adjust standard output stream buffering\n\
101 -e, --error=MODE adjust standard error stream buffering\n\
103 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
104 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
106 If MODE is 'L' the corresponding stream will be line buffered.\n\
107 This option is invalid with standard input.\n"), stdout
);
109 If MODE is '0' the corresponding stream will be unbuffered.\n\
112 Otherwise MODE is a number which may be followed by one of the following:\n\
113 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
114 In this case the corresponding stream will be fully buffered with the buffer\n\
115 size set to MODE bytes.\n\
118 NOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does\n\
119 for e.g.) then that will override corresponding settings changed by 'stdbuf'.\n\
120 Also some filters (like 'dd' and 'cat' etc.) don't use streams for I/O,\n\
121 and are thus unaffected by 'stdbuf' settings.\n\
123 emit_ancillary_info ();
128 /* argv[0] can be anything really, but generally it contains
129 the path to the executable or just a name if it was executed
130 using $PATH. In the latter case to get the path we can:
131 search getenv("PATH"), readlink("/prof/self/exe"), getenv("_"),
132 dladdr(), pstat_getpathname(), etc. */
135 set_program_path (const char *arg
)
137 if (strchr (arg
, '/')) /* Use absolute or relative paths directly. */
139 program_path
= dir_name (arg
);
143 char *path
= xreadlink ("/proc/self/exe");
145 program_path
= dir_name (path
);
146 else if ((path
= getenv ("PATH")))
149 path
= xstrdup (path
);
150 for (dir
= strtok (path
, ":"); dir
!= NULL
; dir
= strtok (NULL
, ":"))
152 char *candidate
= file_name_concat (dir
, arg
, NULL
);
153 if (access (candidate
, X_OK
) == 0)
155 program_path
= dir_name (candidate
);
167 optc_to_fileno (int c
)
188 set_LD_PRELOAD (void)
191 char *old_libs
= getenv ("LD_PRELOAD");
194 /* Note this would auto add the appropriate search path for "libstdbuf.so":
195 gcc stdbuf.c -Wl,-rpath,'$ORIGIN' -Wl,-rpath,$PKGLIBEXECDIR
196 However we want the lookup done for the exec'd command not stdbuf.
198 Since we don't link against libstdbuf.so add it to PKGLIBEXECDIR
199 rather than to LIBDIR. */
200 char const *const search_path
[] = {
206 char const *const *path
= search_path
;
213 if (!**path
) /* system default */
215 libstdbuf
= xstrdup (LIB_NAME
);
218 ret
= asprintf (&libstdbuf
, "%s/%s", *path
, LIB_NAME
);
221 if (stat (libstdbuf
, &sb
) == 0) /* file_exists */
227 error (EXIT_CANCELED
, 0, _("failed to find %s"), quote (LIB_NAME
));
230 /* FIXME: Do we need to support libstdbuf.dll, c:, '\' separators etc? */
233 ret
= asprintf (&LD_PRELOAD
, "LD_PRELOAD=%s:%s", old_libs
, libstdbuf
);
235 ret
= asprintf (&LD_PRELOAD
, "LD_PRELOAD=%s", libstdbuf
);
242 ret
= putenv (LD_PRELOAD
);
246 error (EXIT_CANCELED
, errno
,
247 _("failed to update the environment with %s"),
252 /* Populate environ with _STDBUF_I=$MODE _STDBUF_O=$MODE _STDBUF_E=$MODE */
255 set_libstdbuf_options (void)
259 for (i
= 0; i
< ARRAY_CARDINALITY (stdbuf
); i
++)
261 if (stdbuf
[i
].optarg
)
266 if (*stdbuf
[i
].optarg
== 'L')
267 ret
= asprintf (&var
, "%s%c=L", "_STDBUF_",
268 toupper (stdbuf
[i
].optc
));
270 ret
= asprintf (&var
, "%s%c=%" PRIuMAX
, "_STDBUF_",
271 toupper (stdbuf
[i
].optc
),
272 (uintmax_t) stdbuf
[i
].size
);
276 if (putenv (var
) != 0)
278 error (EXIT_CANCELED
, errno
,
279 _("failed to update the environment with %s"),
287 main (int argc
, char **argv
)
291 initialize_main (&argc
, &argv
);
292 set_program_name (argv
[0]);
293 setlocale (LC_ALL
, "");
294 bindtextdomain (PACKAGE
, LOCALEDIR
);
295 textdomain (PACKAGE
);
297 initialize_exit_failure (EXIT_CANCELED
);
298 atexit (close_stdout
);
300 while ((c
= getopt_long (argc
, argv
, "+i:o:e:", longopts
, NULL
)) != -1)
306 /* Old McDonald had a farm ei... */
310 opt_fileno
= optc_to_fileno (c
);
311 assert (0 <= opt_fileno
&& opt_fileno
< ARRAY_CARDINALITY (stdbuf
));
312 stdbuf
[opt_fileno
].optc
= c
;
313 while (c_isspace (*optarg
))
315 stdbuf
[opt_fileno
].optarg
= optarg
;
316 if (c
== 'i' && *optarg
== 'L')
318 /* -oL will be by far the most common use of this utility,
319 but one could easily think -iL might have the same affect,
320 so disallow it as it could be confusing. */
321 error (0, 0, _("line buffering stdin is meaningless"));
322 usage (EXIT_CANCELED
);
325 if (!STREQ (optarg
, "L")
326 && parse_size (optarg
, &stdbuf
[opt_fileno
].size
) == -1)
327 error (EXIT_CANCELED
, errno
, _("invalid mode %s"), quote (optarg
));
331 case_GETOPT_HELP_CHAR
;
333 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
336 usage (EXIT_CANCELED
);
343 /* must specify at least 1 command. */
346 error (0, 0, _("missing operand"));
347 usage (EXIT_CANCELED
);
350 /* FIXME: Should we mandate at least one option? */
352 set_libstdbuf_options ();
354 /* Try to preload libstdbuf first from the same path as
355 stdbuf is running from. */
356 set_program_path (program_name
);
358 program_path
= xstrdup (PKGLIBDIR
); /* Need to init to non NULL. */
362 execvp (*argv
, argv
);
365 int exit_status
= (errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
);
366 error (0, errno
, _("failed to run command %s"), quote (argv
[0]));