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 xexit(const char *, const int);
74 static void waitchildren(const char *, int);
75 static void pids_init(void);
76 static int pids_empty(void);
77 static int pids_full(void);
78 static void pids_add(pid_t pid);
79 static int pids_remove(pid_t pid);
80 static int findslot(pid_t pid);
81 static int findfreeslot(void);
82 static void clearslot(int slot);
84 static char echo[] = _PATH_ECHO;
85 static char **av, **bxp, **ep, **endxp, **xp;
86 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
87 static const char *eofstr;
88 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
89 static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
90 static int curprocs, maxprocs;
91 static pid_t *childpids;
93 static volatile int childerr;
95 extern char **environ;
98 main(int argc, char *argv[])
101 int ch, Jflag, nargs, nflag, nline;
105 inpline = replstr = NULL;
110 (void)setlocale(LC_ALL, "");
113 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
114 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
115 * that the smallest argument is 2 bytes in length, this means that
116 * the number of arguments is limited to:
118 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
120 * We arbitrarily limit the number of arguments to 5000. This is
121 * allowed by POSIX.2 as long as the resulting minimum exec line is
122 * at least LINE_MAX. Realloc'ing as necessary is possible, but
123 * probably not worthwhile.
126 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
127 errx(1, "sysconf(_SC_ARG_MAX) failed");
128 nline = arg_max - 4 * 1024;
129 while (*ep != NULL) {
130 /* 1 byte for each '\0' */
131 nline -= strlen(*ep++) + 1 + sizeof(*ep);
134 while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
151 Lflag = atoi(optarg);
155 if ((nargs = atoi(optarg)) <= 0)
156 errx(1, "illegal argument count");
162 if ((maxprocs = atoi(optarg)) <= 0)
163 errx(1, "max. processes must be >0");
169 Rflag = strtol(optarg, &endptr, 10);
171 errx(1, "replacements must be a number");
174 /* GNU compatibility */
177 Sflag = strtoul(optarg, &endptr, 10);
179 errx(1, "replsize must be a number");
182 nline = atoi(optarg);
212 if (replstr != NULL && *replstr == '\0')
213 errx(1, "replstr may not be empty");
218 * Allocate pointers for the utility name, the utility arguments,
219 * the maximum arguments to be read from stdin and the trailing
222 linelen = 1 + argc + nargs + 1;
223 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
224 errx(1, "malloc failed");
227 * Use the user's name for the utility as argv[0], just like the
228 * shell. Echo is the default. Set up pointers for the user's
232 cnt = strlen(*bxp++ = echo);
235 if (Jflag && strcmp(*argv, replstr) == 0) {
239 for (avj = argv; *avj; avj++)
240 cnt += strlen(*avj) + 1;
243 cnt += strlen(*bxp++ = *argv) + 1;
244 } while (*++argv != NULL);
248 * Set up begin/end/traversing pointers into the array. The -n
249 * count doesn't include the trailing NULL pointer, so the malloc
250 * added in an extra slot.
252 endxp = (xp = bxp) + nargs;
255 * Allocate buffer space for the arguments read from stdin and the
256 * trailing NULL. Buffer space is defined as the default or specified
257 * space, minus the length of the utility name and arguments. Set up
258 * begin/end/traversing pointers into the array. The -s count does
259 * include the trailing NULL, so the malloc didn't add in an extra
264 errx(1, "insufficient space for command");
266 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
267 errx(1, "malloc failed");
268 ebp = (argp = p = bbp) + nline - 1;
270 parse_input(argc, argv);
274 parse_input(int argc, char *argv[])
281 switch (ch = getchar()) {
283 /* No arguments since last exec. */
289 /* Quotes escape tabs and spaces. */
290 if (insingle || indouble || zflag)
296 * Increment 'count', so that nulls will be treated
297 * as end-of-line, as well as end-of-argument. This
298 * is needed so -0 works properly with -I and -L.
307 count++; /* Indicate end-of-line (used by -L) */
309 /* Quotes do not escape newlines. */
310 arg1: if (insingle || indouble) {
311 warnx("unterminated quote");
315 foundeof = *eofstr != '\0' &&
316 strncmp(argp, eofstr, p - argp) == 0;
318 /* Do not make empty args unless they are quoted */
319 if ((argp != p || wasquoted) && !foundeof) {
329 * If this string is not zero
330 * length, append a space for
331 * separation before the next
334 if ((curlen = strlen(inpline)))
335 strcat(inpline, " ");
339 * Allocate enough to hold what we will
340 * be holding in a second, and to append
341 * a space next time through, if we have
344 inpline = realloc(inpline, curlen + 2 +
346 if (inpline == NULL) {
347 warnx("realloc failed");
351 strcpy(inpline, argp);
353 strcat(inpline, argp);
358 * If max'd out on args or buffer, or reached EOF,
359 * run the command. If xflag and max'd out on buffer
360 * but not on args, object. Having reached the limit
361 * of input lines, as specified by -L is the same as
362 * maxing out on arguments.
364 if (xp == endxp || p > ebp || ch == EOF ||
365 (Lflag <= count && xflag) || foundeof) {
366 if (xflag && xp != endxp && p > ebp) {
367 warnx("insufficient space for arguments");
371 for (avj = argv; *avj; avj++)
375 if (ch == EOF || foundeof)
385 if (indouble || zflag)
387 insingle = !insingle;
391 if (insingle || zflag)
393 indouble = !indouble;
399 /* Backslash escapes anything, is escaped by quotes. */
400 if (!insingle && !indouble && (ch = getchar()) == EOF) {
401 warnx("backslash at EOF");
406 addch: if (p < ebp) {
411 /* If only one argument, not enough buffer space. */
413 warnx("insufficient space for argument");
416 /* Didn't hit argument limit, so if xflag object. */
418 warnx("insufficient space for arguments");
423 for (avj = argv; *avj; avj++)
429 memcpy(bbp, argp, (size_t)cnt);
430 p = (argp = bbp) + cnt;
437 * Do things necessary before run()'ing, such as -I substitution,
438 * and then call run().
441 prerun(int argc, char *argv[])
443 char **tmp, **tmp2, **avj;
448 if (argc == 0 || repls == 0) {
457 * Allocate memory to hold the argument list, and
458 * a NULL at the tail.
460 tmp = malloc((argc + 1) * sizeof(char**));
462 warnx("malloc failed");
468 * Save the first argument and iterate over it, we
469 * cannot do strnsubst() to it.
471 if ((*tmp++ = strdup(*avj++)) == NULL) {
472 warnx("strdup failed");
477 * For each argument to utility, if we have not used up
478 * the number of replacements we are allowed to do, and
479 * if the argument contains at least one occurrence of
480 * replstr, call strnsubst(), else just save the string.
481 * Iterations over elements of avj and tmp are done
486 if (repls && strstr(*tmp, replstr) != NULL) {
487 strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
491 if ((*tmp = strdup(*tmp)) == NULL) {
492 warnx("strdup failed");
506 * Walk from the tail to the head, free along the way.
508 for (; tmp2 != tmp; tmp--)
511 * Now free the list itself.
516 * Free the input line buffer, if we have one.
518 if (inpline != NULL) {
532 * If the user wants to be notified of each command before it is
533 * executed, notify them. If they want the notification to be
534 * followed by a prompt, then prompt them.
536 if (tflag || pflag) {
537 (void)fprintf(stderr, "%s", *argv);
538 for (avec = argv + 1; *avec != NULL; ++avec)
539 (void)fprintf(stderr, " %s", *avec);
541 * If the user has asked to be prompted, do so.
545 * If they asked not to exec, return without execution
546 * but if they asked to, go to the execution. If we
547 * could not open their tty, break the switch and drop
548 * back to -t behaviour.
558 (void)fprintf(stderr, "\n");
559 (void)fflush(stderr);
563 switch (pid = vfork()) {
569 if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
570 err(1, "can't open /dev/tty");
572 fd = open(_PATH_DEVNULL, O_RDONLY);
574 if (fd > STDIN_FILENO) {
575 if (dup2(fd, STDIN_FILENO) != 0)
576 err(1, "can't dup2 to stdin");
579 execvp(argv[0], argv);
584 waitchildren(*argv, 0);
588 * Wait for a tracked child to exit and return its pid and exit status.
590 * Ignores (discards) all untracked child processes.
591 * Returns -1 and sets errno to ECHILD if no tracked children exist.
592 * If block is set, waits indefinitely for a child process to exit.
593 * If block is not set and no children have exited, returns 0 immediately.
596 xwait(int block, int *status) {
604 while ((pid = waitpid(-1, status, block ? 0 : WNOHANG)) > 0)
605 if (pids_remove(pid))
612 xexit(const char *name, const int exit_code) {
613 waitchildren(name, 1);
618 waitchildren(const char *name, int waitall)
624 while ((pid = xwait(waitall || pids_full(), &status)) > 0) {
626 * If we couldn't invoke the utility or if utility exited
627 * because of a signal or with a value of 255, warn (per
628 * POSIX), and then wait until all other children have
629 * exited before exiting 1-125. POSIX requires us to stop
630 * reading if child exits because of a signal or with 255,
631 * but it does not require us to exit immediately; waiting
632 * is preferable to orphaning.
634 if (childerr != 0 && cause_exit == 0) {
637 cause_exit = ENOENT ? 127 : 126;
639 } else if (WIFSIGNALED(status)) {
640 waitall = cause_exit = 1;
641 warnx("%s: terminated with signal %d; aborting",
642 name, WTERMSIG(status));
643 } else if (WEXITSTATUS(status) == 255) {
644 waitall = cause_exit = 1;
645 warnx("%s: exited with status 255; aborting", name);
646 } else if (WEXITSTATUS(status))
652 if (pid == -1 && errno != ECHILD)
663 if ((childpids = malloc(maxprocs * sizeof(*childpids))) == NULL)
664 errx(1, "malloc failed");
666 for (i = 0; i < maxprocs; i++)
674 return (curprocs == 0);
681 return (curprocs >= maxprocs);
689 slot = findfreeslot();
690 childpids[slot] = pid;
695 pids_remove(pid_t pid)
699 if ((slot = findslot(pid)) < 0)
712 if ((slot = findslot(NOPID)) < 0)
713 errx(1, "internal error: no free pid slot");
722 for (slot = 0; slot < maxprocs; slot++)
723 if (childpids[slot] == pid)
732 childpids[slot] = NOPID;
736 * Prompt the user about running a command.
747 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
748 return (2); /* Indicate that the TTY failed to open. */
749 (void)fprintf(stderr, "?...");
750 (void)fflush(stderr);
751 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
752 regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
756 response[rsize - 1] = '\0';
757 match = regexec(&cre, response, 0, NULL, 0);
768 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
769 " [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
770 " [-s size] [utility [argument ...]]\n");