]> git.saurik.com Git - apple/shell_cmds.git/blame - xargs/xargs.c
shell_cmds-216.40.4.tar.gz
[apple/shell_cmds.git] / xargs / xargs.c
CommitLineData
44bd5ea7 1/*-
47d9aef8
A
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
44bd5ea7
A
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * John B. Roll Jr.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
47d9aef8 18 * 3. Neither the name of the University nor the names of its contributors
44bd5ea7
A
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
9bafe280
A
33 *
34 * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
44bd5ea7
A
35 */
36
e1a085ba 37#if 0
44bd5ea7 38#ifndef lint
9bafe280
A
39static const char copyright[] =
40"@(#) Copyright (c) 1990, 1993\n\
41 The Regents of the University of California. All rights reserved.\n";
44bd5ea7
A
42#endif /* not lint */
43
9bafe280 44#ifndef lint
44bd5ea7 45static char sccsid[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
44bd5ea7 46#endif /* not lint */
9bafe280 47#endif
9bafe280 48#include <sys/cdefs.h>
47d9aef8 49__FBSDID("$FreeBSD$");
44bd5ea7 50
47d9aef8 51#include <sys/types.h>
44bd5ea7 52#include <sys/wait.h>
47d9aef8
A
53#include <sys/time.h>
54#include <sys/param.h>
55#include <sys/resource.h>
9bafe280 56#include <err.h>
44bd5ea7 57#include <errno.h>
e1a085ba
A
58#include <fcntl.h>
59#include <langinfo.h>
9bafe280
A
60#include <locale.h>
61#include <paths.h>
62#include <regex.h>
44bd5ea7
A
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <unistd.h>
9bafe280 67
44bd5ea7
A
68#include "pathnames.h"
69
1a5bac72
A
70#ifdef __APPLE__
71#include <get_compat.h>
72#else
73#define COMPAT_MODE(a,b) (1)
74#endif /* __APPLE__ */
75
9bafe280
A
76static void parse_input(int, char *[]);
77static void prerun(int, char *[]);
78static int prompt(void);
79static void run(char **);
80static void usage(void);
81void strnsubst(char **, const char *, const char *, size_t);
47d9aef8
A
82static pid_t xwait(int block, int *status);
83static void xexit(const char *, const int);
e1a085ba 84static void waitchildren(const char *, int);
47d9aef8
A
85static void pids_init(void);
86static int pids_empty(void);
87static int pids_full(void);
88static void pids_add(pid_t pid);
89static int pids_remove(pid_t pid);
90static int findslot(pid_t pid);
91static int findfreeslot(void);
92static void clearslot(int slot);
e1a085ba
A
93
94static int last_was_newline = 1;
95static int last_was_blank = 0;
9bafe280
A
96
97static char echo[] = _PATH_ECHO;
e1a085ba 98static char **av, **bxp, **ep, **endxp, **xp;
9bafe280
A
99static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
100static const char *eofstr;
e1a085ba 101static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
47d9aef8 102static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
e1a085ba 103static int curprocs, maxprocs;
f14763b6 104static size_t pad9314053;
47d9aef8 105static pid_t *childpids;
e1a085ba
A
106
107static volatile int childerr;
44bd5ea7 108
9bafe280 109extern char **environ;
44bd5ea7
A
110
111int
9bafe280 112main(int argc, char *argv[])
44bd5ea7 113{
9bafe280 114 long arg_max;
ddb4a88b
A
115 int ch, Jflag, nflag, nline;
116 size_t nargs;
9bafe280 117 size_t linelen;
47d9aef8 118 struct rlimit rl;
e1a085ba 119 char *endptr;
47d9aef8 120 const char *errstr;
44bd5ea7 121
9bafe280
A
122 inpline = replstr = NULL;
123 ep = environ;
124 eofstr = "";
125 Jflag = nflag = 0;
44bd5ea7 126
e1a085ba
A
127 (void)setlocale(LC_ALL, "");
128
44bd5ea7
A
129 /*
130 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
131 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
132 * that the smallest argument is 2 bytes in length, this means that
133 * the number of arguments is limited to:
134 *
135 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
136 *
137 * We arbitrarily limit the number of arguments to 5000. This is
138 * allowed by POSIX.2 as long as the resulting minimum exec line is
139 * at least LINE_MAX. Realloc'ing as necessary is possible, but
140 * probably not worthwhile.
141 */
142 nargs = 5000;
9bafe280
A
143 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
144 errx(1, "sysconf(_SC_ARG_MAX) failed");
f14763b6
A
145 nline = arg_max - MAXPATHLEN; /* for argv[0] from execvp() */
146 pad9314053 = sizeof(char *); /* reserve for string area rounding */
9bafe280
A
147 while (*ep != NULL) {
148 /* 1 byte for each '\0' */
149 nline -= strlen(*ep++) + 1 + sizeof(*ep);
150 }
f14763b6 151 nline -= pad9314053;
e1a085ba 152 maxprocs = 1;
47d9aef8
A
153 while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
154 switch (ch) {
9bafe280
A
155 case 'E':
156 eofstr = optarg;
157 break;
158 case 'I':
159 Jflag = 0;
160 Iflag = 1;
161 Lflag = 1;
162 replstr = optarg;
163 break;
164 case 'J':
165 Iflag = 0;
166 Jflag = 1;
167 replstr = optarg;
168 break;
169 case 'L':
47d9aef8
A
170 Lflag = strtonum(optarg, 0, INT_MAX, &errstr);
171 if (errstr)
172 errx(1, "-L %s: %s", optarg, errstr);
1a5bac72
A
173 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
174 nflag = 0; /* Override */
175 nargs = 5000;
176 }
44bd5ea7
A
177 break;
178 case 'n':
179 nflag = 1;
ddb4a88b 180 if ((nargs = strtol(optarg, NULL, 10)) <= 0)
e1a085ba 181 errx(1, "illegal argument count");
1a5bac72
A
182 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
183 Lflag = 0; /* Override */
184 }
e1a085ba
A
185 break;
186 case 'o':
187 oflag = 1;
188 break;
189 case 'P':
47d9aef8
A
190 maxprocs = strtonum(optarg, 0, INT_MAX, &errstr);
191 if (errstr)
192 errx(1, "-P %s: %s", optarg, errstr);
193 if (getrlimit(RLIMIT_NPROC, &rl) != 0)
194 errx(1, "getrlimit failed");
195 if (maxprocs == 0 || maxprocs > rl.rlim_cur)
196 maxprocs = rl.rlim_cur;
44bd5ea7 197 break;
9bafe280
A
198 case 'p':
199 pflag = 1;
200 break;
201 case 'R':
e1a085ba
A
202 Rflag = strtol(optarg, &endptr, 10);
203 if (*endptr != '\0')
204 errx(1, "replacements must be a number");
9bafe280 205 break;
47d9aef8
A
206 case 'r':
207 /* GNU compatibility */
208 break;
209 case 'S':
210 Sflag = strtoul(optarg, &endptr, 10);
211 if (*endptr != '\0')
212 errx(1, "replsize must be a number");
213 break;
44bd5ea7 214 case 's':
47d9aef8
A
215 nline = strtonum(optarg, 0, INT_MAX, &errstr);
216 if (errstr)
217 errx(1, "-s %s: %s", optarg, errstr);
f14763b6 218 pad9314053 = 0; /* assume the -s value is valid */
44bd5ea7
A
219 break;
220 case 't':
221 tflag = 1;
222 break;
223 case 'x':
224 xflag = 1;
225 break;
9bafe280
A
226 case '0':
227 zflag = 1;
228 break;
44bd5ea7
A
229 case '?':
230 default:
231 usage();
232 }
233 argc -= optind;
234 argv += optind;
235
9bafe280
A
236 if (!Iflag && Rflag)
237 usage();
47d9aef8
A
238 if (!Iflag && Sflag)
239 usage();
9bafe280
A
240 if (Iflag && !Rflag)
241 Rflag = 5;
47d9aef8
A
242 if (Iflag && !Sflag)
243 Sflag = 255;
44bd5ea7
A
244 if (xflag && !nflag)
245 usage();
9bafe280
A
246 if (Iflag || Lflag)
247 xflag = 1;
248 if (replstr != NULL && *replstr == '\0')
249 errx(1, "replstr may not be empty");
44bd5ea7 250
47d9aef8
A
251 pids_init();
252
44bd5ea7
A
253 /*
254 * Allocate pointers for the utility name, the utility arguments,
255 * the maximum arguments to be read from stdin and the trailing
256 * NULL.
257 */
9bafe280 258 linelen = 1 + argc + nargs + 1;
47d9aef8 259 if ((av = bxp = malloc(linelen * sizeof(char *))) == NULL)
9bafe280 260 errx(1, "malloc failed");
44bd5ea7
A
261
262 /*
263 * Use the user's name for the utility as argv[0], just like the
264 * shell. Echo is the default. Set up pointers for the user's
265 * arguments.
266 */
9bafe280 267 if (*argv == NULL)
f14763b6 268 cnt = strlen(*bxp++ = echo) + pad9314053;
44bd5ea7 269 else {
44bd5ea7 270 do {
9bafe280
A
271 if (Jflag && strcmp(*argv, replstr) == 0) {
272 char **avj;
273 jfound = 1;
274 argv++;
275 for (avj = argv; *avj; avj++)
f14763b6 276 cnt += strlen(*avj) + 1 + pad9314053;
9bafe280
A
277 break;
278 }
f14763b6 279 cnt += strlen(*bxp++ = *argv) + 1 + pad9314053;
9bafe280 280 } while (*++argv != NULL);
44bd5ea7
A
281 }
282
283 /*
284 * Set up begin/end/traversing pointers into the array. The -n
285 * count doesn't include the trailing NULL pointer, so the malloc
286 * added in an extra slot.
287 */
e1a085ba 288 endxp = (xp = bxp) + nargs;
44bd5ea7
A
289
290 /*
291 * Allocate buffer space for the arguments read from stdin and the
292 * trailing NULL. Buffer space is defined as the default or specified
293 * space, minus the length of the utility name and arguments. Set up
294 * begin/end/traversing pointers into the array. The -s count does
295 * include the trailing NULL, so the malloc didn't add in an extra
296 * slot.
297 */
298 nline -= cnt;
299 if (nline <= 0)
300 errx(1, "insufficient space for command");
301
9bafe280
A
302 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
303 errx(1, "malloc failed");
44bd5ea7 304 ebp = (argp = p = bbp) + nline - 1;
9bafe280
A
305 for (;;)
306 parse_input(argc, argv);
307}
44bd5ea7 308
9bafe280
A
309static void
310parse_input(int argc, char *argv[])
311{
312 int ch, foundeof;
313 char **avj;
1a5bac72 314 int last_was_backslashed = 0;
44bd5ea7 315
9bafe280
A
316 foundeof = 0;
317
47d9aef8 318 switch (ch = getchar()) {
9bafe280
A
319 case EOF:
320 /* No arguments since last exec. */
47d9aef8
A
321 if (p == bbp)
322 xexit(*av, rval);
9bafe280
A
323 goto arg1;
324 case ' ':
1a5bac72 325 last_was_blank = 1;
9bafe280
A
326 case '\t':
327 /* Quotes escape tabs and spaces. */
328 if (insingle || indouble || zflag)
329 goto addch;
330 goto arg2;
331 case '\0':
e1a085ba
A
332 if (zflag) {
333 /*
334 * Increment 'count', so that nulls will be treated
335 * as end-of-line, as well as end-of-argument. This
336 * is needed so -0 works properly with -I and -L.
337 */
338 count++;
44bd5ea7 339 goto arg2;
e1a085ba 340 }
9bafe280
A
341 goto addch;
342 case '\n':
e1a085ba
A
343 if (zflag)
344 goto addch;
1a5bac72
A
345 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
346 if (last_was_newline) {
347 /* don't count empty line */
348 break;
349 }
350 if (!last_was_blank ) {
351 /* only count if NOT continuation line */
352 count++;
353 }
354 } else {
355 count++;
356 }
357 last_was_newline = 1;
9bafe280
A
358
359 /* Quotes do not escape newlines. */
47d9aef8
A
360arg1: if (insingle || indouble) {
361 warnx("unterminated quote");
362 xexit(*av, 1);
363 }
9bafe280
A
364arg2:
365 foundeof = *eofstr != '\0' &&
47d9aef8 366 strncmp(argp, eofstr, p - argp) == 0;
9bafe280 367
ddb4a88b
A
368#ifdef __APPLE__
369 /* 6591323: -I specifies that it processes the entire line,
370 * so only recognize eofstr at the end of a line. */
371 if (Iflag && !last_was_newline)
372 foundeof = 0;
373
374 /* 6591323: Essentially the same as the EOF handling above. */
375 if (foundeof && (p - strlen(eofstr) == bbp)) {
376 waitchildren(*argv, 1);
377 exit(rval);
378 }
379#endif
380
9bafe280
A
381 /* Do not make empty args unless they are quoted */
382 if ((argp != p || wasquoted) && !foundeof) {
383 *p++ = '\0';
44bd5ea7 384 *xp++ = argp;
9bafe280
A
385 if (Iflag) {
386 size_t curlen;
44bd5ea7 387
9bafe280
A
388 if (inpline == NULL)
389 curlen = 0;
390 else {
391 /*
392 * If this string is not zero
393 * length, append a space for
e1a085ba 394 * separation before the next
9bafe280
A
395 * argument.
396 */
397 if ((curlen = strlen(inpline)))
398 strcat(inpline, " ");
399 }
400 curlen++;
401 /*
402 * Allocate enough to hold what we will
403 * be holding in a second, and to append
404 * a space next time through, if we have
405 * to.
406 */
407 inpline = realloc(inpline, curlen + 2 +
408 strlen(argp));
47d9aef8
A
409 if (inpline == NULL) {
410 warnx("realloc failed");
411 xexit(*av, 1);
412 }
9bafe280
A
413 if (curlen == 1)
414 strcpy(inpline, argp);
415 else
416 strcat(inpline, argp);
44bd5ea7 417 }
9bafe280 418 }
44bd5ea7 419
9bafe280
A
420 /*
421 * If max'd out on args or buffer, or reached EOF,
422 * run the command. If xflag and max'd out on buffer
423 * but not on args, object. Having reached the limit
424 * of input lines, as specified by -L is the same as
425 * maxing out on arguments.
426 */
f14763b6 427 if (xp == endxp || p + (count * pad9314053) > ebp || ch == EOF ||
9bafe280 428 (Lflag <= count && xflag) || foundeof) {
47d9aef8
A
429 if (xflag && xp != endxp && p + (count * pad9314053) > ebp) {
430 warnx("insufficient space for arguments");
431 xexit(*av, 1);
432 }
9bafe280
A
433 if (jfound) {
434 for (avj = argv; *avj; avj++)
435 *xp++ = *avj;
436 }
437 prerun(argc, av);
47d9aef8
A
438 if (ch == EOF || foundeof)
439 xexit(*av, rval);
9bafe280 440 p = bbp;
44bd5ea7 441 xp = bxp;
9bafe280
A
442 count = 0;
443 }
444 argp = p;
445 wasquoted = 0;
446 break;
447 case '\'':
448 if (indouble || zflag)
449 goto addch;
450 insingle = !insingle;
451 wasquoted = 1;
452 break;
453 case '"':
454 if (insingle || zflag)
455 goto addch;
456 indouble = !indouble;
457 wasquoted = 1;
458 break;
459 case '\\':
1a5bac72 460 last_was_backslashed = 1;
9bafe280
A
461 if (zflag)
462 goto addch;
463 /* Backslash escapes anything, is escaped by quotes. */
47d9aef8
A
464 if (!insingle && !indouble && (ch = getchar()) == EOF) {
465 warnx("backslash at EOF");
466 xexit(*av, 1);
467 }
9bafe280
A
468 /* FALLTHROUGH */
469 default:
470addch: if (p < ebp) {
44bd5ea7
A
471 *p++ = ch;
472 break;
473 }
9bafe280
A
474
475 /* If only one argument, not enough buffer space. */
47d9aef8
A
476 if (bxp == xp) {
477 warnx("insufficient space for argument");
478 xexit(*av, 1);
479 }
9bafe280 480 /* Didn't hit argument limit, so if xflag object. */
47d9aef8
A
481 if (xflag) {
482 warnx("insufficient space for arguments");
483 xexit(*av, 1);
484 }
9bafe280
A
485
486 if (jfound) {
487 for (avj = argv; *avj; avj++)
488 *xp++ = *avj;
489 }
490 prerun(argc, av);
491 xp = bxp;
492 cnt = ebp - argp;
493 memcpy(bbp, argp, (size_t)cnt);
494 p = (argp = bbp) + cnt;
495 *p++ = ch;
496 break;
497 }
1a5bac72
A
498 if (ch != ' ')
499 last_was_blank = 0;
500 if (ch != '\n' || last_was_backslashed)
501 last_was_newline = 0;
44bd5ea7
A
502}
503
9bafe280
A
504/*
505 * Do things necessary before run()'ing, such as -I substitution,
506 * and then call run().
507 */
508static void
509prerun(int argc, char *argv[])
44bd5ea7 510{
9bafe280
A
511 char **tmp, **tmp2, **avj;
512 int repls;
513
514 repls = Rflag;
515
516 if (argc == 0 || repls == 0) {
517 *xp = NULL;
518 run(argv);
519 return;
520 }
521
522 avj = argv;
523
524 /*
525 * Allocate memory to hold the argument list, and
526 * a NULL at the tail.
527 */
47d9aef8
A
528 tmp = malloc((argc + 1) * sizeof(char *));
529 if (tmp == NULL) {
530 warnx("malloc failed");
531 xexit(*argv, 1);
532 }
9bafe280
A
533 tmp2 = tmp;
534
535 /*
536 * Save the first argument and iterate over it, we
537 * cannot do strnsubst() to it.
538 */
47d9aef8
A
539 if ((*tmp++ = strdup(*avj++)) == NULL) {
540 warnx("strdup failed");
541 xexit(*argv, 1);
542 }
9bafe280
A
543
544 /*
545 * For each argument to utility, if we have not used up
546 * the number of replacements we are allowed to do, and
e1a085ba 547 * if the argument contains at least one occurrence of
9bafe280
A
548 * replstr, call strnsubst(), else just save the string.
549 * Iterations over elements of avj and tmp are done
550 * where appropriate.
551 */
552 while (--argc) {
553 *tmp = *avj++;
554 if (repls && strstr(*tmp, replstr) != NULL) {
47d9aef8 555 strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
e1a085ba
A
556 if (repls > 0)
557 repls--;
9bafe280 558 } else {
47d9aef8
A
559 if ((*tmp = strdup(*tmp)) == NULL) {
560 warnx("strdup failed");
561 xexit(*argv, 1);
562 }
9bafe280
A
563 tmp++;
564 }
565 }
566
567 /*
568 * Run it.
569 */
570 *tmp = NULL;
571 run(tmp2);
572
573 /*
574 * Walk from the tail to the head, free along the way.
575 */
576 for (; tmp2 != tmp; tmp--)
577 free(*tmp);
578 /*
579 * Now free the list itself.
580 */
581 free(tmp2);
582
583 /*
584 * Free the input line buffer, if we have one.
585 */
586 if (inpline != NULL) {
587 free(inpline);
588 inpline = NULL;
589 }
590}
591
592static void
593run(char **argv)
594{
44bd5ea7 595 pid_t pid;
e1a085ba
A
596 int fd;
597 char **avec;
44bd5ea7 598
9bafe280
A
599 /*
600 * If the user wants to be notified of each command before it is
601 * executed, notify them. If they want the notification to be
602 * followed by a prompt, then prompt them.
603 */
604 if (tflag || pflag) {
44bd5ea7 605 (void)fprintf(stderr, "%s", *argv);
9bafe280
A
606 for (avec = argv + 1; *avec != NULL; ++avec)
607 (void)fprintf(stderr, " %s", *avec);
608 /*
609 * If the user has asked to be prompted, do so.
610 */
611 if (pflag)
612 /*
613 * If they asked not to exec, return without execution
614 * but if they asked to, go to the execution. If we
615 * could not open their tty, break the switch and drop
616 * back to -t behaviour.
617 */
618 switch (prompt()) {
619 case 0:
620 return;
621 case 1:
622 goto exec;
623 case 2:
624 break;
625 }
44bd5ea7
A
626 (void)fprintf(stderr, "\n");
627 (void)fflush(stderr);
628 }
9bafe280
A
629exec:
630 childerr = 0;
47d9aef8 631 switch (pid = vfork()) {
44bd5ea7 632 case -1:
47d9aef8
A
633 warn("vfork");
634 xexit(*argv, 1);
44bd5ea7 635 case 0:
e1a085ba
A
636 if (oflag) {
637 if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
638 err(1, "can't open /dev/tty");
639 } else {
640 fd = open(_PATH_DEVNULL, O_RDONLY);
641 }
642 if (fd > STDIN_FILENO) {
643 if (dup2(fd, STDIN_FILENO) != 0)
644 err(1, "can't dup2 to stdin");
645 close(fd);
646 }
44bd5ea7 647 execvp(argv[0], argv);
9bafe280 648 childerr = errno;
44bd5ea7
A
649 _exit(1);
650 }
47d9aef8 651 pids_add(pid);
e1a085ba
A
652 waitchildren(*argv, 0);
653}
654
47d9aef8
A
655/*
656 * Wait for a tracked child to exit and return its pid and exit status.
657 *
658 * Ignores (discards) all untracked child processes.
659 * Returns -1 and sets errno to ECHILD if no tracked children exist.
660 * If block is set, waits indefinitely for a child process to exit.
661 * If block is not set and no children have exited, returns 0 immediately.
662 */
663static pid_t
664xwait(int block, int *status) {
665 pid_t pid;
666
667 if (pids_empty()) {
668 errno = ECHILD;
669 return (-1);
670 }
671
672 while ((pid = waitpid(-1, status, block ? 0 : WNOHANG)) > 0)
673 if (pids_remove(pid))
674 break;
675
676 return (pid);
677}
678
679static void
680xexit(const char *name, const int exit_code) {
681 waitchildren(name, 1);
682 exit(exit_code);
683}
684
e1a085ba
A
685static void
686waitchildren(const char *name, int waitall)
687{
688 pid_t pid;
689 int status;
47d9aef8 690 int cause_exit = 0;
e1a085ba 691
47d9aef8 692 while ((pid = xwait(waitall || pids_full(), &status)) > 0) {
e1a085ba 693 /*
47d9aef8
A
694 * If we couldn't invoke the utility or if utility exited
695 * because of a signal or with a value of 255, warn (per
696 * POSIX), and then wait until all other children have
697 * exited before exiting 1-125. POSIX requires us to stop
698 * reading if child exits because of a signal or with 255,
699 * but it does not require us to exit immediately; waiting
700 * is preferable to orphaning.
e1a085ba 701 */
47d9aef8
A
702 if (childerr != 0 && cause_exit == 0) {
703 errno = childerr;
704 waitall = 1;
705 cause_exit = errno == ENOENT ? 127 : 126;
706 warn("%s", name);
707 } else if (WIFSIGNALED(status)) {
708 waitall = cause_exit = 1;
709 warnx("%s: terminated with signal %d; aborting",
710 name, WTERMSIG(status));
711 } else if (WEXITSTATUS(status) == 255) {
712 waitall = cause_exit = 1;
713 warnx("%s: exited with status 255; aborting", name);
714 } else if (WEXITSTATUS(status))
715 rval = 1;
e1a085ba 716 }
47d9aef8
A
717
718 if (cause_exit)
719 exit(cause_exit);
e1a085ba 720 if (pid == -1 && errno != ECHILD)
47d9aef8
A
721 err(1, "waitpid");
722}
723
724#define NOPID (0)
725
726static void
727pids_init(void)
728{
729 int i;
730
731 if ((childpids = malloc(maxprocs * sizeof(*childpids))) == NULL)
732 errx(1, "malloc failed");
733
734 for (i = 0; i < maxprocs; i++)
735 clearslot(i);
736}
737
738static int
739pids_empty(void)
740{
741
742 return (curprocs == 0);
743}
744
745static int
746pids_full(void)
747{
748
749 return (curprocs >= maxprocs);
750}
751
752static void
753pids_add(pid_t pid)
754{
755 int slot;
756
757 slot = findfreeslot();
758 childpids[slot] = pid;
759 curprocs++;
760}
761
762static int
763pids_remove(pid_t pid)
764{
765 int slot;
766
767 if ((slot = findslot(pid)) < 0)
768 return (0);
769
770 clearslot(slot);
771 curprocs--;
772 return (1);
773}
774
775static int
776findfreeslot(void)
777{
778 int slot;
779
780 if ((slot = findslot(NOPID)) < 0)
781 errx(1, "internal error: no free pid slot");
782 return (slot);
783}
784
785static int
786findslot(pid_t pid)
787{
788 int slot;
789
790 for (slot = 0; slot < maxprocs; slot++)
791 if (childpids[slot] == pid)
792 return (slot);
793 return (-1);
794}
795
796static void
797clearslot(int slot)
798{
799
800 childpids[slot] = NOPID;
9bafe280 801}
44bd5ea7 802
9bafe280
A
803/*
804 * Prompt the user about running a command.
805 */
806static int
807prompt(void)
808{
809 regex_t cre;
810 size_t rsize;
811 int match;
812 char *response;
813 FILE *ttyfp;
44bd5ea7 814
9bafe280
A
815 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
816 return (2); /* Indicate that the TTY failed to open. */
817 (void)fprintf(stderr, "?...");
818 (void)fflush(stderr);
819 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
e1a085ba 820 regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
9bafe280
A
821 (void)fclose(ttyfp);
822 return (0);
44bd5ea7 823 }
47d9aef8 824 response[rsize - 1] = '\0';
9bafe280
A
825 match = regexec(&cre, response, 0, NULL, 0);
826 (void)fclose(ttyfp);
827 regfree(&cre);
828 return (match == 0);
44bd5ea7
A
829}
830
9bafe280
A
831static void
832usage(void)
44bd5ea7 833{
47d9aef8 834
9bafe280 835 fprintf(stderr,
47d9aef8
A
836"usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
837" [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
838" [-s size] [utility [argument ...]]\n");
44bd5ea7
A
839 exit(1);
840}