Added Bas van Gompel.
[findutils.git] / xargs / xargs.c
blobd1ba4ff453fcbac8839b085964c9b2fd6f21d4f3
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 IEEE Std 1003.1, 2004 Edition allows this to be NULL.
197 In findutils releases up to and including 4.2.8, this was "_".
199 static char *eof_str = NULL;
201 /* If nonzero, the maximum number of nonblank lines from stdin to use
202 per command line. */
203 static long lines_per_exec = 0;
205 /* The maximum number of arguments to use per command line. */
206 static long args_per_exec = 1024;
208 /* If true, exit if lines_per_exec or args_per_exec is exceeded. */
209 static boolean exit_if_size_exceeded = false;
211 /* The maximum number of characters that can be used per command line. */
212 static long arg_max;
214 /* Storage for elements of `cmd_argv'. */
215 static char *argbuf;
217 /* The list of args being built. */
218 static char **cmd_argv = NULL;
220 /* Number of elements allocated for `cmd_argv'. */
221 static int cmd_argv_alloc = 0;
223 /* Number of valid elements in `cmd_argv'. */
224 static int cmd_argc = 0;
226 /* Number of chars being used in `cmd_argv'. */
227 static int cmd_argv_chars = 0;
229 /* Number of initial arguments given on the command line. */
230 static int initial_argc = 0;
232 /* Number of chars in the initial args. */
233 static int initial_argv_chars = 0;
235 /* true when building up initial arguments in `cmd_argv'. */
236 static boolean initial_args = true;
238 /* If nonzero, the maximum number of child processes that can be running
239 at once. */
240 static int proc_max = 1;
242 /* Total number of child processes that have been executed. */
243 static int procs_executed = 0;
245 /* The number of elements in `pids'. */
246 static int procs_executing = 0;
248 /* List of child processes currently executing. */
249 static pid_t *pids = NULL;
251 /* The number of allocated elements in `pids'. */
252 static int pids_alloc = 0;
254 /* Exit status; nonzero if any child process exited with a
255 status of 1-125. */
256 static int child_error = 0;
258 /* If true, print each command on stderr before executing it. */
259 static boolean print_command = false; /* Option -t */
261 /* If true, query the user before executing each command, and only
262 execute the command if the user responds affirmatively. */
263 static boolean query_before_executing = false;
265 static struct option const longopts[] =
267 {"null", no_argument, NULL, '0'},
268 {"arg-file", required_argument, NULL, 'a'},
269 {"eof", optional_argument, NULL, 'e'},
270 {"replace", optional_argument, NULL, 'I'},
271 {"max-lines", optional_argument, NULL, 'l'},
272 {"max-args", required_argument, NULL, 'n'},
273 {"interactive", no_argument, NULL, 'p'},
274 {"no-run-if-empty", no_argument, NULL, 'r'},
275 {"max-chars", required_argument, NULL, 's'},
276 {"verbose", no_argument, NULL, 't'},
277 {"show-limits", no_argument, NULL, 'S'},
278 {"exit", no_argument, NULL, 'x'},
279 {"max-procs", required_argument, NULL, 'P'},
280 {"version", no_argument, NULL, 'v'},
281 {"help", no_argument, NULL, 'h'},
282 {NULL, no_argument, NULL, 0}
285 static int read_line PARAMS ((void));
286 static int read_string PARAMS ((void));
287 static char *mbstrstr PARAMS ((const char *haystack, const char *needle));
288 static void do_insert PARAMS ((char *arg, size_t arglen, size_t lblen));
289 static void push_arg PARAMS ((char *arg, size_t len));
290 static boolean print_args PARAMS ((boolean ask));
291 static void do_exec PARAMS ((void));
292 static void add_proc PARAMS ((pid_t pid));
293 static void wait_for_proc PARAMS ((boolean all));
294 static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
295 static long env_size PARAMS ((char **envp));
296 static void usage PARAMS ((FILE * stream));
300 static long
301 get_line_max(void)
303 long val;
304 #ifdef _SC_LINE_MAX
305 val = sysconf(_SC_LINE_MAX);
306 #else
307 val = -1;
308 #endif
310 if (val > 0)
311 return val;
313 /* either _SC_LINE_MAX was not available or
314 * there is no particular limit.
316 #ifdef LINE_MAX
317 val = LINE_MAX;
318 #endif
320 if (val > 0)
321 return val;
323 return 2048L; /* a reasonable guess. */
327 static long
328 get_arg_max(void)
330 long val;
331 #ifdef _SC_ARG_MAX
332 val = sysconf(_SC_ARG_MAX);
333 #else
334 val = -1;
335 #endif
337 if (val > 0)
338 return val;
340 /* either _SC_ARG_MAX was not available or
341 * there is no particular limit.
343 #ifdef ARG_MAX
344 val = ARG_MAX;
345 #endif
347 if (val > 0)
348 return val;
350 /* The value returned by this function bounds the
351 * value applied as the ceiling for the -s option.
352 * Hence it the system won't tell us what its limit
353 * is, we allow the user to specify more or less
354 * whatever value they like.
356 return LONG_MAX;
361 main (int argc, char **argv)
363 int optc;
364 int show_limits = 0; /* --show-limits */
365 int always_run_command = 1;
366 char *input_file = "-"; /* "-" is stdin */
367 long posix_arg_size_max;
368 long posix_arg_size_min;
369 long arg_size;
370 long size_of_environment = env_size(environ);
371 char *default_cmd = "/bin/echo";
372 int (*read_args) PARAMS ((void)) = read_line;
374 program_name = argv[0];
376 #ifdef HAVE_SETLOCALE
377 setlocale (LC_ALL, "");
378 #endif
379 bindtextdomain (PACKAGE, LOCALEDIR);
380 textdomain (PACKAGE);
382 /* IEE Std 1003.1, 2003 specifies that the combined argument and
383 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
384 * specifies that it shall be at least LINE_MAX.
386 posix_arg_size_min = get_line_max();
387 posix_arg_size_max = get_arg_max();
388 posix_arg_size_max -= 2048; /* POSIX.2 requires subtracting 2048. */
389 arg_max = posix_arg_size_max;
391 /* Start with a reasonable default size, though this can be
392 * adjusted via the -s option.
394 arg_size = (128 * 1024) + size_of_environment;
396 /* Take the size of the environment into account. */
397 if (size_of_environment > posix_arg_size_max)
399 error (1, 0, _("environment is too large for exec"));
401 else
403 arg_max = posix_arg_size_max - size_of_environment;
406 /* Check against the upper and lower limits. */
407 if (arg_size > arg_max)
408 arg_size = arg_max;
409 if (arg_size < posix_arg_size_min)
410 arg_size = posix_arg_size_min;
415 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:",
416 longopts, (int *) 0)) != -1)
418 switch (optc)
420 case '0':
421 read_args = read_string;
422 break;
424 case 'E': /* POSIX */
425 case 'e': /* deprecated */
426 if (optarg && (strlen(optarg) > 0))
427 eof_str = optarg;
428 else
429 eof_str = 0;
430 break;
432 case 'h':
433 usage (stdout);
434 return 0;
436 case 'I': /* POSIX */
437 case 'i': /* deprecated */
438 if (optarg)
439 replace_pat = optarg;
440 else
441 replace_pat = "{}";
442 /* -i excludes -n -l. */
443 args_per_exec = 0;
444 lines_per_exec = 0;
445 break;
447 case 'L': /* POSIX */
448 case 'l': /* deprecated */
449 if (optarg)
450 lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
451 else
452 lines_per_exec = 1;
453 /* -l excludes -i -n. */
454 args_per_exec = 0;
455 replace_pat = NULL;
456 break;
458 case 'n':
459 args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
460 /* -n excludes -i -l. */
461 lines_per_exec = 0;
462 if (args_per_exec == 1 && replace_pat)
463 /* ignore -n1 in '-i -n1' */
464 args_per_exec = 0;
465 else
466 replace_pat = NULL;
467 break;
469 /* The POSIX standard specifies that it is not an error
470 * for the -s option to specify a size that the implementation
471 * cannot support - in that case, the relevant limit is used.
473 case 's':
474 arg_size = parse_num (optarg, 's', 1L, posix_arg_size_max, 0);
475 if (arg_size > posix_arg_size_max)
477 error (0, 0, "warning: value %ld for -s option is too large, using %ld instead", arg_size, posix_arg_size_max);
478 arg_size = posix_arg_size_max;
480 break;
482 case 'S':
483 show_limits = true;
484 break;
486 case 't':
487 print_command = true;
488 break;
490 case 'x':
491 exit_if_size_exceeded = true;
492 break;
494 case 'p':
495 query_before_executing = true;
496 print_command = true;
497 break;
499 case 'r':
500 always_run_command = 0;
501 break;
503 case 'P':
504 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
505 break;
507 case 'a':
508 input_file = optarg;
509 break;
511 case 'v':
512 printf (_("GNU xargs version %s\n"), version_string);
513 return 0;
515 default:
516 usage (stderr);
517 return 1;
521 if (0 == strcmp (input_file, "-"))
523 input_stream = stdin;
525 else
527 keep_stdin = 1; /* see prep_child_for_exec() */
528 input_stream = fopen (input_file, "r");
529 if (NULL == input_stream)
531 error (1, errno,
532 _("Cannot open input file `%s'"),
533 input_file);
537 if (replace_pat || lines_per_exec)
538 exit_if_size_exceeded = true;
540 if (optind == argc)
542 optind = 0;
543 argc = 1;
544 argv = &default_cmd;
547 /* Taking into account the size of the environment,
548 * figure out how large a buffer we need to
549 * hold all the arguments. We cannot use ARG_MAX
550 * directly since that may be arbitrarily large.
551 * This is from a patch by Bob Prolux, <bob@proulx.com>.
553 if (arg_max > arg_size)
555 if (show_limits)
557 fprintf(stderr,
558 _("Reducing arg_max (%ld) to arg_size (%ld)\n"),
559 arg_max, arg_size);
561 arg_max = arg_size;
564 if (show_limits)
566 fprintf(stderr,
567 _("Your environment variables take up %ld bytes\n"),
568 size_of_environment);
569 fprintf(stderr,
570 _("POSIX lower and upper limits on argument length: %ld, %ld\n"),
571 posix_arg_size_min,
572 posix_arg_size_max);
573 fprintf(stderr,
574 _("Maximum length of command we could actually use: %ld\n"),
575 (posix_arg_size_max - size_of_environment));
576 fprintf(stderr,
577 _("Size of command buffer we are actually using: %ld\n"),
578 arg_size);
581 linebuf = (char *) xmalloc (arg_max + 1);
582 argbuf = (char *) xmalloc (arg_max + 1);
584 /* Make sure to listen for the kids. */
585 signal (SIGCHLD, SIG_DFL);
587 if (!replace_pat)
589 for (; optind < argc; optind++)
590 push_arg (argv[optind], strlen (argv[optind]) + 1);
591 initial_args = false;
592 initial_argc = cmd_argc;
593 initial_argv_chars = cmd_argv_chars;
595 while ((*read_args) () != -1)
596 if (lines_per_exec && lineno >= lines_per_exec)
598 do_exec ();
599 lineno = 0;
602 /* SYSV xargs seems to do at least one exec, even if the
603 input is empty. */
604 if (cmd_argc != initial_argc
605 || (always_run_command && procs_executed == 0))
606 do_exec ();
608 else
610 int i;
611 size_t len;
612 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
614 for (i = optind; i < argc; i++)
615 arglen[i] = strlen(argv[i]);
616 rplen = strlen (replace_pat);
617 while ((len = (*read_args) ()) != -1)
619 /* Don't do insert on the command name. */
620 push_arg (argv[optind], arglen[optind] + 1);
621 len--;
622 for (i = optind + 1; i < argc; i++)
623 do_insert (argv[i], arglen[i], len);
624 do_exec ();
628 wait_for_proc (true);
629 return child_error;
632 #if 0
633 static int
634 append_char_to_buf(char **pbuf, char **pend, char **pp, int c)
636 char *end_of_buffer = *pend;
637 char *start_of_buffer = *pbuf;
638 char *p = *pp;
639 if (p >= end_of_buffer)
641 if (replace_pat)
643 size_t len = end_of_buffer - start_of_buffer;
644 size_t offset = p - start_of_buffer;
645 len *= 2;
646 start_of_buffer = xrealloc(start_of_buffer, len*2);
647 if (NULL != start_of_buffer)
649 end_of_buffer = start_of_buffer + len;
650 p = start_of_buffer + offset;
651 *p++ = c;
653 /* Update the caller's idea of where the buffer is. */
654 *pbuf = start_of_buffer;
655 *pend = end_of_buffer;
656 *pp = p;
658 return 0;
660 else
662 /* Failed to reallocate. */
663 return -1;
666 else
668 /* I suspect that this can never happen now, because append_char_to_buf()
669 * should only be called wen replace_pat is true.
671 error (1, 0, _("argument line too long"));
672 /*NOTREACHED*/
673 return -1;
676 else
678 /* Enough space remains. */
679 *p++ = c;
680 *pp = p;
681 return 0;
684 #endif
687 /* Read a line of arguments from the input and add them to the list of
688 arguments to pass to the command. Ignore blank lines and initial blanks.
689 Single and double quotes and backslashes quote metacharacters and blanks
690 as they do in the shell.
691 Return -1 if eof (either physical or logical) is reached,
692 otherwise the length of the last string read (including the null). */
694 static int
695 read_line (void)
697 static boolean eof = false;
698 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
699 int state = SPACE; /* The type of character we last read. */
700 int prevc; /* The previous value of c. */
701 int quotc = 0; /* The last quote character read. */
702 int c = EOF;
703 boolean first = true; /* true if reading first arg on line. */
704 int len;
705 char *p = linebuf;
706 /* Including the NUL, the args must not grow past this point. */
707 char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
709 if (eof)
710 return -1;
711 while (1)
713 prevc = c;
714 c = getc (input_stream);
715 if (c == EOF)
717 /* COMPAT: SYSV seems to ignore stuff on a line that
718 ends without a \n; we don't. */
719 eof = true;
720 if (p == linebuf)
721 return -1;
722 *p++ = '\0';
723 len = p - linebuf;
724 /* FIXME we don't check for unterminated quotes here. */
725 if (first && EOF_STR (linebuf))
726 return -1;
727 if (!replace_pat)
728 push_arg (linebuf, len);
729 return len;
731 switch (state)
733 case SPACE:
734 if (ISSPACE (c))
735 continue;
736 state = NORM;
737 /* aaahhhh.... */
739 case NORM:
740 if (c == '\n')
742 if (!ISBLANK (prevc))
743 lineno++; /* For -l. */
744 if (p == linebuf)
746 /* Blank line. */
747 state = SPACE;
748 continue;
750 *p++ = '\0';
751 len = p - linebuf;
752 if (EOF_STR (linebuf))
754 eof = true;
755 return first ? -1 : len;
757 if (!replace_pat)
758 push_arg (linebuf, len);
759 return len;
761 if (!replace_pat && ISSPACE (c))
763 *p++ = '\0';
764 len = p - linebuf;
765 if (EOF_STR (linebuf))
767 eof = true;
768 return first ? -1 : len;
770 push_arg (linebuf, len);
771 p = linebuf;
772 state = SPACE;
773 first = false;
774 continue;
776 switch (c)
778 case '\\':
779 state = BACKSLASH;
780 continue;
782 case '\'':
783 case '"':
784 state = QUOTE;
785 quotc = c;
786 continue;
788 break;
790 case QUOTE:
791 if (c == '\n')
792 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
793 quotc == '"' ? _("double") : _("single"));
794 if (c == quotc)
796 state = NORM;
797 continue;
799 break;
801 case BACKSLASH:
802 state = NORM;
803 break;
805 #if 1
806 if (p >= endbuf)
807 error (1, 0, _("argument line too long"));
808 *p++ = c;
809 #else
810 append_char_to_buf(&linebuf, &endbuf, &p, c);
811 #endif
815 /* Read a null-terminated string from the input and add it to the list of
816 arguments to pass to the command.
817 Return -1 if eof (either physical or logical) is reached,
818 otherwise the length of the string read (including the null). */
820 static int
821 read_string (void)
823 static boolean eof = false;
824 int len;
825 char *p = linebuf;
826 /* Including the NUL, the args must not grow past this point. */
827 char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
829 if (eof)
830 return -1;
831 while (1)
833 int c = getc (input_stream);
834 if (c == EOF)
836 eof = true;
837 if (p == linebuf)
838 return -1;
839 *p++ = '\0';
840 len = p - linebuf;
841 if (!replace_pat)
842 push_arg (linebuf, len);
843 return len;
845 if (c == '\0')
847 lineno++; /* For -l. */
848 *p++ = '\0';
849 len = p - linebuf;
850 if (!replace_pat)
851 push_arg (linebuf, len);
852 return len;
854 if (p >= endbuf)
855 error (1, 0, _("argument line too long"));
856 *p++ = c;
860 /* Finds the first occurrence of the substring NEEDLE in the string
861 HAYSTACK. Both strings can be multibyte strings. */
863 static char *
864 mbstrstr (const char *haystack, const char *needle)
866 #if DO_MULTIBYTE
867 if (MB_CUR_MAX > 1)
869 size_t hlen = strlen (haystack);
870 size_t nlen = strlen (needle);
871 mbstate_t mbstate;
872 size_t step;
874 memset (&mbstate, 0, sizeof (mbstate_t));
875 while (hlen >= nlen)
877 if (memcmp (haystack, needle, nlen) == 0)
878 return (char *) haystack;
879 step = mbrlen (haystack, hlen, &mbstate);
880 if (step <= 0)
881 break;
882 haystack += step;
883 hlen -= step;
885 return NULL;
887 #endif
888 return strstr (haystack, needle);
891 /* Replace all instances of `replace_pat' in ARG with `linebuf',
892 and add the resulting string to the list of arguments for the command
893 to execute.
894 ARGLEN is the length of ARG, not including the null.
895 LBLEN is the length of `linebuf', not including the null.
897 COMPAT: insertions on the SYSV version are limited to 255 chars per line,
898 and a max of 5 occurrences of replace_pat in the initial-arguments.
899 Those restrictions do not exist here. */
901 static void
902 do_insert (char *arg, size_t arglen, size_t lblen)
904 /* Temporary copy of each arg with the replace pattern replaced by the
905 real arg. */
906 static char *insertbuf;
907 char *p;
908 int bytes_left = arg_max - 1; /* Bytes left on the command line. */
910 if (!insertbuf)
911 insertbuf = (char *) xmalloc (arg_max + 1);
912 p = insertbuf;
916 size_t len; /* Length in ARG before `replace_pat'. */
917 char *s = mbstrstr (arg, replace_pat);
918 if (s)
919 len = s - arg;
920 else
921 len = arglen;
922 bytes_left -= len;
923 if (bytes_left <= 0)
924 break;
926 strncpy (p, arg, len);
927 p += len;
928 arg += len;
929 arglen -= len;
931 if (s)
933 bytes_left -= lblen;
934 if (bytes_left <= 0)
935 break;
936 strcpy (p, linebuf);
937 arg += rplen;
938 arglen -= rplen;
939 p += lblen;
942 while (*arg);
943 if (*arg)
944 error (1, 0, _("command too long"));
945 *p++ = '\0';
946 push_arg (insertbuf, p - insertbuf);
949 /* Add ARG to the end of the list of arguments `cmd_argv' to pass
950 to the command.
951 LEN is the length of ARG, including the terminating null.
952 If this brings the list up to its maximum size, execute the command. */
954 static void
955 push_arg (char *arg, size_t len)
957 if (arg)
959 if (cmd_argv_chars + len > arg_max)
961 if (initial_args || cmd_argc == initial_argc)
962 error (1, 0, _("can not fit single argument within argument list size limit"));
963 /* option -i (replace_pat) implies -x (exit_if_size_exceeded) */
964 if (replace_pat
965 || (exit_if_size_exceeded &&
966 (lines_per_exec || args_per_exec)))
967 error (1, 0, _("argument list too long"));
968 do_exec ();
970 if (!initial_args && args_per_exec &&
971 cmd_argc - initial_argc == args_per_exec)
972 do_exec ();
975 if (cmd_argc >= cmd_argv_alloc)
977 if (!cmd_argv)
979 cmd_argv_alloc = 64;
980 cmd_argv = (char **) xmalloc (sizeof (char *) * cmd_argv_alloc);
982 else
984 cmd_argv_alloc *= 2;
985 cmd_argv = (char **) xrealloc (cmd_argv,
986 sizeof (char *) * cmd_argv_alloc);
990 if (!arg)
991 cmd_argv[cmd_argc++] = NULL;
992 else
994 cmd_argv[cmd_argc++] = argbuf + cmd_argv_chars;
995 strcpy (argbuf + cmd_argv_chars, arg);
996 cmd_argv_chars += len;
998 /* If we have now collected enough arguments,
999 * do the exec immediately. This must be
1000 * conditional on arg!=NULL, since do_exec()
1001 * actually calls push_arg(NULL, 0).
1003 if (!initial_args
1004 && args_per_exec
1005 && (cmd_argc - initial_argc) == args_per_exec)
1006 do_exec ();
1010 /* Print the arguments of the command to execute.
1011 If ASK is nonzero, prompt the user for a response, and
1012 if the user responds affirmatively, return true;
1013 otherwise, return false. */
1015 static boolean
1016 print_args (boolean ask)
1018 int i;
1020 for (i = 0; i < cmd_argc - 1; i++)
1021 fprintf (stderr, "%s ", cmd_argv[i]);
1022 if (ask)
1024 static FILE *tty_stream;
1025 int c, savec;
1027 if (!tty_stream)
1029 tty_stream = fopen ("/dev/tty", "r");
1030 if (!tty_stream)
1031 error (1, errno, "/dev/tty");
1033 fputs ("?...", stderr);
1034 fflush (stderr);
1035 c = savec = getc (tty_stream);
1036 while (c != EOF && c != '\n')
1037 c = getc (tty_stream);
1038 if (savec == 'y' || savec == 'Y')
1039 return true;
1041 else
1042 putc ('\n', stderr);
1044 return false;
1048 /* Close stdin and attach /dev/null to it.
1049 * This resolves Savannah bug #3992.
1051 static void
1052 prep_child_for_exec (void)
1054 if (!keep_stdin)
1056 const char inputfile[] = "/dev/null";
1057 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
1059 close(0);
1060 if (open(inputfile, O_RDONLY) < 0)
1062 /* This is not entirely fatal, since
1063 * executing the child with a closed
1064 * stdin is almost as good as executing it
1065 * with its stdin attached to /dev/null.
1067 error (0, errno, "%s", inputfile);
1073 /* Execute the command that has been built in `cmd_argv'. This may involve
1074 waiting for processes that were previously executed. */
1076 static void
1077 do_exec (void)
1079 pid_t child;
1081 push_arg ((char *) NULL, 0); /* Null terminate the arg list. */
1082 if (!query_before_executing || print_args (true))
1084 if (proc_max && procs_executing >= proc_max)
1085 wait_for_proc (false);
1086 if (!query_before_executing && print_command)
1087 print_args (false);
1088 /* If we run out of processes, wait for a child to return and
1089 try again. */
1090 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1091 wait_for_proc (false);
1092 switch (child)
1094 case -1:
1095 error (1, errno, _("cannot fork"));
1097 case 0: /* Child. */
1098 prep_child_for_exec();
1099 execvp (cmd_argv[0], cmd_argv);
1100 error (0, errno, "%s", cmd_argv[0]);
1101 _exit (errno == ENOENT ? 127 : 126);
1102 /*NOTREACHED*/
1104 add_proc (child);
1107 cmd_argc = initial_argc;
1108 cmd_argv_chars = initial_argv_chars;
1111 /* Add the process with id PID to the list of processes that have
1112 been executed. */
1114 static void
1115 add_proc (pid_t pid)
1117 int i;
1119 /* Find an empty slot. */
1120 for (i = 0; i < pids_alloc && pids[i]; i++)
1122 if (i == pids_alloc)
1124 if (pids_alloc == 0)
1126 pids_alloc = proc_max ? proc_max : 64;
1127 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1129 else
1131 pids_alloc *= 2;
1132 pids = (pid_t *) xrealloc (pids,
1133 sizeof (pid_t) * pids_alloc);
1135 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1137 pids[i] = pid;
1138 procs_executing++;
1139 procs_executed++;
1142 /* If ALL is true, wait for all child processes to finish;
1143 otherwise, wait for one child process to finish.
1144 Remove the processes that finish from the list of executing processes. */
1146 static void
1147 wait_for_proc (boolean all)
1149 while (procs_executing)
1151 int i, status;
1155 pid_t pid;
1157 while ((pid = wait (&status)) == (pid_t) -1)
1158 if (errno != EINTR)
1159 error (1, errno, _("error waiting for child process"));
1161 /* Find the entry in `pids' for the child process
1162 that exited. */
1163 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1166 while (i == pids_alloc); /* A child died that we didn't start? */
1168 /* Remove the child from the list. */
1169 pids[i] = 0;
1170 procs_executing--;
1172 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1173 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1174 if (WEXITSTATUS (status) == 255)
1175 error (124, 0, _("%s: exited with status 255; aborting"), cmd_argv[0]);
1176 if (WIFSTOPPED (status))
1177 error (125, 0, _("%s: stopped by signal %d"), cmd_argv[0], WSTOPSIG (status));
1178 if (WIFSIGNALED (status))
1179 error (125, 0, _("%s: terminated by signal %d"), cmd_argv[0], WTERMSIG (status));
1180 if (WEXITSTATUS (status) != 0)
1181 child_error = 123;
1183 if (!all)
1184 break;
1188 /* Return the value of the number represented in STR.
1189 OPTION is the command line option to which STR is the argument.
1190 If the value does not fall within the boundaries MIN and MAX,
1191 Print an error message mentioning OPTION. If FATAL is true,
1192 we also exit. */
1194 static long
1195 parse_num (char *str, int option, long int min, long int max, int fatal)
1197 char *eptr;
1198 long val;
1200 val = strtol (str, &eptr, 10);
1201 if (eptr == str || *eptr)
1203 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1204 program_name, option);
1205 usage (stderr);
1206 exit(1);
1208 else if (val < min)
1210 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1211 program_name, option, min);
1212 if (fatal)
1214 usage (stderr);
1215 exit(1);
1217 else
1219 val = min;
1222 else if (max >= 0 && val > max)
1224 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1225 program_name, option, max);
1226 if (fatal)
1228 usage (stderr);
1229 exit(1);
1231 else
1233 val = max;
1236 return val;
1239 /* Return how much of ARG_MAX is used by the environment. */
1241 static long
1242 env_size (char **envp)
1244 long len = 0;
1246 while (*envp)
1247 len += strlen (*envp++) + 1;
1249 return len;
1252 static void
1253 usage (FILE *stream)
1255 fprintf (stream, _("\
1256 Usage: %s [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]\n\
1257 [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]\n\
1258 [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]\n\
1259 [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]\n\
1260 [--max-args=max-args] [--no-run-if-empty] [--arg-file=file]\n\
1261 [--version] [--help] [command [initial-arguments]]\n"),
1262 program_name);
1263 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);