tests: cleanup trapping of signal names
[coreutils.git] / src / stdbuf.c
blob116619d7a913f9f6917d3570f29a4b97db23e5d1
1 /* stdbuf -- setup the standard streams for a command
2 Copyright (C) 2009-2015 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 && SIZE_MAX < tmp_size)
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 : errno);
80 return -1;
83 void
84 usage (int status)
86 if (status != EXIT_SUCCESS)
87 emit_try_help ();
88 else
90 printf (_("Usage: %s OPTION... COMMAND\n"), program_name);
91 fputs (_("\
92 Run COMMAND, with modified buffering operations for its standard streams.\n\
93 "), stdout);
95 emit_mandatory_arg_note ();
97 fputs (_("\
98 -i, --input=MODE adjust standard input stream buffering\n\
99 -o, --output=MODE adjust standard output stream buffering\n\
100 -e, --error=MODE adjust standard error stream buffering\n\
101 "), stdout);
102 fputs (HELP_OPTION_DESCRIPTION, stdout);
103 fputs (VERSION_OPTION_DESCRIPTION, stdout);
104 fputs (_("\n\
105 If MODE is 'L' the corresponding stream will be line buffered.\n\
106 This option is invalid with standard input.\n"), stdout);
107 fputs (_("\n\
108 If MODE is '0' the corresponding stream will be unbuffered.\n\
109 "), stdout);
110 fputs (_("\n\
111 Otherwise MODE is a number which may be followed by one of the following:\n\
112 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
113 In this case the corresponding stream will be fully buffered with the buffer\n\
114 size set to MODE bytes.\n\
115 "), stdout);
116 fputs (_("\n\
117 NOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does\n\
118 for example) then that will override corresponding changes by 'stdbuf'.\n\
119 Also some filters (like 'dd' and 'cat' etc.) don't use streams for I/O,\n\
120 and are thus unaffected by 'stdbuf' settings.\n\
121 "), stdout);
122 emit_ancillary_info (PROGRAM_NAME);
124 exit (status);
127 /* argv[0] can be anything really, but generally it contains
128 the path to the executable or just a name if it was executed
129 using $PATH. In the latter case to get the path we can:
130 search getenv("PATH"), readlink("/prof/self/exe"), getenv("_"),
131 dladdr(), pstat_getpathname(), etc. */
133 static void
134 set_program_path (const char *arg)
136 if (strchr (arg, '/')) /* Use absolute or relative paths directly. */
138 program_path = dir_name (arg);
140 else
142 char *path = xreadlink ("/proc/self/exe");
143 if (path)
144 program_path = dir_name (path);
145 else if ((path = getenv ("PATH")))
147 char *dir;
148 path = xstrdup (path);
149 for (dir = strtok (path, ":"); dir != NULL; dir = strtok (NULL, ":"))
151 char *candidate = file_name_concat (dir, arg, NULL);
152 if (access (candidate, X_OK) == 0)
154 program_path = dir_name (candidate);
155 free (candidate);
156 break;
158 free (candidate);
161 free (path);
165 static int
166 optc_to_fileno (int c)
168 int ret = -1;
170 switch (c)
172 case 'e':
173 ret = STDERR_FILENO;
174 break;
175 case 'i':
176 ret = STDIN_FILENO;
177 break;
178 case 'o':
179 ret = STDOUT_FILENO;
180 break;
183 return ret;
186 static void
187 set_LD_PRELOAD (void)
189 int ret;
190 #ifdef __APPLE__
191 char const *preload_env = "DYLD_INSERT_LIBRARIES";
192 #else
193 char const *preload_env = "LD_PRELOAD";
194 #endif
195 char *old_libs = getenv (preload_env);
196 char *LD_PRELOAD;
198 /* Note this would auto add the appropriate search path for "libstdbuf.so":
199 gcc stdbuf.c -Wl,-rpath,'$ORIGIN' -Wl,-rpath,$PKGLIBEXECDIR
200 However we want the lookup done for the exec'd command not stdbuf.
202 Since we don't link against libstdbuf.so add it to PKGLIBEXECDIR
203 rather than to LIBDIR.
205 Note we could add "" as the penultimate item in the following list
206 to enable searching for libstdbuf.so in the default system lib paths.
207 However that would not indicate an error if libstdbuf.so was not found.
208 Also while this could support auto selecting the right arch in a multilib
209 environment, what we really want is to auto select based on the arch of the
210 command being run, rather than that of stdbuf itself. This is currently
211 not supported due to the unusual need for controlling the stdio buffering
212 of programs that are a different architecture to the default on the
213 system (and that of stdbuf itself). */
214 char const *const search_path[] = {
215 program_path,
216 PKGLIBEXECDIR,
217 NULL
220 char const *const *path = search_path;
221 char *libstdbuf;
223 while (true)
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 ++path;
240 if ( ! *path)
241 error (EXIT_CANCELED, 0, _("failed to find %s"), quote (LIB_NAME));
244 /* FIXME: Do we need to support libstdbuf.dll, c:, '\' separators etc? */
246 if (old_libs)
247 ret = asprintf (&LD_PRELOAD, "%s=%s:%s", preload_env, old_libs, libstdbuf);
248 else
249 ret = asprintf (&LD_PRELOAD, "%s=%s", preload_env, libstdbuf);
251 if (ret < 0)
252 xalloc_die ();
254 free (libstdbuf);
256 ret = putenv (LD_PRELOAD);
257 #ifdef __APPLE__
258 if (ret == 0)
259 ret = setenv ("DYLD_FORCE_FLAT_NAMESPACE", "y", 1);
260 #endif
262 if (ret != 0)
264 error (EXIT_CANCELED, errno,
265 _("failed to update the environment with %s"),
266 quote (LD_PRELOAD));
270 /* Populate environ with _STDBUF_I=$MODE _STDBUF_O=$MODE _STDBUF_E=$MODE.
271 Return TRUE if any environment variables set. */
273 static bool
274 set_libstdbuf_options (void)
276 bool env_set = false;
277 size_t i;
279 for (i = 0; i < ARRAY_CARDINALITY (stdbuf); i++)
281 if (stdbuf[i].optarg)
283 char *var;
284 int ret;
286 if (*stdbuf[i].optarg == 'L')
287 ret = asprintf (&var, "%s%c=L", "_STDBUF_",
288 toupper (stdbuf[i].optc));
289 else
290 ret = asprintf (&var, "%s%c=%" PRIuMAX, "_STDBUF_",
291 toupper (stdbuf[i].optc),
292 (uintmax_t) stdbuf[i].size);
293 if (ret < 0)
294 xalloc_die ();
296 if (putenv (var) != 0)
298 error (EXIT_CANCELED, errno,
299 _("failed to update the environment with %s"),
300 quote (var));
303 env_set = true;
307 return env_set;
311 main (int argc, char **argv)
313 int c;
315 initialize_main (&argc, &argv);
316 set_program_name (argv[0]);
317 setlocale (LC_ALL, "");
318 bindtextdomain (PACKAGE, LOCALEDIR);
319 textdomain (PACKAGE);
321 initialize_exit_failure (EXIT_CANCELED);
322 atexit (close_stdout);
324 while ((c = getopt_long (argc, argv, "+i:o:e:", longopts, NULL)) != -1)
326 int opt_fileno;
328 switch (c)
330 /* Old McDonald had a farm ei... */
331 case 'e':
332 case 'i':
333 case 'o':
334 opt_fileno = optc_to_fileno (c);
335 assert (0 <= opt_fileno && opt_fileno < ARRAY_CARDINALITY (stdbuf));
336 stdbuf[opt_fileno].optc = c;
337 while (c_isspace (*optarg))
338 optarg++;
339 stdbuf[opt_fileno].optarg = optarg;
340 if (c == 'i' && *optarg == 'L')
342 /* -oL will be by far the most common use of this utility,
343 but one could easily think -iL might have the same affect,
344 so disallow it as it could be confusing. */
345 error (0, 0, _("line buffering stdin is meaningless"));
346 usage (EXIT_CANCELED);
349 if (!STREQ (optarg, "L")
350 && parse_size (optarg, &stdbuf[opt_fileno].size) == -1)
351 error (EXIT_CANCELED, errno, _("invalid mode %s"), quote (optarg));
353 break;
355 case_GETOPT_HELP_CHAR;
357 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
359 default:
360 usage (EXIT_CANCELED);
364 argv += optind;
365 argc -= optind;
367 /* must specify at least 1 command. */
368 if (argc < 1)
370 error (0, 0, _("missing operand"));
371 usage (EXIT_CANCELED);
374 if (! set_libstdbuf_options ())
376 error (0, 0, _("you must specify a buffering mode option"));
377 usage (EXIT_CANCELED);
380 /* Try to preload libstdbuf first from the same path as
381 stdbuf is running from. */
382 set_program_path (program_name);
383 if (!program_path)
384 program_path = xstrdup (PKGLIBDIR); /* Need to init to non NULL. */
385 set_LD_PRELOAD ();
386 free (program_path);
388 execvp (*argv, argv);
390 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
391 error (0, errno, _("failed to run command %s"), quote (argv[0]));
392 return exit_status;