If stat() fails with ELOOP, we issue a diagnostic message.
[findutils.git] / xargs / xargs.c
blob6c0187ada5c3696fc3e4c94250c992079392b4c2
1 /* xargs -- build and execute command lines from standard input
2 Copyright (C) 1990, 91, 92, 93, 94, 2000,2003 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.ai.mit.edu>. */
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(HAVE_STRING_H) || defined(STDC_HEADERS)
58 #include <string.h>
59 #if !defined(STDC_HEADERS)
60 #include <memory.h>
61 #endif
62 #else
63 #include <strings.h>
64 #define memcpy(dest, source, count) (bcopy((source), (dest), (count)))
65 #endif
67 #ifndef _POSIX_SOURCE
68 #include <sys/param.h>
69 #endif
71 #ifdef HAVE_LIMITS_H
72 #include <limits.h>
73 #endif
75 #ifndef LONG_MAX
76 #define LONG_MAX (~(1 << (sizeof (long) * 8 - 1)))
77 #endif
79 #ifdef HAVE_UNISTD_H
80 #include <unistd.h>
81 #endif
83 #include <signal.h>
85 #if !defined(SIGCHLD) && defined(SIGCLD)
86 #define SIGCHLD SIGCLD
87 #endif
89 /* COMPAT: SYSV version defaults size (and has a max value of) to 470.
90 We try to make it as large as possible. */
91 #if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
92 #define ARG_MAX sysconf (_SC_ARG_MAX)
93 #endif
94 #ifndef ARG_MAX
95 #define ARG_MAX NCARGS
96 #endif
98 #include "wait.h"
100 /* States for read_line. */
101 #define NORM 0
102 #define SPACE 1
103 #define QUOTE 2
104 #define BACKSLASH 3
106 #ifdef STDC_HEADERS
107 #include <stdlib.h>
108 #else
109 extern int errno;
110 #endif
112 #ifdef HAVE_LOCALE_H
113 #include <locale.h>
114 #endif
115 #if ENABLE_NLS
116 # include <libintl.h>
117 # define _(Text) gettext (Text)
118 #else
119 # define _(Text) Text
120 #define textdomain(Domain)
121 #define bindtextdomain(Package, Directory)
122 #endif
123 #ifdef gettext_noop
124 # define N_(String) gettext_noop (String)
125 #else
126 /* See locate.c for explanation as to why not use (String) */
127 # define N_(String) String
128 #endif
130 /* Return nonzero if S is the EOF string. */
131 #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
133 extern char **environ;
135 /* Do multibyte processing if multibyte characters are supported,
136 unless multibyte sequences are search safe. Multibyte sequences
137 are search safe if searching for a substring using the byte
138 comparison function 'strstr' gives no false positives. All 8-bit
139 encodings and the UTF-8 multibyte encoding are search safe, but
140 the EUC encodings are not.
141 BeOS uses the UTF-8 encoding exclusively, so it is search safe. */
142 #if defined __BEOS__
143 # define MULTIBYTE_IS_SEARCH_SAFE 1
144 #endif
145 #define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE)
147 #if DO_MULTIBYTE
148 # if HAVE_MBRLEN
149 # include <wchar.h>
150 # else
151 /* Simulate mbrlen with mblen as best we can. */
152 # define mbstate_t int
153 # define mbrlen(s, n, ps) mblen (s, n)
154 # endif
155 #endif
157 /* Not char because of type promotion; NeXT gcc can't handle it. */
158 typedef int boolean;
159 #define true 1
160 #define false 0
162 #if __STDC__
163 #define VOID void
164 #else
165 #define VOID char
166 #endif
168 #include <xalloc.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;
180 static int keep_stdin = 0;
182 /* Line number in stdin since the last command was executed. */
183 static int lineno = 0;
185 /* If nonzero, then instead of putting the args from stdin at
186 the end of the command argument list, they are each stuck into the
187 initial args, replacing each occurrence of the `replace_pat' in the
188 initial args. */
189 static char *replace_pat = NULL;
191 /* The length of `replace_pat'. */
192 static size_t rplen = 0;
194 /* If nonzero, when this string is read on stdin it is treated as
195 end of file.
196 I don't like this - it should default to NULL. */
197 static char *eof_str = "_";
199 /* If nonzero, the maximum number of nonblank lines from stdin to use
200 per command line. */
201 static long lines_per_exec = 0;
203 /* The maximum number of arguments to use per command line. */
204 static long args_per_exec = 1024;
206 /* If true, exit if lines_per_exec or args_per_exec is exceeded. */
207 static boolean exit_if_size_exceeded = false;
209 /* The maximum number of characters that can be used per command line. */
210 static long arg_max;
212 /* Storage for elements of `cmd_argv'. */
213 static char *argbuf;
215 /* The list of args being built. */
216 static char **cmd_argv = NULL;
218 /* Number of elements allocated for `cmd_argv'. */
219 static int cmd_argv_alloc = 0;
221 /* Number of valid elements in `cmd_argv'. */
222 static int cmd_argc = 0;
224 /* Number of chars being used in `cmd_argv'. */
225 static int cmd_argv_chars = 0;
227 /* Number of initial arguments given on the command line. */
228 static int initial_argc = 0;
230 /* Number of chars in the initial args. */
231 static int initial_argv_chars = 0;
233 /* true when building up initial arguments in `cmd_argv'. */
234 static boolean initial_args = true;
236 /* If nonzero, the maximum number of child processes that can be running
237 at once. */
238 static int proc_max = 1;
240 /* Total number of child processes that have been executed. */
241 static int procs_executed = 0;
243 /* The number of elements in `pids'. */
244 static int procs_executing = 0;
246 /* List of child processes currently executing. */
247 static pid_t *pids = NULL;
249 /* The number of allocated elements in `pids'. */
250 static int pids_alloc = 0;
252 /* Exit status; nonzero if any child process exited with a
253 status of 1-125. */
254 static int child_error = 0;
256 /* If true, print each command on stderr before executing it. */
257 static boolean print_command = false; /* Option -t */
259 /* If true, query the user before executing each command, and only
260 execute the command if the user responds affirmatively. */
261 static boolean query_before_executing = false;
263 static struct option const longopts[] =
265 {"null", no_argument, NULL, '0'},
266 {"arg-file", required_argument, NULL, 'a'},
267 {"eof", optional_argument, NULL, 'e'},
268 {"replace", optional_argument, NULL, 'i'},
269 {"max-lines", optional_argument, NULL, 'l'},
270 {"max-args", required_argument, NULL, 'n'},
271 {"interactive", no_argument, NULL, 'p'},
272 {"no-run-if-empty", no_argument, NULL, 'r'},
273 {"max-chars", required_argument, NULL, 's'},
274 {"verbose", no_argument, NULL, 't'},
275 {"show-limits", no_argument, NULL, 'S'},
276 {"exit", no_argument, NULL, 'x'},
277 {"max-procs", required_argument, NULL, 'P'},
278 {"version", no_argument, NULL, 'v'},
279 {"help", no_argument, NULL, 'h'},
280 {NULL, no_argument, NULL, 0}
283 static int read_line PARAMS ((void));
284 static int read_string PARAMS ((void));
285 static char *mbstrstr PARAMS ((const char *haystack, const char *needle));
286 static void do_insert PARAMS ((char *arg, size_t arglen, size_t lblen));
287 static void push_arg PARAMS ((char *arg, size_t len));
288 static boolean print_args PARAMS ((boolean ask));
289 static void do_exec PARAMS ((void));
290 static void add_proc PARAMS ((pid_t pid));
291 static void wait_for_proc PARAMS ((boolean all));
292 static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
293 static long env_size PARAMS ((char **envp));
294 static void usage PARAMS ((FILE * stream));
298 static long
299 get_line_max(void)
301 long val;
302 #ifdef _SC_LINE_MAX
303 val = sysconf(_SC_LINE_MAX);
304 #else
305 val = -1;
306 #endif
308 if (val > 0)
309 return val;
311 /* either _SC_LINE_MAX was not available or
312 * there is no particular limit.
314 #ifdef LINE_MAX
315 val = LINE_MAX;
316 #endif
318 if (val > 0)
319 return val;
321 return 2048L; /* a reasonable guess. */
325 static long
326 get_arg_max(void)
328 long val;
329 #ifdef _SC_ARG_MAX
330 val = sysconf(_SC_ARG_MAX);
331 #else
332 val = -1;
333 #endif
335 if (val > 0)
336 return val;
338 /* either _SC_ARG_MAX was not available or
339 * there is no particular limit.
341 #ifdef ARG_MAX
342 val = ARG_MAX;
343 #endif
345 if (val > 0)
346 return val;
348 /* The value returned by this function bounds the
349 * value applied as the ceiling for the -s option.
350 * Hence it the system won't tell us what its limit
351 * is, we allow the user to specify more or less
352 * whatever value they like.
354 return LONG_MAX;
359 main (int argc, char **argv)
361 int optc;
362 int show_limits = 0; /* --show-limits */
363 int always_run_command = 1;
364 char *input_file = "-"; /* "-" is stdin */
365 long posix_arg_size_max;
366 long posix_arg_size_min;
367 long arg_size;
368 long size_of_environment = env_size(environ);
369 char *default_cmd = "/bin/echo";
370 int (*read_args) PARAMS ((void)) = read_line;
372 program_name = argv[0];
374 #ifdef HAVE_SETLOCALE
375 setlocale (LC_ALL, "");
376 #endif
377 bindtextdomain (PACKAGE, LOCALEDIR);
378 textdomain (PACKAGE);
380 /* IEE Std 1003.1, 2003 specifies that the combined argument and
381 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
382 * specifies that it shall be at least LINE_MAX.
384 posix_arg_size_min = get_line_max();
385 posix_arg_size_max = get_arg_max();
386 posix_arg_size_max -= 2048; /* POSIX.2 requires subtracting 2048. */
387 arg_max = posix_arg_size_max;
389 /* Start with a reasonable default size, though this can be
390 * adjusted via the -s option.
392 arg_size = (128 * 1024) + size_of_environment;
394 /* Take the size of the environment into account. */
395 if (size_of_environment > posix_arg_size_max)
397 error (1, 0, _("environment is too large for exec"));
399 else
401 arg_max = posix_arg_size_max - size_of_environment;
404 /* Check against the upper and lower limits. */
405 if (arg_size > arg_max)
406 arg_size = arg_max;
407 if (arg_size < posix_arg_size_min)
408 arg_size = posix_arg_size_min;
413 while ((optc = getopt_long (argc, argv, "+0a:e::i::l::n:prs:txP:",
414 longopts, (int *) 0)) != -1)
416 switch (optc)
418 case '0':
419 read_args = read_string;
420 break;
422 case 'e':
423 if (optarg)
424 eof_str = optarg;
425 else
426 eof_str = 0;
427 break;
429 case 'h':
430 usage (stdout);
431 return 0;
433 case 'i':
434 if (optarg)
435 replace_pat = optarg;
436 else
437 replace_pat = "{}";
438 /* -i excludes -n -l. */
439 args_per_exec = 0;
440 lines_per_exec = 0;
441 break;
443 case 'l':
444 if (optarg)
445 lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
446 else
447 lines_per_exec = 1;
448 /* -l excludes -i -n. */
449 args_per_exec = 0;
450 replace_pat = NULL;
451 break;
453 case 'n':
454 args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
455 /* -n excludes -i -l. */
456 lines_per_exec = 0;
457 if (args_per_exec == 1 && replace_pat)
458 /* ignore -n1 in '-i -n1' */
459 args_per_exec = 0;
460 else
461 replace_pat = NULL;
462 break;
464 /* The POSIX standard specifies that it is not an error
465 * for the -s option to specify a size that the implementation
466 * cannot support - in that case, the relevant limit is used.
468 case 's':
469 arg_size = parse_num (optarg, 's', 1L, posix_arg_size_max, 0);
470 if (arg_size > posix_arg_size_max)
472 error (0, 0, "warning: value %ld for -s option is too large, using %ld instead", arg_size, posix_arg_size_max);
473 arg_size = posix_arg_size_max;
475 break;
477 case 'S':
478 show_limits = true;
479 break;
481 case 't':
482 print_command = true;
483 break;
485 case 'x':
486 exit_if_size_exceeded = true;
487 break;
489 case 'p':
490 query_before_executing = true;
491 print_command = true;
492 break;
494 case 'r':
495 always_run_command = 0;
496 break;
498 case 'P':
499 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
500 break;
502 case 'a':
503 input_file = optarg;
504 break;
506 case 'v':
507 printf (_("GNU xargs version %s\n"), version_string);
508 return 0;
510 default:
511 usage (stderr);
512 return 1;
516 if (0 == strcmp (input_file, "-"))
518 input_stream = stdin;
520 else
522 keep_stdin = 1; /* see prep_child_for_exec() */
523 input_stream = fopen (input_file, "r");
524 if (NULL == input_stream)
526 error (1, errno,
527 _("Cannot open input file `%s'"),
528 input_file);
532 if (replace_pat || lines_per_exec)
533 exit_if_size_exceeded = true;
535 if (optind == argc)
537 optind = 0;
538 argc = 1;
539 argv = &default_cmd;
542 /* Taking into account the size of the environment,
543 * figure out how large a buffer we need to
544 * hold all the arguments. We cannot use ARG_MAX
545 * directly since that may be arbitrarily large.
546 * This is from a patch by Bob Prolux, <bob@proulx.com>.
548 if (arg_max > arg_size)
550 if (show_limits)
552 fprintf(stderr,
553 _("Reducing arg_max (%ld) to arg_size (%ld)\n"),
554 arg_max, arg_size);
556 arg_max = arg_size;
559 if (show_limits)
561 fprintf(stderr,
562 _("Your environment variables take up %ld bytes\n"),
563 size_of_environment);
564 fprintf(stderr,
565 _("POSIX lower and upper limits on argument length: %ld, %ld\n"),
566 posix_arg_size_min,
567 posix_arg_size_max);
568 fprintf(stderr,
569 _("Maximum length of command we could actually use: %ld\n"),
570 (posix_arg_size_max - size_of_environment));
571 fprintf(stderr,
572 _("Size of command buffer we are actually using: %ld\n"),
573 arg_size);
576 linebuf = (char *) xmalloc (arg_max + 1);
577 argbuf = (char *) xmalloc (arg_max + 1);
579 /* Make sure to listen for the kids. */
580 signal (SIGCHLD, SIG_DFL);
582 if (!replace_pat)
584 for (; optind < argc; optind++)
585 push_arg (argv[optind], strlen (argv[optind]) + 1);
586 initial_args = false;
587 initial_argc = cmd_argc;
588 initial_argv_chars = cmd_argv_chars;
590 while ((*read_args) () != -1)
591 if (lines_per_exec && lineno >= lines_per_exec)
593 do_exec ();
594 lineno = 0;
597 /* SYSV xargs seems to do at least one exec, even if the
598 input is empty. */
599 if (cmd_argc != initial_argc
600 || (always_run_command && procs_executed == 0))
601 do_exec ();
603 else
605 int i;
606 size_t len;
607 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
609 for (i = optind; i < argc; i++)
610 arglen[i] = strlen(argv[i]);
611 rplen = strlen (replace_pat);
612 while ((len = (*read_args) ()) != -1)
614 /* Don't do insert on the command name. */
615 push_arg (argv[optind], arglen[optind] + 1);
616 len--;
617 for (i = optind + 1; i < argc; i++)
618 do_insert (argv[i], arglen[i], len);
619 do_exec ();
623 wait_for_proc (true);
624 return child_error;
627 #if 0
628 static int
629 append_char_to_buf(char **pbuf, char **pend, char **pp, int c)
631 char *end_of_buffer = *pend;
632 char *start_of_buffer = *pbuf;
633 char *p = *pp;
634 if (p >= end_of_buffer)
636 if (replace_pat)
638 size_t len = end_of_buffer - start_of_buffer;
639 size_t offset = p - start_of_buffer;
640 len *= 2;
641 start_of_buffer = xrealloc(start_of_buffer, len*2);
642 if (NULL != start_of_buffer)
644 end_of_buffer = start_of_buffer + len;
645 p = start_of_buffer + offset;
646 *p++ = c;
648 /* Update the caller's idea of where the buffer is. */
649 *pbuf = start_of_buffer;
650 *pend = end_of_buffer;
651 *pp = p;
653 return 0;
655 else
657 /* Failed to reallocate. */
658 return -1;
661 else
663 /* I suspect that this can never happen now, because append_char_to_buf()
664 * should only be called wen replace_pat is true.
666 error (1, 0, _("argument line too long"));
667 /*NOTREACHED*/
668 return -1;
671 else
673 /* Enough space remains. */
674 *p++ = c;
675 *pp = p;
676 return 0;
679 #endif
682 /* Read a line of arguments from the input and add them to the list of
683 arguments to pass to the command. Ignore blank lines and initial blanks.
684 Single and double quotes and backslashes quote metacharacters and blanks
685 as they do in the shell.
686 Return -1 if eof (either physical or logical) is reached,
687 otherwise the length of the last string read (including the null). */
689 static int
690 read_line (void)
692 static boolean eof = false;
693 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
694 int state = SPACE; /* The type of character we last read. */
695 int prevc; /* The previous value of c. */
696 int quotc = 0; /* The last quote character read. */
697 int c = EOF;
698 boolean first = true; /* true if reading first arg on line. */
699 int len;
700 char *p = linebuf;
701 /* Including the NUL, the args must not grow past this point. */
702 char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
704 if (eof)
705 return -1;
706 while (1)
708 prevc = c;
709 c = getc (input_stream);
710 if (c == EOF)
712 /* COMPAT: SYSV seems to ignore stuff on a line that
713 ends without a \n; we don't. */
714 eof = true;
715 if (p == linebuf)
716 return -1;
717 *p++ = '\0';
718 len = p - linebuf;
719 /* FIXME we don't check for unterminated quotes here. */
720 if (first && EOF_STR (linebuf))
721 return -1;
722 if (!replace_pat)
723 push_arg (linebuf, len);
724 return len;
726 switch (state)
728 case SPACE:
729 if (ISSPACE (c))
730 continue;
731 state = NORM;
732 /* aaahhhh.... */
734 case NORM:
735 if (c == '\n')
737 if (!ISBLANK (prevc))
738 lineno++; /* For -l. */
739 if (p == linebuf)
741 /* Blank line. */
742 state = SPACE;
743 continue;
745 *p++ = '\0';
746 len = p - linebuf;
747 if (EOF_STR (linebuf))
749 eof = true;
750 return first ? -1 : len;
752 if (!replace_pat)
753 push_arg (linebuf, len);
754 return len;
756 if (!replace_pat && ISSPACE (c))
758 *p++ = '\0';
759 len = p - linebuf;
760 if (EOF_STR (linebuf))
762 eof = true;
763 return first ? -1 : len;
765 push_arg (linebuf, len);
766 p = linebuf;
767 state = SPACE;
768 first = false;
769 continue;
771 switch (c)
773 case '\\':
774 state = BACKSLASH;
775 continue;
777 case '\'':
778 case '"':
779 state = QUOTE;
780 quotc = c;
781 continue;
783 break;
785 case QUOTE:
786 if (c == '\n')
787 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
788 quotc == '"' ? _("double") : _("single"));
789 if (c == quotc)
791 state = NORM;
792 continue;
794 break;
796 case BACKSLASH:
797 state = NORM;
798 break;
800 #if 1
801 if (p >= endbuf)
802 error (1, 0, _("argument line too long"));
803 *p++ = c;
804 #else
805 append_char_to_buf(&linebuf, &endbuf, &p, c);
806 #endif
810 /* Read a null-terminated string from the input and add it to the list of
811 arguments to pass to the command.
812 Return -1 if eof (either physical or logical) is reached,
813 otherwise the length of the string read (including the null). */
815 static int
816 read_string (void)
818 static boolean eof = false;
819 int len;
820 char *p = linebuf;
821 /* Including the NUL, the args must not grow past this point. */
822 char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
824 if (eof)
825 return -1;
826 while (1)
828 int c = getc (input_stream);
829 if (c == EOF)
831 eof = true;
832 if (p == linebuf)
833 return -1;
834 *p++ = '\0';
835 len = p - linebuf;
836 if (!replace_pat)
837 push_arg (linebuf, len);
838 return len;
840 if (c == '\0')
842 lineno++; /* For -l. */
843 *p++ = '\0';
844 len = p - linebuf;
845 if (!replace_pat)
846 push_arg (linebuf, len);
847 return len;
849 if (p >= endbuf)
850 error (1, 0, _("argument line too long"));
851 *p++ = c;
855 /* Finds the first occurrence of the substring NEEDLE in the string
856 HAYSTACK. Both strings can be multibyte strings. */
858 static char *
859 mbstrstr (const char *haystack, const char *needle)
861 #if DO_MULTIBYTE
862 if (MB_CUR_MAX > 1)
864 size_t hlen = strlen (haystack);
865 size_t nlen = strlen (needle);
866 mbstate_t mbstate;
867 size_t step;
869 memset (&mbstate, 0, sizeof (mbstate_t));
870 while (hlen >= nlen)
872 if (memcmp (haystack, needle, nlen) == 0)
873 return (char *) haystack;
874 step = mbrlen (haystack, hlen, &mbstate);
875 if (step <= 0)
876 break;
877 haystack += step;
878 hlen -= step;
880 return NULL;
882 #endif
883 return strstr (haystack, needle);
886 /* Replace all instances of `replace_pat' in ARG with `linebuf',
887 and add the resulting string to the list of arguments for the command
888 to execute.
889 ARGLEN is the length of ARG, not including the null.
890 LBLEN is the length of `linebuf', not including the null.
892 COMPAT: insertions on the SYSV version are limited to 255 chars per line,
893 and a max of 5 occurrences of replace_pat in the initial-arguments.
894 Those restrictions do not exist here. */
896 static void
897 do_insert (char *arg, size_t arglen, size_t lblen)
899 /* Temporary copy of each arg with the replace pattern replaced by the
900 real arg. */
901 static char *insertbuf;
902 char *p;
903 int bytes_left = arg_max - 1; /* Bytes left on the command line. */
905 if (!insertbuf)
906 insertbuf = (char *) xmalloc (arg_max + 1);
907 p = insertbuf;
911 size_t len; /* Length in ARG before `replace_pat'. */
912 char *s = mbstrstr (arg, replace_pat);
913 if (s)
914 len = s - arg;
915 else
916 len = arglen;
917 bytes_left -= len;
918 if (bytes_left <= 0)
919 break;
921 strncpy (p, arg, len);
922 p += len;
923 arg += len;
924 arglen -= len;
926 if (s)
928 bytes_left -= lblen;
929 if (bytes_left <= 0)
930 break;
931 strcpy (p, linebuf);
932 arg += rplen;
933 arglen -= rplen;
934 p += lblen;
937 while (*arg);
938 if (*arg)
939 error (1, 0, _("command too long"));
940 *p++ = '\0';
941 push_arg (insertbuf, p - insertbuf);
944 /* Add ARG to the end of the list of arguments `cmd_argv' to pass
945 to the command.
946 LEN is the length of ARG, including the terminating null.
947 If this brings the list up to its maximum size, execute the command. */
949 static void
950 push_arg (char *arg, size_t len)
952 if (arg)
954 if (cmd_argv_chars + len > arg_max)
956 if (initial_args || cmd_argc == initial_argc)
957 error (1, 0, _("can not fit single argument within argument list size limit"));
958 /* option -i (replace_pat) implies -x (exit_if_size_exceeded) */
959 if (replace_pat
960 || (exit_if_size_exceeded &&
961 (lines_per_exec || args_per_exec)))
962 error (1, 0, _("argument list too long"));
963 do_exec ();
965 if (!initial_args && args_per_exec &&
966 cmd_argc - initial_argc == args_per_exec)
967 do_exec ();
970 if (cmd_argc >= cmd_argv_alloc)
972 if (!cmd_argv)
974 cmd_argv_alloc = 64;
975 cmd_argv = (char **) xmalloc (sizeof (char *) * cmd_argv_alloc);
977 else
979 cmd_argv_alloc *= 2;
980 cmd_argv = (char **) xrealloc (cmd_argv,
981 sizeof (char *) * cmd_argv_alloc);
985 if (!arg)
986 cmd_argv[cmd_argc++] = NULL;
987 else
989 cmd_argv[cmd_argc++] = argbuf + cmd_argv_chars;
990 strcpy (argbuf + cmd_argv_chars, arg);
991 cmd_argv_chars += len;
993 /* If we have now collected enough arguments,
994 * do the exec immediately. This must be
995 * conditional on arg!=NULL, sinc do_exec()
996 * actually calls push_arg(NULL, 0).
998 if (!initial_args
999 && args_per_exec
1000 && (cmd_argc - initial_argc) == args_per_exec)
1001 do_exec ();
1005 /* Print the arguments of the command to execute.
1006 If ASK is nonzero, prompt the user for a response, and
1007 if the user responds affirmatively, return true;
1008 otherwise, return false. */
1010 static boolean
1011 print_args (boolean ask)
1013 int i;
1015 for (i = 0; i < cmd_argc - 1; i++)
1016 fprintf (stderr, "%s ", cmd_argv[i]);
1017 if (ask)
1019 static FILE *tty_stream;
1020 int c, savec;
1022 if (!tty_stream)
1024 tty_stream = fopen ("/dev/tty", "r");
1025 if (!tty_stream)
1026 error (1, errno, "/dev/tty");
1028 fputs ("?...", stderr);
1029 fflush (stderr);
1030 c = savec = getc (tty_stream);
1031 while (c != EOF && c != '\n')
1032 c = getc (tty_stream);
1033 if (savec == 'y' || savec == 'Y')
1034 return true;
1036 else
1037 putc ('\n', stderr);
1039 return false;
1043 /* Close stdin and attach /dev/null to it.
1044 * This resolves Savannah bug #3992.
1046 static void
1047 prep_child_for_exec (void)
1049 if (!keep_stdin)
1051 const char inputfile[] = "/dev/null";
1052 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
1054 close(0);
1055 if (open(inputfile, O_RDONLY) < 0)
1057 /* This is not entirely fatal, since
1058 * executing the child with a closed
1059 * stdin is almost as good as executing it
1060 * with its stdin attached to /dev/null.
1062 error (0, errno, "%s", inputfile);
1068 /* Execute the command that has been built in `cmd_argv'. This may involve
1069 waiting for processes that were previously executed. */
1071 static void
1072 do_exec (void)
1074 pid_t child;
1076 push_arg ((char *) NULL, 0); /* Null terminate the arg list. */
1077 if (!query_before_executing || print_args (true))
1079 if (proc_max && procs_executing >= proc_max)
1080 wait_for_proc (false);
1081 if (!query_before_executing && print_command)
1082 print_args (false);
1083 /* If we run out of processes, wait for a child to return and
1084 try again. */
1085 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1086 wait_for_proc (false);
1087 switch (child)
1089 case -1:
1090 error (1, errno, _("cannot fork"));
1092 case 0: /* Child. */
1093 prep_child_for_exec();
1094 execvp (cmd_argv[0], cmd_argv);
1095 error (0, errno, "%s", cmd_argv[0]);
1096 _exit (errno == ENOENT ? 127 : 126);
1097 /*NOTREACHED*/
1099 add_proc (child);
1102 cmd_argc = initial_argc;
1103 cmd_argv_chars = initial_argv_chars;
1106 /* Add the process with id PID to the list of processes that have
1107 been executed. */
1109 static void
1110 add_proc (pid_t pid)
1112 int i;
1114 /* Find an empty slot. */
1115 for (i = 0; i < pids_alloc && pids[i]; i++)
1117 if (i == pids_alloc)
1119 if (pids_alloc == 0)
1121 pids_alloc = proc_max ? proc_max : 64;
1122 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1124 else
1126 pids_alloc *= 2;
1127 pids = (pid_t *) xrealloc (pids,
1128 sizeof (pid_t) * pids_alloc);
1130 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1132 pids[i] = pid;
1133 procs_executing++;
1134 procs_executed++;
1137 /* If ALL is true, wait for all child processes to finish;
1138 otherwise, wait for one child process to finish.
1139 Remove the processes that finish from the list of executing processes. */
1141 static void
1142 wait_for_proc (boolean all)
1144 while (procs_executing)
1146 int i, status;
1150 pid_t pid;
1152 while ((pid = wait (&status)) == (pid_t) -1)
1153 if (errno != EINTR)
1154 error (1, errno, _("error waiting for child process"));
1156 /* Find the entry in `pids' for the child process
1157 that exited. */
1158 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1161 while (i == pids_alloc); /* A child died that we didn't start? */
1163 /* Remove the child from the list. */
1164 pids[i] = 0;
1165 procs_executing--;
1167 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1168 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1169 if (WEXITSTATUS (status) == 255)
1170 error (124, 0, _("%s: exited with status 255; aborting"), cmd_argv[0]);
1171 if (WIFSTOPPED (status))
1172 error (125, 0, _("%s: stopped by signal %d"), cmd_argv[0], WSTOPSIG (status));
1173 if (WIFSIGNALED (status))
1174 error (125, 0, _("%s: terminated by signal %d"), cmd_argv[0], WTERMSIG (status));
1175 if (WEXITSTATUS (status) != 0)
1176 child_error = 123;
1178 if (!all)
1179 break;
1183 /* Return the value of the number represented in STR.
1184 OPTION is the command line option to which STR is the argument.
1185 If the value does not fall within the boundaries MIN and MAX,
1186 Print an error message mentioning OPTION. If FATAL is true,
1187 we also exit. */
1189 static long
1190 parse_num (char *str, int option, long int min, long int max, int fatal)
1192 char *eptr;
1193 long val;
1195 val = strtol (str, &eptr, 10);
1196 if (eptr == str || *eptr)
1198 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1199 program_name, option);
1200 usage (stderr);
1201 exit(1);
1203 else if (val < min)
1205 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1206 program_name, option, min);
1207 if (fatal)
1209 usage (stderr);
1210 exit(1);
1212 else
1214 val = min;
1217 else if (max >= 0 && val > max)
1219 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1220 program_name, option, max);
1221 if (fatal)
1223 usage (stderr);
1224 exit(1);
1226 else
1228 val = max;
1231 return val;
1234 /* Return how much of ARG_MAX is used by the environment. */
1236 static long
1237 env_size (char **envp)
1239 long len = 0;
1241 while (*envp)
1242 len += strlen (*envp++) + 1;
1244 return len;
1247 static void
1248 usage (FILE *stream)
1250 fprintf (stream, _("\
1251 Usage: %s [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]\n\
1252 [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]\n\
1253 [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]\n\
1254 [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]\n\
1255 [--max-args=max-args] [--no-run-if-empty] [--arg-file=file]\n\
1256 [--version] [--help] [command [initial-arguments]]\n"),
1257 program_name);
1258 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);