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 * 3. 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 $
34 * @(#) Copyright (c) 1990, 1993 The Regents of the University of California. All rights reserved.
35 * @(#)xargs.c 8.1 (Berkeley) 6/6/93
36 * $FreeBSD: src/usr.bin/xargs/xargs.c,v 1.9.2.6 2003/06/01 21:40:35 mux Exp $
39 #include <sys/types.h>
54 #include "pathnames.h"
56 static void parse_input(int, char *[]);
57 static void prerun(int, char *[]);
58 static int prompt(void);
59 static void run(char **);
60 static void usage(void);
61 void strnsubst(char **, const char *, const char *, size_t);
62 static void waitchildren(const char *, int);
64 static char echo
[] = _PATH_ECHO
;
65 static char **av
, **bxp
, **ep
, **expx
, **xp
;
66 static char *argp
, *bbp
, *ebp
, *inpline
, *p
, *replstr
;
67 static const char *eofstr
;
68 static int count
, insingle
, indouble
, oflag
, pflag
, tflag
, Rflag
, rval
, zflag
;
69 static int cnt
, Iflag
, jfound
, Lflag
, wasquoted
, xflag
;
70 static int curprocs
, maxprocs
;
71 static volatile int childerr
;
73 extern char **environ
;
76 main(int argc
, char *argv
[])
80 int ch
, Jflag
, nargs
, nflag
, nline
;
83 inpline
= replstr
= NULL
;
88 (void)setlocale(LC_MESSAGES
, "");
91 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
92 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
93 * that the smallest argument is 2 bytes in length, this means that
94 * the number of arguments is limited to:
96 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
98 * We arbitrarily limit the number of arguments to 5000. This is
99 * allowed by POSIX.2 as long as the resulting minimum exec line is
100 * at least LINE_MAX. Realloc'ing as necessary is possible, but
101 * probably not worthwhile.
104 if ((arg_max
= sysconf(_SC_ARG_MAX
)) == -1)
105 errx(1, "sysconf(_SC_ARG_MAX) failed");
106 nline
= arg_max
- 4 * 1024;
107 while (*ep
!= NULL
) {
108 /* 1 byte for each '\0' */
109 nline
-= strlen(*ep
++) + 1 + sizeof(*ep
);
113 while ((ch
= getopt(argc
, argv
, "0E:I:J:L:n:oprP:R:s:tx")) != -1)
130 Lflag
= strtol(optarg
, &tmp
, 10);
131 if (*tmp
!= 0 || *optarg
== 0)
132 errx(1, "illegal argument count");
136 if ((nargs
= atoi(optarg
)) <= 0)
137 errx(1, "illegal argument count");
146 if ((maxprocs
= atoi(optarg
)) <= 0)
147 errx(1, "max.processes must be >0");
150 if ((Rflag
= atoi(optarg
)) <= 0)
151 errx(1, "illegal number of replacements");
154 /* GNU compatibility */
155 /* --no-run-if-empty (this is our default) */
158 nline
= atoi(optarg
);
184 if (replstr
!= NULL
&& *replstr
== '\0')
185 errx(1, "replstr may not be empty");
188 * Allocate pointers for the utility name, the utility arguments,
189 * the maximum arguments to be read from stdin and the trailing
192 linelen
= 1 + argc
+ nargs
+ 1;
193 if ((av
= bxp
= malloc(linelen
* sizeof(char **))) == NULL
)
194 errx(1, "malloc failed");
197 * Use the user's name for the utility as argv[0], just like the
198 * shell. Echo is the default. Set up pointers for the user's
202 cnt
= strlen(*bxp
++ = echo
);
205 if (Jflag
&& strcmp(*argv
, replstr
) == 0) {
209 for (avj
= argv
; *avj
; avj
++)
210 cnt
+= strlen(*avj
) + 1;
213 cnt
+= strlen(*bxp
++ = *argv
) + 1;
214 } while (*++argv
!= NULL
);
218 * Set up begin/end/traversing pointers into the array. The -n
219 * count doesn't include the trailing NULL pointer, so the malloc
220 * added in an extra slot.
222 expx
= (xp
= bxp
) + nargs
;
225 * Allocate buffer space for the arguments read from stdin and the
226 * trailing NULL. Buffer space is defined as the default or specified
227 * space, minus the length of the utility name and arguments. Set up
228 * begin/end/traversing pointers into the array. The -s count does
229 * include the trailing NULL, so the malloc didn't add in an extra
234 errx(1, "insufficient space for command");
236 if ((bbp
= malloc((size_t)(nline
+ 1))) == NULL
)
237 errx(1, "malloc failed");
238 ebp
= (argp
= p
= bbp
) + nline
- 1;
240 parse_input(argc
, argv
);
244 parse_input(int argc
, char *argv
[])
251 switch(ch
= getchar()) {
253 /* No arguments since last exec. */
255 waitchildren(*argv
, 1);
261 /* Quotes escape tabs and spaces. */
262 if (insingle
|| indouble
|| zflag
)
274 /* Quotes do not escape newlines. */
275 arg1
: if (insingle
|| indouble
)
276 errx(1, "unterminated quote");
278 foundeof
= *eofstr
!= '\0' &&
279 strcmp(argp
, eofstr
) == 0;
281 /* Do not make empty args unless they are quoted */
282 if ((argp
!= p
|| wasquoted
) && !foundeof
) {
292 * If this string is not zero
293 * length, append a space for
294 * separation before the next
297 if ((curlen
= strlen(inpline
)))
298 strcat(inpline
, " ");
302 * Allocate enough to hold what we will
303 * be holding in a second, and to append
304 * a space next time through, if we have
307 inpline
= realloc(inpline
, curlen
+ 2 +
310 errx(1, "realloc failed");
312 strcpy(inpline
, argp
);
314 strcat(inpline
, argp
);
319 * If max'd out on args or buffer, or reached EOF,
320 * run the command. If xflag and max'd out on buffer
321 * but not on args, object. Having reached the limit
322 * of input lines, as specified by -L is the same as
323 * maxing out on arguments.
325 if (xp
== expx
|| p
> ebp
|| ch
== EOF
||
326 (Lflag
<= count
&& xflag
) || foundeof
) {
327 if (xflag
&& xp
!= expx
&& p
> ebp
)
328 errx(1, "insufficient space for arguments");
330 for (avj
= argv
; *avj
; avj
++)
334 if (ch
== EOF
|| foundeof
) {
335 waitchildren(*argv
, 1);
346 if (indouble
|| zflag
)
348 insingle
= !insingle
;
352 if (insingle
|| zflag
)
354 indouble
= !indouble
;
360 /* Backslash escapes anything, is escaped by quotes. */
361 if (!insingle
&& !indouble
&& (ch
= getchar()) == EOF
)
362 errx(1, "backslash at EOF");
365 addch
: if (p
< ebp
) {
370 /* If only one argument, not enough buffer space. */
372 errx(1, "insufficient space for argument");
373 /* Didn't hit argument limit, so if xflag object. */
375 errx(1, "insufficient space for arguments");
378 for (avj
= argv
; *avj
; avj
++)
384 memcpy(bbp
, argp
, (size_t)cnt
);
385 p
= (argp
= bbp
) + cnt
;
393 * Do things necessary before run()'ing, such as -I substitution,
394 * and then call run().
397 prerun(int argc
, char *argv
[])
399 char **tmp
, **tmp2
, **avj
;
404 if (argc
== 0 || repls
== 0) {
413 * Allocate memory to hold the argument list, and
414 * a NULL at the tail.
416 tmp
= malloc((argc
+ 1) * sizeof(char**));
418 errx(1, "malloc failed");
422 * Save the first argument and iterate over it, we
423 * cannot do strnsubst() to it.
425 if ((*tmp
++ = strdup(*avj
++)) == NULL
)
426 errx(1, "strdup failed");
429 * For each argument to utility, if we have not used up
430 * the number of replacements we are allowed to do, and
431 * if the argument contains at least one occurrence of
432 * replstr, call strnsubst(), else just save the string.
433 * Iterations over elements of avj and tmp are done
438 if (repls
&& strstr(*tmp
, replstr
) != NULL
) {
439 strnsubst(tmp
++, replstr
, inpline
, (size_t)255);
442 if ((*tmp
= strdup(*tmp
)) == NULL
)
443 errx(1, "strdup failed");
455 * Walk from the tail to the head, free along the way.
457 for (; tmp2
!= tmp
; tmp
--)
460 * Now free the list itself.
465 * Free the input line buffer, if we have one.
467 if (inpline
!= NULL
) {
480 * If the user wants to be notified of each command before it is
481 * executed, notify them. If they want the notification to be
482 * followed by a prompt, then prompt them.
484 if (tflag
|| pflag
) {
485 (void)fprintf(stderr
, "%s", *argv
);
486 for (avec
= argv
+ 1; *avec
!= NULL
; ++avec
)
487 (void)fprintf(stderr
, " %s", *avec
);
489 * If the user has asked to be prompted, do so.
493 * If they asked not to exec, return without execution
494 * but if they asked to, go to the execution. If we
495 * could not open their tty, break the switch and drop
496 * back to -t behaviour.
506 (void)fprintf(stderr
, "\n");
507 (void)fflush(stderr
);
511 switch(pid
= vfork()) {
517 if (open("/dev/tty", O_RDONLY
) == -1)
518 err(1, "open /dev/tty");
520 if (open("/dev/null", O_RDONLY
) == -1)
521 err(1, "open /dev/null");
523 execvp(argv
[0], argv
);
528 waitchildren(*argv
, 0);
532 * Handle child processes.
535 waitchildren(const char *name
, int waitall
)
540 while ((pid
= wait3(&status
, !waitall
&& curprocs
< maxprocs
?
541 WNOHANG
: 0, NULL
)) > 0) {
544 /* If we couldn't invoke the utility, exit. */
547 err(errno
== ENOENT
? 127 : 126, "%s", name
);
551 * If utility signaled or exited with a value of 255,
554 if (WIFSIGNALED(status
) || WEXITSTATUS(status
) == 255)
556 if (WEXITSTATUS(status
))
559 if (pid
== -1 && errno
!= ECHILD
)
564 * Prompt the user about running a command.
575 if ((ttyfp
= fopen(_PATH_TTY
, "r")) == NULL
)
576 return (2); /* Indicate that the TTY failed to open. */
577 (void)fprintf(stderr
, "?...");
578 (void)fflush(stderr
);
579 if ((response
= fgetln(ttyfp
, &rsize
)) == NULL
||
581 nl_langinfo(YESEXPR
),
586 match
= regexec(&cre
, response
, 0, NULL
, 0);
596 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
597 " [-L number] [-n number [-x] [-P maxprocs] [-s size]\n"
598 " [utility [argument ...]]\n");