safely_chdir_lstat(): if we didn't end up in the right place, and then
[findutils.git] / xargs / xargs.c
blob1d891d50f176e4e8e11dde342dd4f15a7d012a73
1 /* xargs -- build and execute command lines from standard input
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2005 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 USA.
20 /* Written by Mike Rendell <michael@cs.mun.ca>
21 and David MacKenzie <djm@gnu.org>. */
23 #include <config.h>
25 # ifndef PARAMS
26 # if defined PROTOTYPES || (defined __STDC__ && __STDC__)
27 # define PARAMS(Args) Args
28 # else
29 # define PARAMS(Args) ()
30 # endif
31 # endif
33 #include <ctype.h>
35 #if !defined (isascii) || defined (STDC_HEADERS)
36 #ifdef isascii
37 #undef isascii
38 #endif
39 #define isascii(c) 1
40 #endif
42 #ifdef isblank
43 #define ISBLANK(c) (isascii (c) && isblank (c))
44 #else
45 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
46 #endif
48 #define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
49 || (c) == '\f' || (c) == '\v')
51 #include <sys/types.h>
52 #include <stdio.h>
53 #include <errno.h>
54 #include <getopt.h>
55 #include <fcntl.h>
57 #if defined(STDC_HEADERS)
58 #include <assert.h>
59 #endif
61 #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
62 #include <string.h>
63 #if !defined(STDC_HEADERS)
64 #include <memory.h>
65 #endif
66 #else
67 #include <strings.h>
68 #define memcpy(dest, source, count) (bcopy((source), (dest), (count)))
69 #endif
71 #ifndef _POSIX_SOURCE
72 #include <sys/param.h>
73 #endif
75 #ifdef HAVE_LIMITS_H
76 #include <limits.h>
77 #endif
79 #ifndef LONG_MAX
80 #define LONG_MAX (~(1 << (sizeof (long) * 8 - 1)))
81 #endif
83 #ifdef HAVE_UNISTD_H
84 #include <unistd.h>
85 #endif
87 #include <signal.h>
89 #if !defined(SIGCHLD) && defined(SIGCLD)
90 #define SIGCHLD SIGCLD
91 #endif
93 #include "wait.h"
95 /* States for read_line. */
96 #define NORM 0
97 #define SPACE 1
98 #define QUOTE 2
99 #define BACKSLASH 3
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 extern char **environ;
133 /* Do multibyte processing if multibyte characters are supported,
134 unless multibyte sequences are search safe. Multibyte sequences
135 are search safe if searching for a substring using the byte
136 comparison function 'strstr' gives no false positives. All 8-bit
137 encodings and the UTF-8 multibyte encoding are search safe, but
138 the EUC encodings are not.
139 BeOS uses the UTF-8 encoding exclusively, so it is search safe. */
140 #if defined __BEOS__
141 # define MULTIBYTE_IS_SEARCH_SAFE 1
142 #endif
143 #define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE)
145 #if DO_MULTIBYTE
146 # if HAVE_MBRLEN
147 # include <wchar.h>
148 # else
149 /* Simulate mbrlen with mblen as best we can. */
150 # define mbstate_t int
151 # define mbrlen(s, n, ps) mblen (s, n)
152 # endif
153 #endif
155 /* Not char because of type promotion; NeXT gcc can't handle it. */
156 typedef int boolean;
157 #define true 1
158 #define false 0
160 #if __STDC__
161 #define VOID void
162 #else
163 #define VOID char
164 #endif
166 #include <xalloc.h>
167 #include "closeout.h"
169 void error PARAMS ((int status, int errnum, char *message,...));
171 extern char *version_string;
173 /* The name this program was run with. */
174 char *program_name;
176 static FILE *input_stream;
178 /* Buffer for reading arguments from input. */
179 static char *linebuf;
181 static int keep_stdin = 0;
183 /* Line number in stdin since the last command was executed. */
184 static int lineno = 0;
186 static struct buildcmd_state bc_state;
187 static struct buildcmd_control bc_ctl;
190 #if 0
191 /* If nonzero, then instead of putting the args from stdin at
192 the end of the command argument list, they are each stuck into the
193 initial args, replacing each occurrence of the `replace_pat' in the
194 initial args. */
195 static char *replace_pat = NULL;
198 /* The length of `replace_pat'. */
199 static size_t rplen = 0;
200 #endif
202 /* If nonzero, when this string is read on stdin it is treated as
203 end of file.
204 IEEE Std 1003.1, 2004 Edition allows this to be NULL.
205 In findutils releases up to and including 4.2.8, this was "_".
207 static char *eof_str = NULL;
209 #if 0
210 /* If nonzero, the maximum number of nonblank lines from stdin to use
211 per command line. */
212 static long lines_per_exec = 0;
214 /* The maximum number of arguments to use per command line. */
215 static long args_per_exec = 1024;
217 /* If true, exit if lines_per_exec or args_per_exec is exceeded. */
218 static boolean exit_if_size_exceeded = false;
219 /* The maximum number of characters that can be used per command line. */
220 static long arg_max;
221 /* Storage for elements of `cmd_argv'. */
222 static char *argbuf;
223 #endif
225 #if 0
226 /* The list of args being built. */
227 static char **cmd_argv = NULL;
229 /* Number of elements allocated for `cmd_argv'. */
230 static int cmd_argv_alloc = 0;
231 #endif
233 #if 0
234 /* Number of valid elements in `cmd_argv'. */
235 static int cmd_argc = 0;
236 /* Number of chars being used in `cmd_argv'. */
237 static int cmd_argv_chars = 0;
239 /* Number of initial arguments given on the command line. */
240 static int initial_argc = 0;
241 #endif
243 /* Number of chars in the initial args. */
244 /* static int initial_argv_chars = 0; */
246 /* true when building up initial arguments in `cmd_argv'. */
247 static boolean initial_args = true;
249 /* If nonzero, the maximum number of child processes that can be running
250 at once. */
251 static int proc_max = 1;
253 /* Total number of child processes that have been executed. */
254 static int procs_executed = 0;
256 /* The number of elements in `pids'. */
257 static int procs_executing = 0;
259 /* List of child processes currently executing. */
260 static pid_t *pids = NULL;
262 /* The number of allocated elements in `pids'. */
263 static int pids_alloc = 0;
265 /* Exit status; nonzero if any child process exited with a
266 status of 1-125. */
267 static int child_error = 0;
269 /* If true, print each command on stderr before executing it. */
270 static boolean print_command = false; /* Option -t */
272 /* If true, query the user before executing each command, and only
273 execute the command if the user responds affirmatively. */
274 static boolean query_before_executing = false;
276 static struct option const longopts[] =
278 {"null", no_argument, NULL, '0'},
279 {"arg-file", required_argument, NULL, 'a'},
280 {"eof", optional_argument, NULL, 'e'},
281 {"replace", optional_argument, NULL, 'I'},
282 {"max-lines", optional_argument, NULL, 'l'},
283 {"max-args", required_argument, NULL, 'n'},
284 {"interactive", no_argument, NULL, 'p'},
285 {"no-run-if-empty", no_argument, NULL, 'r'},
286 {"max-chars", required_argument, NULL, 's'},
287 {"verbose", no_argument, NULL, 't'},
288 {"show-limits", no_argument, NULL, 'S'},
289 {"exit", no_argument, NULL, 'x'},
290 {"max-procs", required_argument, NULL, 'P'},
291 {"version", no_argument, NULL, 'v'},
292 {"help", no_argument, NULL, 'h'},
293 {NULL, no_argument, NULL, 0}
296 static int read_line PARAMS ((void));
297 static int read_string PARAMS ((void));
298 #if 0
299 static char *mbstrstr PARAMS ((const char *haystack, const char *needle));
300 static void do_insert PARAMS ((char *arg, size_t arglen, size_t lblen));
301 static void push_arg PARAMS ((char *arg, size_t len));
302 #endif
303 static boolean print_args PARAMS ((boolean ask));
304 /* static void do_exec PARAMS ((void)); */
305 static int xargs_do_exec (const struct buildcmd_control *cl, struct buildcmd_state *state);
306 static void add_proc PARAMS ((pid_t pid));
307 static void wait_for_proc PARAMS ((boolean all));
308 static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
309 static long env_size PARAMS ((char **envp));
310 static void usage PARAMS ((FILE * stream));
314 static long
315 get_line_max(void)
317 long val;
318 #ifdef _SC_LINE_MAX
319 val = sysconf(_SC_LINE_MAX);
320 #else
321 val = -1;
322 #endif
324 if (val > 0)
325 return val;
327 /* either _SC_LINE_MAX was not available or
328 * there is no particular limit.
330 #ifdef LINE_MAX
331 val = LINE_MAX;
332 #endif
334 if (val > 0)
335 return val;
337 return 2048L; /* a reasonable guess. */
342 main (int argc, char **argv)
344 int optc;
345 int show_limits = 0; /* --show-limits */
346 int always_run_command = 1;
347 char *input_file = "-"; /* "-" is stdin */
348 long posix_arg_size_max;
349 long posix_arg_size_min;
350 long arg_size;
351 long size_of_environment = env_size(environ);
352 char *default_cmd = "/bin/echo";
353 int (*read_args) PARAMS ((void)) = read_line;
355 program_name = argv[0];
357 #ifdef HAVE_SETLOCALE
358 setlocale (LC_ALL, "");
359 #endif
360 bindtextdomain (PACKAGE, LOCALEDIR);
361 textdomain (PACKAGE);
362 atexit (close_stdout);
364 /* IEE Std 1003.1, 2003 specifies that the combined argument and
365 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
366 * specifies that it shall be at least LINE_MAX.
368 posix_arg_size_min = get_line_max();
369 posix_arg_size_max = bc_get_arg_max();
370 posix_arg_size_max -= 2048; /* POSIX.2 requires subtracting 2048. */
372 bc_init_controlinfo(&bc_ctl);
373 assert(bc_ctl.arg_max == posix_arg_size_max);
375 bc_ctl.exec_callback = xargs_do_exec;
378 /* Start with a reasonable default size, though this can be
379 * adjusted via the -s option.
381 arg_size = (128 * 1024) + size_of_environment;
383 /* Take the size of the environment into account. */
384 if (size_of_environment > posix_arg_size_max)
386 error (1, 0, _("environment is too large for exec"));
388 else
390 bc_ctl.arg_max = posix_arg_size_max - size_of_environment;
393 /* Check against the upper and lower limits. */
394 if (arg_size > bc_ctl.arg_max)
395 arg_size = bc_ctl.arg_max;
396 if (arg_size < posix_arg_size_min)
397 arg_size = posix_arg_size_min;
402 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:",
403 longopts, (int *) 0)) != -1)
405 switch (optc)
407 case '0':
408 read_args = read_string;
409 break;
411 case 'E': /* POSIX */
412 case 'e': /* deprecated */
413 if (optarg && (strlen(optarg) > 0))
414 eof_str = optarg;
415 else
416 eof_str = 0;
417 break;
419 case 'h':
420 usage (stdout);
421 return 0;
423 case 'I': /* POSIX */
424 case 'i': /* deprecated */
425 if (optarg)
426 bc_ctl.replace_pat = optarg;
427 else
428 bc_ctl.replace_pat = "{}";
429 /* -i excludes -n -l. */
430 bc_ctl.args_per_exec = 0;
431 bc_ctl.lines_per_exec = 0;
432 break;
434 case 'L': /* POSIX */
435 case 'l': /* deprecated */
436 if (optarg)
437 bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
438 else
439 bc_ctl.lines_per_exec = 1;
440 /* -l excludes -i -n. */
441 bc_ctl.args_per_exec = 0;
442 bc_ctl.replace_pat = NULL;
443 break;
445 case 'n':
446 bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
447 /* -n excludes -i -l. */
448 bc_ctl.lines_per_exec = 0;
449 if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
450 /* ignore -n1 in '-i -n1' */
451 bc_ctl.args_per_exec = 0;
452 else
453 bc_ctl.replace_pat = NULL;
454 break;
456 /* The POSIX standard specifies that it is not an error
457 * for the -s option to specify a size that the implementation
458 * cannot support - in that case, the relevant limit is used.
460 case 's':
461 arg_size = parse_num (optarg, 's', 1L, posix_arg_size_max, 0);
462 if (arg_size > posix_arg_size_max)
464 error (0, 0, "warning: value %ld for -s option is too large, using %ld instead", arg_size, posix_arg_size_max);
465 arg_size = posix_arg_size_max;
467 break;
469 case 'S':
470 show_limits = true;
471 break;
473 case 't':
474 print_command = true;
475 break;
477 case 'x':
478 bc_ctl.exit_if_size_exceeded = true;
479 break;
481 case 'p':
482 query_before_executing = true;
483 print_command = true;
484 break;
486 case 'r':
487 always_run_command = 0;
488 break;
490 case 'P':
491 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
492 break;
494 case 'a':
495 input_file = optarg;
496 break;
498 case 'v':
499 printf (_("GNU xargs version %s\n"), version_string);
500 return 0;
502 default:
503 usage (stderr);
504 return 1;
508 if (0 == strcmp (input_file, "-"))
510 input_stream = stdin;
512 else
514 keep_stdin = 1; /* see prep_child_for_exec() */
515 input_stream = fopen (input_file, "r");
516 if (NULL == input_stream)
518 error (1, errno,
519 _("Cannot open input file `%s'"),
520 input_file);
524 if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
525 bc_ctl.exit_if_size_exceeded = true;
527 if (optind == argc)
529 optind = 0;
530 argc = 1;
531 argv = &default_cmd;
534 /* Taking into account the size of the environment,
535 * figure out how large a buffer we need to
536 * hold all the arguments. We cannot use ARG_MAX
537 * directly since that may be arbitrarily large.
538 * This is from a patch by Bob Prolux, <bob@proulx.com>.
540 if (bc_ctl.arg_max > arg_size)
542 if (show_limits)
544 fprintf(stderr,
545 _("Reducing arg_max (%ld) to arg_size (%ld)\n"),
546 bc_ctl.arg_max, arg_size);
548 bc_ctl.arg_max = arg_size;
551 if (show_limits)
553 fprintf(stderr,
554 _("Your environment variables take up %ld bytes\n"),
555 size_of_environment);
556 fprintf(stderr,
557 _("POSIX lower and upper limits on argument length: %ld, %ld\n"),
558 posix_arg_size_min,
559 posix_arg_size_max);
560 fprintf(stderr,
561 _("Maximum length of command we could actually use: %ld\n"),
562 (posix_arg_size_max - size_of_environment));
563 fprintf(stderr,
564 _("Size of command buffer we are actually using: %ld\n"),
565 arg_size);
568 linebuf = (char *) xmalloc (bc_ctl.arg_max + 1);
569 bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1);
571 /* Make sure to listen for the kids. */
572 signal (SIGCHLD, SIG_DFL);
574 if (!bc_ctl.replace_pat)
576 for (; optind < argc; optind++)
577 bc_push_arg (&bc_ctl, &bc_state,
578 argv[optind], strlen (argv[optind]) + 1,
579 NULL, 0,
580 initial_args);
581 initial_args = false;
582 bc_ctl.initial_argc = bc_state.cmd_argc;
583 bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
585 while ((*read_args) () != -1)
586 if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
588 xargs_do_exec (&bc_ctl, &bc_state);
589 lineno = 0;
592 /* SYSV xargs seems to do at least one exec, even if the
593 input is empty. */
594 if (bc_state.cmd_argc != bc_ctl.initial_argc
595 || (always_run_command && procs_executed == 0))
596 xargs_do_exec (&bc_ctl, &bc_state);
599 else
601 int i;
602 size_t len;
603 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
605 for (i = optind; i < argc; i++)
606 arglen[i] = strlen(argv[i]);
607 bc_ctl.rplen = strlen (bc_ctl.replace_pat);
608 while ((len = (*read_args) ()) != -1)
610 /* Don't do insert on the command name. */
611 bc_clear_args(&bc_ctl, &bc_state);
612 bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
614 bc_push_arg (&bc_ctl, &bc_state,
615 argv[optind], arglen[optind] + 1,
616 NULL, 0,
617 initial_args);
618 len--;
619 initial_args = false;
621 for (i = optind + 1; i < argc; i++)
622 bc_do_insert (&bc_ctl, &bc_state,
623 argv[i], arglen[i],
624 NULL, 0,
625 linebuf, len,
626 initial_args);
627 xargs_do_exec (&bc_ctl, &bc_state);
631 wait_for_proc (true);
632 return child_error;
635 #if 0
636 static int
637 append_char_to_buf(char **pbuf, char **pend, char **pp, int c)
639 char *end_of_buffer = *pend;
640 char *start_of_buffer = *pbuf;
641 char *p = *pp;
642 if (p >= end_of_buffer)
644 if (bc_ctl.replace_pat)
646 size_t len = end_of_buffer - start_of_buffer;
647 size_t offset = p - start_of_buffer;
648 len *= 2;
649 start_of_buffer = xrealloc(start_of_buffer, len*2);
650 if (NULL != start_of_buffer)
652 end_of_buffer = start_of_buffer + len;
653 p = start_of_buffer + offset;
654 *p++ = c;
656 /* Update the caller's idea of where the buffer is. */
657 *pbuf = start_of_buffer;
658 *pend = end_of_buffer;
659 *pp = p;
661 return 0;
663 else
665 /* Failed to reallocate. */
666 return -1;
669 else
671 /* I suspect that this can never happen now, because append_char_to_buf()
672 * should only be called when replace_pat is true.
674 error (1, 0, _("argument line too long"));
675 /*NOTREACHED*/
676 return -1;
679 else
681 /* Enough space remains. */
682 *p++ = c;
683 *pp = p;
684 return 0;
687 #endif
690 /* Read a line of arguments from the input and add them to the list of
691 arguments to pass to the command. Ignore blank lines and initial blanks.
692 Single and double quotes and backslashes quote metacharacters and blanks
693 as they do in the shell.
694 Return -1 if eof (either physical or logical) is reached,
695 otherwise the length of the last string read (including the null). */
697 static int
698 read_line (void)
700 static boolean eof = false;
701 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
702 int state = SPACE; /* The type of character we last read. */
703 int prevc; /* The previous value of c. */
704 int quotc = 0; /* The last quote character read. */
705 int c = EOF;
706 boolean first = true; /* true if reading first arg on line. */
707 int len;
708 char *p = linebuf;
709 /* Including the NUL, the args must not grow past this point. */
710 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
712 if (eof)
713 return -1;
714 while (1)
716 prevc = c;
717 c = getc (input_stream);
718 if (c == EOF)
720 /* COMPAT: SYSV seems to ignore stuff on a line that
721 ends without a \n; we don't. */
722 eof = true;
723 if (p == linebuf)
724 return -1;
725 *p++ = '\0';
726 len = p - linebuf;
727 /* FIXME we don't check for unterminated quotes here. */
728 if (first && EOF_STR (linebuf))
729 return -1;
730 if (!bc_ctl.replace_pat)
731 bc_push_arg (&bc_ctl, &bc_state,
732 linebuf, len,
733 NULL, 0,
734 initial_args);
735 return len;
737 switch (state)
739 case SPACE:
740 if (ISSPACE (c))
741 continue;
742 state = NORM;
743 /* aaahhhh.... */
745 case NORM:
746 if (c == '\n')
748 if (!ISBLANK (prevc))
749 lineno++; /* For -l. */
750 if (p == linebuf)
752 /* Blank line. */
753 state = SPACE;
754 continue;
756 *p++ = '\0';
757 len = p - linebuf;
758 if (EOF_STR (linebuf))
760 eof = true;
761 return first ? -1 : len;
763 if (!bc_ctl.replace_pat)
764 bc_push_arg (&bc_ctl, &bc_state,
765 linebuf, len,
766 NULL, 0,
767 initial_args);
768 return len;
770 if (!bc_ctl.replace_pat && ISSPACE (c))
772 *p++ = '\0';
773 len = p - linebuf;
774 if (EOF_STR (linebuf))
776 eof = true;
777 return first ? -1 : len;
779 bc_push_arg (&bc_ctl, &bc_state,
780 linebuf, len,
781 NULL, 0,
782 initial_args);
783 p = linebuf;
784 state = SPACE;
785 first = false;
786 continue;
788 switch (c)
790 case '\\':
791 state = BACKSLASH;
792 continue;
794 case '\'':
795 case '"':
796 state = QUOTE;
797 quotc = c;
798 continue;
800 break;
802 case QUOTE:
803 if (c == '\n')
804 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
805 quotc == '"' ? _("double") : _("single"));
806 if (c == quotc)
808 state = NORM;
809 continue;
811 break;
813 case BACKSLASH:
814 state = NORM;
815 break;
817 #if 1
818 if (p >= endbuf)
819 error (1, 0, _("argument line too long"));
820 *p++ = c;
821 #else
822 append_char_to_buf(&linebuf, &endbuf, &p, c);
823 #endif
827 /* Read a null-terminated string from the input and add it to the list of
828 arguments to pass to the command.
829 Return -1 if eof (either physical or logical) is reached,
830 otherwise the length of the string read (including the null). */
832 static int
833 read_string (void)
835 static boolean eof = false;
836 int len;
837 char *p = linebuf;
838 /* Including the NUL, the args must not grow past this point. */
839 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
841 if (eof)
842 return -1;
843 while (1)
845 int c = getc (input_stream);
846 if (c == EOF)
848 eof = true;
849 if (p == linebuf)
850 return -1;
851 *p++ = '\0';
852 len = p - linebuf;
853 if (!bc_ctl.replace_pat)
854 bc_push_arg (&bc_ctl, &bc_state,
855 linebuf, len,
856 NULL, 0,
857 initial_args);
858 return len;
860 if (c == '\0')
862 lineno++; /* For -l. */
863 *p++ = '\0';
864 len = p - linebuf;
865 if (!bc_ctl.replace_pat)
866 bc_push_arg (&bc_ctl, &bc_state,
867 linebuf, len,
868 NULL, 0,
869 initial_args);
870 return len;
872 if (p >= endbuf)
873 error (1, 0, _("argument line too long"));
874 *p++ = c;
878 /* Print the arguments of the command to execute.
879 If ASK is nonzero, prompt the user for a response, and
880 if the user responds affirmatively, return true;
881 otherwise, return false. */
883 static boolean
884 print_args (boolean ask)
886 int i;
888 for (i = 0; i < bc_state.cmd_argc - 1; i++)
889 fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
890 if (ask)
892 static FILE *tty_stream;
893 int c, savec;
895 if (!tty_stream)
897 tty_stream = fopen ("/dev/tty", "r");
898 if (!tty_stream)
899 error (1, errno, "/dev/tty");
901 fputs ("?...", stderr);
902 fflush (stderr);
903 c = savec = getc (tty_stream);
904 while (c != EOF && c != '\n')
905 c = getc (tty_stream);
906 if (savec == 'y' || savec == 'Y')
907 return true;
909 else
910 putc ('\n', stderr);
912 return false;
916 /* Close stdin and attach /dev/null to it.
917 * This resolves Savannah bug #3992.
919 static void
920 prep_child_for_exec (void)
922 if (!keep_stdin)
924 const char inputfile[] = "/dev/null";
925 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
927 close(0);
928 if (open(inputfile, O_RDONLY) < 0)
930 /* This is not entirely fatal, since
931 * executing the child with a closed
932 * stdin is almost as good as executing it
933 * with its stdin attached to /dev/null.
935 error (0, errno, "%s", inputfile);
941 /* Execute the command that has been built in `cmd_argv'. This may involve
942 waiting for processes that were previously executed. */
944 static int
945 xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
947 pid_t child;
949 bc_push_arg (&bc_ctl, &bc_state,
950 (char *) NULL, 0,
951 NULL, 0,
952 false); /* Null terminate the arg list. */
954 if (!query_before_executing || print_args (true))
956 if (proc_max && procs_executing >= proc_max)
957 wait_for_proc (false);
958 if (!query_before_executing && print_command)
959 print_args (false);
960 /* If we run out of processes, wait for a child to return and
961 try again. */
962 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
963 wait_for_proc (false);
964 switch (child)
966 case -1:
967 error (1, errno, _("cannot fork"));
969 case 0: /* Child. */
970 prep_child_for_exec();
971 execvp (bc_state.cmd_argv[0], bc_state.cmd_argv);
972 error (0, errno, "%s", bc_state.cmd_argv[0]);
973 _exit (errno == ENOENT ? 127 : 126);
974 /*NOTREACHED*/
976 add_proc (child);
979 bc_clear_args(&bc_ctl, &bc_state);
980 return 1; /* Success */
983 /* Add the process with id PID to the list of processes that have
984 been executed. */
986 static void
987 add_proc (pid_t pid)
989 int i;
991 /* Find an empty slot. */
992 for (i = 0; i < pids_alloc && pids[i]; i++)
994 if (i == pids_alloc)
996 if (pids_alloc == 0)
998 pids_alloc = proc_max ? proc_max : 64;
999 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1001 else
1003 pids_alloc *= 2;
1004 pids = (pid_t *) xrealloc (pids,
1005 sizeof (pid_t) * pids_alloc);
1007 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1009 pids[i] = pid;
1010 procs_executing++;
1011 procs_executed++;
1014 /* If ALL is true, wait for all child processes to finish;
1015 otherwise, wait for one child process to finish.
1016 Remove the processes that finish from the list of executing processes. */
1018 static void
1019 wait_for_proc (boolean all)
1021 while (procs_executing)
1023 int i, status;
1027 pid_t pid;
1029 while ((pid = wait (&status)) == (pid_t) -1)
1030 if (errno != EINTR)
1031 error (1, errno, _("error waiting for child process"));
1033 /* Find the entry in `pids' for the child process
1034 that exited. */
1035 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1038 while (i == pids_alloc); /* A child died that we didn't start? */
1040 /* Remove the child from the list. */
1041 pids[i] = 0;
1042 procs_executing--;
1044 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1045 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1046 if (WEXITSTATUS (status) == 255)
1047 error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1048 if (WIFSTOPPED (status))
1049 error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1050 if (WIFSIGNALED (status))
1051 error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1052 if (WEXITSTATUS (status) != 0)
1053 child_error = 123;
1055 if (!all)
1056 break;
1060 /* Return the value of the number represented in STR.
1061 OPTION is the command line option to which STR is the argument.
1062 If the value does not fall within the boundaries MIN and MAX,
1063 Print an error message mentioning OPTION. If FATAL is true,
1064 we also exit. */
1066 static long
1067 parse_num (char *str, int option, long int min, long int max, int fatal)
1069 char *eptr;
1070 long val;
1072 val = strtol (str, &eptr, 10);
1073 if (eptr == str || *eptr)
1075 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1076 program_name, option);
1077 usage (stderr);
1078 exit(1);
1080 else if (val < min)
1082 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1083 program_name, option, min);
1084 if (fatal)
1086 usage (stderr);
1087 exit(1);
1089 else
1091 val = min;
1094 else if (max >= 0 && val > max)
1096 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1097 program_name, option, max);
1098 if (fatal)
1100 usage (stderr);
1101 exit(1);
1103 else
1105 val = max;
1108 return val;
1111 /* Return how much of ARG_MAX is used by the environment. */
1113 static long
1114 env_size (char **envp)
1116 long len = 0;
1118 while (*envp)
1119 len += strlen (*envp++) + 1;
1121 return len;
1124 static void
1125 usage (FILE *stream)
1127 fprintf (stream, _("\
1128 Usage: %s [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]\n\
1129 [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]\n\
1130 [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]\n\
1131 [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]\n\
1132 [--max-args=max-args] [--no-run-if-empty] [--arg-file=file]\n\
1133 [--version] [--help] [command [initial-arguments]]\n"),
1134 program_name);
1135 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);