Applied patch from Eric Blake fixing Savannab bug# 19660
[findutils.git] / xargs / xargs.c
blobddbe0cb787ce329c1cd5595ed168ba3950351f02
1 /* xargs -- build and execute command lines from standard input
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005, 2006, 2007 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"
101 #ifdef STDC_HEADERS
102 #include <stdlib.h>
103 #else
104 extern int errno;
105 #endif
107 #ifdef HAVE_LOCALE_H
108 #include <locale.h>
109 #endif
110 #if ENABLE_NLS
111 # include <libintl.h>
112 # define _(Text) gettext (Text)
113 #else
114 # define _(Text) Text
115 #define textdomain(Domain)
116 #define bindtextdomain(Package, Directory)
117 #endif
118 #ifdef gettext_noop
119 # define N_(String) gettext_noop (String)
120 #else
121 /* See locate.c for explanation as to why not use (String) */
122 # define N_(String) String
123 #endif
125 #include "buildcmd.h"
128 /* Return nonzero if S is the EOF string. */
129 #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
131 /* Do multibyte processing if multibyte characters are supported,
132 unless multibyte sequences are search safe. Multibyte sequences
133 are search safe if searching for a substring using the byte
134 comparison function 'strstr' gives no false positives. All 8-bit
135 encodings and the UTF-8 multibyte encoding are search safe, but
136 the EUC encodings are not.
137 BeOS uses the UTF-8 encoding exclusively, so it is search safe. */
138 #if defined __BEOS__
139 # define MULTIBYTE_IS_SEARCH_SAFE 1
140 #endif
141 #define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE)
143 #if DO_MULTIBYTE
144 # if HAVE_MBRLEN
145 # include <wchar.h>
146 # else
147 /* Simulate mbrlen with mblen as best we can. */
148 # define mbstate_t int
149 # define mbrlen(s, n, ps) mblen (s, n)
150 # endif
151 #endif
153 /* Not char because of type promotion; NeXT gcc can't handle it. */
154 typedef int boolean;
155 #define true 1
156 #define false 0
158 #if __STDC__
159 #define VOID void
160 #else
161 #define VOID char
162 #endif
164 #include <xalloc.h>
165 #include "closeout.h"
166 #include "gnulib-version.h"
168 void error PARAMS ((int status, int errnum, char *message,...));
170 extern char *version_string;
172 /* The name this program was run with. */
173 char *program_name;
175 static FILE *input_stream;
177 /* Buffer for reading arguments from input. */
178 static char *linebuf;
180 static int keep_stdin = 0;
182 /* Line number in stdin since the last command was executed. */
183 static int lineno = 0;
185 static struct buildcmd_state bc_state;
186 static struct buildcmd_control bc_ctl;
188 /* Did we already complain about NUL characters in the input? */
189 static int nullwarning_given = 0;
192 /* If nonzero, when this string is read on stdin it is treated as
193 end of file.
194 IEEE Std 1003.1, 2004 Edition allows this to be NULL.
195 In findutils releases up to and including 4.2.8, this was "_".
197 static char *eof_str = NULL;
199 /* Number of chars in the initial args. */
200 /* static int initial_argv_chars = 0; */
202 /* true when building up initial arguments in `cmd_argv'. */
203 static boolean initial_args = true;
205 /* If nonzero, the maximum number of child processes that can be running
206 at once. */
207 static int proc_max = 1;
209 /* Total number of child processes that have been executed. */
210 static int procs_executed = 0;
212 /* The number of elements in `pids'. */
213 static int procs_executing = 0;
215 /* List of child processes currently executing. */
216 static pid_t *pids = NULL;
218 /* The number of allocated elements in `pids'. */
219 static int pids_alloc = 0;
221 /* Exit status; nonzero if any child process exited with a
222 status of 1-125. */
223 static volatile int child_error = 0;
225 static volatile int original_exit_value;
227 /* If true, print each command on stderr before executing it. */
228 static boolean print_command = false; /* Option -t */
230 /* If true, query the user before executing each command, and only
231 execute the command if the user responds affirmatively. */
232 static boolean query_before_executing = false;
234 /* The delimiter for input arguments. This is only consulted if the
235 * -0 or -d option had been given.
237 static char input_delimiter = '\0';
240 static struct option const longopts[] =
242 {"null", no_argument, NULL, '0'},
243 {"arg-file", required_argument, NULL, 'a'},
244 {"delimiter", required_argument, NULL, 'd'},
245 {"eof", optional_argument, NULL, 'e'},
246 {"replace", optional_argument, NULL, 'I'},
247 {"max-lines", optional_argument, NULL, 'l'},
248 {"max-args", required_argument, NULL, 'n'},
249 {"interactive", no_argument, NULL, 'p'},
250 {"no-run-if-empty", no_argument, NULL, 'r'},
251 {"max-chars", required_argument, NULL, 's'},
252 {"verbose", no_argument, NULL, 't'},
253 {"show-limits", no_argument, NULL, 'S'},
254 {"exit", no_argument, NULL, 'x'},
255 {"max-procs", required_argument, NULL, 'P'},
256 {"version", no_argument, NULL, 'v'},
257 {"help", no_argument, NULL, 'h'},
258 {NULL, no_argument, NULL, 0}
261 static int read_line PARAMS ((void));
262 static int read_string PARAMS ((void));
263 static boolean print_args PARAMS ((boolean ask));
264 /* static void do_exec PARAMS ((void)); */
265 static int xargs_do_exec (const struct buildcmd_control *cl, struct buildcmd_state *state);
266 static void exec_if_possible PARAMS ((void));
267 static void add_proc PARAMS ((pid_t pid));
268 static void wait_for_proc PARAMS ((boolean all));
269 static void wait_for_proc_all PARAMS ((void));
270 static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
271 static void usage PARAMS ((FILE * stream));
275 static char
276 get_char_oct_or_hex_escape(const char *s)
278 const char * p;
279 int base = 8;
280 unsigned long val;
281 char *endp;
283 assert('\\' == s[0]);
285 if ('x' == s[1])
287 /* hex */
288 p = s+2;
289 base = 16;
291 else if (isdigit(s[1]))
293 /* octal */
294 p = s+1;
295 base = 8;
297 else
299 p = NULL; /* Silence compiler warning. */
300 error(1, 0,
301 _("Invalid escape sequence %s in input delimiter specification."),
304 errno = 0;
305 endp = (char*)p;
306 val = strtoul(p, &endp, base);
308 /* This if condition is carefully constructed to do
309 * the right thing if UCHAR_MAX has the same
310 * value as ULONG_MAX. IF UCHAR_MAX==ULONG_MAX,
311 * then val can never be greater than UCHAR_MAX.
313 if ((ULONG_MAX == val && ERANGE == errno)
314 || (val > UCHAR_MAX))
316 if (16 == base)
318 error(1, 0,
319 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lx."),
320 s, (unsigned long)UCHAR_MAX);
322 else
324 error(1, 0,
325 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lo."),
326 s, (unsigned long)UCHAR_MAX);
330 /* check for trailing garbage */
331 if (0 != *endp)
333 error(1, 0,
334 _("Invalid escape sequence %s in input delimiter specification; trailing characters %s not recognised."),
335 s, endp);
338 return (char) val;
342 static char
343 get_input_delimiter(const char *s)
345 if (1 == strlen(s))
347 return s[0];
349 else
351 if ('\\' == s[0])
353 /* an escape code */
354 switch (s[1])
356 case 'a':
357 return '\a';
358 case 'b':
359 return '\b';
360 case 'f':
361 return '\f';
362 case 'n':
363 return '\n';
364 case 'r':
365 return '\r';
366 case 't':
367 return'\t';
368 case 'v':
369 return '\v';
370 case '\\':
371 return '\\';
372 default:
373 return get_char_oct_or_hex_escape(s);
376 else
378 error(1, 0,
379 _("Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\."),
381 /*NOTREACHED*/
382 return 0;
387 static void
388 noop (void)
390 /* does nothing. */
393 static void
394 fail_due_to_env_size (void)
396 error (1, 0, _("environment is too large for exec"));
401 main (int argc, char **argv)
403 int optc;
404 int show_limits = 0; /* --show-limits */
405 int always_run_command = 1;
406 char *input_file = "-"; /* "-" is stdin */
407 char *default_cmd = "/bin/echo";
408 int (*read_args) PARAMS ((void)) = read_line;
409 void (*act_on_init_result)(void) = noop;
410 enum BC_INIT_STATUS bcstatus;
412 program_name = argv[0];
413 original_exit_value = 0;
415 #ifdef HAVE_SETLOCALE
416 setlocale (LC_ALL, "");
417 #endif
418 bindtextdomain (PACKAGE, LOCALEDIR);
419 textdomain (PACKAGE);
420 atexit (close_stdout);
421 atexit (wait_for_proc_all);
423 bcstatus = bc_init_controlinfo(&bc_ctl);
425 /* The bc_init_controlinfo call may have determined that the
426 * environment is too big. In that case, we will fail with
427 * an error message after processing the command-line options,
428 * as "xargs --help" should still work even if the environment is
429 * too big.
431 * Some of the argument processing depends on the contents of
432 * bc_ctl, which will be in an undefined state if bc_init_controlinfo()
433 * failed.
435 if (BC_INIT_ENV_TOO_BIG == bcstatus)
437 act_on_init_result = fail_due_to_env_size;
439 else
441 /* IEEE Std 1003.1, 2003 specifies that the combined argument and
442 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
443 * specifies that it shall be at least LINE_MAX.
445 #if defined(ARG_MAX)
446 assert(bc_ctl.arg_max <= (ARG_MAX-2048));
447 #endif
448 #ifdef LINE_MAX
449 assert(bc_ctl.arg_max >= LINE_MAX);
450 #endif
452 bc_ctl.exec_callback = xargs_do_exec;
454 /* Start with a reasonable default size, though this can be
455 * adjusted via the -s option.
457 bc_use_sensible_arg_max(&bc_ctl);
460 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:d:",
461 longopts, (int *) 0)) != -1)
463 switch (optc)
465 case '0':
466 read_args = read_string;
467 input_delimiter = '\0';
468 break;
470 case 'd':
471 read_args = read_string;
472 input_delimiter = get_input_delimiter(optarg);
473 break;
475 case 'E': /* POSIX */
476 case 'e': /* deprecated */
477 if (optarg && (strlen(optarg) > 0))
478 eof_str = optarg;
479 else
480 eof_str = 0;
481 break;
483 case 'h':
484 usage (stdout);
485 return 0;
487 case 'I': /* POSIX */
488 case 'i': /* deprecated */
489 if (optarg)
490 bc_ctl.replace_pat = optarg;
491 else
492 bc_ctl.replace_pat = "{}";
493 /* -i excludes -n -l. */
494 bc_ctl.args_per_exec = 0;
495 bc_ctl.lines_per_exec = 0;
496 break;
498 case 'L': /* POSIX */
499 bc_ctl.lines_per_exec = parse_num (optarg, 'L', 1L, -1L, 1);
500 /* -L excludes -i -n. */
501 bc_ctl.args_per_exec = 0;
502 bc_ctl.replace_pat = NULL;
503 break;
505 case 'l': /* deprecated */
506 if (optarg)
507 bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
508 else
509 bc_ctl.lines_per_exec = 1;
510 /* -l excludes -i -n. */
511 bc_ctl.args_per_exec = 0;
512 bc_ctl.replace_pat = NULL;
513 break;
515 case 'n':
516 bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
517 /* -n excludes -i -l. */
518 bc_ctl.lines_per_exec = 0;
519 if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
520 /* ignore -n1 in '-i -n1' */
521 bc_ctl.args_per_exec = 0;
522 else
523 bc_ctl.replace_pat = NULL;
524 break;
526 /* The POSIX standard specifies that it is not an error
527 * for the -s option to specify a size that the implementation
528 * cannot support - in that case, the relevant limit is used.
530 case 's':
532 size_t arg_size;
533 act_on_init_result();
534 arg_size = parse_num (optarg, 's', 1L,
535 bc_ctl.posix_arg_size_max, 0);
536 if (arg_size > bc_ctl.posix_arg_size_max)
538 error (0, 0,
539 _("warning: value %ld for -s option is too large, "
540 "using %ld instead"),
541 arg_size, bc_ctl.posix_arg_size_max);
542 arg_size = bc_ctl.posix_arg_size_max;
544 bc_ctl.arg_max = arg_size;
546 break;
548 case 'S':
549 show_limits = true;
550 break;
552 case 't':
553 print_command = true;
554 break;
556 case 'x':
557 bc_ctl.exit_if_size_exceeded = true;
558 break;
560 case 'p':
561 query_before_executing = true;
562 print_command = true;
563 break;
565 case 'r':
566 always_run_command = 0;
567 break;
569 case 'P':
570 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
571 break;
573 case 'a':
574 input_file = optarg;
575 break;
577 case 'v':
578 printf (_("GNU xargs version %s\n"), version_string);
579 printf (_("Built using GNU gnulib version %s\n"), gnulib_version);
580 return 0;
582 default:
583 usage (stderr);
584 return 1;
588 /* If we had deferred failing due to problems in bc_init_controlinfo(),
589 * do it now.
591 * We issue this error message after processing command line
592 * arguments so that it is possible to use "xargs --help" even if
593 * the environment is too large.
595 act_on_init_result();
596 assert(BC_INIT_OK == bcstatus);
598 if (0 == strcmp (input_file, "-"))
600 input_stream = stdin;
602 else
604 keep_stdin = 1; /* see prep_child_for_exec() */
605 input_stream = fopen (input_file, "r");
606 if (NULL == input_stream)
608 error (1, errno,
609 _("Cannot open input file `%s'"),
610 input_file);
614 if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
615 bc_ctl.exit_if_size_exceeded = true;
617 if (optind == argc)
619 optind = 0;
620 argc = 1;
621 argv = &default_cmd;
624 /* We want to be able to print size_t values as unsigned long, so if
625 * the cast isn't value-preserving, we have a problem. This isn't a
626 * problem in C89, because size_t was known to be no wider than
627 * unsigned long. In C99 this is no longer the case, but there are
628 * special C99 ways to print such values. Unfortunately this
629 * program tries to work on both C89 and C99 systems.
631 #if defined(SIZE_MAX)
632 # if SIZE_MAX > ULONG_MAX
633 # error "I'm not sure how to print size_t values on your system"
634 # endif
635 #else
636 /* Without SIZE_MAX (i.e. limits.h) this is probably
637 * close to the best we can do.
639 assert(sizeof(size_t) <= sizeof(unsigned long));
640 #endif
642 if (show_limits)
644 fprintf(stderr,
645 _("Your environment variables take up %lu bytes\n"),
646 (unsigned long)bc_size_of_environment());
647 fprintf(stderr,
648 _("POSIX lower and upper limits on argument length: %lu, %lu\n"),
649 (unsigned long)bc_ctl.posix_arg_size_min,
650 (unsigned long)bc_ctl.posix_arg_size_max);
651 fprintf(stderr,
652 _("Maximum length of command we could actually use: %ld\n"),
653 (unsigned long)(bc_ctl.posix_arg_size_max -
654 bc_size_of_environment()));
655 fprintf(stderr,
656 _("Size of command buffer we are actually using: %lu\n"),
657 (unsigned long)bc_ctl.arg_max);
659 if (isatty(STDIN_FILENO))
661 fprintf(stderr,
662 _("\n"
663 "Execution of xargs will continue now, and it will "
664 "try to read its input and run commands; if this is "
665 "not what you wanted to happen, please type the "
666 "end-of-file keystroke.\n"));
667 if (always_run_command)
669 fprintf(stderr,
670 _("Warning: %s will be run at least once. "
671 "If you do not want that to happen, then press "
672 "the interrupt keystroke.\n"),
673 argv[optind]);
678 linebuf = (char *) xmalloc (bc_ctl.arg_max + 1);
679 bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1);
681 /* Make sure to listen for the kids. */
682 signal (SIGCHLD, SIG_DFL);
684 if (!bc_ctl.replace_pat)
686 for (; optind < argc; optind++)
687 bc_push_arg (&bc_ctl, &bc_state,
688 argv[optind], strlen (argv[optind]) + 1,
689 NULL, 0,
690 initial_args);
691 initial_args = false;
692 bc_ctl.initial_argc = bc_state.cmd_argc;
693 bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
695 while ((*read_args) () != -1)
696 if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
698 xargs_do_exec (&bc_ctl, &bc_state);
699 lineno = 0;
702 /* SYSV xargs seems to do at least one exec, even if the
703 input is empty. */
704 if (bc_state.cmd_argc != bc_ctl.initial_argc
705 || (always_run_command && procs_executed == 0))
706 xargs_do_exec (&bc_ctl, &bc_state);
709 else
711 int i;
712 size_t len;
713 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
715 for (i = optind; i < argc; i++)
716 arglen[i] = strlen(argv[i]);
717 bc_ctl.rplen = strlen (bc_ctl.replace_pat);
718 while ((len = (*read_args) ()) != -1)
720 /* Don't do insert on the command name. */
721 bc_clear_args(&bc_ctl, &bc_state);
722 bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
724 bc_push_arg (&bc_ctl, &bc_state,
725 argv[optind], arglen[optind] + 1,
726 NULL, 0,
727 initial_args);
728 len--;
729 initial_args = false;
731 for (i = optind + 1; i < argc; i++)
732 bc_do_insert (&bc_ctl, &bc_state,
733 argv[i], arglen[i],
734 NULL, 0,
735 linebuf, len,
736 initial_args);
737 xargs_do_exec (&bc_ctl, &bc_state);
741 original_exit_value = child_error;
742 return child_error;
746 /* Read a line of arguments from the input and add them to the list of
747 arguments to pass to the command. Ignore blank lines and initial blanks.
748 Single and double quotes and backslashes quote metacharacters and blanks
749 as they do in the shell.
750 Return -1 if eof (either physical or logical) is reached,
751 otherwise the length of the last string read (including the null). */
753 static int
754 read_line (void)
756 /* States for read_line. */
757 enum read_line_state
759 NORM = 0,
760 SPACE = 1,
761 QUOTE = 2,
762 BACKSLASH = 3
764 static boolean eof = false;
765 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
766 enum read_line_state state = SPACE; /* The type of character we last read. */
767 int prevc; /* The previous value of c. */
768 int quotc = 0; /* The last quote character read. */
769 int c = EOF;
770 boolean first = true; /* true if reading first arg on line. */
771 boolean seen_arg = false; /* true if we have seen any arg (or part of one) yet */
772 int len;
773 char *p = linebuf;
774 /* Including the NUL, the args must not grow past this point. */
775 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
777 if (eof)
778 return -1;
779 while (1)
781 prevc = c;
782 c = getc (input_stream);
784 if (c == EOF)
786 /* COMPAT: SYSV seems to ignore stuff on a line that
787 ends without a \n; we don't. */
788 eof = true;
789 if (p == linebuf)
790 return -1;
791 *p++ = '\0';
792 len = p - linebuf;
793 if (state == QUOTE)
795 exec_if_possible ();
796 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
797 quotc == '"' ? _("double") : _("single"));
799 if (first && EOF_STR (linebuf))
800 return -1;
801 if (!bc_ctl.replace_pat)
802 bc_push_arg (&bc_ctl, &bc_state,
803 linebuf, len,
804 NULL, 0,
805 initial_args);
806 return len;
808 switch (state)
810 case SPACE:
811 if (ISSPACE (c))
812 continue;
813 state = NORM;
814 /* aaahhhh.... */
816 case NORM:
817 if (c == '\n')
819 if (!ISBLANK (prevc))
820 lineno++; /* For -l. */
821 if (p == linebuf)
823 if (seen_arg)
825 /* An empty argument, add it to the list as normal. */
827 else
829 /* Blank line. */
830 state = SPACE;
831 continue;
834 *p++ = '\0';
835 len = p - linebuf;
836 if (EOF_STR (linebuf))
838 eof = true;
839 return first ? -1 : len;
841 if (!bc_ctl.replace_pat)
842 bc_push_arg (&bc_ctl, &bc_state,
843 linebuf, len,
844 NULL, 0,
845 initial_args);
846 return len;
848 seen_arg = true;
850 /* POSIX: In the POSIX locale, the separators are <SPC> and
851 * <TAB>, but not <FF> or <VT>.
853 if (!bc_ctl.replace_pat && ISBLANK (c))
855 *p++ = '\0';
856 len = p - linebuf;
857 if (EOF_STR (linebuf))
859 eof = true;
860 return first ? -1 : len;
862 bc_push_arg (&bc_ctl, &bc_state,
863 linebuf, len,
864 NULL, 0,
865 initial_args);
866 p = linebuf;
867 state = SPACE;
868 first = false;
869 continue;
871 switch (c)
873 case '\\':
874 state = BACKSLASH;
875 continue;
877 case '\'':
878 case '"':
879 state = QUOTE;
880 quotc = c;
881 continue;
883 break;
885 case QUOTE:
886 if (c == '\n')
888 exec_if_possible ();
889 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
890 quotc == '"' ? _("double") : _("single"));
892 if (c == quotc)
894 state = NORM;
895 seen_arg = true; /* Makes a difference for e.g. just '' or "" as the first arg on a line */
896 continue;
898 break;
900 case BACKSLASH:
901 state = NORM;
902 break;
905 if ( (0 == c) && !nullwarning_given )
907 /* This is just a warning message. We only issue it once. */
908 error (0, 0,
909 _("warning: a NUL character occurred in the input. "
910 "It cannot be passed through in the argument list. "
911 "Did you mean to use the --null option?"));
912 nullwarning_given = 1;
915 #if 1
916 if (p >= endbuf)
918 exec_if_possible ();
919 error (1, 0, _("argument line too long"));
921 *p++ = c;
922 #else
923 append_char_to_buf(&linebuf, &endbuf, &p, c);
924 #endif
928 /* Read a null-terminated string from the input and add it to the list of
929 arguments to pass to the command.
930 Return -1 if eof (either physical or logical) is reached,
931 otherwise the length of the string read (including the null). */
933 static int
934 read_string (void)
936 static boolean eof = false;
937 int len;
938 char *p = linebuf;
939 /* Including the NUL, the args must not grow past this point. */
940 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
942 if (eof)
943 return -1;
944 while (1)
946 int c = getc (input_stream);
947 if (c == EOF)
949 eof = true;
950 if (p == linebuf)
951 return -1;
952 *p++ = '\0';
953 len = p - linebuf;
954 if (!bc_ctl.replace_pat)
955 bc_push_arg (&bc_ctl, &bc_state,
956 linebuf, len,
957 NULL, 0,
958 initial_args);
959 return len;
961 if (c == input_delimiter)
963 lineno++; /* For -l. */
964 *p++ = '\0';
965 len = p - linebuf;
966 if (!bc_ctl.replace_pat)
967 bc_push_arg (&bc_ctl, &bc_state,
968 linebuf, len,
969 NULL, 0,
970 initial_args);
971 return len;
973 if (p >= endbuf)
975 exec_if_possible ();
976 error (1, 0, _("argument line too long"));
978 *p++ = c;
982 /* Print the arguments of the command to execute.
983 If ASK is nonzero, prompt the user for a response, and
984 if the user responds affirmatively, return true;
985 otherwise, return false. */
987 static boolean
988 print_args (boolean ask)
990 int i;
992 for (i = 0; i < bc_state.cmd_argc - 1; i++)
993 fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
994 if (ask)
996 static FILE *tty_stream;
997 int c, savec;
999 if (!tty_stream)
1001 tty_stream = fopen ("/dev/tty", "r");
1002 if (!tty_stream)
1003 error (1, errno, "/dev/tty");
1005 fputs ("?...", stderr);
1006 fflush (stderr);
1007 c = savec = getc (tty_stream);
1008 while (c != EOF && c != '\n')
1009 c = getc (tty_stream);
1010 if (savec == 'y' || savec == 'Y')
1011 return true;
1013 else
1014 putc ('\n', stderr);
1016 return false;
1020 /* Close stdin and attach /dev/null to it.
1021 * This resolves Savannah bug #3992.
1023 static void
1024 prep_child_for_exec (void)
1026 if (!keep_stdin)
1028 const char inputfile[] = "/dev/null";
1029 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
1031 close(0);
1032 if (open(inputfile, O_RDONLY) < 0)
1034 /* This is not entirely fatal, since
1035 * executing the child with a closed
1036 * stdin is almost as good as executing it
1037 * with its stdin attached to /dev/null.
1039 error (0, errno, "%s", inputfile);
1045 /* Execute the command that has been built in `cmd_argv'. This may involve
1046 waiting for processes that were previously executed. */
1048 static int
1049 xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
1051 pid_t child;
1053 (void) ctl;
1054 (void) state;
1056 bc_push_arg (&bc_ctl, &bc_state,
1057 (char *) NULL, 0,
1058 NULL, 0,
1059 false); /* Null terminate the arg list. */
1061 if (!query_before_executing || print_args (true))
1063 if (proc_max && procs_executing >= proc_max)
1064 wait_for_proc (false);
1065 if (!query_before_executing && print_command)
1066 print_args (false);
1067 /* If we run out of processes, wait for a child to return and
1068 try again. */
1069 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1070 wait_for_proc (false);
1071 switch (child)
1073 case -1:
1074 error (1, errno, _("cannot fork"));
1076 case 0: /* Child. */
1077 prep_child_for_exec();
1078 execvp (bc_state.cmd_argv[0], bc_state.cmd_argv);
1079 error (0, errno, "%s", bc_state.cmd_argv[0]);
1080 _exit (errno == ENOENT ? 127 : 126);
1081 /*NOTREACHED*/
1083 add_proc (child);
1086 bc_clear_args(&bc_ctl, &bc_state);
1087 return 1; /* Success */
1090 /* Execute the command if possible. */
1092 static void
1093 exec_if_possible (void)
1095 if (bc_ctl.replace_pat || initial_args ||
1096 bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded)
1097 return;
1098 xargs_do_exec (&bc_ctl, &bc_state);
1101 /* Add the process with id PID to the list of processes that have
1102 been executed. */
1104 static void
1105 add_proc (pid_t pid)
1107 int i;
1109 /* Find an empty slot. */
1110 for (i = 0; i < pids_alloc && pids[i]; i++)
1112 if (i == pids_alloc)
1114 if (pids_alloc == 0)
1116 pids_alloc = proc_max ? proc_max : 64;
1117 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1119 else
1121 pids_alloc *= 2;
1122 pids = (pid_t *) xrealloc (pids,
1123 sizeof (pid_t) * pids_alloc);
1125 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1127 pids[i] = pid;
1128 procs_executing++;
1129 procs_executed++;
1132 /* If ALL is true, wait for all child processes to finish;
1133 otherwise, wait for one child process to finish.
1134 Remove the processes that finish from the list of executing processes. */
1136 static void
1137 wait_for_proc (boolean all)
1139 while (procs_executing)
1141 int i, status;
1145 pid_t pid;
1147 while ((pid = wait (&status)) == (pid_t) -1)
1148 if (errno != EINTR)
1149 error (1, errno, _("error waiting for child process"));
1151 /* Find the entry in `pids' for the child process
1152 that exited. */
1153 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1156 while (i == pids_alloc); /* A child died that we didn't start? */
1158 /* Remove the child from the list. */
1159 pids[i] = 0;
1160 procs_executing--;
1162 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1163 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1164 if (WEXITSTATUS (status) == 255)
1165 error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1166 if (WIFSTOPPED (status))
1167 error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1168 if (WIFSIGNALED (status))
1169 error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1170 if (WEXITSTATUS (status) != 0)
1171 child_error = 123;
1173 if (!all)
1174 break;
1178 /* Wait for all child processes to finish. */
1180 static void
1181 wait_for_proc_all (void)
1183 static boolean waiting = false;
1185 if (waiting)
1186 return;
1188 waiting = true;
1189 wait_for_proc (true);
1190 waiting = false;
1192 if (original_exit_value != child_error)
1194 /* wait_for_proc() changed the value of child_error(). This
1195 * function is registered via atexit(), and so may have been
1196 * called from exit(). We now know that the original value
1197 * passed to exit() is no longer the exit status we require.
1198 * The POSIX standard states that the behaviour if exit() is
1199 * called more than once is undefined. Therefore we now have to
1200 * exit with _exit() instead of exit().
1202 _exit(child_error);
1207 /* Return the value of the number represented in STR.
1208 OPTION is the command line option to which STR is the argument.
1209 If the value does not fall within the boundaries MIN and MAX,
1210 Print an error message mentioning OPTION. If FATAL is true,
1211 we also exit. */
1213 static long
1214 parse_num (char *str, int option, long int min, long int max, int fatal)
1216 char *eptr;
1217 long val;
1219 val = strtol (str, &eptr, 10);
1220 if (eptr == str || *eptr)
1222 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1223 program_name, option);
1224 usage (stderr);
1225 exit(1);
1227 else if (val < min)
1229 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1230 program_name, option, min);
1231 if (fatal)
1233 usage (stderr);
1234 exit(1);
1236 else
1238 val = min;
1241 else if (max >= 0 && val > max)
1243 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1244 program_name, option, max);
1245 if (fatal)
1247 usage (stderr);
1248 exit(1);
1250 else
1252 val = max;
1255 return val;
1258 static void
1259 usage (FILE *stream)
1261 fprintf (stream, _("\
1262 Usage: %s [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]\n\
1263 [-E eof-str] [-e[eof-str]] [--eof[=eof-str]]\n\
1264 [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]\n\
1265 [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]\n\
1266 [-n max-args] [--max-args=max-args]\n\
1267 [-s max-chars] [--max-chars=max-chars]\n\
1268 [-P max-procs] [--max-procs=max-procs] [--show-limits]\n\
1269 [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]\n\
1270 [--version] [--help] [command [initial-arguments]]\n"),
1271 program_name);
1272 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);