Fixed spelling errors in Bob Proulx's name. Sorry, Bob.
[findutils.git] / xargs / xargs.c
blob3eba3662eec73339f968ec43e7f5ffaacec0e703
1 /* xargs -- build and execute command lines from standard input
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2005 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 2, or (at your option)
7 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, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 USA.
20 /* Written by Mike Rendell <michael@cs.mun.ca>
21 and David MacKenzie <djm@gnu.org>.
22 Modifications by
23 James Youngman
24 Dmitry V. Levin
27 #include <config.h>
29 # ifndef PARAMS
30 # if defined PROTOTYPES || (defined __STDC__ && __STDC__)
31 # define PARAMS(Args) Args
32 # else
33 # define PARAMS(Args) ()
34 # endif
35 # endif
37 #include <ctype.h>
39 #if !defined (isascii) || defined (STDC_HEADERS)
40 #ifdef isascii
41 #undef isascii
42 #endif
43 #define isascii(c) 1
44 #endif
46 #ifdef isblank
47 #define ISBLANK(c) (isascii (c) && isblank (c))
48 #else
49 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
50 #endif
52 #define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
53 || (c) == '\f' || (c) == '\v')
55 #include <sys/types.h>
56 #include <stdio.h>
57 #include <errno.h>
58 #include <getopt.h>
59 #include <fcntl.h>
61 #if defined(STDC_HEADERS)
62 #include <assert.h>
63 #endif
65 #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
66 #include <string.h>
67 #if !defined(STDC_HEADERS)
68 #include <memory.h>
69 #endif
70 #else
71 #include <strings.h>
72 #define memcpy(dest, source, count) (bcopy((source), (dest), (count)))
73 #endif
75 #ifndef _POSIX_SOURCE
76 #include <sys/param.h>
77 #endif
79 #ifdef HAVE_LIMITS_H
80 #include <limits.h>
81 #endif
83 #ifndef LONG_MAX
84 #define LONG_MAX (~(1 << (sizeof (long) * 8 - 1)))
85 #endif
87 /* The presence of unistd.h is assumed by gnulib these days, so we
88 * might as well assume it too.
90 #include <unistd.h>
92 #include <signal.h>
94 #if !defined(SIGCHLD) && defined(SIGCLD)
95 #define SIGCHLD SIGCLD
96 #endif
98 #include "wait.h"
100 /* States for read_line. */
101 #define NORM 0
102 #define SPACE 1
103 #define QUOTE 2
104 #define BACKSLASH 3
106 #ifdef STDC_HEADERS
107 #include <stdlib.h>
108 #else
109 extern int errno;
110 #endif
112 #ifdef HAVE_LOCALE_H
113 #include <locale.h>
114 #endif
115 #if ENABLE_NLS
116 # include <libintl.h>
117 # define _(Text) gettext (Text)
118 #else
119 # define _(Text) Text
120 #define textdomain(Domain)
121 #define bindtextdomain(Package, Directory)
122 #endif
123 #ifdef gettext_noop
124 # define N_(String) gettext_noop (String)
125 #else
126 /* See locate.c for explanation as to why not use (String) */
127 # define N_(String) String
128 #endif
130 #include "buildcmd.h"
133 /* Return nonzero if S is the EOF string. */
134 #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
136 extern char **environ;
138 /* Do multibyte processing if multibyte characters are supported,
139 unless multibyte sequences are search safe. Multibyte sequences
140 are search safe if searching for a substring using the byte
141 comparison function 'strstr' gives no false positives. All 8-bit
142 encodings and the UTF-8 multibyte encoding are search safe, but
143 the EUC encodings are not.
144 BeOS uses the UTF-8 encoding exclusively, so it is search safe. */
145 #if defined __BEOS__
146 # define MULTIBYTE_IS_SEARCH_SAFE 1
147 #endif
148 #define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE)
150 #if DO_MULTIBYTE
151 # if HAVE_MBRLEN
152 # include <wchar.h>
153 # else
154 /* Simulate mbrlen with mblen as best we can. */
155 # define mbstate_t int
156 # define mbrlen(s, n, ps) mblen (s, n)
157 # endif
158 #endif
160 /* Not char because of type promotion; NeXT gcc can't handle it. */
161 typedef int boolean;
162 #define true 1
163 #define false 0
165 #if __STDC__
166 #define VOID void
167 #else
168 #define VOID char
169 #endif
171 #include <xalloc.h>
172 #include "closeout.h"
174 void error PARAMS ((int status, int errnum, char *message,...));
176 extern char *version_string;
178 /* The name this program was run with. */
179 char *program_name;
181 static FILE *input_stream;
183 /* Buffer for reading arguments from input. */
184 static char *linebuf;
186 static int keep_stdin = 0;
188 /* Line number in stdin since the last command was executed. */
189 static int lineno = 0;
191 static struct buildcmd_state bc_state;
192 static struct buildcmd_control bc_ctl;
195 /* If nonzero, when this string is read on stdin it is treated as
196 end of file.
197 IEEE Std 1003.1, 2004 Edition allows this to be NULL.
198 In findutils releases up to and including 4.2.8, this was "_".
200 static char *eof_str = NULL;
202 /* Number of chars in the initial args. */
203 /* static int initial_argv_chars = 0; */
205 /* true when building up initial arguments in `cmd_argv'. */
206 static boolean initial_args = true;
208 /* If nonzero, the maximum number of child processes that can be running
209 at once. */
210 static int proc_max = 1;
212 /* Total number of child processes that have been executed. */
213 static int procs_executed = 0;
215 /* The number of elements in `pids'. */
216 static int procs_executing = 0;
218 /* List of child processes currently executing. */
219 static pid_t *pids = NULL;
221 /* The number of allocated elements in `pids'. */
222 static int pids_alloc = 0;
224 /* Exit status; nonzero if any child process exited with a
225 status of 1-125. */
226 volatile static int child_error = 0;
228 volatile static int original_exit_value;
230 /* If true, print each command on stderr before executing it. */
231 static boolean print_command = false; /* Option -t */
233 /* If true, query the user before executing each command, and only
234 execute the command if the user responds affirmatively. */
235 static boolean query_before_executing = false;
237 /* The delimiter for input arguments. This is only consulted if the
238 * -0 or -d option had been given.
240 static char input_delimiter = '\0';
243 static struct option const longopts[] =
245 {"null", no_argument, NULL, '0'},
246 {"arg-file", required_argument, NULL, 'a'},
247 {"delimiter", required_argument, NULL, 'd'},
248 {"eof", optional_argument, NULL, 'e'},
249 {"replace", optional_argument, NULL, 'I'},
250 {"max-lines", optional_argument, NULL, 'l'},
251 {"max-args", required_argument, NULL, 'n'},
252 {"interactive", no_argument, NULL, 'p'},
253 {"no-run-if-empty", no_argument, NULL, 'r'},
254 {"max-chars", required_argument, NULL, 's'},
255 {"verbose", no_argument, NULL, 't'},
256 {"show-limits", no_argument, NULL, 'S'},
257 {"exit", no_argument, NULL, 'x'},
258 {"max-procs", required_argument, NULL, 'P'},
259 {"version", no_argument, NULL, 'v'},
260 {"help", no_argument, NULL, 'h'},
261 {NULL, no_argument, NULL, 0}
264 static int read_line PARAMS ((void));
265 static int read_string PARAMS ((void));
266 static boolean print_args PARAMS ((boolean ask));
267 /* static void do_exec PARAMS ((void)); */
268 static int xargs_do_exec (const struct buildcmd_control *cl, struct buildcmd_state *state);
269 static void exec_if_possible PARAMS ((void));
270 static void add_proc PARAMS ((pid_t pid));
271 static void wait_for_proc PARAMS ((boolean all));
272 static void wait_for_proc_all PARAMS ((void));
273 static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
274 static long env_size PARAMS ((char **envp));
275 static void usage PARAMS ((FILE * stream));
279 static long
280 get_line_max(void)
282 long val;
283 #ifdef _SC_LINE_MAX
284 val = sysconf(_SC_LINE_MAX);
285 #else
286 val = -1;
287 #endif
289 if (val > 0)
290 return val;
292 /* either _SC_LINE_MAX was not available or
293 * there is no particular limit.
295 #ifdef LINE_MAX
296 val = LINE_MAX;
297 #endif
299 if (val > 0)
300 return val;
302 return 2048L; /* a reasonable guess. */
305 static char
306 get_char_oct_or_hex_escape(const char *s)
308 const char * p;
309 int base = 8;
310 unsigned long val;
311 char *endp;
313 assert('\\' == s[0]);
315 if ('x' == s[1])
317 /* hex */
318 p = s+2;
319 base = 16;
321 else if (isdigit(s[1]))
323 /* octal */
324 p = s+1;
325 base = 8;
327 else
329 error(1, 0,
330 _("Invalid escape sequence %s in input delimiter specification."),
333 errno = 0;
334 endp = (char*)p;
335 val = strtoul(p, &endp, base);
337 /* This if condition is carefully constructed to do
338 * the right thing if UCHAR_MAX has the same
339 * value as ULONG_MAX. IF UCHAR_MAX==ULONG_MAX,
340 * then val can never be greater than UCHAR_MAX.
342 if ((ULONG_MAX == val && ERANGE == errno)
343 || (val > UCHAR_MAX))
345 if (16 == base)
347 error(1, 0,
348 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lx."),
349 s, (unsigned long)UCHAR_MAX);
351 else
353 error(1, 0,
354 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lo."),
355 s, (unsigned long)UCHAR_MAX);
359 /* check for trailing garbage */
360 if (0 != *endp)
362 error(1, 0,
363 _("Invalid escape sequence %s in input delimiter specification; trailing characters %s not recognised."),
364 s, endp);
367 return (char) val;
371 static char
372 get_input_delimiter(const char *s)
374 char result = '\0';
376 if (1 == strlen(s))
378 return s[0];
380 else
382 if ('\\' == s[0])
384 /* an escape code */
385 switch (s[1])
387 case 'a':
388 return '\a';
389 case 'b':
390 return '\b';
391 case 'f':
392 return '\f';
393 case 'n':
394 return '\n';
395 case 'r':
396 return '\r';
397 case 't':
398 return'\t';
399 case 'v':
400 return '\v';
401 case '\\':
402 return '\\';
403 default:
404 return get_char_oct_or_hex_escape(s);
407 else
409 error(1, 0,
410 _("Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\."),
419 main (int argc, char **argv)
421 int optc;
422 int show_limits = 0; /* --show-limits */
423 int always_run_command = 1;
424 char *input_file = "-"; /* "-" is stdin */
425 long posix_arg_size_max;
426 long posix_arg_size_min;
427 long arg_size;
428 long size_of_environment = env_size(environ);
429 char *default_cmd = "/bin/echo";
430 int (*read_args) PARAMS ((void)) = read_line;
431 int env_too_big = 0;
433 program_name = argv[0];
434 original_exit_value = 0;
436 #ifdef HAVE_SETLOCALE
437 setlocale (LC_ALL, "");
438 #endif
439 bindtextdomain (PACKAGE, LOCALEDIR);
440 textdomain (PACKAGE);
441 atexit (close_stdout);
442 atexit (wait_for_proc_all);
444 /* IEEE Std 1003.1, 2003 specifies that the combined argument and
445 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
446 * specifies that it shall be at least LINE_MAX.
448 posix_arg_size_min = get_line_max();
449 posix_arg_size_max = bc_get_arg_max();
450 posix_arg_size_max -= 2048; /* POSIX.2 requires subtracting 2048. */
452 bc_init_controlinfo(&bc_ctl);
453 assert(bc_ctl.arg_max == posix_arg_size_max);
455 bc_ctl.exec_callback = xargs_do_exec;
458 /* Start with a reasonable default size, though this can be
459 * adjusted via the -s option.
461 arg_size = (128 * 1024) + size_of_environment;
463 /* Take the size of the environment into account. */
464 if (size_of_environment > posix_arg_size_max)
466 bc_ctl.arg_max = 0;
467 env_too_big = 1;
469 else
471 bc_ctl.arg_max = posix_arg_size_max - size_of_environment;
474 /* Check against the upper and lower limits. */
475 if (arg_size > bc_ctl.arg_max)
476 arg_size = bc_ctl.arg_max;
477 if (arg_size < posix_arg_size_min)
478 arg_size = posix_arg_size_min;
483 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:d:",
484 longopts, (int *) 0)) != -1)
486 switch (optc)
488 case '0':
489 read_args = read_string;
490 input_delimiter = '\0';
491 break;
493 case 'd':
494 read_args = read_string;
495 input_delimiter = get_input_delimiter(optarg);
496 break;
498 case 'E': /* POSIX */
499 case 'e': /* deprecated */
500 if (optarg && (strlen(optarg) > 0))
501 eof_str = optarg;
502 else
503 eof_str = 0;
504 break;
506 case 'h':
507 usage (stdout);
508 return 0;
510 case 'I': /* POSIX */
511 case 'i': /* deprecated */
512 if (optarg)
513 bc_ctl.replace_pat = optarg;
514 else
515 bc_ctl.replace_pat = "{}";
516 /* -i excludes -n -l. */
517 bc_ctl.args_per_exec = 0;
518 bc_ctl.lines_per_exec = 0;
519 break;
521 case 'L': /* POSIX */
522 bc_ctl.lines_per_exec = parse_num (optarg, 'L', 1L, -1L, 1);
523 /* -L excludes -i -n. */
524 bc_ctl.args_per_exec = 0;
525 bc_ctl.replace_pat = NULL;
526 break;
528 case 'l': /* deprecated */
529 if (optarg)
530 bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
531 else
532 bc_ctl.lines_per_exec = 1;
533 /* -l excludes -i -n. */
534 bc_ctl.args_per_exec = 0;
535 bc_ctl.replace_pat = NULL;
536 break;
538 case 'n':
539 bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
540 /* -n excludes -i -l. */
541 bc_ctl.lines_per_exec = 0;
542 if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
543 /* ignore -n1 in '-i -n1' */
544 bc_ctl.args_per_exec = 0;
545 else
546 bc_ctl.replace_pat = NULL;
547 break;
549 /* The POSIX standard specifies that it is not an error
550 * for the -s option to specify a size that the implementation
551 * cannot support - in that case, the relevant limit is used.
553 case 's':
554 arg_size = parse_num (optarg, 's', 1L, posix_arg_size_max, 0);
555 if (arg_size > posix_arg_size_max)
557 error (0, 0, "warning: value %ld for -s option is too large, using %ld instead", arg_size, posix_arg_size_max);
558 arg_size = posix_arg_size_max;
560 break;
562 case 'S':
563 show_limits = true;
564 break;
566 case 't':
567 print_command = true;
568 break;
570 case 'x':
571 bc_ctl.exit_if_size_exceeded = true;
572 break;
574 case 'p':
575 query_before_executing = true;
576 print_command = true;
577 break;
579 case 'r':
580 always_run_command = 0;
581 break;
583 case 'P':
584 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
585 break;
587 case 'a':
588 input_file = optarg;
589 break;
591 case 'v':
592 printf (_("GNU xargs version %s\n"), version_string);
593 return 0;
595 default:
596 usage (stderr);
597 return 1;
601 if (env_too_big)
603 /* We issue this error message after processing command line
604 * arguments so that it is possible to use "xargs --help" even if
605 * the environment is too large.
607 error (1, 0, _("environment is too large for exec"));
610 if (0 == strcmp (input_file, "-"))
612 input_stream = stdin;
614 else
616 keep_stdin = 1; /* see prep_child_for_exec() */
617 input_stream = fopen (input_file, "r");
618 if (NULL == input_stream)
620 error (1, errno,
621 _("Cannot open input file `%s'"),
622 input_file);
626 if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
627 bc_ctl.exit_if_size_exceeded = true;
629 if (optind == argc)
631 optind = 0;
632 argc = 1;
633 argv = &default_cmd;
636 /* Taking into account the size of the environment,
637 * figure out how large a buffer we need to
638 * hold all the arguments. We cannot use ARG_MAX
639 * directly since that may be arbitrarily large.
640 * This is from a patch by Bob Proulx, <bob@proulx.com>.
642 if (bc_ctl.arg_max > arg_size)
644 if (show_limits)
646 fprintf(stderr,
647 _("Reducing arg_max (%ld) to arg_size (%ld)\n"),
648 bc_ctl.arg_max, arg_size);
650 bc_ctl.arg_max = arg_size;
653 if (show_limits)
655 fprintf(stderr,
656 _("Your environment variables take up %ld bytes\n"),
657 size_of_environment);
658 fprintf(stderr,
659 _("POSIX lower and upper limits on argument length: %ld, %ld\n"),
660 posix_arg_size_min,
661 posix_arg_size_max);
662 fprintf(stderr,
663 _("Maximum length of command we could actually use: %ld\n"),
664 (posix_arg_size_max - size_of_environment));
665 fprintf(stderr,
666 _("Size of command buffer we are actually using: %ld\n"),
667 bc_ctl.arg_max);
669 if (isatty(STDIN_FILENO))
671 fprintf(stderr,
672 "\n"
673 "Execution of xargs will continue now, and it will "
674 "try to read its input and run commands; if this is "
675 "not what you wanted to happen, please type the "
676 "end-of-file keystroke.\n");
681 linebuf = (char *) xmalloc (bc_ctl.arg_max + 1);
682 bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1);
684 /* Make sure to listen for the kids. */
685 signal (SIGCHLD, SIG_DFL);
687 if (!bc_ctl.replace_pat)
689 for (; optind < argc; optind++)
690 bc_push_arg (&bc_ctl, &bc_state,
691 argv[optind], strlen (argv[optind]) + 1,
692 NULL, 0,
693 initial_args);
694 initial_args = false;
695 bc_ctl.initial_argc = bc_state.cmd_argc;
696 bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
698 while ((*read_args) () != -1)
699 if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
701 xargs_do_exec (&bc_ctl, &bc_state);
702 lineno = 0;
705 /* SYSV xargs seems to do at least one exec, even if the
706 input is empty. */
707 if (bc_state.cmd_argc != bc_ctl.initial_argc
708 || (always_run_command && procs_executed == 0))
709 xargs_do_exec (&bc_ctl, &bc_state);
712 else
714 int i;
715 size_t len;
716 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
718 for (i = optind; i < argc; i++)
719 arglen[i] = strlen(argv[i]);
720 bc_ctl.rplen = strlen (bc_ctl.replace_pat);
721 while ((len = (*read_args) ()) != -1)
723 /* Don't do insert on the command name. */
724 bc_clear_args(&bc_ctl, &bc_state);
725 bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
727 bc_push_arg (&bc_ctl, &bc_state,
728 argv[optind], arglen[optind] + 1,
729 NULL, 0,
730 initial_args);
731 len--;
732 initial_args = false;
734 for (i = optind + 1; i < argc; i++)
735 bc_do_insert (&bc_ctl, &bc_state,
736 argv[i], arglen[i],
737 NULL, 0,
738 linebuf, len,
739 initial_args);
740 xargs_do_exec (&bc_ctl, &bc_state);
744 original_exit_value = child_error;
745 return child_error;
749 /* Read a line of arguments from the input and add them to the list of
750 arguments to pass to the command. Ignore blank lines and initial blanks.
751 Single and double quotes and backslashes quote metacharacters and blanks
752 as they do in the shell.
753 Return -1 if eof (either physical or logical) is reached,
754 otherwise the length of the last string read (including the null). */
756 static int
757 read_line (void)
759 static boolean eof = false;
760 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
761 int state = SPACE; /* The type of character we last read. */
762 int prevc; /* The previous value of c. */
763 int quotc = 0; /* The last quote character read. */
764 int c = EOF;
765 boolean first = true; /* true if reading first arg on line. */
766 int len;
767 char *p = linebuf;
768 /* Including the NUL, the args must not grow past this point. */
769 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
771 if (eof)
772 return -1;
773 while (1)
775 prevc = c;
776 c = getc (input_stream);
777 if (c == EOF)
779 /* COMPAT: SYSV seems to ignore stuff on a line that
780 ends without a \n; we don't. */
781 eof = true;
782 if (p == linebuf)
783 return -1;
784 *p++ = '\0';
785 len = p - linebuf;
786 if (state == QUOTE)
788 exec_if_possible ();
789 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
790 quotc == '"' ? _("double") : _("single"));
792 if (first && EOF_STR (linebuf))
793 return -1;
794 if (!bc_ctl.replace_pat)
795 bc_push_arg (&bc_ctl, &bc_state,
796 linebuf, len,
797 NULL, 0,
798 initial_args);
799 return len;
801 switch (state)
803 case SPACE:
804 if (ISSPACE (c))
805 continue;
806 state = NORM;
807 /* aaahhhh.... */
809 case NORM:
810 if (c == '\n')
812 if (!ISBLANK (prevc))
813 lineno++; /* For -l. */
814 if (p == linebuf)
816 /* Blank line. */
817 state = SPACE;
818 continue;
820 *p++ = '\0';
821 len = p - linebuf;
822 if (EOF_STR (linebuf))
824 eof = true;
825 return first ? -1 : len;
827 if (!bc_ctl.replace_pat)
828 bc_push_arg (&bc_ctl, &bc_state,
829 linebuf, len,
830 NULL, 0,
831 initial_args);
832 return len;
834 if (!bc_ctl.replace_pat && ISSPACE (c))
836 *p++ = '\0';
837 len = p - linebuf;
838 if (EOF_STR (linebuf))
840 eof = true;
841 return first ? -1 : len;
843 bc_push_arg (&bc_ctl, &bc_state,
844 linebuf, len,
845 NULL, 0,
846 initial_args);
847 p = linebuf;
848 state = SPACE;
849 first = false;
850 continue;
852 switch (c)
854 case '\\':
855 state = BACKSLASH;
856 continue;
858 case '\'':
859 case '"':
860 state = QUOTE;
861 quotc = c;
862 continue;
864 break;
866 case QUOTE:
867 if (c == '\n')
869 exec_if_possible ();
870 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
871 quotc == '"' ? _("double") : _("single"));
873 if (c == quotc)
875 state = NORM;
876 continue;
878 break;
880 case BACKSLASH:
881 state = NORM;
882 break;
884 #if 1
885 if (p >= endbuf)
887 exec_if_possible ();
888 error (1, 0, _("argument line too long"));
890 *p++ = c;
891 #else
892 append_char_to_buf(&linebuf, &endbuf, &p, c);
893 #endif
897 /* Read a null-terminated string from the input and add it to the list of
898 arguments to pass to the command.
899 Return -1 if eof (either physical or logical) is reached,
900 otherwise the length of the string read (including the null). */
902 static int
903 read_string (void)
905 static boolean eof = false;
906 int len;
907 char *p = linebuf;
908 /* Including the NUL, the args must not grow past this point. */
909 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
911 if (eof)
912 return -1;
913 while (1)
915 int c = getc (input_stream);
916 if (c == EOF)
918 eof = true;
919 if (p == linebuf)
920 return -1;
921 *p++ = '\0';
922 len = p - linebuf;
923 if (!bc_ctl.replace_pat)
924 bc_push_arg (&bc_ctl, &bc_state,
925 linebuf, len,
926 NULL, 0,
927 initial_args);
928 return len;
930 if (c == input_delimiter)
932 lineno++; /* For -l. */
933 *p++ = '\0';
934 len = p - linebuf;
935 if (!bc_ctl.replace_pat)
936 bc_push_arg (&bc_ctl, &bc_state,
937 linebuf, len,
938 NULL, 0,
939 initial_args);
940 return len;
942 if (p >= endbuf)
944 exec_if_possible ();
945 error (1, 0, _("argument line too long"));
947 *p++ = c;
951 /* Print the arguments of the command to execute.
952 If ASK is nonzero, prompt the user for a response, and
953 if the user responds affirmatively, return true;
954 otherwise, return false. */
956 static boolean
957 print_args (boolean ask)
959 int i;
961 for (i = 0; i < bc_state.cmd_argc - 1; i++)
962 fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
963 if (ask)
965 static FILE *tty_stream;
966 int c, savec;
968 if (!tty_stream)
970 tty_stream = fopen ("/dev/tty", "r");
971 if (!tty_stream)
972 error (1, errno, "/dev/tty");
974 fputs ("?...", stderr);
975 fflush (stderr);
976 c = savec = getc (tty_stream);
977 while (c != EOF && c != '\n')
978 c = getc (tty_stream);
979 if (savec == 'y' || savec == 'Y')
980 return true;
982 else
983 putc ('\n', stderr);
985 return false;
989 /* Close stdin and attach /dev/null to it.
990 * This resolves Savannah bug #3992.
992 static void
993 prep_child_for_exec (void)
995 if (!keep_stdin)
997 const char inputfile[] = "/dev/null";
998 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
1000 close(0);
1001 if (open(inputfile, O_RDONLY) < 0)
1003 /* This is not entirely fatal, since
1004 * executing the child with a closed
1005 * stdin is almost as good as executing it
1006 * with its stdin attached to /dev/null.
1008 error (0, errno, "%s", inputfile);
1014 /* Execute the command that has been built in `cmd_argv'. This may involve
1015 waiting for processes that were previously executed. */
1017 static int
1018 xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
1020 pid_t child;
1022 bc_push_arg (&bc_ctl, &bc_state,
1023 (char *) NULL, 0,
1024 NULL, 0,
1025 false); /* Null terminate the arg list. */
1027 if (!query_before_executing || print_args (true))
1029 if (proc_max && procs_executing >= proc_max)
1030 wait_for_proc (false);
1031 if (!query_before_executing && print_command)
1032 print_args (false);
1033 /* If we run out of processes, wait for a child to return and
1034 try again. */
1035 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1036 wait_for_proc (false);
1037 switch (child)
1039 case -1:
1040 error (1, errno, _("cannot fork"));
1042 case 0: /* Child. */
1043 prep_child_for_exec();
1044 execvp (bc_state.cmd_argv[0], bc_state.cmd_argv);
1045 error (0, errno, "%s", bc_state.cmd_argv[0]);
1046 _exit (errno == ENOENT ? 127 : 126);
1047 /*NOTREACHED*/
1049 add_proc (child);
1052 bc_clear_args(&bc_ctl, &bc_state);
1053 return 1; /* Success */
1056 /* Execute the command if possible. */
1058 static void
1059 exec_if_possible (void)
1061 if (bc_ctl.replace_pat || initial_args ||
1062 bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded)
1063 return;
1064 xargs_do_exec (&bc_ctl, &bc_state);
1067 /* Add the process with id PID to the list of processes that have
1068 been executed. */
1070 static void
1071 add_proc (pid_t pid)
1073 int i;
1075 /* Find an empty slot. */
1076 for (i = 0; i < pids_alloc && pids[i]; i++)
1078 if (i == pids_alloc)
1080 if (pids_alloc == 0)
1082 pids_alloc = proc_max ? proc_max : 64;
1083 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1085 else
1087 pids_alloc *= 2;
1088 pids = (pid_t *) xrealloc (pids,
1089 sizeof (pid_t) * pids_alloc);
1091 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1093 pids[i] = pid;
1094 procs_executing++;
1095 procs_executed++;
1098 /* If ALL is true, wait for all child processes to finish;
1099 otherwise, wait for one child process to finish.
1100 Remove the processes that finish from the list of executing processes. */
1102 static void
1103 wait_for_proc (boolean all)
1105 while (procs_executing)
1107 int i, status;
1111 pid_t pid;
1113 while ((pid = wait (&status)) == (pid_t) -1)
1114 if (errno != EINTR)
1115 error (1, errno, _("error waiting for child process"));
1117 /* Find the entry in `pids' for the child process
1118 that exited. */
1119 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1122 while (i == pids_alloc); /* A child died that we didn't start? */
1124 /* Remove the child from the list. */
1125 pids[i] = 0;
1126 procs_executing--;
1128 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1129 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1130 if (WEXITSTATUS (status) == 255)
1131 error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1132 if (WIFSTOPPED (status))
1133 error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1134 if (WIFSIGNALED (status))
1135 error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1136 if (WEXITSTATUS (status) != 0)
1137 child_error = 123;
1139 if (!all)
1140 break;
1144 /* Wait for all child processes to finish. */
1146 static void
1147 wait_for_proc_all (void)
1149 static boolean waiting = false;
1151 if (waiting)
1152 return;
1154 waiting = true;
1155 wait_for_proc (true);
1156 waiting = false;
1158 if (original_exit_value != child_error)
1160 /* wait_for_proc() changed the value of child_error(). This
1161 * function is registered via atexit(), and so may have been
1162 * called from exit(). We now know that the original value
1163 * passed to exit() is no longer the exit status we require.
1164 * The POSIX standard states that the behaviour if exit() is
1165 * called more than once is undefined. Therefore we now have to
1166 * exit with _exit() instead of exit().
1168 _exit(child_error);
1173 /* Return the value of the number represented in STR.
1174 OPTION is the command line option to which STR is the argument.
1175 If the value does not fall within the boundaries MIN and MAX,
1176 Print an error message mentioning OPTION. If FATAL is true,
1177 we also exit. */
1179 static long
1180 parse_num (char *str, int option, long int min, long int max, int fatal)
1182 char *eptr;
1183 long val;
1185 val = strtol (str, &eptr, 10);
1186 if (eptr == str || *eptr)
1188 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1189 program_name, option);
1190 usage (stderr);
1191 exit(1);
1193 else if (val < min)
1195 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1196 program_name, option, min);
1197 if (fatal)
1199 usage (stderr);
1200 exit(1);
1202 else
1204 val = min;
1207 else if (max >= 0 && val > max)
1209 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1210 program_name, option, max);
1211 if (fatal)
1213 usage (stderr);
1214 exit(1);
1216 else
1218 val = max;
1221 return val;
1224 /* Return how much of ARG_MAX is used by the environment. */
1226 static long
1227 env_size (char **envp)
1229 long len = 0;
1231 while (*envp)
1232 len += strlen (*envp++) + 1;
1234 return len;
1237 static void
1238 usage (FILE *stream)
1240 fprintf (stream, _("\
1241 Usage: %s [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]\n\
1242 [-E eof-str] [-e[eof-str]] [--eof[=eof-str]]\n\
1243 [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]\n\
1244 [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]\n\
1245 [-n max-args] [--max-args=max-args]\n\
1246 [-s max-chars] [--max-chars=max-chars]\n\
1247 [-P max-procs] [--max-procs=max-procs]\n\
1248 [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]\n\
1249 [--version] [--help] [command [initial-arguments]]\n"),
1250 program_name);
1251 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);