cvsimport
[findutils.git] / xargs / xargs.c
blobd7dfe81eda87274296d11b21bcd7b4f613baf8d9
1 /* xargs -- build and execute command lines from standard input
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005, 2006,
3 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
18 USA.
21 /* Written by Mike Rendell <michael@cs.mun.ca>
22 and David MacKenzie <djm@gnu.org>.
23 Modifications by
24 James Youngman
25 Dmitry V. Levin
28 #include <config.h>
30 # ifndef PARAMS
31 # if defined PROTOTYPES || (defined __STDC__ && __STDC__)
32 # define PARAMS(Args) Args
33 # else
34 # define PARAMS(Args) ()
35 # endif
36 # endif
38 #include <ctype.h>
40 #if !defined (isascii) || defined (STDC_HEADERS)
41 #ifdef isascii
42 #undef isascii
43 #endif
44 #define isascii(c) 1
45 #endif
47 #ifdef isblank
48 #define ISBLANK(c) (isascii (c) && isblank (c))
49 #else
50 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
51 #endif
53 #define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
54 || (c) == '\f' || (c) == '\v')
56 #include <sys/types.h>
57 #include <stdio.h>
58 #include <errno.h>
59 #include <getopt.h>
60 #include <fcntl.h>
62 #if defined STDC_HEADERS
63 #include <assert.h>
64 #endif
66 #if defined HAVE_STRING_H || defined STDC_HEADERS
67 #include <string.h>
68 #if !defined STDC_HEADERS
69 #include <memory.h>
70 #endif
71 #else
72 #include <strings.h>
73 #define memcpy(dest, source, count) (bcopy((source), (dest), (count)))
74 #endif
76 #ifndef _POSIX_SOURCE
77 #include <sys/param.h>
78 #endif
80 #ifdef HAVE_LIMITS_H
81 #include <limits.h>
82 #endif
84 #ifndef LONG_MAX
85 #define LONG_MAX (~(1 << (sizeof (long) * 8 - 1)))
86 #endif
88 /* The presence of unistd.h is assumed by gnulib these days, so we
89 * might as well assume it too.
91 #include <unistd.h>
93 #include <signal.h>
95 #if !defined(SIGCHLD) && defined(SIGCLD)
96 #define SIGCHLD SIGCLD
97 #endif
99 #include "verify.h"
100 #include "wait.h"
101 #include "quotearg.h"
104 #ifdef STDC_HEADERS
105 #include <stdlib.h>
106 #else
107 extern int errno;
108 #endif
110 #ifdef HAVE_LOCALE_H
111 #include <locale.h>
112 #endif
113 #if ENABLE_NLS
114 # include <libintl.h>
115 # define _(Text) gettext (Text)
116 #else
117 # define _(Text) Text
118 #define textdomain(Domain)
119 #define bindtextdomain(Package, Directory)
120 #endif
121 #ifdef gettext_noop
122 # define N_(String) gettext_noop (String)
123 #else
124 /* See locate.c for explanation as to why not use (String) */
125 # define N_(String) String
126 #endif
128 #include "buildcmd.h"
131 /* Return nonzero if S is the EOF string. */
132 #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
134 /* Do multibyte processing if multibyte characters are supported,
135 unless multibyte sequences are search safe. Multibyte sequences
136 are search safe if searching for a substring using the byte
137 comparison function 'strstr' gives no false positives. All 8-bit
138 encodings and the UTF-8 multibyte encoding are search safe, but
139 the EUC encodings are not.
140 BeOS uses the UTF-8 encoding exclusively, so it is search safe. */
141 #if defined __BEOS__
142 # define MULTIBYTE_IS_SEARCH_SAFE 1
143 #endif
144 #define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE)
146 #if DO_MULTIBYTE
147 # if HAVE_MBRLEN
148 # include <wchar.h>
149 # else
150 /* Simulate mbrlen with mblen as best we can. */
151 # define mbstate_t int
152 # define mbrlen(s, n, ps) mblen (s, n)
153 # endif
154 #endif
156 /* Not char because of type promotion; NeXT gcc can't handle it. */
157 typedef int boolean;
158 #define true 1
159 #define false 0
161 #if __STDC__
162 #define VOID void
163 #else
164 #define VOID char
165 #endif
167 #include <xalloc.h>
168 #include "closein.h"
169 #include "gnulib-version.h"
171 void error PARAMS ((int status, int errnum, char *message,...));
173 extern char *version_string;
175 /* The name this program was run with. */
176 char *program_name;
178 static FILE *input_stream;
180 /* Buffer for reading arguments from input. */
181 static char *linebuf;
183 static int keep_stdin = 0;
185 /* Line number in stdin since the last command was executed. */
186 static int lineno = 0;
188 static struct buildcmd_state bc_state;
189 static struct buildcmd_control bc_ctl;
191 /* Did we already complain about NUL characters in the input? */
192 static int nullwarning_given = 0;
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 static volatile int child_error = 0;
228 static volatile 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 void usage PARAMS ((FILE * stream));
278 static char
279 get_char_oct_or_hex_escape(const char *s)
281 const char * p;
282 int base = 8;
283 unsigned long val;
284 char *endp;
286 assert ('\\' == s[0]);
288 if ('x' == s[1])
290 /* hex */
291 p = s+2;
292 base = 16;
294 else if (isdigit(s[1]))
296 /* octal */
297 p = s+1;
298 base = 8;
300 else
302 p = NULL; /* Silence compiler warning. */
303 error(1, 0,
304 _("Invalid escape sequence %s in input delimiter specification."),
307 errno = 0;
308 endp = (char*)p;
309 val = strtoul(p, &endp, base);
311 /* This if condition is carefully constructed to do
312 * the right thing if UCHAR_MAX has the same
313 * value as ULONG_MAX. IF UCHAR_MAX==ULONG_MAX,
314 * then val can never be greater than UCHAR_MAX.
316 if ((ULONG_MAX == val && ERANGE == errno)
317 || (val > UCHAR_MAX))
319 if (16 == base)
321 error(1, 0,
322 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lx."),
323 s, (unsigned long)UCHAR_MAX);
325 else
327 error(1, 0,
328 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lo."),
329 s, (unsigned long)UCHAR_MAX);
333 /* check for trailing garbage */
334 if (0 != *endp)
336 error(1, 0,
337 _("Invalid escape sequence %s in input delimiter specification; trailing characters %s not recognised."),
338 s, endp);
341 return (char) val;
345 static char
346 get_input_delimiter(const char *s)
348 if (1 == strlen(s))
350 return s[0];
352 else
354 if ('\\' == s[0])
356 /* an escape code */
357 switch (s[1])
359 case 'a':
360 return '\a';
361 case 'b':
362 return '\b';
363 case 'f':
364 return '\f';
365 case 'n':
366 return '\n';
367 case 'r':
368 return '\r';
369 case 't':
370 return'\t';
371 case 'v':
372 return '\v';
373 case '\\':
374 return '\\';
375 default:
376 return get_char_oct_or_hex_escape(s);
379 else
381 error(1, 0,
382 _("Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\."),
384 /*NOTREACHED*/
385 return 0;
390 static void
391 noop (void)
393 /* does nothing. */
396 static void
397 fail_due_to_env_size (void)
399 error (1, 0, _("environment is too large for exec"));
404 main (int argc, char **argv)
406 int optc;
407 int show_limits = 0; /* --show-limits */
408 int always_run_command = 1;
409 char *input_file = "-"; /* "-" is stdin */
410 char *default_cmd = "/bin/echo";
411 int (*read_args) PARAMS ((void)) = read_line;
412 void (*act_on_init_result)(void) = noop;
413 enum BC_INIT_STATUS bcstatus;
414 enum { XARGS_POSIX_HEADROOM = 2048u };
416 program_name = argv[0];
417 original_exit_value = 0;
419 #ifdef HAVE_SETLOCALE
420 setlocale (LC_ALL, "");
421 #endif
422 bindtextdomain (PACKAGE, LOCALEDIR);
423 textdomain (PACKAGE);
424 atexit (close_stdin);
425 atexit (wait_for_proc_all);
427 /* xargs is required by POSIX to allow 2048 bytes of headroom
428 * for extra environment variables (that perhaps the utliity might
429 * want to set before execing something else).
431 bcstatus = bc_init_controlinfo(&bc_ctl, XARGS_POSIX_HEADROOM);
433 /* The bc_init_controlinfo call may have determined that the
434 * environment is too big. In that case, we will fail with
435 * an error message after processing the command-line options,
436 * as "xargs --help" should still work even if the environment is
437 * too big.
439 * Some of the argument processing depends on the contents of
440 * bc_ctl, which will be in an undefined state if bc_init_controlinfo()
441 * failed.
443 if (BC_INIT_ENV_TOO_BIG == bcstatus)
445 act_on_init_result = fail_due_to_env_size;
447 else if (BC_INIT_CANNOT_ACCOMODATE_HEADROOM == bcstatus)
449 /* All POSIX systems are required to support ARG_MAX of at least
450 * 4096. For everything to work the total of (command line +
451 * headroom + environment) must fit into this. POSIX requires
452 * that we use a headroom of 2048 bytes. The user is in control
453 * of the size of the environment.
455 * In general if bc_init_controlinfo() returns
456 * BC_INIT_CANNOT_ACCOMODATE_HEADROOM, its caller can try again
457 * with a smaller headroom. However, in the case of xargs, this
458 * would not be POSIX-compliant.
460 act_on_init_result = fail_due_to_env_size;
462 else
464 /* IEEE Std 1003.1, 2003 specifies that the combined argument and
465 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
466 * specifies that it shall be at least LINE_MAX.
468 #ifdef _SC_ARG_MAX
469 long val = sysconf(_SC_ARG_MAX);
470 if (val > 0)
472 /* Note that val can in fact be greater than ARG_MAX
473 * and bc_ctl.arg_max can also be greater than ARG_MAX.
475 assert (bc_ctl.arg_max <= (val-XARGS_POSIX_HEADROOM));
477 else
479 # if defined ARG_MAX
480 assert (bc_ctl.arg_max <= (ARG_MAX-XARGS_POSIX_HEADROOM));
481 # endif
483 #else
484 /* No _SC_ARG_MAX */
485 assert (bc_ctl.arg_max <= (ARG_MAX-XARGS_POSIX_HEADROOM));
486 #endif
489 #ifdef LINE_MAX
490 /* This assertion ensures that this xargs implementation
491 * conforms to the POSIX requirement that the default command
492 * line length shall be at least LINE_MAX.
494 assert (bc_ctl.arg_max >= LINE_MAX);
495 #endif
497 bc_ctl.exec_callback = xargs_do_exec;
499 /* Start with a reasonable default size, though this can be
500 * adjusted via the -s option.
502 bc_use_sensible_arg_max(&bc_ctl);
505 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:d:",
506 longopts, (int *) 0)) != -1)
508 switch (optc)
510 case '0':
511 read_args = read_string;
512 input_delimiter = '\0';
513 break;
515 case 'd':
516 read_args = read_string;
517 input_delimiter = get_input_delimiter(optarg);
518 break;
520 case 'E': /* POSIX */
521 case 'e': /* deprecated */
522 if (optarg && (strlen(optarg) > 0))
523 eof_str = optarg;
524 else
525 eof_str = 0;
526 break;
528 case 'h':
529 usage (stdout);
530 return 0;
532 case 'I': /* POSIX */
533 case 'i': /* deprecated */
534 if (optarg)
535 bc_ctl.replace_pat = optarg;
536 else
537 bc_ctl.replace_pat = "{}";
538 /* -i excludes -n -l. */
539 bc_ctl.args_per_exec = 0;
540 bc_ctl.lines_per_exec = 0;
541 break;
543 case 'L': /* POSIX */
544 bc_ctl.lines_per_exec = parse_num (optarg, 'L', 1L, -1L, 1);
545 /* -L excludes -i -n. */
546 bc_ctl.args_per_exec = 0;
547 bc_ctl.replace_pat = NULL;
548 break;
550 case 'l': /* deprecated */
551 if (optarg)
552 bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
553 else
554 bc_ctl.lines_per_exec = 1;
555 /* -l excludes -i -n. */
556 bc_ctl.args_per_exec = 0;
557 bc_ctl.replace_pat = NULL;
558 break;
560 case 'n':
561 bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
562 /* -n excludes -i -l. */
563 bc_ctl.lines_per_exec = 0;
564 if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
565 /* ignore -n1 in '-i -n1' */
566 bc_ctl.args_per_exec = 0;
567 else
568 bc_ctl.replace_pat = NULL;
569 break;
571 /* The POSIX standard specifies that it is not an error
572 * for the -s option to specify a size that the implementation
573 * cannot support - in that case, the relevant limit is used.
575 case 's':
577 size_t arg_size;
578 act_on_init_result();
579 arg_size = parse_num (optarg, 's', 1L,
580 bc_ctl.posix_arg_size_max, 0);
581 if (arg_size > bc_ctl.posix_arg_size_max)
583 error (0, 0,
584 _("warning: value %ld for -s option is too large, "
585 "using %ld instead"),
586 arg_size, bc_ctl.posix_arg_size_max);
587 arg_size = bc_ctl.posix_arg_size_max;
589 bc_ctl.arg_max = arg_size;
591 break;
593 case 'S':
594 show_limits = true;
595 break;
597 case 't':
598 print_command = true;
599 break;
601 case 'x':
602 bc_ctl.exit_if_size_exceeded = true;
603 break;
605 case 'p':
606 query_before_executing = true;
607 print_command = true;
608 break;
610 case 'r':
611 always_run_command = 0;
612 break;
614 case 'P':
615 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
616 break;
618 case 'a':
619 input_file = optarg;
620 break;
622 case 'v':
623 printf (_("GNU xargs version %s\n"), version_string);
624 printf (_("Built using GNU gnulib version %s\n"), gnulib_version);
625 return 0;
627 default:
628 usage (stderr);
629 return 1;
633 /* If we had deferred failing due to problems in bc_init_controlinfo(),
634 * do it now.
636 * We issue this error message after processing command line
637 * arguments so that it is possible to use "xargs --help" even if
638 * the environment is too large.
640 act_on_init_result();
641 assert (BC_INIT_OK == bcstatus);
643 if (0 == strcmp (input_file, "-"))
645 input_stream = stdin;
647 else
649 keep_stdin = 1; /* see prep_child_for_exec() */
650 input_stream = fopen (input_file, "r");
651 if (NULL == input_stream)
653 error (1, errno,
654 _("Cannot open input file %s"),
655 quotearg_n_style(0, locale_quoting_style, input_file));
659 if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
660 bc_ctl.exit_if_size_exceeded = true;
662 if (optind == argc)
664 optind = 0;
665 argc = 1;
666 argv = &default_cmd;
669 /* We want to be able to print size_t values as unsigned long, so if
670 * the cast isn't value-preserving, we have a problem. This isn't a
671 * problem in C89, because size_t was known to be no wider than
672 * unsigned long. In C99 this is no longer the case, but there are
673 * special C99 ways to print such values. Unfortunately this
674 * program tries to work on both C89 and C99 systems.
676 #if defined SIZE_MAX
677 # if SIZE_MAX > ULONG_MAX
678 # error "I'm not sure how to print size_t values on your system"
679 # endif
680 #else
681 /* Without SIZE_MAX (i.e. limits.h) this is probably
682 * close to the best we can do.
684 verify_true (sizeof(size_t) <= sizeof(unsigned long));
685 #endif
687 if (show_limits)
689 fprintf(stderr,
690 _("Your environment variables take up %lu bytes\n"),
691 (unsigned long)bc_size_of_environment());
692 fprintf(stderr,
693 _("POSIX upper limit on argument length (this system): %lu\n"),
694 (unsigned long)bc_ctl.posix_arg_size_max);
695 fprintf(stderr,
696 _("POSIX smallest allowable upper limit on argument length (all systems): %lu\n"),
697 (unsigned long)bc_ctl.posix_arg_size_min);
698 fprintf(stderr,
699 _("Maximum length of command we could actually use: %ld\n"),
700 (unsigned long)(bc_ctl.posix_arg_size_max -
701 bc_size_of_environment()));
702 fprintf(stderr,
703 _("Size of command buffer we are actually using: %lu\n"),
704 (unsigned long)bc_ctl.arg_max);
706 if (isatty(STDIN_FILENO))
708 fprintf(stderr,
709 _("\n"
710 "Execution of xargs will continue now, and it will "
711 "try to read its input and run commands; if this is "
712 "not what you wanted to happen, please type the "
713 "end-of-file keystroke.\n"));
714 if (always_run_command)
716 fprintf(stderr,
717 _("Warning: %s will be run at least once. "
718 "If you do not want that to happen, then press "
719 "the interrupt keystroke.\n"),
720 argv[optind]);
725 linebuf = xmalloc (bc_ctl.arg_max + 1);
726 bc_state.argbuf = xmalloc (bc_ctl.arg_max + 1);
728 /* Make sure to listen for the kids. */
729 signal (SIGCHLD, SIG_DFL);
731 if (!bc_ctl.replace_pat)
733 for (; optind < argc; optind++)
734 bc_push_arg (&bc_ctl, &bc_state,
735 argv[optind], strlen (argv[optind]) + 1,
736 NULL, 0,
737 initial_args);
738 initial_args = false;
739 bc_ctl.initial_argc = bc_state.cmd_argc;
740 bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
742 while ((*read_args) () != -1)
743 if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
745 xargs_do_exec (&bc_ctl, &bc_state);
746 lineno = 0;
749 /* SYSV xargs seems to do at least one exec, even if the
750 input is empty. */
751 if (bc_state.cmd_argc != bc_ctl.initial_argc
752 || (always_run_command && procs_executed == 0))
753 xargs_do_exec (&bc_ctl, &bc_state);
756 else
758 int i;
759 size_t len;
760 size_t *arglen = xmalloc (sizeof (size_t) * argc);
762 for (i = optind; i < argc; i++)
763 arglen[i] = strlen(argv[i]);
764 bc_ctl.rplen = strlen (bc_ctl.replace_pat);
765 while ((len = (*read_args) ()) != -1)
767 /* Don't do insert on the command name. */
768 bc_clear_args(&bc_ctl, &bc_state);
769 bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
771 bc_push_arg (&bc_ctl, &bc_state,
772 argv[optind], arglen[optind] + 1,
773 NULL, 0,
774 initial_args);
775 len--;
776 initial_args = false;
778 for (i = optind + 1; i < argc; i++)
779 bc_do_insert (&bc_ctl, &bc_state,
780 argv[i], arglen[i],
781 NULL, 0,
782 linebuf, len,
783 initial_args);
784 xargs_do_exec (&bc_ctl, &bc_state);
788 original_exit_value = child_error;
789 return child_error;
793 /* Read a line of arguments from the input and add them to the list of
794 arguments to pass to the command. Ignore blank lines and initial blanks.
795 Single and double quotes and backslashes quote metacharacters and blanks
796 as they do in the shell.
797 Return -1 if eof (either physical or logical) is reached,
798 otherwise the length of the last string read (including the null). */
800 static int
801 read_line (void)
803 /* States for read_line. */
804 enum read_line_state
806 NORM = 0,
807 SPACE = 1,
808 QUOTE = 2,
809 BACKSLASH = 3
811 static boolean eof = false;
812 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
813 enum read_line_state state = SPACE; /* The type of character we last read. */
814 int prevc; /* The previous value of c. */
815 int quotc = 0; /* The last quote character read. */
816 int c = EOF;
817 boolean first = true; /* true if reading first arg on line. */
818 boolean seen_arg = false; /* true if we have seen any arg (or part of one) yet */
819 int len;
820 char *p = linebuf;
821 /* Including the NUL, the args must not grow past this point. */
822 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
824 if (eof)
825 return -1;
826 while (1)
828 prevc = c;
829 c = getc (input_stream);
831 if (c == EOF)
833 /* COMPAT: SYSV seems to ignore stuff on a line that
834 ends without a \n; we don't. */
835 eof = true;
836 if (p == linebuf)
837 return -1;
838 *p++ = '\0';
839 len = p - linebuf;
840 if (state == QUOTE)
842 exec_if_possible ();
843 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
844 quotc == '"' ? _("double") : _("single"));
846 if (first && EOF_STR (linebuf))
847 return -1;
848 if (!bc_ctl.replace_pat)
849 bc_push_arg (&bc_ctl, &bc_state,
850 linebuf, len,
851 NULL, 0,
852 initial_args);
853 return len;
855 switch (state)
857 case SPACE:
858 if (ISSPACE (c))
859 continue;
860 state = NORM;
861 /* aaahhhh.... */
863 case NORM:
864 if (c == '\n')
866 if (!ISBLANK (prevc))
867 lineno++; /* For -l. */
868 if (p == linebuf)
870 if (seen_arg)
872 /* An empty argument, add it to the list as normal. */
874 else
876 /* Blank line. */
877 state = SPACE;
878 continue;
881 *p++ = '\0';
882 len = p - linebuf;
883 if (EOF_STR (linebuf))
885 eof = true;
886 return first ? -1 : len;
888 if (!bc_ctl.replace_pat)
889 bc_push_arg (&bc_ctl, &bc_state,
890 linebuf, len,
891 NULL, 0,
892 initial_args);
893 return len;
895 seen_arg = true;
897 /* POSIX: In the POSIX locale, the separators are <SPC> and
898 * <TAB>, but not <FF> or <VT>.
900 if (!bc_ctl.replace_pat && ISBLANK (c))
902 *p++ = '\0';
903 len = p - linebuf;
904 if (EOF_STR (linebuf))
906 eof = true;
907 return first ? -1 : len;
909 bc_push_arg (&bc_ctl, &bc_state,
910 linebuf, len,
911 NULL, 0,
912 initial_args);
913 p = linebuf;
914 state = SPACE;
915 first = false;
916 continue;
918 switch (c)
920 case '\\':
921 state = BACKSLASH;
922 continue;
924 case '\'':
925 case '"':
926 state = QUOTE;
927 quotc = c;
928 continue;
930 break;
932 case QUOTE:
933 if (c == '\n')
935 exec_if_possible ();
936 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
937 quotc == '"' ? _("double") : _("single"));
939 if (c == quotc)
941 state = NORM;
942 seen_arg = true; /* Makes a difference for e.g. just '' or "" as the first arg on a line */
943 continue;
945 break;
947 case BACKSLASH:
948 state = NORM;
949 break;
952 if ( (0 == c) && !nullwarning_given )
954 /* This is just a warning message. We only issue it once. */
955 error (0, 0,
956 _("warning: a NUL character occurred in the input. "
957 "It cannot be passed through in the argument list. "
958 "Did you mean to use the --null option?"));
959 nullwarning_given = 1;
962 #if 1
963 if (p >= endbuf)
965 exec_if_possible ();
966 error (1, 0, _("argument line too long"));
968 *p++ = c;
969 #else
970 append_char_to_buf(&linebuf, &endbuf, &p, c);
971 #endif
975 /* Read a null-terminated string from the input and add it to the list of
976 arguments to pass to the command.
977 Return -1 if eof (either physical or logical) is reached,
978 otherwise the length of the string read (including the null). */
980 static int
981 read_string (void)
983 static boolean eof = false;
984 int len;
985 char *p = linebuf;
986 /* Including the NUL, the args must not grow past this point. */
987 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
989 if (eof)
990 return -1;
991 while (1)
993 int c = getc (input_stream);
994 if (c == EOF)
996 eof = true;
997 if (p == linebuf)
998 return -1;
999 *p++ = '\0';
1000 len = p - linebuf;
1001 if (!bc_ctl.replace_pat)
1002 bc_push_arg (&bc_ctl, &bc_state,
1003 linebuf, len,
1004 NULL, 0,
1005 initial_args);
1006 return len;
1008 if (c == input_delimiter)
1010 lineno++; /* For -l. */
1011 *p++ = '\0';
1012 len = p - linebuf;
1013 if (!bc_ctl.replace_pat)
1014 bc_push_arg (&bc_ctl, &bc_state,
1015 linebuf, len,
1016 NULL, 0,
1017 initial_args);
1018 return len;
1020 if (p >= endbuf)
1022 exec_if_possible ();
1023 error (1, 0, _("argument line too long"));
1025 *p++ = c;
1029 /* Print the arguments of the command to execute.
1030 If ASK is nonzero, prompt the user for a response, and
1031 if the user responds affirmatively, return true;
1032 otherwise, return false. */
1034 static boolean
1035 print_args (boolean ask)
1037 int i;
1039 for (i = 0; i < bc_state.cmd_argc - 1; i++)
1040 fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
1041 if (ask)
1043 static FILE *tty_stream;
1044 int c, savec;
1046 if (!tty_stream)
1048 tty_stream = fopen ("/dev/tty", "r");
1049 if (!tty_stream)
1050 error (1, errno, "/dev/tty");
1052 fputs ("?...", stderr);
1053 fflush (stderr);
1054 c = savec = getc (tty_stream);
1055 while (c != EOF && c != '\n')
1056 c = getc (tty_stream);
1057 if (savec == 'y' || savec == 'Y')
1058 return true;
1060 else
1061 putc ('\n', stderr);
1063 return false;
1067 /* Close stdin and attach /dev/null to it.
1068 * This resolves Savannah bug #3992.
1070 static void
1071 prep_child_for_exec (void)
1073 if (!keep_stdin)
1075 const char inputfile[] = "/dev/null";
1076 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
1078 close(0);
1079 if (open(inputfile, O_RDONLY) < 0)
1081 /* This is not entirely fatal, since
1082 * executing the child with a closed
1083 * stdin is almost as good as executing it
1084 * with its stdin attached to /dev/null.
1086 error (0, errno, "%s", quotearg_n_style(0, locale_quoting_style, inputfile));
1092 /* Execute the command that has been built in `cmd_argv'. This may involve
1093 waiting for processes that were previously executed. */
1095 static int
1096 xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
1098 pid_t child;
1100 (void) ctl;
1101 (void) state;
1103 bc_push_arg (&bc_ctl, &bc_state,
1104 (char *) NULL, 0,
1105 NULL, 0,
1106 false); /* Null terminate the arg list. */
1108 if (!query_before_executing || print_args (true))
1110 if (proc_max && procs_executing >= proc_max)
1111 wait_for_proc (false);
1112 if (!query_before_executing && print_command)
1113 print_args (false);
1114 /* If we run out of processes, wait for a child to return and
1115 try again. */
1116 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1117 wait_for_proc (false);
1118 switch (child)
1120 case -1:
1121 error (1, errno, _("cannot fork"));
1123 case 0: /* Child. */
1124 prep_child_for_exec();
1125 execvp (bc_state.cmd_argv[0], bc_state.cmd_argv);
1126 error (0, errno, "%s", bc_state.cmd_argv[0]);
1127 _exit (errno == ENOENT ? 127 : 126);
1128 /*NOTREACHED*/
1130 add_proc (child);
1133 bc_clear_args(&bc_ctl, &bc_state);
1134 return 1; /* Success */
1137 /* Execute the command if possible. */
1139 static void
1140 exec_if_possible (void)
1142 if (bc_ctl.replace_pat || initial_args ||
1143 bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded)
1144 return;
1145 xargs_do_exec (&bc_ctl, &bc_state);
1148 /* Add the process with id PID to the list of processes that have
1149 been executed. */
1151 static void
1152 add_proc (pid_t pid)
1154 int i;
1156 /* Find an empty slot. */
1157 for (i = 0; i < pids_alloc && pids[i]; i++)
1159 if (i == pids_alloc)
1161 if (pids_alloc == 0)
1163 pids_alloc = proc_max ? proc_max : 64;
1164 pids = xmalloc (sizeof (pid_t) * pids_alloc);
1166 else
1168 pids_alloc *= 2;
1169 pids = xrealloc (pids,
1170 sizeof (pid_t) * pids_alloc);
1172 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1174 pids[i] = pid;
1175 procs_executing++;
1176 procs_executed++;
1179 /* If ALL is true, wait for all child processes to finish;
1180 otherwise, wait for one child process to finish.
1181 Remove the processes that finish from the list of executing processes. */
1183 static void
1184 wait_for_proc (boolean all)
1186 while (procs_executing)
1188 int i, status;
1192 pid_t pid;
1194 while ((pid = wait (&status)) == (pid_t) -1)
1195 if (errno != EINTR)
1196 error (1, errno, _("error waiting for child process"));
1198 /* Find the entry in `pids' for the child process
1199 that exited. */
1200 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1203 while (i == pids_alloc); /* A child died that we didn't start? */
1205 /* Remove the child from the list. */
1206 pids[i] = 0;
1207 procs_executing--;
1209 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1210 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1211 if (WEXITSTATUS (status) == 255)
1212 error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1213 if (WIFSTOPPED (status))
1214 error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1215 if (WIFSIGNALED (status))
1216 error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1217 if (WEXITSTATUS (status) != 0)
1218 child_error = 123;
1220 if (!all)
1221 break;
1225 /* Wait for all child processes to finish. */
1227 static void
1228 wait_for_proc_all (void)
1230 static boolean waiting = false;
1232 if (waiting)
1233 return;
1235 waiting = true;
1236 wait_for_proc (true);
1237 waiting = false;
1239 if (original_exit_value != child_error)
1241 /* wait_for_proc() changed the value of child_error(). This
1242 * function is registered via atexit(), and so may have been
1243 * called from exit(). We now know that the original value
1244 * passed to exit() is no longer the exit status we require.
1245 * The POSIX standard states that the behaviour if exit() is
1246 * called more than once is undefined. Therefore we now have to
1247 * exit with _exit() instead of exit().
1249 _exit(child_error);
1254 /* Return the value of the number represented in STR.
1255 OPTION is the command line option to which STR is the argument.
1256 If the value does not fall within the boundaries MIN and MAX,
1257 Print an error message mentioning OPTION. If FATAL is true,
1258 we also exit. */
1260 static long
1261 parse_num (char *str, int option, long int min, long int max, int fatal)
1263 char *eptr;
1264 long val;
1266 val = strtol (str, &eptr, 10);
1267 if (eptr == str || *eptr)
1269 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1270 program_name, option);
1271 usage (stderr);
1272 exit(1);
1274 else if (val < min)
1276 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1277 program_name, option, min);
1278 if (fatal)
1280 usage (stderr);
1281 exit(1);
1283 else
1285 val = min;
1288 else if (max >= 0 && val > max)
1290 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1291 program_name, option, max);
1292 if (fatal)
1294 usage (stderr);
1295 exit(1);
1297 else
1299 val = max;
1302 return val;
1305 static void
1306 usage (FILE *stream)
1308 fprintf (stream, _("\
1309 Usage: %s [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]\n\
1310 [-E eof-str] [-e[eof-str]] [--eof[=eof-str]]\n\
1311 [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]\n\
1312 [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]\n\
1313 [-n max-args] [--max-args=max-args]\n\
1314 [-s max-chars] [--max-chars=max-chars]\n\
1315 [-P max-procs] [--max-procs=max-procs] [--show-limits]\n\
1316 [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]\n\
1317 [--version] [--help] [command [initial-arguments]]\n"),
1318 program_name);
1319 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);