2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
37 static const char copyright[] =
38 "@(#) Copyright (c) 1990, 1993\n\
39 The Regents of the University of California. All rights reserved.\n";
43 static char sccsid[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
49 #include <sys/param.h>
64 #include "pathnames.h"
66 static void parse_input(int, char *[]);
67 static void prerun(int, char *[]);
68 static int prompt(void);
69 static void run(char **);
70 static void usage(void);
71 void strnsubst(char **, const char *, const char *, size_t);
72 static pid_t xwait(int block, int *status);
73 static void waitchildren(const char *, int);
74 static void pids_init(void);
75 static int pids_empty(void);
76 static int pids_full(void);
77 static void pids_add(pid_t pid);
78 static int pids_remove(pid_t pid);
79 static int findslot(pid_t pid);
80 static int findfreeslot(void);
81 static void clearslot(int slot);
83 static char echo[] = _PATH_ECHO;
84 static char **av, **bxp, **ep, **endxp, **xp;
85 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
86 static const char *eofstr;
87 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
88 static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
89 static int curprocs, maxprocs;
90 static pid_t *childpids;
92 static volatile int childerr;
94 extern char **environ;
97 main(int argc, char *argv[])
100 int ch, Jflag, nargs, nflag, nline;
104 inpline = replstr = NULL;
109 (void)setlocale(LC_ALL, "");
112 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
113 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
114 * that the smallest argument is 2 bytes in length, this means that
115 * the number of arguments is limited to:
117 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
119 * We arbitrarily limit the number of arguments to 5000. This is
120 * allowed by POSIX.2 as long as the resulting minimum exec line is
121 * at least LINE_MAX. Realloc'ing as necessary is possible, but
122 * probably not worthwhile.
125 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
126 errx(1, "sysconf(_SC_ARG_MAX) failed");
127 nline = arg_max - 4 * 1024;
128 while (*ep != NULL) {
129 /* 1 byte for each '\0' */
130 nline -= strlen(*ep++) + 1 + sizeof(*ep);
133 while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
150 Lflag = atoi(optarg);
154 if ((nargs = atoi(optarg)) <= 0)
155 errx(1, "illegal argument count");
161 if ((maxprocs = atoi(optarg)) <= 0)
162 errx(1, "max. processes must be >0");
168 Rflag = strtol(optarg, &endptr, 10);
170 errx(1, "replacements must be a number");
173 /* GNU compatibility */
176 Sflag = strtoul(optarg, &endptr, 10);
178 errx(1, "replsize must be a number");
181 nline = atoi(optarg);
211 if (replstr != NULL && *replstr == '\0')
212 errx(1, "replstr may not be empty");
217 * Allocate pointers for the utility name, the utility arguments,
218 * the maximum arguments to be read from stdin and the trailing
221 linelen = 1 + argc + nargs + 1;
222 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
223 errx(1, "malloc failed");
226 * Use the user's name for the utility as argv[0], just like the
227 * shell. Echo is the default. Set up pointers for the user's
231 cnt = strlen(*bxp++ = echo);
234 if (Jflag && strcmp(*argv, replstr) == 0) {
238 for (avj = argv; *avj; avj++)
239 cnt += strlen(*avj) + 1;
242 cnt += strlen(*bxp++ = *argv) + 1;
243 } while (*++argv != NULL);
247 * Set up begin/end/traversing pointers into the array. The -n
248 * count doesn't include the trailing NULL pointer, so the malloc
249 * added in an extra slot.
251 endxp = (xp = bxp) + nargs;
254 * Allocate buffer space for the arguments read from stdin and the
255 * trailing NULL. Buffer space is defined as the default or specified
256 * space, minus the length of the utility name and arguments. Set up
257 * begin/end/traversing pointers into the array. The -s count does
258 * include the trailing NULL, so the malloc didn't add in an extra
263 errx(1, "insufficient space for command");
265 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
266 errx(1, "malloc failed");
267 ebp = (argp = p = bbp) + nline - 1;
269 parse_input(argc, argv);
273 parse_input(int argc, char *argv[])
280 switch (ch = getchar()) {
282 /* No arguments since last exec. */
284 waitchildren(*argv, 1);
290 /* Quotes escape tabs and spaces. */
291 if (insingle || indouble || zflag)
297 * Increment 'count', so that nulls will be treated
298 * as end-of-line, as well as end-of-argument. This
299 * is needed so -0 works properly with -I and -L.
308 count++; /* Indicate end-of-line (used by -L) */
310 /* Quotes do not escape newlines. */
311 arg1: if (insingle || indouble)
312 errx(1, "unterminated quote");
314 foundeof = *eofstr != '\0' &&
315 strncmp(argp, eofstr, p - argp) == 0;
317 /* Do not make empty args unless they are quoted */
318 if ((argp != p || wasquoted) && !foundeof) {
328 * If this string is not zero
329 * length, append a space for
330 * separation before the next
333 if ((curlen = strlen(inpline)))
334 strcat(inpline, " ");
338 * Allocate enough to hold what we will
339 * be holding in a second, and to append
340 * a space next time through, if we have
343 inpline = realloc(inpline, curlen + 2 +
346 errx(1, "realloc failed");
348 strcpy(inpline, argp);
350 strcat(inpline, argp);
355 * If max'd out on args or buffer, or reached EOF,
356 * run the command. If xflag and max'd out on buffer
357 * but not on args, object. Having reached the limit
358 * of input lines, as specified by -L is the same as
359 * maxing out on arguments.
361 if (xp == endxp || p > ebp || ch == EOF ||
362 (Lflag <= count && xflag) || foundeof) {
363 if (xflag && xp != endxp && p > ebp)
364 errx(1, "insufficient space for arguments");
366 for (avj = argv; *avj; avj++)
370 if (ch == EOF || foundeof) {
371 waitchildren(*argv, 1);
382 if (indouble || zflag)
384 insingle = !insingle;
388 if (insingle || zflag)
390 indouble = !indouble;
396 /* Backslash escapes anything, is escaped by quotes. */
397 if (!insingle && !indouble && (ch = getchar()) == EOF)
398 errx(1, "backslash at EOF");
401 addch: if (p < ebp) {
406 /* If only one argument, not enough buffer space. */
408 errx(1, "insufficient space for argument");
409 /* Didn't hit argument limit, so if xflag object. */
411 errx(1, "insufficient space for arguments");
414 for (avj = argv; *avj; avj++)
420 memcpy(bbp, argp, (size_t)cnt);
421 p = (argp = bbp) + cnt;
428 * Do things necessary before run()'ing, such as -I substitution,
429 * and then call run().
432 prerun(int argc, char *argv[])
434 char **tmp, **tmp2, **avj;
439 if (argc == 0 || repls == 0) {
448 * Allocate memory to hold the argument list, and
449 * a NULL at the tail.
451 tmp = malloc((argc + 1) * sizeof(char**));
453 errx(1, "malloc failed");
457 * Save the first argument and iterate over it, we
458 * cannot do strnsubst() to it.
460 if ((*tmp++ = strdup(*avj++)) == NULL)
461 errx(1, "strdup failed");
464 * For each argument to utility, if we have not used up
465 * the number of replacements we are allowed to do, and
466 * if the argument contains at least one occurrence of
467 * replstr, call strnsubst(), else just save the string.
468 * Iterations over elements of avj and tmp are done
473 if (repls && strstr(*tmp, replstr) != NULL) {
474 strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
478 if ((*tmp = strdup(*tmp)) == NULL)
479 errx(1, "strdup failed");
491 * Walk from the tail to the head, free along the way.
493 for (; tmp2 != tmp; tmp--)
496 * Now free the list itself.
501 * Free the input line buffer, if we have one.
503 if (inpline != NULL) {
517 * If the user wants to be notified of each command before it is
518 * executed, notify them. If they want the notification to be
519 * followed by a prompt, then prompt them.
521 if (tflag || pflag) {
522 (void)fprintf(stderr, "%s", *argv);
523 for (avec = argv + 1; *avec != NULL; ++avec)
524 (void)fprintf(stderr, " %s", *avec);
526 * If the user has asked to be prompted, do so.
530 * If they asked not to exec, return without execution
531 * but if they asked to, go to the execution. If we
532 * could not open their tty, break the switch and drop
533 * back to -t behaviour.
543 (void)fprintf(stderr, "\n");
544 (void)fflush(stderr);
548 switch (pid = vfork()) {
553 if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
554 err(1, "can't open /dev/tty");
556 fd = open(_PATH_DEVNULL, O_RDONLY);
558 if (fd > STDIN_FILENO) {
559 if (dup2(fd, STDIN_FILENO) != 0)
560 err(1, "can't dup2 to stdin");
563 execvp(argv[0], argv);
568 waitchildren(*argv, 0);
572 * Wait for a tracked child to exit and return its pid and exit status.
574 * Ignores (discards) all untracked child processes.
575 * Returns -1 and sets errno to ECHILD if no tracked children exist.
576 * If block is set, waits indefinitely for a child process to exit.
577 * If block is not set and no children have exited, returns 0 immediately.
580 xwait(int block, int *status) {
588 while ((pid = waitpid(-1, status, block ? 0 : WNOHANG)) > 0)
589 if (pids_remove(pid))
596 waitchildren(const char *name, int waitall)
601 while ((pid = xwait(waitall || pids_full(), &status)) > 0) {
602 /* If we couldn't invoke the utility, exit. */
605 err(errno == ENOENT ? 127 : 126, "%s", name);
608 * If utility signaled or exited with a value of 255,
611 if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
613 if (WEXITSTATUS(status))
617 if (pid == -1 && errno != ECHILD)
628 if ((childpids = malloc(maxprocs * sizeof(*childpids))) == NULL)
629 errx(1, "malloc failed");
631 for (i = 0; i < maxprocs; i++)
638 return (curprocs == 0);
644 return (curprocs >= maxprocs);
652 slot = findfreeslot();
653 childpids[slot] = pid;
658 pids_remove(pid_t pid)
662 if ((slot = findslot(pid)) < 0)
675 if ((slot = findslot(NOPID)) < 0)
676 errx(1, "internal error: no free pid slot");
686 for (slot = 0; slot < maxprocs; slot++)
687 if (childpids[slot] == pid)
696 childpids[slot] = NOPID;
700 * Prompt the user about running a command.
711 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
712 return (2); /* Indicate that the TTY failed to open. */
713 (void)fprintf(stderr, "?...");
714 (void)fflush(stderr);
715 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
716 regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
720 response[rsize - 1] = '\0';
721 match = regexec(&cre, response, 0, NULL, 0);
731 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
732 " [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
733 " [-s size] [utility [argument ...]]\n");