home *** CD-ROM | disk | FTP | other *** search
/ Il CD di internet / CD.iso / SOURCE / A / FIND / FINDUTIL.1 / FINDUTIL / findutils-4.1 / xargs / xargs.c < prev   
Encoding:
C/C++ Source or Header  |  1994-10-07  |  21.4 KB  |  919 lines

  1. /* xargs -- build and execute command lines from standard input
  2.    Copyright (C) 1990, 91, 92, 93, 94 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., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Mike Rendell <michael@cs.mun.ca>
  19.    and David MacKenzie <djm@gnu.ai.mit.edu>.  */
  20.  
  21. #include <config.h>
  22.  
  23. #if __STDC__
  24. #define P_(s) s
  25. #else
  26. #define P_(s) ()
  27. #endif
  28.  
  29. #define _GNU_SOURCE
  30. #include <ctype.h>
  31.  
  32. #if !defined (isascii) || defined (STDC_HEADERS)
  33. #ifdef isascii
  34. #undef isascii
  35. #endif
  36. #define isascii(c) 1
  37. #endif
  38.  
  39. #ifdef isblank
  40. #define ISBLANK(c) (isascii (c) && isblank (c))
  41. #else
  42. #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
  43. #endif
  44.  
  45. #define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
  46.             || (c) == '\f' || (c) == '\v')
  47.  
  48. #include <sys/types.h>
  49. #include <stdio.h>
  50. #include <errno.h>
  51. #include <getopt.h>
  52.  
  53. #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
  54. #include <string.h>
  55. #if !defined(STDC_HEADERS)
  56. #include <memory.h>
  57. #endif
  58. #else
  59. #include <strings.h>
  60. #define memcpy(dest, source, count) (bcopy((source), (dest), (count)))
  61. #endif
  62.  
  63. char *strstr ();
  64. char *strdup ();
  65.  
  66. #ifndef _POSIX_SOURCE
  67. #include <sys/param.h>
  68. #endif
  69.  
  70. #ifdef HAVE_LIMITS_H
  71. #include <limits.h>
  72. #endif
  73.  
  74. #ifdef HAVE_UNISTD_H
  75. #include <unistd.h>
  76. #endif
  77.  
  78. #include <signal.h>
  79.  
  80. #if !defined(SIGCHLD) && defined(SIGCLD)
  81. #define SIGCHLD SIGCLD
  82. #endif
  83.  
  84. /* COMPAT:  SYSV version defaults size (and has a max value of) to 470.
  85.    We try to make it as large as possible. */
  86. #if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
  87. #define ARG_MAX sysconf (_SC_ARG_MAX)
  88. #endif
  89. #ifndef ARG_MAX
  90. #define ARG_MAX NCARGS
  91. #endif
  92.  
  93. #include "wait.h"
  94.  
  95. /* States for read_line. */
  96. #define NORM 0
  97. #define SPACE 1
  98. #define QUOTE 2
  99. #define BACKSLASH 3
  100.  
  101. #ifdef STDC_HEADERS
  102. #include <stdlib.h>
  103. #else
  104. char *malloc ();
  105. void exit ();
  106. void free ();
  107. long strtol ();
  108.  
  109. extern int errno;
  110. #endif
  111.  
  112. /* Return nonzero if S is the EOF string.  */
  113. #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
  114.  
  115. extern char **environ;
  116.  
  117. /* Not char because of type promotion; NeXT gcc can't handle it.  */
  118. typedef int boolean;
  119. #define        true    1
  120. #define        false    0
  121.  
  122. #if __STDC__
  123. #define VOID void
  124. #else
  125. #define VOID char
  126. #endif
  127.  
  128. VOID *xmalloc P_ ((size_t n));
  129. VOID *xrealloc P_ ((VOID * p, size_t n));
  130. void error P_ ((int status, int errnum, char *message,...));
  131.  
  132. extern char *version_string;
  133.  
  134. /* The name this program was run with.  */
  135. char *program_name;
  136.  
  137. /* Buffer for reading arguments from stdin.  */
  138. static char *linebuf;
  139.  
  140. /* Line number in stdin since the last command was executed.  */
  141. static int lineno = 0;
  142.  
  143. /* If nonzero, then instead of putting the args from stdin at
  144.    the end of the command argument list, they are each stuck into the
  145.    initial args, replacing each occurrence of the `replace_pat' in the
  146.    initial args.  */
  147. static char *replace_pat = NULL;
  148.  
  149. /* The length of `replace_pat'.  */
  150. static size_t rplen = 0;
  151.  
  152. /* If nonzero, when this string is read on stdin it is treated as
  153.    end of file.
  154.    I don't like this - it should default to NULL.  */
  155. static char *eof_str = "_";
  156.  
  157. /* If nonzero, the maximum number of nonblank lines from stdin to use
  158.    per command line.  */
  159. static long lines_per_exec = 0;
  160.  
  161. /* The maximum number of arguments to use per command line.  */
  162. static long args_per_exec = 1024;
  163.  
  164. /* If true, exit if lines_per_exec or args_per_exec is exceeded.  */
  165. static boolean exit_if_size_exceeded = false;
  166.  
  167. /* The maximum number of characters that can be used per command line.  */
  168. static long arg_max;
  169.  
  170. /* Storage for elements of `cmd_argv'.  */
  171. static char *argbuf;
  172.  
  173. /* The list of args being built.  */
  174. static char **cmd_argv = NULL;
  175.  
  176. /* Number of elements allocated for `cmd_argv'.  */
  177. static int cmd_argv_alloc = 0;
  178.  
  179. /* Number of valid elements in `cmd_argv'.  */
  180. static int cmd_argc = 0;
  181.  
  182. /* Number of chars being used in `cmd_argv'.  */
  183. static int cmd_argv_chars = 0;
  184.  
  185. /* Number of initial arguments given on the command line.  */
  186. static int initial_argc = 0;
  187.  
  188. /* Number of chars in the initial args.  */
  189. static int initial_argv_chars = 0;
  190.  
  191. /* true when building up initial arguments in `cmd_argv'.  */
  192. static boolean initial_args = true;
  193.  
  194. /* If nonzero, the maximum number of child processes that can be running
  195.    at once.  */
  196. static int proc_max = 1;
  197.  
  198. /* Total number of child processes that have been executed.  */
  199. static int procs_executed = 0;
  200.  
  201. /* The number of elements in `pids'.  */
  202. static int procs_executing = 0;
  203.  
  204. /* List of child processes currently executing.  */
  205. static pid_t *pids = NULL;
  206.  
  207. /* The number of allocated elements in `pids'. */
  208. static int pids_alloc = 0;
  209.  
  210. /* Exit status; nonzero if any child process exited with a
  211.    status of 1-125.  */
  212. static int child_error = 0;
  213.  
  214. /* If true, print each command on stderr before executing it.  */
  215. static boolean print_command = false;
  216.  
  217. /* If true, query the user before executing each command, and only
  218.    execute the command if the user responds affirmatively.  */
  219. static boolean query_before_executing = false;
  220.  
  221. static struct option const longopts[] =
  222. {
  223.   {"null", no_argument, NULL, '0'},
  224.   {"eof", optional_argument, NULL, 'e'},
  225.   {"replace", optional_argument, NULL, 'i'},
  226.   {"max-lines", optional_argument, NULL, 'l'},
  227.   {"max-args", required_argument, NULL, 'n'},
  228.   {"interactive", no_argument, NULL, 'p'},
  229.   {"no-run-if-empty", no_argument, NULL, 'r'},
  230.   {"max-chars", required_argument, NULL, 's'},
  231.   {"verbose", no_argument, NULL, 't'},
  232.   {"exit", no_argument, NULL, 'x'},
  233.   {"max-procs", required_argument, NULL, 'P'},
  234.   {"version", no_argument, NULL, 'v'},
  235.   {"help", no_argument, NULL, 'h'},
  236.   {NULL, no_argument, NULL, 0}
  237. };
  238.  
  239. static int read_line P_ ((void));
  240. static int read_string P_ ((void));
  241. static void do_insert P_ ((char *arg, size_t arglen, size_t lblen));
  242. static void push_arg P_ ((char *arg, size_t len));
  243. static boolean print_args P_ ((boolean ask));
  244. static void do_exec P_ ((void));
  245. static void add_proc P_ ((pid_t pid));
  246. static void wait_for_proc P_ ((boolean all));
  247. static long parse_num P_ ((char *str, int option, long min, long max));
  248. static long env_size P_ ((char **envp));
  249. static void usage P_ ((FILE * stream, int status));
  250.  
  251. void
  252. main (argc, argv)
  253.      int argc;
  254.      char **argv;
  255. {
  256.   int optc;
  257.   int always_run_command = 1;
  258.   long orig_arg_max;
  259.   char *default_cmd = "/bin/echo";
  260.   int (*read_args) P_ ((void)) = read_line;
  261.  
  262.   program_name = argv[0];
  263.  
  264.   orig_arg_max = ARG_MAX - 2048; /* POSIX.2 requires subtracting 2048.  */
  265.   arg_max = orig_arg_max;
  266.  
  267.   /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
  268.      have it at 1 meg).  Things will work fine with a large ARG_MAX but it
  269.      will probably hurt the system more than it needs to; an array of this
  270.      size is allocated.  */
  271.   if (arg_max > 20 * 1024)
  272.     arg_max = 20 * 1024;
  273.  
  274.   /* Take the size of the environment into account.  */
  275.   arg_max -= env_size (environ);
  276.   if (arg_max <= 0)
  277.     error (1, 0, "environment is too large for exec");
  278.  
  279.   while ((optc = getopt_long (argc, argv, "+0e::i::l::n:prs:txP:",
  280.                   longopts, (int *) 0)) != -1)
  281.     {
  282.       switch (optc)
  283.     {
  284.     case '0':
  285.       read_args = read_string;
  286.       break;
  287.  
  288.     case 'e':
  289.       if (optarg)
  290.         eof_str = optarg;
  291.       else
  292.         eof_str = 0;
  293.       break;
  294.  
  295.     case 'h':
  296.       usage (stdout, 0);
  297.  
  298.     case 'i':
  299.       if (optarg)
  300.         replace_pat = optarg;
  301.       else
  302.         replace_pat = "{}";
  303.       /* -i excludes -n -l.  */
  304.       args_per_exec = 0;
  305.       lines_per_exec = 0;
  306.       break;
  307.  
  308.     case 'l':
  309.       if (optarg)
  310.         lines_per_exec = parse_num (optarg, 'l', 1L, -1L);
  311.       else
  312.         lines_per_exec = 1;
  313.       /* -l excludes -i -n.  */
  314.       args_per_exec = 0;
  315.       replace_pat = NULL;
  316.       break;
  317.  
  318.     case 'n':
  319.       args_per_exec = parse_num (optarg, 'n', 1L, -1L);
  320.       /* -n excludes -i -l.  */
  321.       lines_per_exec = 0;
  322.       replace_pat = NULL;
  323.       break;
  324.  
  325.     case 's':
  326.       arg_max = parse_num (optarg, 's', 1L, orig_arg_max);
  327.       break;
  328.  
  329.     case 't':
  330.       print_command = true;
  331.       break;
  332.  
  333.     case 'x':
  334.       exit_if_size_exceeded = true;
  335.       break;
  336.  
  337.     case 'p':
  338.       query_before_executing = true;
  339.       print_command = true;
  340.       break;
  341.  
  342.     case 'r':
  343.       always_run_command = 0;
  344.       break;
  345.  
  346.     case 'P':
  347.       proc_max = parse_num (optarg, 'P', 0L, -1L);
  348.       break;
  349.  
  350.     case 'v':
  351.       printf ("GNU xargs version %s\n", version_string);
  352.       exit (0);
  353.  
  354.     default:
  355.       usage (stderr, 1);
  356.     }
  357.     }
  358.  
  359.   if (replace_pat || lines_per_exec)
  360.     exit_if_size_exceeded = true;
  361.  
  362.   if (optind == argc)
  363.     {
  364.       optind = 0;
  365.       argc = 1;
  366.       argv = &default_cmd;
  367.     }
  368.  
  369.   linebuf = (char *) xmalloc (arg_max + 1);
  370.   argbuf = (char *) xmalloc (arg_max + 1);
  371.  
  372.   /* Make sure to listen for the kids.  */
  373.   signal (SIGCHLD, SIG_DFL);
  374.  
  375.   if (!replace_pat)
  376.     {
  377.       for (; optind < argc; optind++)
  378.     push_arg (argv[optind], strlen (argv[optind]) + 1);
  379.       initial_args = false;
  380.       initial_argc = cmd_argc;
  381.       initial_argv_chars = cmd_argv_chars;
  382.  
  383.       while ((*read_args) () != -1)
  384.     if (lines_per_exec && lineno >= lines_per_exec)
  385.       {
  386.         do_exec ();
  387.         lineno = 0;
  388.       }
  389.  
  390.       /* SYSV xargs seems to do at least one exec, even if the
  391.          input is empty.  */
  392.       if (cmd_argc != initial_argc
  393.       || (always_run_command && procs_executed == 0))
  394.     do_exec ();
  395.     }
  396.   else
  397.     {
  398.       int i;
  399.       size_t len;
  400.       size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
  401.  
  402.       for (i = optind; i < argc; i++)
  403.     arglen[i] = strlen(argv[i]);
  404.       rplen = strlen (replace_pat);
  405.       while ((len = (*read_args) ()) != -1)
  406.     {
  407.       /* Don't do insert on the command name.  */
  408.       push_arg (argv[optind], arglen[optind] + 1);
  409.       len--;
  410.       for (i = optind + 1; i < argc; i++)
  411.         do_insert (argv[i], arglen[i], len);
  412.       do_exec ();
  413.     }
  414.     }
  415.  
  416.   wait_for_proc (true);
  417.   exit (child_error);
  418. }
  419.  
  420. /* Read a line of arguments from stdin and add them to the list of
  421.    arguments to pass to the command.  Ignore blank lines and initial blanks.
  422.    Single and double quotes and backslashes quote metacharacters and blanks
  423.    as they do in the shell.
  424.    Return -1 if eof (either physical or logical) is reached,
  425.    otherwise the length of the last string read (including the null).  */
  426.  
  427. static int
  428. read_line ()
  429. {
  430.   static boolean eof = false;
  431.   /* Start out in mode SPACE to always strip leading spaces (even with -i).  */
  432.   int state = SPACE;        /* The type of character we last read.  */
  433.   int prevc;            /* The previous value of c.  */
  434.   int quotc = 0;        /* The last quote character read.  */
  435.   int c = EOF;
  436.   boolean first = true;        /* true if reading first arg on line.  */
  437.   int len;
  438.   char *p = linebuf;
  439.   /* Including the NUL, the args must not grow past this point.  */
  440.   char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
  441.  
  442.   if (eof)
  443.     return -1;
  444.   while (1)
  445.     {
  446.       prevc = c;
  447.       c = getc (stdin);
  448.       if (c == EOF)
  449.     {
  450.       /* COMPAT: SYSV seems to ignore stuff on a line that
  451.          ends without a \n; we don't.  */
  452.       eof = true;
  453.       if (p == linebuf)
  454.         return -1;
  455.       *p++ = '\0';
  456.       len = p - linebuf;
  457.       /* FIXME we don't check for unterminated quotes here.  */
  458.       if (first && EOF_STR (linebuf))
  459.         return -1;
  460.       if (!replace_pat)
  461.         push_arg (linebuf, len);
  462.       return len;
  463.     }
  464.       switch (state)
  465.     {
  466.     case SPACE:
  467.       if (ISSPACE (c))
  468.         continue;
  469.       state = NORM;
  470.       /* aaahhhh....  */
  471.  
  472.     case NORM:
  473.       if (c == '\n')
  474.         {
  475.           if (!ISBLANK (prevc))
  476.         lineno++;    /* For -l.  */
  477.           if (p == linebuf)
  478.         {
  479.           /* Blank line.  */
  480.           state = SPACE;
  481.           continue;
  482.         }
  483.           *p++ = '\0';
  484.           len = p - linebuf;
  485.           if (EOF_STR (linebuf))
  486.         {
  487.           eof = true;
  488.           return first ? -1 : len;
  489.         }
  490.           if (!replace_pat)
  491.         push_arg (linebuf, len);
  492.           return len;
  493.         }
  494.       if (!replace_pat && ISSPACE (c))
  495.         {
  496.           *p++ = '\0';
  497.           len = p - linebuf;
  498.           if (EOF_STR (linebuf))
  499.         {
  500.           eof = true;
  501.           return first ? -1 : len;
  502.         }
  503.           push_arg (linebuf, len);
  504.           p = linebuf;
  505.           state = SPACE;
  506.           first = false;
  507.           continue;
  508.         }
  509.       switch (c)
  510.         {
  511.         case '\\':
  512.           state = BACKSLASH;
  513.           continue;
  514.  
  515.         case '\'':
  516.         case '"':
  517.           state = QUOTE;
  518.           quotc = c;
  519.           continue;
  520.         }
  521.       break;
  522.  
  523.     case QUOTE:
  524.       if (c == '\n')
  525.         error (1, 0, "unmatched %s quote",
  526.            quotc == '"' ? "double" : "single");
  527.       if (c == quotc)
  528.         {
  529.           state = NORM;
  530.           continue;
  531.         }
  532.       break;
  533.  
  534.     case BACKSLASH:
  535.       state = NORM;
  536.       break;
  537.     }
  538.       if (p >= endbuf)
  539.     error (1, 0, "argument line too long");
  540.       *p++ = c;
  541.     }
  542. }
  543.  
  544. /* Read a null-terminated string from stdin and add it to the list of
  545.    arguments to pass to the command.
  546.    Return -1 if eof (either physical or logical) is reached,
  547.    otherwise the length of the string read (including the null).  */
  548.  
  549. static int
  550. read_string ()
  551. {
  552.   static boolean eof = false;
  553.   int len;
  554.   char *p = linebuf;
  555.   /* Including the NUL, the args must not grow past this point.  */
  556.   char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
  557.  
  558.   if (eof)
  559.     return -1;
  560.   while (1)
  561.     {
  562.       int c = getc (stdin);
  563.       if (c == EOF)
  564.     {
  565.       eof = true;
  566.       if (p == linebuf)
  567.         return -1;
  568.       *p++ = '\0';
  569.       len = p - linebuf;
  570.       if (!replace_pat)
  571.         push_arg (linebuf, len);
  572.       return len;
  573.     }
  574.       if (c == '\0')
  575.     {
  576.       lineno++;        /* For -l.  */
  577.       *p++ = '\0';
  578.       len = p - linebuf;
  579.       if (!replace_pat)
  580.         push_arg (linebuf, len);
  581.       return len;
  582.     }
  583.       if (p >= endbuf)
  584.     error (1, 0, "argument line too long");
  585.       *p++ = c;
  586.     }
  587. }
  588.  
  589. /* Replace all instances of `replace_pat' in ARG with `linebuf',
  590.    and add the resulting string to the list of arguments for the command
  591.    to execute.
  592.    ARGLEN is the length of ARG, not including the null.
  593.    LBLEN is the length of `linebuf', not including the null.
  594.  
  595.    COMPAT: insertions on the SYSV version are limited to 255 chars per line,
  596.    and a max of 5 occurences of replace_pat in the initial-arguments.
  597.    Those restrictions do not exist here.  */
  598.  
  599. static void
  600. do_insert (arg, arglen, lblen)
  601.      char *arg;
  602.      size_t arglen;
  603.      size_t lblen;
  604. {
  605.   /* Temporary copy of each arg with the replace pattern replaced by the
  606.      real arg.  */
  607.   static char *insertbuf;
  608.   char *p;
  609.   int bytes_left = arg_max - 1;    /* Bytes left on the command line.  */
  610.  
  611.   if (!insertbuf)
  612.     insertbuf = (char *) xmalloc (arg_max + 1);
  613.   p = insertbuf;
  614.  
  615.   do
  616.     {
  617.       size_t len;        /* Length in ARG before `replace_pat'.  */
  618.       char *s = strstr (arg, replace_pat);
  619.       if (s)
  620.     len = s - arg;
  621.       else
  622.     len = arglen;
  623.       bytes_left -= len;
  624.       if (bytes_left <= 0)
  625.     break;
  626.  
  627.       strncpy (p, arg, len);
  628.       p += len;
  629.       arg += len;
  630.  
  631.       if (s)
  632.     {
  633.       bytes_left -= lblen;
  634.       if (bytes_left <= 0)
  635.         break;
  636.       strcpy (p, linebuf);
  637.       arg += rplen;
  638.       p += lblen;
  639.     }
  640.     }
  641.   while (*arg);
  642.   if (*arg)
  643.     error (1, 0, "command too long");
  644.   *p++ = '\0';
  645.   push_arg (insertbuf, p - insertbuf);
  646. }
  647.  
  648. /* Add ARG to the end of the list of arguments `cmd_argv' to pass
  649.    to the command.
  650.    LEN is the length of ARG, including the terminating null.
  651.    If this brings the list up to its maximum size, execute the command.  */
  652.  
  653. static void
  654. push_arg (arg, len)
  655.      char *arg;
  656.      size_t len;
  657. {
  658.   if (arg)
  659.     {
  660.       if (cmd_argv_chars + len > arg_max)
  661.     {
  662.       if (initial_args || cmd_argc == initial_argc)
  663.         error (1, 0, "can not fit single argument within argument list size limit");
  664.       if (replace_pat
  665.           || (exit_if_size_exceeded &&
  666.           (lines_per_exec || args_per_exec)))
  667.         error (1, 0, "argument list too long");
  668.       do_exec ();
  669.     }
  670.       if (!initial_args && args_per_exec &&
  671.       cmd_argc - initial_argc == args_per_exec)
  672.     do_exec ();
  673.     }
  674.  
  675.   if (cmd_argc >= cmd_argv_alloc)
  676.     {
  677.       if (!cmd_argv)
  678.     {
  679.       cmd_argv_alloc = 64;
  680.       cmd_argv = (char **) xmalloc (sizeof (char *) * cmd_argv_alloc);
  681.     }
  682.       else
  683.     {
  684.       cmd_argv_alloc *= 2;
  685.       cmd_argv = (char **) xrealloc (cmd_argv,
  686.                      sizeof (char *) * cmd_argv_alloc);
  687.     }
  688.     }
  689.  
  690.   if (!arg)
  691.     cmd_argv[cmd_argc++] = NULL;
  692.   else
  693.     {
  694.       cmd_argv[cmd_argc++] = argbuf + cmd_argv_chars;
  695.       strcpy (argbuf + cmd_argv_chars, arg);
  696.       cmd_argv_chars += len;
  697.     }
  698. }
  699.  
  700. /* Print the arguments of the command to execute.
  701.    If ASK is nonzero, prompt the user for a response, and
  702.    if the user responds affirmatively, return true;
  703.    otherwise, return false.  */
  704.  
  705. static boolean
  706. print_args (ask)
  707.      boolean ask;
  708. {
  709.   int i;
  710.  
  711.   for (i = 0; i < cmd_argc - 1; i++)
  712.     fprintf (stderr, "%s ", cmd_argv[i]);
  713.   if (ask)
  714.     {
  715.       static FILE *tty_stream;
  716.       int c, savec;
  717.  
  718.       if (!tty_stream)
  719.     {
  720.       tty_stream = fopen ("/dev/tty", "r");
  721.       if (!tty_stream)
  722.         error (1, errno, "/dev/tty");
  723.     }
  724.       fputs ("?...", stderr);
  725.       fflush (stderr);
  726.       c = savec = getc (tty_stream);
  727.       while (c != EOF && c != '\n')
  728.     c = getc (tty_stream);
  729.       if (savec == 'y' || savec == 'Y')
  730.     return true;
  731.     }
  732.   else
  733.     putc ('\n', stderr);
  734.  
  735.   return false;
  736. }
  737.  
  738. /* Execute the command that has been built in `cmd_argv'.  This may involve
  739.    waiting for processes that were previously executed.  */
  740.  
  741. static void
  742. do_exec ()
  743. {
  744.   pid_t child;
  745.  
  746.   push_arg ((char *) NULL, 0);    /* Null terminate the arg list.  */
  747.   if (!query_before_executing || print_args (true))
  748.     {
  749.       if (proc_max && procs_executing >= proc_max)
  750.     wait_for_proc (false);
  751.       if (!query_before_executing && print_command)
  752.     print_args (false);
  753.       /* If we run out of processes, wait for a child to return and
  754.          try again.  */
  755.       while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
  756.     wait_for_proc (false);
  757.       switch (child)
  758.     {
  759.     case -1:
  760.       error (1, errno, "cannot fork");
  761.  
  762.     case 0:        /* Child.  */
  763.       execvp (cmd_argv[0], cmd_argv);
  764.       error (0, errno, "%s", cmd_argv[0]);
  765.       _exit (errno == ENOENT ? 127 : 126);
  766.     }
  767.       add_proc (child);
  768.     }
  769.  
  770.   cmd_argc = initial_argc;
  771.   cmd_argv_chars = initial_argv_chars;
  772. }
  773.  
  774. /* Add the process with id PID to the list of processes that have
  775.    been executed.  */
  776.  
  777. static void
  778. add_proc (pid)
  779.      pid_t pid;
  780. {
  781.   int i;
  782.  
  783.   /* Find an empty slot.  */
  784.   for (i = 0; i < pids_alloc && pids[i]; i++)
  785.     ;
  786.   if (i == pids_alloc)
  787.     {
  788.       if (pids_alloc == 0)
  789.     {
  790.       pids_alloc = proc_max ? proc_max : 64;
  791.       pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
  792.     }
  793.       else
  794.     {
  795.       pids_alloc *= 2;
  796.       pids = (pid_t *) xrealloc (pids,
  797.                      sizeof (pid_t) * pids_alloc);
  798.     }
  799.       memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
  800.     }
  801.   pids[i] = pid;
  802.   procs_executing++;
  803.   procs_executed++;
  804. }
  805.  
  806. /* If ALL is true, wait for all child processes to finish;
  807.    otherwise, wait for one child process to finish.
  808.    Remove the processes that finish from the list of executing processes.  */
  809.  
  810. static void
  811. wait_for_proc (all)
  812.      boolean all;
  813. {
  814.   while (procs_executing)
  815.     {
  816.       int i, status;
  817.  
  818.       do
  819.     {
  820.       pid_t pid;
  821.  
  822.       pid = wait (&status);
  823.       if (pid < 0)
  824.         error (1, errno, "error waiting for child process");
  825.  
  826.       /* Find the entry in `pids' for the child process
  827.          that exited.  */
  828.       for (i = 0; i < pids_alloc && pid != pids[i]; i++)
  829.         ;
  830.     }
  831.       while (i == pids_alloc);    /* A child died that we didn't start? */
  832.  
  833.       /* Remove the child from the list.  */
  834.       pids[i] = 0;
  835.       procs_executing--;
  836.  
  837.       if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
  838.     exit (WEXITSTATUS (status));    /* Can't find or run the command.  */
  839.       if (WEXITSTATUS (status) == 255)
  840.     error (124, 0, "%s: exited with status 255; aborting", cmd_argv[0]);
  841.       if (WIFSTOPPED (status))
  842.     error (125, 0, "%s: stopped by signal %d", cmd_argv[0], WSTOPSIG (status));
  843.       if (WIFSIGNALED (status))
  844.     error (125, 0, "%s: terminated by signal %d", cmd_argv[0], WTERMSIG (status));
  845.       if (WEXITSTATUS (status) != 0)
  846.     child_error = 123;
  847.  
  848.       if (!all)
  849.     break;
  850.     }
  851. }
  852.  
  853. /* Return the value of the number represented in STR.
  854.    OPTION is the command line option to which STR is the argument.
  855.    If the value does not fall within the boundaries MIN and MAX,
  856.    Print an error message mentioning OPTION and exit.  */
  857.  
  858. static long
  859. parse_num (str, option, min, max)
  860.      char *str;
  861.      int option;
  862.      long min;
  863.      long max;
  864. {
  865.   char *eptr;
  866.   long val;
  867.  
  868.   val = strtol (str, &eptr, 10);
  869.   if (eptr == str || *eptr)
  870.     {
  871.       fprintf (stderr, "%s: invalid number for -%c option\n",
  872.            program_name, option);
  873.       usage (stderr, 1);
  874.     }
  875.   else if (val < min)
  876.     {
  877.       fprintf (stderr, "%s: value for -%c option must be >= %ld\n",
  878.            program_name, option, min);
  879.       usage (stderr, 1);
  880.     }
  881.   else if (max >= 0 && val > max)
  882.     {
  883.       fprintf (stderr, "%s: value for -%c option must be < %ld\n",
  884.            program_name, option, max);
  885.       usage (stderr, 1);
  886.     }
  887.   return val;
  888. }
  889.  
  890. /* Return how much of ARG_MAX is used by the environment.  */
  891.  
  892. static long
  893. env_size (envp)
  894.      char **envp;
  895. {
  896.   long len = 0;
  897.  
  898.   while (*envp)
  899.     len += strlen (*envp++) + 1;
  900.  
  901.   return len;
  902. }
  903.  
  904. static void
  905. usage (stream, status)
  906.      FILE *stream;
  907.      int status;
  908. {
  909.   fprintf (stream, "\
  910. Usage: %s [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]\n\
  911.        [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]\n\
  912.        [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]\n\
  913.        [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]\n\
  914.        [--max-args=max-args] [--no-run-if-empty] [--version] [--help]\n\
  915.        [command [initial-arguments]]\n",
  916.        program_name);
  917.   exit (status);
  918. }
  919.