Eliminated a few compiler warnings
[findutils.git] / xargs / xargs.c
blobe8d7edff5e41efd5b6ca287d7d5b31cd0e682a04
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"
167 void error PARAMS ((int status, int errnum, char *message,...));
169 extern char *version_string;
171 /* The name this program was run with. */
172 char *program_name;
174 static FILE *input_stream;
176 /* Buffer for reading arguments from input. */
177 static char *linebuf;
179 static int keep_stdin = 0;
181 /* Line number in stdin since the last command was executed. */
182 static int lineno = 0;
184 static struct buildcmd_state bc_state;
185 static struct buildcmd_control bc_ctl;
187 /* Did we already complain about NUL characters in the input? */
188 static int nullwarning_given = 0;
191 /* If nonzero, when this string is read on stdin it is treated as
192 end of file.
193 IEEE Std 1003.1, 2004 Edition allows this to be NULL.
194 In findutils releases up to and including 4.2.8, this was "_".
196 static char *eof_str = NULL;
198 /* Number of chars in the initial args. */
199 /* static int initial_argv_chars = 0; */
201 /* true when building up initial arguments in `cmd_argv'. */
202 static boolean initial_args = true;
204 /* If nonzero, the maximum number of child processes that can be running
205 at once. */
206 static int proc_max = 1;
208 /* Total number of child processes that have been executed. */
209 static int procs_executed = 0;
211 /* The number of elements in `pids'. */
212 static int procs_executing = 0;
214 /* List of child processes currently executing. */
215 static pid_t *pids = NULL;
217 /* The number of allocated elements in `pids'. */
218 static int pids_alloc = 0;
220 /* Exit status; nonzero if any child process exited with a
221 status of 1-125. */
222 static volatile int child_error = 0;
224 static volatile int original_exit_value;
226 /* If true, print each command on stderr before executing it. */
227 static boolean print_command = false; /* Option -t */
229 /* If true, query the user before executing each command, and only
230 execute the command if the user responds affirmatively. */
231 static boolean query_before_executing = false;
233 /* The delimiter for input arguments. This is only consulted if the
234 * -0 or -d option had been given.
236 static char input_delimiter = '\0';
239 static struct option const longopts[] =
241 {"null", no_argument, NULL, '0'},
242 {"arg-file", required_argument, NULL, 'a'},
243 {"delimiter", required_argument, NULL, 'd'},
244 {"eof", optional_argument, NULL, 'e'},
245 {"replace", optional_argument, NULL, 'I'},
246 {"max-lines", optional_argument, NULL, 'l'},
247 {"max-args", required_argument, NULL, 'n'},
248 {"interactive", no_argument, NULL, 'p'},
249 {"no-run-if-empty", no_argument, NULL, 'r'},
250 {"max-chars", required_argument, NULL, 's'},
251 {"verbose", no_argument, NULL, 't'},
252 {"show-limits", no_argument, NULL, 'S'},
253 {"exit", no_argument, NULL, 'x'},
254 {"max-procs", required_argument, NULL, 'P'},
255 {"version", no_argument, NULL, 'v'},
256 {"help", no_argument, NULL, 'h'},
257 {NULL, no_argument, NULL, 0}
260 static int read_line PARAMS ((void));
261 static int read_string PARAMS ((void));
262 static boolean print_args PARAMS ((boolean ask));
263 /* static void do_exec PARAMS ((void)); */
264 static int xargs_do_exec (const struct buildcmd_control *cl, struct buildcmd_state *state);
265 static void exec_if_possible PARAMS ((void));
266 static void add_proc PARAMS ((pid_t pid));
267 static void wait_for_proc PARAMS ((boolean all));
268 static void wait_for_proc_all PARAMS ((void));
269 static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
270 static void usage PARAMS ((FILE * stream));
274 static char
275 get_char_oct_or_hex_escape(const char *s)
277 const char * p;
278 int base = 8;
279 unsigned long val;
280 char *endp;
282 assert('\\' == s[0]);
284 if ('x' == s[1])
286 /* hex */
287 p = s+2;
288 base = 16;
290 else if (isdigit(s[1]))
292 /* octal */
293 p = s+1;
294 base = 8;
296 else
298 p = NULL; /* Silence compiler warning. */
299 error(1, 0,
300 _("Invalid escape sequence %s in input delimiter specification."),
303 errno = 0;
304 endp = (char*)p;
305 val = strtoul(p, &endp, base);
307 /* This if condition is carefully constructed to do
308 * the right thing if UCHAR_MAX has the same
309 * value as ULONG_MAX. IF UCHAR_MAX==ULONG_MAX,
310 * then val can never be greater than UCHAR_MAX.
312 if ((ULONG_MAX == val && ERANGE == errno)
313 || (val > UCHAR_MAX))
315 if (16 == base)
317 error(1, 0,
318 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lx."),
319 s, (unsigned long)UCHAR_MAX);
321 else
323 error(1, 0,
324 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lo."),
325 s, (unsigned long)UCHAR_MAX);
329 /* check for trailing garbage */
330 if (0 != *endp)
332 error(1, 0,
333 _("Invalid escape sequence %s in input delimiter specification; trailing characters %s not recognised."),
334 s, endp);
337 return (char) val;
341 static char
342 get_input_delimiter(const char *s)
344 if (1 == strlen(s))
346 return s[0];
348 else
350 if ('\\' == s[0])
352 /* an escape code */
353 switch (s[1])
355 case 'a':
356 return '\a';
357 case 'b':
358 return '\b';
359 case 'f':
360 return '\f';
361 case 'n':
362 return '\n';
363 case 'r':
364 return '\r';
365 case 't':
366 return'\t';
367 case 'v':
368 return '\v';
369 case '\\':
370 return '\\';
371 default:
372 return get_char_oct_or_hex_escape(s);
375 else
377 error(1, 0,
378 _("Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\."),
380 /*NOTREACHED*/
381 return 0;
386 static void
387 noop (void)
389 /* does nothing. */
392 static void
393 fail_due_to_env_size (void)
395 error (1, 0, _("environment is too large for exec"));
400 main (int argc, char **argv)
402 int optc;
403 int show_limits = 0; /* --show-limits */
404 int always_run_command = 1;
405 char *input_file = "-"; /* "-" is stdin */
406 char *default_cmd = "/bin/echo";
407 int (*read_args) PARAMS ((void)) = read_line;
408 void (*act_on_init_result)(void) = noop;
409 enum BC_INIT_STATUS bcstatus;
411 program_name = argv[0];
412 original_exit_value = 0;
414 #ifdef HAVE_SETLOCALE
415 setlocale (LC_ALL, "");
416 #endif
417 bindtextdomain (PACKAGE, LOCALEDIR);
418 textdomain (PACKAGE);
419 atexit (close_stdout);
420 atexit (wait_for_proc_all);
422 bcstatus = bc_init_controlinfo(&bc_ctl);
424 /* The bc_init_controlinfo call may have determined that the
425 * environment is too big. In that case, we will fail with
426 * an error message after processing the command-line options,
427 * as "xargs --help" should still work even if the environment is
428 * too big.
430 * Some of the argument processing depends on the contents of
431 * bc_ctl, which will be in an undefined state if bc_init_controlinfo()
432 * failed.
434 if (BC_INIT_ENV_TOO_BIG == bcstatus)
436 act_on_init_result = fail_due_to_env_size;
438 else
440 /* IEEE Std 1003.1, 2003 specifies that the combined argument and
441 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
442 * specifies that it shall be at least LINE_MAX.
444 #if defined(ARG_MAX)
445 assert(bc_ctl.arg_max <= (ARG_MAX-2048));
446 #endif
447 assert(bc_ctl.arg_max >= LINE_MAX);
449 bc_ctl.exec_callback = xargs_do_exec;
451 /* Start with a reasonable default size, though this can be
452 * adjusted via the -s option.
454 bc_use_sensible_arg_max(&bc_ctl);
457 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:d:",
458 longopts, (int *) 0)) != -1)
460 switch (optc)
462 case '0':
463 read_args = read_string;
464 input_delimiter = '\0';
465 break;
467 case 'd':
468 read_args = read_string;
469 input_delimiter = get_input_delimiter(optarg);
470 break;
472 case 'E': /* POSIX */
473 case 'e': /* deprecated */
474 if (optarg && (strlen(optarg) > 0))
475 eof_str = optarg;
476 else
477 eof_str = 0;
478 break;
480 case 'h':
481 usage (stdout);
482 return 0;
484 case 'I': /* POSIX */
485 case 'i': /* deprecated */
486 if (optarg)
487 bc_ctl.replace_pat = optarg;
488 else
489 bc_ctl.replace_pat = "{}";
490 /* -i excludes -n -l. */
491 bc_ctl.args_per_exec = 0;
492 bc_ctl.lines_per_exec = 0;
493 break;
495 case 'L': /* POSIX */
496 bc_ctl.lines_per_exec = parse_num (optarg, 'L', 1L, -1L, 1);
497 /* -L excludes -i -n. */
498 bc_ctl.args_per_exec = 0;
499 bc_ctl.replace_pat = NULL;
500 break;
502 case 'l': /* deprecated */
503 if (optarg)
504 bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
505 else
506 bc_ctl.lines_per_exec = 1;
507 /* -l excludes -i -n. */
508 bc_ctl.args_per_exec = 0;
509 bc_ctl.replace_pat = NULL;
510 break;
512 case 'n':
513 bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
514 /* -n excludes -i -l. */
515 bc_ctl.lines_per_exec = 0;
516 if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
517 /* ignore -n1 in '-i -n1' */
518 bc_ctl.args_per_exec = 0;
519 else
520 bc_ctl.replace_pat = NULL;
521 break;
523 /* The POSIX standard specifies that it is not an error
524 * for the -s option to specify a size that the implementation
525 * cannot support - in that case, the relevant limit is used.
527 case 's':
529 size_t arg_size;
530 act_on_init_result();
531 arg_size = parse_num (optarg, 's', 1L,
532 bc_ctl.posix_arg_size_max, 0);
533 if (arg_size > bc_ctl.posix_arg_size_max)
535 error (0, 0,
536 _("warning: value %ld for -s option is too large, "
537 "using %ld instead"),
538 arg_size, bc_ctl.posix_arg_size_max);
539 arg_size = bc_ctl.posix_arg_size_max;
541 bc_ctl.arg_max = arg_size;
543 break;
545 case 'S':
546 show_limits = true;
547 break;
549 case 't':
550 print_command = true;
551 break;
553 case 'x':
554 bc_ctl.exit_if_size_exceeded = true;
555 break;
557 case 'p':
558 query_before_executing = true;
559 print_command = true;
560 break;
562 case 'r':
563 always_run_command = 0;
564 break;
566 case 'P':
567 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
568 break;
570 case 'a':
571 input_file = optarg;
572 break;
574 case 'v':
575 printf (_("GNU xargs version %s\n"), version_string);
576 return 0;
578 default:
579 usage (stderr);
580 return 1;
584 /* If we had deferred failing due to problems in bc_init_controlinfo(),
585 * do it now.
587 * We issue this error message after processing command line
588 * arguments so that it is possible to use "xargs --help" even if
589 * the environment is too large.
591 act_on_init_result();
592 assert(BC_INIT_OK == bcstatus);
594 if (0 == strcmp (input_file, "-"))
596 input_stream = stdin;
598 else
600 keep_stdin = 1; /* see prep_child_for_exec() */
601 input_stream = fopen (input_file, "r");
602 if (NULL == input_stream)
604 error (1, errno,
605 _("Cannot open input file `%s'"),
606 input_file);
610 if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
611 bc_ctl.exit_if_size_exceeded = true;
613 if (optind == argc)
615 optind = 0;
616 argc = 1;
617 argv = &default_cmd;
620 /* We want to be able to print size_t values as unsigned long, so if
621 * the cast isn't value-preserving, we have a problem. This isn't a
622 * problem in C89, because size_t was known to be no wider than
623 * unsigned long. In C99 this is no longer the case, but there are
624 * special C99 ways to print such values. Unfortunately this
625 * program tries to work on both C89 and C99 systems.
627 #if defined(SIZE_MAX)
628 # if SIZE_MAX > ULONG_MAX
629 # error "I'm not sure how to print size_t values on your system"
630 # endif
631 #else
632 /* Without SIZE_MAX (i.e. limits.h) this is probably
633 * close to the best we can do.
635 assert(sizeof(size_t) <= sizeof(unsigned long));
636 #endif
638 if (show_limits)
640 fprintf(stderr,
641 _("Your environment variables take up %lu bytes\n"),
642 (unsigned long)bc_size_of_environment());
643 fprintf(stderr,
644 _("POSIX lower and upper limits on argument length: %lu, %lu\n"),
645 (unsigned long)bc_ctl.posix_arg_size_min,
646 (unsigned long)bc_ctl.posix_arg_size_max);
647 fprintf(stderr,
648 _("Maximum length of command we could actually use: %ld\n"),
649 (unsigned long)(bc_ctl.posix_arg_size_max -
650 bc_size_of_environment()));
651 fprintf(stderr,
652 _("Size of command buffer we are actually using: %lu\n"),
653 (unsigned long)bc_ctl.arg_max);
655 if (isatty(STDIN_FILENO))
657 fprintf(stderr,
658 "\n"
659 "Execution of xargs will continue now, and it will "
660 "try to read its input and run commands; if this is "
661 "not what you wanted to happen, please type the "
662 "end-of-file keystroke.\n");
666 linebuf = (char *) xmalloc (bc_ctl.arg_max + 1);
667 bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1);
669 /* Make sure to listen for the kids. */
670 signal (SIGCHLD, SIG_DFL);
672 if (!bc_ctl.replace_pat)
674 for (; optind < argc; optind++)
675 bc_push_arg (&bc_ctl, &bc_state,
676 argv[optind], strlen (argv[optind]) + 1,
677 NULL, 0,
678 initial_args);
679 initial_args = false;
680 bc_ctl.initial_argc = bc_state.cmd_argc;
681 bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
683 while ((*read_args) () != -1)
684 if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
686 xargs_do_exec (&bc_ctl, &bc_state);
687 lineno = 0;
690 /* SYSV xargs seems to do at least one exec, even if the
691 input is empty. */
692 if (bc_state.cmd_argc != bc_ctl.initial_argc
693 || (always_run_command && procs_executed == 0))
694 xargs_do_exec (&bc_ctl, &bc_state);
697 else
699 int i;
700 size_t len;
701 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
703 for (i = optind; i < argc; i++)
704 arglen[i] = strlen(argv[i]);
705 bc_ctl.rplen = strlen (bc_ctl.replace_pat);
706 while ((len = (*read_args) ()) != -1)
708 /* Don't do insert on the command name. */
709 bc_clear_args(&bc_ctl, &bc_state);
710 bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
712 bc_push_arg (&bc_ctl, &bc_state,
713 argv[optind], arglen[optind] + 1,
714 NULL, 0,
715 initial_args);
716 len--;
717 initial_args = false;
719 for (i = optind + 1; i < argc; i++)
720 bc_do_insert (&bc_ctl, &bc_state,
721 argv[i], arglen[i],
722 NULL, 0,
723 linebuf, len,
724 initial_args);
725 xargs_do_exec (&bc_ctl, &bc_state);
729 original_exit_value = child_error;
730 return child_error;
734 /* Read a line of arguments from the input and add them to the list of
735 arguments to pass to the command. Ignore blank lines and initial blanks.
736 Single and double quotes and backslashes quote metacharacters and blanks
737 as they do in the shell.
738 Return -1 if eof (either physical or logical) is reached,
739 otherwise the length of the last string read (including the null). */
741 static int
742 read_line (void)
744 /* States for read_line. */
745 enum read_line_state
747 NORM = 0,
748 SPACE = 1,
749 QUOTE = 2,
750 BACKSLASH = 3
752 static boolean eof = false;
753 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
754 enum read_line_state state = SPACE; /* The type of character we last read. */
755 int prevc; /* The previous value of c. */
756 int quotc = 0; /* The last quote character read. */
757 int c = EOF;
758 boolean first = true; /* true if reading first arg on line. */
759 boolean seen_arg = false; /* true if we have seen any arg (or part of one) yet */
760 int len;
761 char *p = linebuf;
762 /* Including the NUL, the args must not grow past this point. */
763 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
765 if (eof)
766 return -1;
767 while (1)
769 prevc = c;
770 c = getc (input_stream);
772 if (c == EOF)
774 /* COMPAT: SYSV seems to ignore stuff on a line that
775 ends without a \n; we don't. */
776 eof = true;
777 if (p == linebuf)
778 return -1;
779 *p++ = '\0';
780 len = p - linebuf;
781 if (state == QUOTE)
783 exec_if_possible ();
784 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
785 quotc == '"' ? _("double") : _("single"));
787 if (first && EOF_STR (linebuf))
788 return -1;
789 if (!bc_ctl.replace_pat)
790 bc_push_arg (&bc_ctl, &bc_state,
791 linebuf, len,
792 NULL, 0,
793 initial_args);
794 return len;
796 switch (state)
798 case SPACE:
799 if (ISSPACE (c))
800 continue;
801 state = NORM;
802 /* aaahhhh.... */
804 case NORM:
805 if (c == '\n')
807 if (!ISBLANK (prevc))
808 lineno++; /* For -l. */
809 if (p == linebuf)
811 if (seen_arg)
813 /* An empty argument, add it to the list as normal. */
815 else
817 /* Blank line. */
818 state = SPACE;
819 continue;
822 *p++ = '\0';
823 len = p - linebuf;
824 if (EOF_STR (linebuf))
826 eof = true;
827 return first ? -1 : len;
829 if (!bc_ctl.replace_pat)
830 bc_push_arg (&bc_ctl, &bc_state,
831 linebuf, len,
832 NULL, 0,
833 initial_args);
834 return len;
836 seen_arg = true;
838 /* POSIX: In the POSIX locale, the separators are <SPC> and
839 * <TAB>, but not <FF> or <VT>.
841 if (!bc_ctl.replace_pat && ISBLANK (c))
843 *p++ = '\0';
844 len = p - linebuf;
845 if (EOF_STR (linebuf))
847 eof = true;
848 return first ? -1 : len;
850 bc_push_arg (&bc_ctl, &bc_state,
851 linebuf, len,
852 NULL, 0,
853 initial_args);
854 p = linebuf;
855 state = SPACE;
856 first = false;
857 continue;
859 switch (c)
861 case '\\':
862 state = BACKSLASH;
863 continue;
865 case '\'':
866 case '"':
867 state = QUOTE;
868 quotc = c;
869 continue;
871 break;
873 case QUOTE:
874 if (c == '\n')
876 exec_if_possible ();
877 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
878 quotc == '"' ? _("double") : _("single"));
880 if (c == quotc)
882 state = NORM;
883 seen_arg = true; /* Makes a difference for e.g. just '' or "" as the first arg on a line */
884 continue;
886 break;
888 case BACKSLASH:
889 state = NORM;
890 break;
893 if ( (0 == c) && !nullwarning_given )
895 /* This is just a warning message. We only issue it once. */
896 error (0, 0,
897 _("warning: a NUL character occurred in the input. "
898 "It cannot be passed through in the argument list. "
899 "Did you mean to use the --null option?"));
900 nullwarning_given = 1;
903 #if 1
904 if (p >= endbuf)
906 exec_if_possible ();
907 error (1, 0, _("argument line too long"));
909 *p++ = c;
910 #else
911 append_char_to_buf(&linebuf, &endbuf, &p, c);
912 #endif
916 /* Read a null-terminated string from the input and add it to the list of
917 arguments to pass to the command.
918 Return -1 if eof (either physical or logical) is reached,
919 otherwise the length of the string read (including the null). */
921 static int
922 read_string (void)
924 static boolean eof = false;
925 int len;
926 char *p = linebuf;
927 /* Including the NUL, the args must not grow past this point. */
928 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
930 if (eof)
931 return -1;
932 while (1)
934 int c = getc (input_stream);
935 if (c == EOF)
937 eof = true;
938 if (p == linebuf)
939 return -1;
940 *p++ = '\0';
941 len = p - linebuf;
942 if (!bc_ctl.replace_pat)
943 bc_push_arg (&bc_ctl, &bc_state,
944 linebuf, len,
945 NULL, 0,
946 initial_args);
947 return len;
949 if (c == input_delimiter)
951 lineno++; /* For -l. */
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 (p >= endbuf)
963 exec_if_possible ();
964 error (1, 0, _("argument line too long"));
966 *p++ = c;
970 /* Print the arguments of the command to execute.
971 If ASK is nonzero, prompt the user for a response, and
972 if the user responds affirmatively, return true;
973 otherwise, return false. */
975 static boolean
976 print_args (boolean ask)
978 int i;
980 for (i = 0; i < bc_state.cmd_argc - 1; i++)
981 fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
982 if (ask)
984 static FILE *tty_stream;
985 int c, savec;
987 if (!tty_stream)
989 tty_stream = fopen ("/dev/tty", "r");
990 if (!tty_stream)
991 error (1, errno, "/dev/tty");
993 fputs ("?...", stderr);
994 fflush (stderr);
995 c = savec = getc (tty_stream);
996 while (c != EOF && c != '\n')
997 c = getc (tty_stream);
998 if (savec == 'y' || savec == 'Y')
999 return true;
1001 else
1002 putc ('\n', stderr);
1004 return false;
1008 /* Close stdin and attach /dev/null to it.
1009 * This resolves Savannah bug #3992.
1011 static void
1012 prep_child_for_exec (void)
1014 if (!keep_stdin)
1016 const char inputfile[] = "/dev/null";
1017 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
1019 close(0);
1020 if (open(inputfile, O_RDONLY) < 0)
1022 /* This is not entirely fatal, since
1023 * executing the child with a closed
1024 * stdin is almost as good as executing it
1025 * with its stdin attached to /dev/null.
1027 error (0, errno, "%s", inputfile);
1033 /* Execute the command that has been built in `cmd_argv'. This may involve
1034 waiting for processes that were previously executed. */
1036 static int
1037 xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
1039 pid_t child;
1041 (void) ctl;
1042 (void) state;
1044 bc_push_arg (&bc_ctl, &bc_state,
1045 (char *) NULL, 0,
1046 NULL, 0,
1047 false); /* Null terminate the arg list. */
1049 if (!query_before_executing || print_args (true))
1051 if (proc_max && procs_executing >= proc_max)
1052 wait_for_proc (false);
1053 if (!query_before_executing && print_command)
1054 print_args (false);
1055 /* If we run out of processes, wait for a child to return and
1056 try again. */
1057 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1058 wait_for_proc (false);
1059 switch (child)
1061 case -1:
1062 error (1, errno, _("cannot fork"));
1064 case 0: /* Child. */
1065 prep_child_for_exec();
1066 execvp (bc_state.cmd_argv[0], bc_state.cmd_argv);
1067 error (0, errno, "%s", bc_state.cmd_argv[0]);
1068 _exit (errno == ENOENT ? 127 : 126);
1069 /*NOTREACHED*/
1071 add_proc (child);
1074 bc_clear_args(&bc_ctl, &bc_state);
1075 return 1; /* Success */
1078 /* Execute the command if possible. */
1080 static void
1081 exec_if_possible (void)
1083 if (bc_ctl.replace_pat || initial_args ||
1084 bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded)
1085 return;
1086 xargs_do_exec (&bc_ctl, &bc_state);
1089 /* Add the process with id PID to the list of processes that have
1090 been executed. */
1092 static void
1093 add_proc (pid_t pid)
1095 int i;
1097 /* Find an empty slot. */
1098 for (i = 0; i < pids_alloc && pids[i]; i++)
1100 if (i == pids_alloc)
1102 if (pids_alloc == 0)
1104 pids_alloc = proc_max ? proc_max : 64;
1105 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1107 else
1109 pids_alloc *= 2;
1110 pids = (pid_t *) xrealloc (pids,
1111 sizeof (pid_t) * pids_alloc);
1113 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1115 pids[i] = pid;
1116 procs_executing++;
1117 procs_executed++;
1120 /* If ALL is true, wait for all child processes to finish;
1121 otherwise, wait for one child process to finish.
1122 Remove the processes that finish from the list of executing processes. */
1124 static void
1125 wait_for_proc (boolean all)
1127 while (procs_executing)
1129 int i, status;
1133 pid_t pid;
1135 while ((pid = wait (&status)) == (pid_t) -1)
1136 if (errno != EINTR)
1137 error (1, errno, _("error waiting for child process"));
1139 /* Find the entry in `pids' for the child process
1140 that exited. */
1141 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1144 while (i == pids_alloc); /* A child died that we didn't start? */
1146 /* Remove the child from the list. */
1147 pids[i] = 0;
1148 procs_executing--;
1150 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1151 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1152 if (WEXITSTATUS (status) == 255)
1153 error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1154 if (WIFSTOPPED (status))
1155 error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1156 if (WIFSIGNALED (status))
1157 error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1158 if (WEXITSTATUS (status) != 0)
1159 child_error = 123;
1161 if (!all)
1162 break;
1166 /* Wait for all child processes to finish. */
1168 static void
1169 wait_for_proc_all (void)
1171 static boolean waiting = false;
1173 if (waiting)
1174 return;
1176 waiting = true;
1177 wait_for_proc (true);
1178 waiting = false;
1180 if (original_exit_value != child_error)
1182 /* wait_for_proc() changed the value of child_error(). This
1183 * function is registered via atexit(), and so may have been
1184 * called from exit(). We now know that the original value
1185 * passed to exit() is no longer the exit status we require.
1186 * The POSIX standard states that the behaviour if exit() is
1187 * called more than once is undefined. Therefore we now have to
1188 * exit with _exit() instead of exit().
1190 _exit(child_error);
1195 /* Return the value of the number represented in STR.
1196 OPTION is the command line option to which STR is the argument.
1197 If the value does not fall within the boundaries MIN and MAX,
1198 Print an error message mentioning OPTION. If FATAL is true,
1199 we also exit. */
1201 static long
1202 parse_num (char *str, int option, long int min, long int max, int fatal)
1204 char *eptr;
1205 long val;
1207 val = strtol (str, &eptr, 10);
1208 if (eptr == str || *eptr)
1210 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1211 program_name, option);
1212 usage (stderr);
1213 exit(1);
1215 else if (val < min)
1217 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1218 program_name, option, min);
1219 if (fatal)
1221 usage (stderr);
1222 exit(1);
1224 else
1226 val = min;
1229 else if (max >= 0 && val > max)
1231 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1232 program_name, option, max);
1233 if (fatal)
1235 usage (stderr);
1236 exit(1);
1238 else
1240 val = max;
1243 return val;
1246 static void
1247 usage (FILE *stream)
1249 fprintf (stream, _("\
1250 Usage: %s [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]\n\
1251 [-E eof-str] [-e[eof-str]] [--eof[=eof-str]]\n\
1252 [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]\n\
1253 [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]\n\
1254 [-n max-args] [--max-args=max-args]\n\
1255 [-s max-chars] [--max-chars=max-chars]\n\
1256 [-P max-procs] [--max-procs=max-procs] [--show-limits]\n\
1257 [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]\n\
1258 [--version] [--help] [command [initial-arguments]]\n"),
1259 program_name);
1260 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);