source: trunk/essentials/sys-apps/findutils/xargs/xargs.c

Last change on this file was 3170, checked in by bird, 18 years ago

findutils 4.3.2

File size: 29.4 KB
Line 
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.
3
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.
8
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.
13
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.
18*/
19
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
25*/
26
27
28#include <config.h>
29
30# ifndef PARAMS
31# if defined PROTOTYPES || (defined __STDC__ && __STDC__)
32# define PARAMS(Args) Args
33# else
34# define PARAMS(Args) ()
35# endif
36# endif
37
38#include <ctype.h>
39
40#if !defined (isascii) || defined (STDC_HEADERS)
41#ifdef isascii
42#undef isascii
43#endif
44#define isascii(c) 1
45#endif
46
47#ifdef isblank
48#define ISBLANK(c) (isascii (c) && isblank (c))
49#else
50#define ISBLANK(c) ((c) == ' ' || (c) == '\t')
51#endif
52
53#define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
54 || (c) == '\f' || (c) == '\v')
55
56#include <sys/types.h>
57#include <stdio.h>
58#include <errno.h>
59#include <getopt.h>
60#include <fcntl.h>
61
62#if defined(STDC_HEADERS)
63#include <assert.h>
64#endif
65
66#if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
67#include <string.h>
68#if !defined(STDC_HEADERS)
69#include <memory.h>
70#endif
71#else
72#include <strings.h>
73#define memcpy(dest, source, count) (bcopy((source), (dest), (count)))
74#endif
75
76#ifndef _POSIX_SOURCE
77#include <sys/param.h>
78#endif
79
80#ifdef HAVE_LIMITS_H
81#include <limits.h>
82#endif
83
84#ifndef LONG_MAX
85#define LONG_MAX (~(1 << (sizeof (long) * 8 - 1)))
86#endif
87
88/* The presence of unistd.h is assumed by gnulib these days, so we
89 * might as well assume it too.
90 */
91#include <unistd.h>
92
93#include <signal.h>
94
95#if !defined(SIGCHLD) && defined(SIGCLD)
96#define SIGCHLD SIGCLD
97#endif
98
99#include "wait.h"
100
101/* States for read_line. */
102#define NORM 0
103#define SPACE 1
104#define QUOTE 2
105#define BACKSLASH 3
106
107#ifdef STDC_HEADERS
108#include <stdlib.h>
109#else
110extern int errno;
111#endif
112
113#ifdef HAVE_LOCALE_H
114#include <locale.h>
115#endif
116#if ENABLE_NLS
117# include <libintl.h>
118# define _(Text) gettext (Text)
119#else
120# define _(Text) Text
121#define textdomain(Domain)
122#define bindtextdomain(Package, Directory)
123#endif
124#ifdef gettext_noop
125# define N_(String) gettext_noop (String)
126#else
127/* See locate.c for explanation as to why not use (String) */
128# define N_(String) String
129#endif
130
131#include "buildcmd.h"
132
133
134/* Return nonzero if S is the EOF string. */
135#define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
136
137/* Do multibyte processing if multibyte characters are supported,
138 unless multibyte sequences are search safe. Multibyte sequences
139 are search safe if searching for a substring using the byte
140 comparison function 'strstr' gives no false positives. All 8-bit
141 encodings and the UTF-8 multibyte encoding are search safe, but
142 the EUC encodings are not.
143 BeOS uses the UTF-8 encoding exclusively, so it is search safe. */
144#if defined __BEOS__
145# define MULTIBYTE_IS_SEARCH_SAFE 1
146#endif
147#define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE)
148
149#if DO_MULTIBYTE
150# if HAVE_MBRLEN
151# include <wchar.h>
152# else
153 /* Simulate mbrlen with mblen as best we can. */
154# define mbstate_t int
155# define mbrlen(s, n, ps) mblen (s, n)
156# endif
157#endif
158
159/* Not char because of type promotion; NeXT gcc can't handle it. */
160typedef int boolean;
161#define true 1
162#define false 0
163
164#if __STDC__
165#define VOID void
166#else
167#define VOID char
168#endif
169
170#include <xalloc.h>
171#include "closeout.h"
172
173void error PARAMS ((int status, int errnum, char *message,...));
174
175extern char *version_string;
176
177/* The name this program was run with. */
178char *program_name;
179
180static FILE *input_stream;
181
182/* Buffer for reading arguments from input. */
183static char *linebuf;
184
185static int keep_stdin = 0;
186
187/* Line number in stdin since the last command was executed. */
188static int lineno = 0;
189
190static struct buildcmd_state bc_state;
191static struct buildcmd_control bc_ctl;
192
193
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 "_".
198*/
199static char *eof_str = NULL;
200
201/* Number of chars in the initial args. */
202/* static int initial_argv_chars = 0; */
203
204/* true when building up initial arguments in `cmd_argv'. */
205static boolean initial_args = true;
206
207/* If nonzero, the maximum number of child processes that can be running
208 at once. */
209static int proc_max = 1;
210
211/* Total number of child processes that have been executed. */
212static int procs_executed = 0;
213
214/* The number of elements in `pids'. */
215static int procs_executing = 0;
216
217/* List of child processes currently executing. */
218static pid_t *pids = NULL;
219
220/* The number of allocated elements in `pids'. */
221static int pids_alloc = 0;
222
223/* Exit status; nonzero if any child process exited with a
224 status of 1-125. */
225static volatile int child_error = 0;
226
227static volatile int original_exit_value;
228
229/* If true, print each command on stderr before executing it. */
230static boolean print_command = false; /* Option -t */
231
232/* If true, query the user before executing each command, and only
233 execute the command if the user responds affirmatively. */
234static boolean query_before_executing = false;
235
236/* The delimiter for input arguments. This is only consulted if the
237 * -0 or -d option had been given.
238 */
239static char input_delimiter = '\0';
240
241
242static struct option const longopts[] =
243{
244 {"null", no_argument, NULL, '0'},
245 {"arg-file", required_argument, NULL, 'a'},
246 {"delimiter", required_argument, NULL, 'd'},
247 {"eof", optional_argument, NULL, 'e'},
248 {"replace", optional_argument, NULL, 'I'},
249 {"max-lines", optional_argument, NULL, 'l'},
250 {"max-args", required_argument, NULL, 'n'},
251 {"interactive", no_argument, NULL, 'p'},
252 {"no-run-if-empty", no_argument, NULL, 'r'},
253 {"max-chars", required_argument, NULL, 's'},
254 {"verbose", no_argument, NULL, 't'},
255 {"show-limits", no_argument, NULL, 'S'},
256 {"exit", no_argument, NULL, 'x'},
257 {"max-procs", required_argument, NULL, 'P'},
258 {"version", no_argument, NULL, 'v'},
259 {"help", no_argument, NULL, 'h'},
260 {NULL, no_argument, NULL, 0}
261};
262
263static int read_line PARAMS ((void));
264static int read_string PARAMS ((void));
265static boolean print_args PARAMS ((boolean ask));
266/* static void do_exec PARAMS ((void)); */
267static int xargs_do_exec (const struct buildcmd_control *cl, struct buildcmd_state *state);
268static void exec_if_possible PARAMS ((void));
269static void add_proc PARAMS ((pid_t pid));
270static void wait_for_proc PARAMS ((boolean all));
271static void wait_for_proc_all PARAMS ((void));
272static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
273static void usage PARAMS ((FILE * stream));
274
275
276
277static char
278get_char_oct_or_hex_escape(const char *s)
279{
280 const char * p;
281 int base = 8;
282 unsigned long val;
283 char *endp;
284
285 assert('\\' == s[0]);
286
287 if ('x' == s[1])
288 {
289 /* hex */
290 p = s+2;
291 base = 16;
292 }
293 else if (isdigit(s[1]))
294 {
295 /* octal */
296 p = s+1;
297 base = 8;
298 }
299 else
300 {
301 error(1, 0,
302 _("Invalid escape sequence %s in input delimiter specification."),
303 s);
304 }
305 errno = 0;
306 endp = (char*)p;
307 val = strtoul(p, &endp, base);
308
309 /* This if condition is carefully constructed to do
310 * the right thing if UCHAR_MAX has the same
311 * value as ULONG_MAX. IF UCHAR_MAX==ULONG_MAX,
312 * then val can never be greater than UCHAR_MAX.
313 */
314 if ((ULONG_MAX == val && ERANGE == errno)
315 || (val > UCHAR_MAX))
316 {
317 if (16 == base)
318 {
319 error(1, 0,
320 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lx."),
321 s, (unsigned long)UCHAR_MAX);
322 }
323 else
324 {
325 error(1, 0,
326 _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lo."),
327 s, (unsigned long)UCHAR_MAX);
328 }
329 }
330
331 /* check for trailing garbage */
332 if (0 != *endp)
333 {
334 error(1, 0,
335 _("Invalid escape sequence %s in input delimiter specification; trailing characters %s not recognised."),
336 s, endp);
337 }
338
339 return (char) val;
340}
341
342
343static char
344get_input_delimiter(const char *s)
345{
346 if (1 == strlen(s))
347 {
348 return s[0];
349 }
350 else
351 {
352 if ('\\' == s[0])
353 {
354 /* an escape code */
355 switch (s[1])
356 {
357 case 'a':
358 return '\a';
359 case 'b':
360 return '\b';
361 case 'f':
362 return '\f';
363 case 'n':
364 return '\n';
365 case 'r':
366 return '\r';
367 case 't':
368 return'\t';
369 case 'v':
370 return '\v';
371 case '\\':
372 return '\\';
373 default:
374 return get_char_oct_or_hex_escape(s);
375 }
376 }
377 else
378 {
379 error(1, 0,
380 _("Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\."),
381 s);
382 /*NOTREACHED*/
383 return 0;
384 }
385 }
386}
387
388static void
389noop (void)
390{
391 /* does nothing. */
392}
393
394static void
395fail_due_to_env_size (void)
396{
397 error (1, 0, _("environment is too large for exec"));
398}
399
400
401int
402main (int argc, char **argv)
403{
404 int optc;
405 int show_limits = 0; /* --show-limits */
406 int always_run_command = 1;
407 char *input_file = "-"; /* "-" is stdin */
408 char *default_cmd = "/bin/echo";
409 int (*read_args) PARAMS ((void)) = read_line;
410 void (*act_on_init_result)(void) = noop;
411 int env_too_big = 0;
412 enum BC_INIT_STATUS bcstatus;
413
414 program_name = argv[0];
415 original_exit_value = 0;
416
417#ifdef HAVE_SETLOCALE
418 setlocale (LC_ALL, "");
419#endif
420 bindtextdomain (PACKAGE, LOCALEDIR);
421 textdomain (PACKAGE);
422 atexit (close_stdout);
423 atexit (wait_for_proc_all);
424
425 bcstatus = bc_init_controlinfo(&bc_ctl);
426
427 /* The bc_init_controlinfo call may have determined that the
428 * environment is too big. In that case, we will fail with
429 * an error message after processing the command-line options,
430 * as "xargs --help" should still work even if the environment is
431 * too big.
432 *
433 * Some of the argument processing depends on the contents of
434 * bc_ctl, which will be in an undefined state if bc_init_controlinfo()
435 * failed.
436 */
437 if (BC_INIT_ENV_TOO_BIG == bcstatus)
438 {
439 act_on_init_result = fail_due_to_env_size;
440 }
441 else
442 {
443 /* IEEE Std 1003.1, 2003 specifies that the combined argument and
444 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
445 * specifies that it shall be at least LINE_MAX.
446 */
447#if defined(ARG_MAX)
448 assert(bc_ctl.arg_max <= (ARG_MAX-2048));
449#endif
450 assert(bc_ctl.arg_max >= LINE_MAX);
451
452 bc_ctl.exec_callback = xargs_do_exec;
453
454 /* Start with a reasonable default size, though this can be
455 * adjusted via the -s option.
456 */
457 bc_use_sensible_arg_max(&bc_ctl);
458 }
459
460 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:d:",
461 longopts, (int *) 0)) != -1)
462 {
463 switch (optc)
464 {
465 case '0':
466 read_args = read_string;
467 input_delimiter = '\0';
468 break;
469
470 case 'd':
471 read_args = read_string;
472 input_delimiter = get_input_delimiter(optarg);
473 break;
474
475 case 'E': /* POSIX */
476 case 'e': /* deprecated */
477 if (optarg && (strlen(optarg) > 0))
478 eof_str = optarg;
479 else
480 eof_str = 0;
481 break;
482
483 case 'h':
484 usage (stdout);
485 return 0;
486
487 case 'I': /* POSIX */
488 case 'i': /* deprecated */
489 if (optarg)
490 bc_ctl.replace_pat = optarg;
491 else
492 bc_ctl.replace_pat = "{}";
493 /* -i excludes -n -l. */
494 bc_ctl.args_per_exec = 0;
495 bc_ctl.lines_per_exec = 0;
496 break;
497
498 case 'L': /* POSIX */
499 bc_ctl.lines_per_exec = parse_num (optarg, 'L', 1L, -1L, 1);
500 /* -L excludes -i -n. */
501 bc_ctl.args_per_exec = 0;
502 bc_ctl.replace_pat = NULL;
503 break;
504
505 case 'l': /* deprecated */
506 if (optarg)
507 bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
508 else
509 bc_ctl.lines_per_exec = 1;
510 /* -l excludes -i -n. */
511 bc_ctl.args_per_exec = 0;
512 bc_ctl.replace_pat = NULL;
513 break;
514
515 case 'n':
516 bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
517 /* -n excludes -i -l. */
518 bc_ctl.lines_per_exec = 0;
519 if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
520 /* ignore -n1 in '-i -n1' */
521 bc_ctl.args_per_exec = 0;
522 else
523 bc_ctl.replace_pat = NULL;
524 break;
525
526 /* The POSIX standard specifies that it is not an error
527 * for the -s option to specify a size that the implementation
528 * cannot support - in that case, the relevant limit is used.
529 */
530 case 's':
531 {
532 size_t arg_size;
533 act_on_init_result();
534 arg_size = parse_num (optarg, 's', 1L,
535 bc_ctl.posix_arg_size_max, 0);
536 if (arg_size > bc_ctl.posix_arg_size_max)
537 {
538 error (0, 0,
539 _("warning: value %ld for -s option is too large, "
540 "using %ld instead"),
541 arg_size, bc_ctl.posix_arg_size_max);
542 arg_size = bc_ctl.posix_arg_size_max;
543 }
544 bc_ctl.arg_max = arg_size;
545 }
546 break;
547
548 case 'S':
549 show_limits = true;
550 break;
551
552 case 't':
553 print_command = true;
554 break;
555
556 case 'x':
557 bc_ctl.exit_if_size_exceeded = true;
558 break;
559
560 case 'p':
561 query_before_executing = true;
562 print_command = true;
563 break;
564
565 case 'r':
566 always_run_command = 0;
567 break;
568
569 case 'P':
570 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
571 break;
572
573 case 'a':
574 input_file = optarg;
575 break;
576
577 case 'v':
578 printf (_("GNU xargs version %s\n"), version_string);
579 return 0;
580
581 default:
582 usage (stderr);
583 return 1;
584 }
585 }
586
587 /* If we had deferred failing due to problems in bc_init_controlinfo(),
588 * do it now.
589 *
590 * We issue this error message after processing command line
591 * arguments so that it is possible to use "xargs --help" even if
592 * the environment is too large.
593 */
594 act_on_init_result();
595 assert(BC_INIT_OK == bcstatus);
596
597 if (0 == strcmp (input_file, "-"))
598 {
599 input_stream = stdin;
600 }
601 else
602 {
603 keep_stdin = 1; /* see prep_child_for_exec() */
604 input_stream = fopen (input_file, "r");
605 if (NULL == input_stream)
606 {
607 error (1, errno,
608 _("Cannot open input file `%s'"),
609 input_file);
610 }
611 }
612
613 if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
614 bc_ctl.exit_if_size_exceeded = true;
615
616 if (optind == argc)
617 {
618 optind = 0;
619 argc = 1;
620 argv = &default_cmd;
621 }
622
623 /* We want to be able to print size_t values as unsigned long, so if
624 * the cast isn't value-preserving, we have a problem. This isn't a
625 * problem in C89, because size_t was known to be no wider than
626 * unsigned long. In C99 this is no longer the case, but there are
627 * special C99 ways to print such values. Unfortunately this
628 * program tries to work on both C89 and C99 systems.
629 */
630#if defined(SIZE_MAX)
631# if SIZE_MAX > ULONG_MAX
632# error "I'm not sure how to print size_t values on your system"
633# endif
634#else
635 /* Without SIZE_MAX (i.e. limits.h) this is probably
636 * close to the best we can do.
637 */
638 assert(sizeof(size_t) <= sizeof(unsigned long));
639#endif
640
641 if (show_limits)
642 {
643 fprintf(stderr,
644 _("Your environment variables take up %lu bytes\n"),
645 (unsigned long)bc_size_of_environment());
646 fprintf(stderr,
647 _("POSIX lower and upper limits on argument length: %lu, %lu\n"),
648 (unsigned long)bc_ctl.posix_arg_size_min,
649 (unsigned long)bc_ctl.posix_arg_size_max);
650 fprintf(stderr,
651 _("Maximum length of command we could actually use: %ld\n"),
652 (unsigned long)(bc_ctl.posix_arg_size_max -
653 bc_size_of_environment()));
654 fprintf(stderr,
655 _("Size of command buffer we are actually using: %lu\n"),
656 (unsigned long)bc_ctl.arg_max);
657
658 if (isatty(STDIN_FILENO))
659 {
660 fprintf(stderr,
661 "\n"
662 "Execution of xargs will continue now, and it will "
663 "try to read its input and run commands; if this is "
664 "not what you wanted to happen, please type the "
665 "end-of-file keystroke.\n");
666 }
667 }
668
669 linebuf = (char *) xmalloc (bc_ctl.arg_max + 1);
670 bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1);
671
672 /* Make sure to listen for the kids. */
673 signal (SIGCHLD, SIG_DFL);
674
675 if (!bc_ctl.replace_pat)
676 {
677 for (; optind < argc; optind++)
678 bc_push_arg (&bc_ctl, &bc_state,
679 argv[optind], strlen (argv[optind]) + 1,
680 NULL, 0,
681 initial_args);
682 initial_args = false;
683 bc_ctl.initial_argc = bc_state.cmd_argc;
684 bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
685
686 while ((*read_args) () != -1)
687 if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
688 {
689 xargs_do_exec (&bc_ctl, &bc_state);
690 lineno = 0;
691 }
692
693 /* SYSV xargs seems to do at least one exec, even if the
694 input is empty. */
695 if (bc_state.cmd_argc != bc_ctl.initial_argc
696 || (always_run_command && procs_executed == 0))
697 xargs_do_exec (&bc_ctl, &bc_state);
698
699 }
700 else
701 {
702 int i;
703 size_t len;
704 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
705
706 for (i = optind; i < argc; i++)
707 arglen[i] = strlen(argv[i]);
708 bc_ctl.rplen = strlen (bc_ctl.replace_pat);
709 while ((len = (*read_args) ()) != -1)
710 {
711 /* Don't do insert on the command name. */
712 bc_clear_args(&bc_ctl, &bc_state);
713 bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
714
715 bc_push_arg (&bc_ctl, &bc_state,
716 argv[optind], arglen[optind] + 1,
717 NULL, 0,
718 initial_args);
719 len--;
720 initial_args = false;
721
722 for (i = optind + 1; i < argc; i++)
723 bc_do_insert (&bc_ctl, &bc_state,
724 argv[i], arglen[i],
725 NULL, 0,
726 linebuf, len,
727 initial_args);
728 xargs_do_exec (&bc_ctl, &bc_state);
729 }
730 }
731
732 original_exit_value = child_error;
733 return child_error;
734}
735
736
737/* Read a line of arguments from the input and add them to the list of
738 arguments to pass to the command. Ignore blank lines and initial blanks.
739 Single and double quotes and backslashes quote metacharacters and blanks
740 as they do in the shell.
741 Return -1 if eof (either physical or logical) is reached,
742 otherwise the length of the last string read (including the null). */
743
744static int
745read_line (void)
746{
747 static boolean eof = false;
748 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
749 int state = SPACE; /* The type of character we last read. */
750 int prevc; /* The previous value of c. */
751 int quotc = 0; /* The last quote character read. */
752 int c = EOF;
753 boolean first = true; /* true if reading first arg on line. */
754 int len;
755 char *p = linebuf;
756 /* Including the NUL, the args must not grow past this point. */
757 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
758
759 if (eof)
760 return -1;
761 while (1)
762 {
763 prevc = c;
764 c = getc (input_stream);
765 if (c == EOF)
766 {
767 /* COMPAT: SYSV seems to ignore stuff on a line that
768 ends without a \n; we don't. */
769 eof = true;
770 if (p == linebuf)
771 return -1;
772 *p++ = '\0';
773 len = p - linebuf;
774 if (state == QUOTE)
775 {
776 exec_if_possible ();
777 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
778 quotc == '"' ? _("double") : _("single"));
779 }
780 if (first && EOF_STR (linebuf))
781 return -1;
782 if (!bc_ctl.replace_pat)
783 bc_push_arg (&bc_ctl, &bc_state,
784 linebuf, len,
785 NULL, 0,
786 initial_args);
787 return len;
788 }
789 switch (state)
790 {
791 case SPACE:
792 if (ISSPACE (c))
793 continue;
794 state = NORM;
795 /* aaahhhh.... */
796
797 case NORM:
798 if (c == '\n')
799 {
800 if (!ISBLANK (prevc))
801 lineno++; /* For -l. */
802 if (p == linebuf)
803 {
804 /* Blank line. */
805 state = SPACE;
806 continue;
807 }
808 *p++ = '\0';
809 len = p - linebuf;
810 if (EOF_STR (linebuf))
811 {
812 eof = true;
813 return first ? -1 : len;
814 }
815 if (!bc_ctl.replace_pat)
816 bc_push_arg (&bc_ctl, &bc_state,
817 linebuf, len,
818 NULL, 0,
819 initial_args);
820 return len;
821 }
822 if (!bc_ctl.replace_pat && ISSPACE (c))
823 {
824 *p++ = '\0';
825 len = p - linebuf;
826 if (EOF_STR (linebuf))
827 {
828 eof = true;
829 return first ? -1 : len;
830 }
831 bc_push_arg (&bc_ctl, &bc_state,
832 linebuf, len,
833 NULL, 0,
834 initial_args);
835 p = linebuf;
836 state = SPACE;
837 first = false;
838 continue;
839 }
840 switch (c)
841 {
842 case '\\':
843 state = BACKSLASH;
844 continue;
845
846 case '\'':
847 case '"':
848 state = QUOTE;
849 quotc = c;
850 continue;
851 }
852 break;
853
854 case QUOTE:
855 if (c == '\n')
856 {
857 exec_if_possible ();
858 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
859 quotc == '"' ? _("double") : _("single"));
860 }
861 if (c == quotc)
862 {
863 state = NORM;
864 continue;
865 }
866 break;
867
868 case BACKSLASH:
869 state = NORM;
870 break;
871 }
872#if 1
873 if (p >= endbuf)
874 {
875 exec_if_possible ();
876 error (1, 0, _("argument line too long"));
877 }
878 *p++ = c;
879#else
880 append_char_to_buf(&linebuf, &endbuf, &p, c);
881#endif
882 }
883}
884
885/* Read a null-terminated string from the input and add it to the list of
886 arguments to pass to the command.
887 Return -1 if eof (either physical or logical) is reached,
888 otherwise the length of the string read (including the null). */
889
890static int
891read_string (void)
892{
893 static boolean eof = false;
894 int len;
895 char *p = linebuf;
896 /* Including the NUL, the args must not grow past this point. */
897 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
898
899 if (eof)
900 return -1;
901 while (1)
902 {
903 int c = getc (input_stream);
904 if (c == EOF)
905 {
906 eof = true;
907 if (p == linebuf)
908 return -1;
909 *p++ = '\0';
910 len = p - linebuf;
911 if (!bc_ctl.replace_pat)
912 bc_push_arg (&bc_ctl, &bc_state,
913 linebuf, len,
914 NULL, 0,
915 initial_args);
916 return len;
917 }
918 if (c == input_delimiter)
919 {
920 lineno++; /* For -l. */
921 *p++ = '\0';
922 len = p - linebuf;
923 if (!bc_ctl.replace_pat)
924 bc_push_arg (&bc_ctl, &bc_state,
925 linebuf, len,
926 NULL, 0,
927 initial_args);
928 return len;
929 }
930 if (p >= endbuf)
931 {
932 exec_if_possible ();
933 error (1, 0, _("argument line too long"));
934 }
935 *p++ = c;
936 }
937}
938
939/* Print the arguments of the command to execute.
940 If ASK is nonzero, prompt the user for a response, and
941 if the user responds affirmatively, return true;
942 otherwise, return false. */
943
944static boolean
945print_args (boolean ask)
946{
947 int i;
948
949 for (i = 0; i < bc_state.cmd_argc - 1; i++)
950 fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
951 if (ask)
952 {
953 static FILE *tty_stream;
954 int c, savec;
955
956 if (!tty_stream)
957 {
958 tty_stream = fopen ("/dev/tty", "r");
959 if (!tty_stream)
960 error (1, errno, "/dev/tty");
961 }
962 fputs ("?...", stderr);
963 fflush (stderr);
964 c = savec = getc (tty_stream);
965 while (c != EOF && c != '\n')
966 c = getc (tty_stream);
967 if (savec == 'y' || savec == 'Y')
968 return true;
969 }
970 else
971 putc ('\n', stderr);
972
973 return false;
974}
975
976
977/* Close stdin and attach /dev/null to it.
978 * This resolves Savannah bug #3992.
979 */
980static void
981prep_child_for_exec (void)
982{
983 if (!keep_stdin)
984 {
985 const char inputfile[] = "/dev/null";
986 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
987
988 close(0);
989 if (open(inputfile, O_RDONLY) < 0)
990 {
991 /* This is not entirely fatal, since
992 * executing the child with a closed
993 * stdin is almost as good as executing it
994 * with its stdin attached to /dev/null.
995 */
996 error (0, errno, "%s", inputfile);
997 }
998 }
999}
1000
1001
1002/* Execute the command that has been built in `cmd_argv'. This may involve
1003 waiting for processes that were previously executed. */
1004
1005static int
1006xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
1007{
1008 pid_t child;
1009
1010 (void) ctl;
1011 (void) state;
1012
1013 bc_push_arg (&bc_ctl, &bc_state,
1014 (char *) NULL, 0,
1015 NULL, 0,
1016 false); /* Null terminate the arg list. */
1017
1018 if (!query_before_executing || print_args (true))
1019 {
1020 if (proc_max && procs_executing >= proc_max)
1021 wait_for_proc (false);
1022 if (!query_before_executing && print_command)
1023 print_args (false);
1024 /* If we run out of processes, wait for a child to return and
1025 try again. */
1026 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1027 wait_for_proc (false);
1028 switch (child)
1029 {
1030 case -1:
1031 error (1, errno, _("cannot fork"));
1032
1033 case 0: /* Child. */
1034 prep_child_for_exec();
1035 execvp (bc_state.cmd_argv[0], bc_state.cmd_argv);
1036 error (0, errno, "%s", bc_state.cmd_argv[0]);
1037 _exit (errno == ENOENT ? 127 : 126);
1038 /*NOTREACHED*/
1039 }
1040 add_proc (child);
1041 }
1042
1043 bc_clear_args(&bc_ctl, &bc_state);
1044 return 1; /* Success */
1045}
1046
1047/* Execute the command if possible. */
1048
1049static void
1050exec_if_possible (void)
1051{
1052 if (bc_ctl.replace_pat || initial_args ||
1053 bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded)
1054 return;
1055 xargs_do_exec (&bc_ctl, &bc_state);
1056}
1057
1058/* Add the process with id PID to the list of processes that have
1059 been executed. */
1060
1061static void
1062add_proc (pid_t pid)
1063{
1064 int i;
1065
1066 /* Find an empty slot. */
1067 for (i = 0; i < pids_alloc && pids[i]; i++)
1068 ;
1069 if (i == pids_alloc)
1070 {
1071 if (pids_alloc == 0)
1072 {
1073 pids_alloc = proc_max ? proc_max : 64;
1074 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1075 }
1076 else
1077 {
1078 pids_alloc *= 2;
1079 pids = (pid_t *) xrealloc (pids,
1080 sizeof (pid_t) * pids_alloc);
1081 }
1082 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1083 }
1084 pids[i] = pid;
1085 procs_executing++;
1086 procs_executed++;
1087}
1088
1089/* If ALL is true, wait for all child processes to finish;
1090 otherwise, wait for one child process to finish.
1091 Remove the processes that finish from the list of executing processes. */
1092
1093static void
1094wait_for_proc (boolean all)
1095{
1096 while (procs_executing)
1097 {
1098 int i, status;
1099
1100 do
1101 {
1102 pid_t pid;
1103
1104 while ((pid = wait (&status)) == (pid_t) -1)
1105 if (errno != EINTR)
1106 error (1, errno, _("error waiting for child process"));
1107
1108 /* Find the entry in `pids' for the child process
1109 that exited. */
1110 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1111 ;
1112 }
1113 while (i == pids_alloc); /* A child died that we didn't start? */
1114
1115 /* Remove the child from the list. */
1116 pids[i] = 0;
1117 procs_executing--;
1118
1119 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1120 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1121 if (WEXITSTATUS (status) == 255)
1122 error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1123 if (WIFSTOPPED (status))
1124 error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1125 if (WIFSIGNALED (status))
1126 error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1127 if (WEXITSTATUS (status) != 0)
1128 child_error = 123;
1129
1130 if (!all)
1131 break;
1132 }
1133}
1134
1135/* Wait for all child processes to finish. */
1136
1137static void
1138wait_for_proc_all (void)
1139{
1140 static boolean waiting = false;
1141
1142 if (waiting)
1143 return;
1144
1145 waiting = true;
1146 wait_for_proc (true);
1147 waiting = false;
1148
1149 if (original_exit_value != child_error)
1150 {
1151 /* wait_for_proc() changed the value of child_error(). This
1152 * function is registered via atexit(), and so may have been
1153 * called from exit(). We now know that the original value
1154 * passed to exit() is no longer the exit status we require.
1155 * The POSIX standard states that the behaviour if exit() is
1156 * called more than once is undefined. Therefore we now have to
1157 * exit with _exit() instead of exit().
1158 */
1159 _exit(child_error);
1160 }
1161
1162}
1163
1164/* Return the value of the number represented in STR.
1165 OPTION is the command line option to which STR is the argument.
1166 If the value does not fall within the boundaries MIN and MAX,
1167 Print an error message mentioning OPTION. If FATAL is true,
1168 we also exit. */
1169
1170static long
1171parse_num (char *str, int option, long int min, long int max, int fatal)
1172{
1173 char *eptr;
1174 long val;
1175
1176 val = strtol (str, &eptr, 10);
1177 if (eptr == str || *eptr)
1178 {
1179 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1180 program_name, option);
1181 usage (stderr);
1182 exit(1);
1183 }
1184 else if (val < min)
1185 {
1186 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1187 program_name, option, min);
1188 if (fatal)
1189 {
1190 usage (stderr);
1191 exit(1);
1192 }
1193 else
1194 {
1195 val = min;
1196 }
1197 }
1198 else if (max >= 0 && val > max)
1199 {
1200 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1201 program_name, option, max);
1202 if (fatal)
1203 {
1204 usage (stderr);
1205 exit(1);
1206 }
1207 else
1208 {
1209 val = max;
1210 }
1211 }
1212 return val;
1213}
1214
1215static void
1216usage (FILE *stream)
1217{
1218 fprintf (stream, _("\
1219Usage: %s [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]\n\
1220 [-E eof-str] [-e[eof-str]] [--eof[=eof-str]]\n\
1221 [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]\n\
1222 [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]\n\
1223 [-n max-args] [--max-args=max-args]\n\
1224 [-s max-chars] [--max-chars=max-chars]\n\
1225 [-P max-procs] [--max-procs=max-procs] [[--show-limits]\n\
1226 [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]\n\
1227 [--version] [--help] [command [initial-arguments]]\n"),
1228 program_name);
1229 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);
1230}
Note: See TracBrowser for help on using the repository browser.