Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.106.2.2
      1 /*	$NetBSD: jobs.c,v 1.106.2.2 2021/04/28 09:58:42 martin Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 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  * Kenneth Almquist.
      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.
     18  * 3. Neither the name of the University nor the names of its contributors
     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.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
     39 #else
     40 __RCSID("$NetBSD: jobs.c,v 1.106.2.2 2021/04/28 09:58:42 martin Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <stdio.h>
     45 #include <fcntl.h>
     46 #include <signal.h>
     47 #include <errno.h>
     48 #include <unistd.h>
     49 #include <stdlib.h>
     50 #include <paths.h>
     51 #include <sys/types.h>
     52 #include <sys/param.h>
     53 #ifdef BSD
     54 #include <sys/wait.h>
     55 #include <sys/time.h>
     56 #include <sys/resource.h>
     57 #endif
     58 #include <sys/ioctl.h>
     59 
     60 #include "shell.h"
     61 #if JOBS
     62 #if OLD_TTY_DRIVER
     63 #include "sgtty.h"
     64 #else
     65 #include <termios.h>
     66 #endif
     67 #undef CEOF			/* syntax.h redefines this */
     68 #endif
     69 #include "redir.h"
     70 #include "show.h"
     71 #include "main.h"
     72 #include "parser.h"
     73 #include "nodes.h"
     74 #include "jobs.h"
     75 #include "var.h"
     76 #include "options.h"
     77 #include "builtins.h"
     78 #include "trap.h"
     79 #include "syntax.h"
     80 #include "input.h"
     81 #include "output.h"
     82 #include "memalloc.h"
     83 #include "error.h"
     84 #include "mystring.h"
     85 
     86 
     87 #ifndef	WCONTINUED
     88 #define	WCONTINUED 0		/* So we can compile on old systems */
     89 #endif
     90 #ifndef	WIFCONTINUED
     91 #define	WIFCONTINUED(x)	(0)		/* ditto */
     92 #endif
     93 
     94 
     95 static struct job *jobtab;		/* array of jobs */
     96 static int njobs;			/* size of array */
     97 static int jobs_invalid;		/* set in child */
     98 MKINIT pid_t backgndpid = -1;	/* pid of last background process */
     99 #if JOBS
    100 int initialpgrp;		/* pgrp of shell on invocation */
    101 static int curjob = -1;		/* current job */
    102 #endif
    103 static int ttyfd = -1;
    104 
    105 STATIC void restartjob(struct job *);
    106 STATIC void freejob(struct job *);
    107 STATIC struct job *getjob(const char *, int);
    108 STATIC int dowait(int, struct job *, struct job **);
    109 #define WBLOCK	1
    110 #define WNOFREE 2
    111 #define WSILENT 4
    112 STATIC int jobstatus(const struct job *, int);
    113 STATIC int waitproc(int, struct job *, int *);
    114 STATIC void cmdtxt(union node *);
    115 STATIC void cmdlist(union node *, int);
    116 STATIC void cmdputs(const char *);
    117 inline static void cmdputi(int);
    118 
    119 #ifdef SYSV
    120 STATIC int onsigchild(void);
    121 #endif
    122 
    123 #ifdef OLD_TTY_DRIVER
    124 static pid_t tcgetpgrp(int fd);
    125 static int tcsetpgrp(int fd, pid_t pgrp);
    126 
    127 static pid_t
    128 tcgetpgrp(int fd)
    129 {
    130 	pid_t pgrp;
    131 	if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
    132 		return -1;
    133 	else
    134 		return pgrp;
    135 }
    136 
    137 static int
    138 tcsetpgrp(int fd, pid_tpgrp)
    139 {
    140 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
    141 }
    142 #endif
    143 
    144 static void
    145 ttyfd_change(int from, int to)
    146 {
    147 	if (ttyfd == from)
    148 		ttyfd = to;
    149 }
    150 
    151 /*
    152  * Turn job control on and off.
    153  *
    154  * Note:  This code assumes that the third arg to ioctl is a character
    155  * pointer, which is true on Berkeley systems but not System V.  Since
    156  * System V doesn't have job control yet, this isn't a problem now.
    157  */
    158 
    159 MKINIT int jobctl;
    160 
    161 void
    162 setjobctl(int on)
    163 {
    164 #ifdef OLD_TTY_DRIVER
    165 	int ldisc;
    166 #endif
    167 
    168 	if (on == jobctl || rootshell == 0)
    169 		return;
    170 	if (on) {
    171 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
    172 		int i;
    173 
    174 		if (ttyfd != -1)
    175 			sh_close(ttyfd);
    176 		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
    177 			for (i = 0; i < 3; i++) {
    178 				if (isatty(i) && (ttyfd = dup(i)) != -1)
    179 					break;
    180 			}
    181 			if (i == 3)
    182 				goto out;
    183 		}
    184 		ttyfd = to_upper_fd(ttyfd);	/* Move to a high fd */
    185 		register_sh_fd(ttyfd, ttyfd_change);
    186 #else
    187 		out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
    188 		goto out;
    189 #endif
    190 		do { /* while we are in the background */
    191 			if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
    192  out:
    193 				out2str("sh: can't access tty; job control turned off\n");
    194 				mflag = 0;
    195 				return;
    196 			}
    197 			if (initialpgrp == -1)
    198 				initialpgrp = getpgrp();
    199 			else if (initialpgrp != getpgrp()) {
    200 				killpg(0, SIGTTIN);
    201 				continue;
    202 			}
    203 		} while (0);
    204 
    205 #ifdef OLD_TTY_DRIVER
    206 		if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
    207 		    || ldisc != NTTYDISC) {
    208 			out2str("sh: need new tty driver to run job control; job control turned off\n");
    209 			mflag = 0;
    210 			return;
    211 		}
    212 #endif
    213 		setsignal(SIGTSTP, 0);
    214 		setsignal(SIGTTOU, 0);
    215 		setsignal(SIGTTIN, 0);
    216 		if (getpgrp() != rootpid && setpgid(0, rootpid) == -1)
    217 			error("Cannot set process group (%s) at %d",
    218 			    strerror(errno), __LINE__);
    219 		if (tcsetpgrp(ttyfd, rootpid) == -1)
    220 			error("Cannot set tty process group (%s) at %d",
    221 			    strerror(errno), __LINE__);
    222 	} else { /* turning job control off */
    223 		if (getpgrp() != initialpgrp && setpgid(0, initialpgrp) == -1)
    224 			error("Cannot set process group (%s) at %d",
    225 			    strerror(errno), __LINE__);
    226 		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
    227 			error("Cannot set tty process group (%s) at %d",
    228 			    strerror(errno), __LINE__);
    229 		sh_close(ttyfd);
    230 		ttyfd = -1;
    231 		setsignal(SIGTSTP, 0);
    232 		setsignal(SIGTTOU, 0);
    233 		setsignal(SIGTTIN, 0);
    234 	}
    235 	jobctl = on;
    236 }
    237 
    238 
    239 #ifdef mkinit
    240 INCLUDE <stdlib.h>
    241 
    242 SHELLPROC {
    243 	backgndpid = -1;
    244 #if JOBS
    245 	jobctl = 0;
    246 #endif
    247 }
    248 
    249 #endif
    250 
    251 
    252 
    253 #if JOBS
    254 static int
    255 do_fgcmd(const char *arg_ptr)
    256 {
    257 	struct job *jp;
    258 	int i;
    259 	int status;
    260 
    261 	if (jobs_invalid)
    262 		error("No current jobs");
    263 	jp = getjob(arg_ptr, 0);
    264 	if (jp->jobctl == 0)
    265 		error("job not created under job control");
    266 	out1fmt("%s", jp->ps[0].cmd);
    267 	for (i = 1; i < jp->nprocs; i++)
    268 		out1fmt(" | %s", jp->ps[i].cmd );
    269 	out1c('\n');
    270 	flushall();
    271 
    272 	for (i = 0; i < jp->nprocs; i++)
    273 	    if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
    274 		    break;
    275 
    276 	if (i >= jp->nprocs) {
    277 		error("Cannot set tty process group (%s) at %d",
    278 		    strerror(errno), __LINE__);
    279 	}
    280 	INTOFF;
    281 	restartjob(jp);
    282 	status = waitforjob(jp);
    283 	INTON;
    284 	return status;
    285 }
    286 
    287 int
    288 fgcmd(int argc, char **argv)
    289 {
    290 	nextopt("");
    291 	return do_fgcmd(*argptr);
    292 }
    293 
    294 int
    295 fgcmd_percent(int argc, char **argv)
    296 {
    297 	nextopt("");
    298 	return do_fgcmd(*argv);
    299 }
    300 
    301 static void
    302 set_curjob(struct job *jp, int mode)
    303 {
    304 	struct job *jp1, *jp2;
    305 	int i, ji;
    306 
    307 	ji = jp - jobtab;
    308 
    309 	/* first remove from list */
    310 	if (ji == curjob)
    311 		curjob = jp->prev_job;
    312 	else {
    313 		for (i = 0; i < njobs; i++) {
    314 			if (jobtab[i].prev_job != ji)
    315 				continue;
    316 			jobtab[i].prev_job = jp->prev_job;
    317 			break;
    318 		}
    319 	}
    320 
    321 	/* Then re-insert in correct position */
    322 	switch (mode) {
    323 	case 0:	/* job being deleted */
    324 		jp->prev_job = -1;
    325 		break;
    326 	case 1:	/* newly created job or backgrounded job,
    327 		   put after all stopped jobs. */
    328 		if (curjob != -1 && jobtab[curjob].state == JOBSTOPPED) {
    329 			for (jp1 = jobtab + curjob; ; jp1 = jp2) {
    330 				if (jp1->prev_job == -1)
    331 					break;
    332 				jp2 = jobtab + jp1->prev_job;
    333 				if (jp2->state != JOBSTOPPED)
    334 					break;
    335 			}
    336 			jp->prev_job = jp1->prev_job;
    337 			jp1->prev_job = ji;
    338 			break;
    339 		}
    340 		/* FALLTHROUGH */
    341 	case 2:	/* newly stopped job - becomes curjob */
    342 		jp->prev_job = curjob;
    343 		curjob = ji;
    344 		break;
    345 	}
    346 }
    347 
    348 int
    349 bgcmd(int argc, char **argv)
    350 {
    351 	struct job *jp;
    352 	int i;
    353 
    354 	nextopt("");
    355 	if (jobs_invalid)
    356 		error("No current jobs");
    357 	do {
    358 		jp = getjob(*argptr, 0);
    359 		if (jp->jobctl == 0)
    360 			error("job not created under job control");
    361 		set_curjob(jp, 1);
    362 		out1fmt("[%ld] %s", (long)(jp - jobtab + 1), jp->ps[0].cmd);
    363 		for (i = 1; i < jp->nprocs; i++)
    364 			out1fmt(" | %s", jp->ps[i].cmd );
    365 		out1c('\n');
    366 		flushall();
    367 		restartjob(jp);
    368 	} while (*argptr && *++argptr);
    369 	return 0;
    370 }
    371 
    372 
    373 STATIC void
    374 restartjob(struct job *jp)
    375 {
    376 	struct procstat *ps;
    377 	int i, e;
    378 
    379 	if (jp->state == JOBDONE)
    380 		return;
    381 	INTOFF;
    382 	for (e = i = 0; i < jp->nprocs; i++) {
    383 		if (killpg(jp->ps[i].pid, SIGCONT) != -1)
    384 			break;
    385 		if (e == 0 && errno != ESRCH)
    386 			e = errno;
    387 	}
    388 	if (i >= jp->nprocs)
    389 		error("Cannot continue job (%s)", strerror(e ? e : ESRCH));
    390 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
    391 		if (WIFSTOPPED(ps->status)) {
    392 			VTRACE(DBG_JOBS, (
    393 			   "restartjob: [%zu] pid %d status change"
    394 			   " from %#x (stopped) to -1 (running)\n",
    395 			   (size_t)(jp-jobtab+1), ps->pid, ps->status));
    396 			ps->status = -1;
    397 			jp->state = JOBRUNNING;
    398 		}
    399 	}
    400 	INTON;
    401 }
    402 #endif
    403 
    404 inline static void
    405 cmdputi(int n)
    406 {
    407 	char str[20];
    408 
    409 	fmtstr(str, sizeof str, "%d", n);
    410 	cmdputs(str);
    411 }
    412 
    413 static void
    414 showjob(struct output *out, struct job *jp, int mode)
    415 {
    416 	int procno;
    417 	int st;
    418 	struct procstat *ps;
    419 	int col;
    420 	char s[64];
    421 
    422 #if JOBS
    423 	if (mode & SHOW_PGID) {
    424 		/* just output process (group) id of pipeline */
    425 		outfmt(out, "%ld\n", (long)jp->ps->pid);
    426 		return;
    427 	}
    428 #endif
    429 
    430 	procno = jp->nprocs;
    431 	if (!procno)
    432 		return;
    433 
    434 	if (mode & SHOW_PID)
    435 		mode |= SHOW_MULTILINE;
    436 
    437 	if ((procno > 1 && !(mode & SHOW_MULTILINE))
    438 	    || (mode & SHOW_SIGNALLED)) {
    439 		/* See if we have more than one status to report */
    440 		ps = jp->ps;
    441 		st = ps->status;
    442 		do {
    443 			int st1 = ps->status;
    444 			if (st1 != st)
    445 				/* yes - need multi-line output */
    446 				mode |= SHOW_MULTILINE;
    447 			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
    448 				continue;
    449 			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
    450 			    && st1 != SIGINT && st1 != SIGPIPE))
    451 				mode |= SHOW_ISSIG;
    452 
    453 		} while (ps++, --procno);
    454 		procno = jp->nprocs;
    455 	}
    456 
    457 	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
    458 		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
    459 			VTRACE(DBG_JOBS, ("showjob: freeing job %d\n",
    460 			    jp - jobtab + 1));
    461 			freejob(jp);
    462 		}
    463 		return;
    464 	}
    465 
    466 	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
    467 		if (ps == jp->ps)
    468 			fmtstr(s, 16, "[%ld] %c ",
    469 				(long)(jp - jobtab + 1),
    470 #if JOBS
    471 				jp - jobtab == curjob ?
    472 									  '+' :
    473 				curjob != -1 &&
    474 				    jp - jobtab == jobtab[curjob].prev_job ?
    475 									  '-' :
    476 #endif
    477 				' ');
    478 		else
    479 			fmtstr(s, 16, "      " );
    480 		col = strlen(s);
    481 		if (mode & SHOW_PID) {
    482 			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
    483 			     col += strlen(s + col);
    484 		}
    485 		if (ps->status == -1) {
    486 			scopy("Running", s + col);
    487 		} else if (WIFEXITED(ps->status)) {
    488 			st = WEXITSTATUS(ps->status);
    489 			if (st)
    490 				fmtstr(s + col, 16, "Done(%d)", st);
    491 			else
    492 				fmtstr(s + col, 16, "Done");
    493 		} else {
    494 #if JOBS
    495 			if (WIFSTOPPED(ps->status))
    496 				st = WSTOPSIG(ps->status);
    497 			else /* WIFSIGNALED(ps->status) */
    498 #endif
    499 				st = WTERMSIG(ps->status);
    500 			scopyn(strsignal(st), s + col, 32);
    501 			if (WCOREDUMP(ps->status)) {
    502 				col += strlen(s + col);
    503 				scopyn(" (core dumped)", s + col,  64 - col);
    504 			}
    505 		}
    506 		col += strlen(s + col);
    507 		outstr(s, out);
    508 		do {
    509 			outc(' ', out);
    510 			col++;
    511 		} while (col < 30);
    512 		outstr(ps->cmd, out);
    513 		if (mode & SHOW_MULTILINE) {
    514 			if (procno > 0) {
    515 				outc(' ', out);
    516 				outc('|', out);
    517 			}
    518 		} else {
    519 			while (--procno >= 0)
    520 				outfmt(out, " | %s", (++ps)->cmd );
    521 		}
    522 		outc('\n', out);
    523 	}
    524 	flushout(out);
    525 	jp->flags &= ~JOBCHANGED;
    526 	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
    527 		freejob(jp);
    528 }
    529 
    530 int
    531 jobscmd(int argc, char **argv)
    532 {
    533 	int mode, m;
    534 
    535 	mode = 0;
    536 	while ((m = nextopt("lp")))
    537 		if (m == 'l')
    538 			mode = SHOW_PID;
    539 		else
    540 			mode = SHOW_PGID;
    541 
    542 	if (!iflag && !posix)
    543 		mode |= SHOW_NO_FREE;
    544 
    545 	if (*argptr) {
    546 		do
    547 			showjob(out1, getjob(*argptr,0), mode);
    548 		while (*++argptr);
    549 	} else
    550 		showjobs(out1, mode);
    551 	return 0;
    552 }
    553 
    554 
    555 /*
    556  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
    557  * statuses have changed since the last call to showjobs.
    558  *
    559  * If the shell is interrupted in the process of creating a job, the
    560  * result may be a job structure containing zero processes.  Such structures
    561  * will be freed here.
    562  */
    563 
    564 void
    565 showjobs(struct output *out, int mode)
    566 {
    567 	int jobno;
    568 	struct job *jp;
    569 	int silent = 0, gotpid;
    570 
    571 	CTRACE(DBG_JOBS, ("showjobs(%x) called\n", mode));
    572 
    573 	/* If not even one one job changed, there is nothing to do */
    574 	gotpid = dowait(WSILENT, NULL, NULL);
    575 	while (dowait(WSILENT, NULL, NULL) > 0)
    576 		continue;
    577 #ifdef JOBS
    578 	/*
    579 	 * Check if we are not in our foreground group, and if not
    580 	 * put us in it.
    581 	 */
    582 	if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
    583 		if (tcsetpgrp(ttyfd, getpid()) == -1)
    584 			error("Cannot set tty process group (%s) at %d",
    585 			    strerror(errno), __LINE__);
    586 		VTRACE(DBG_JOBS|DBG_INPUT, ("repaired tty process group\n"));
    587 		silent = 1;
    588 	}
    589 #endif
    590 
    591 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
    592 		if (!jp->used)
    593 			continue;
    594 		if (jp->nprocs == 0) {
    595 			if (!jobs_invalid)
    596 				freejob(jp);
    597 			continue;
    598 		}
    599 		if ((mode & SHOW_CHANGED) && !(jp->flags & JOBCHANGED))
    600 			continue;
    601 		if (silent && (jp->flags & JOBCHANGED)) {
    602 			jp->flags &= ~JOBCHANGED;
    603 			continue;
    604 		}
    605 		showjob(out, jp, mode);
    606 	}
    607 }
    608 
    609 /*
    610  * Mark a job structure as unused.
    611  */
    612 
    613 STATIC void
    614 freejob(struct job *jp)
    615 {
    616 	INTOFF;
    617 	if (jp->ps != &jp->ps0) {
    618 		ckfree(jp->ps);
    619 		jp->ps = &jp->ps0;
    620 	}
    621 	jp->nprocs = 0;
    622 	jp->used = 0;
    623 #if JOBS
    624 	set_curjob(jp, 0);
    625 #endif
    626 	INTON;
    627 }
    628 
    629 /*
    630  * Extract the status of a completed job (for $?)
    631  */
    632 STATIC int
    633 jobstatus(const struct job *jp, int raw)
    634 {
    635 	int status = 0;
    636 	int retval;
    637 
    638 	if ((jp->flags & JPIPEFAIL) && jp->nprocs) {
    639 		int i;
    640 
    641 		for (i = 0; i < jp->nprocs; i++)
    642 			if (jp->ps[i].status != 0)
    643 				status = jp->ps[i].status;
    644 	} else
    645 		status = jp->ps[jp->nprocs ? jp->nprocs - 1 : 0].status;
    646 
    647 	if (raw)
    648 		return status;
    649 
    650 	if (WIFEXITED(status))
    651 		retval = WEXITSTATUS(status);
    652 #if JOBS
    653 	else if (WIFSTOPPED(status))
    654 		retval = WSTOPSIG(status) + 128;
    655 #endif
    656 	else {
    657 		/* XXX: limits number of signals */
    658 		retval = WTERMSIG(status) + 128;
    659 	}
    660 
    661 	return retval;
    662 }
    663 
    664 
    665 
    666 int
    667 waitcmd(int argc, char **argv)
    668 {
    669 	struct job *job, *last;
    670 	int retval;
    671 	struct job *jp;
    672 	int i;
    673 	int any = 0;
    674 	int found;
    675 	char *pid = NULL, *fpid;
    676 	char **arg;
    677 	char idstring[20];
    678 
    679 	while ((i = nextopt("np:")) != '\0') {
    680 		switch (i) {
    681 		case 'n':
    682 			any = 1;
    683 			break;
    684 		case 'p':
    685 			if (pid)
    686 				error("more than one -p unsupported");
    687 			pid = optionarg;
    688 			break;
    689 		}
    690 	}
    691 
    692 	if (pid != NULL) {
    693 		if (!validname(pid, '\0', NULL))
    694 			error("invalid name: -p '%s'", pid);
    695 		if (unsetvar(pid, 0))
    696 			error("%s readonly", pid);
    697 	}
    698 
    699 	/*
    700 	 * If we have forked, and not yet created any new jobs, then
    701 	 * we have no children, whatever jobtab claims,
    702 	 * so simply return in that case.
    703 	 *
    704 	 * The return code is 127 if we had any pid args (none are found)
    705 	 * or if we had -n (nothing exited), but 0 for plain old "wait".
    706 	 */
    707 	if (jobs_invalid) {
    708 		CTRACE(DBG_WAIT, ("builtin wait%s%s in child, invalid jobtab\n",
    709 		    any ? " -n" : "", *argptr ? " pid..." : ""));
    710 		return (any || *argptr) ? 127 : 0;
    711 	}
    712 
    713 	/*
    714 	 * clear stray flags left from previous waitcmd
    715 	 * or set them instead if anything will do ("wait -n")
    716 	 */
    717 	for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    718 		if (any && *argptr == NULL)
    719 			jp->flags |= JOBWANTED;
    720 		else
    721 			jp->flags &= ~JOBWANTED;
    722 		jp->ref = NULL;
    723 	}
    724 
    725 	CTRACE(DBG_WAIT,
    726 	    ("builtin wait%s%s\n", any ? " -n" : "", *argptr ? " pid..." : ""));
    727 
    728 	/*
    729 	 * First, validate the jobnum args, count how many refer to
    730 	 * (different) running jobs, and if we had -n, and found that one has
    731 	 * already finished, we return that one.   Otherwise remember
    732 	 * which ones we are looking for (JOBWANTED).
    733 	 */
    734 	found = 0;
    735 	last = NULL;
    736 	for (arg = argptr; *arg; arg++) {
    737 		last = jp = getjob(*arg, 1);
    738 		if (!jp)
    739 			continue;
    740 		if (jp->ref == NULL)
    741 			jp->ref = *arg;
    742 		if (any && jp->state == JOBDONE) {
    743 			/*
    744 			 * We just want any of them, and this one is
    745 			 * ready for consumption, bon apetit ...
    746 			 */
    747 			retval = jobstatus(jp, 0);
    748 			if (pid)
    749 				setvar(pid, *arg, 0);
    750 			if (!iflag)
    751 				freejob(jp);
    752 			CTRACE(DBG_WAIT, ("wait -n found %s already done: %d\n",			    *arg, retval));
    753 			return retval;
    754 		}
    755 		if (!(jp->flags & JOBWANTED)) {
    756 			/*
    757 			 * It is possible to list the same job several
    758 			 * times - the obvious "wait 1 1 1" or
    759 			 * "wait %% %2 102" where job 2 is current and pid 102
    760 			 * However many times it is requested, it is found once.
    761 			 */
    762 			found++;
    763 			jp->flags |= JOBWANTED;
    764 		}
    765 		job = jp;
    766 	}
    767 
    768 	VTRACE(DBG_WAIT, ("wait %s%s%sfound %d candidates (last %s)\n",
    769 	    any ? "-n " : "", *argptr ? *argptr : "",
    770 	    argptr[0] && argptr[1] ? "... " : " ", found,
    771 	    job && job->used ? (job->ref ? job->ref : "<no-arg>") : "none"));
    772 
    773 	/*
    774 	 * If we were given a list of jobnums:
    775 	 * and none of those exist, then we're done.
    776 	 */
    777 	if (*argptr && found == 0)
    778 		return 127;
    779 
    780 	/*
    781 	 * Otherwise we need to wait for something to complete
    782 	 * When it does, we check and see if it is one of the
    783 	 * jobs we're waiting on, and if so, we clean it up.
    784 	 * If we had -n, then we're done, otherwise we do it all again
    785 	 * until all we had listed are done, of if there were no
    786 	 * jobnum args, all are done.
    787 	 */
    788 
    789 	retval = any || *argptr ? 127 : 0;
    790 	fpid = NULL;
    791 	for (;;) {
    792 		VTRACE(DBG_WAIT, ("wait waiting (%d remain): ", found));
    793 		job = NULL;
    794 		for (jp = jobtab, i = njobs; --i >= 0; jp++) {
    795 			if (jp->used && jp->flags & JOBWANTED &&
    796 			    jp->state == JOBDONE) {
    797 				job = jp;
    798 				break;
    799 			}
    800 			if (jp->used && jp->state == JOBRUNNING)
    801 				job = jp;
    802 		}
    803 		if (i < 0 && job == NULL) {
    804 			CTRACE(DBG_WAIT, ("nothing running (ret: %d) fpid %s\n",
    805 			    retval, fpid ? fpid : "unset"));
    806 			if (pid && fpid)
    807 				setvar(pid, fpid, 0);
    808 			return retval;
    809 		}
    810 		jp = job;
    811 		VTRACE(DBG_WAIT, ("found @%d/%d state: %d\n", njobs-i, njobs,
    812 		    jp->state));
    813 
    814 		/*
    815 		 * There is at least 1 job running, so we can
    816 		 * safely wait() for something to exit.
    817 		 */
    818 		if (jp->state == JOBRUNNING) {
    819 			job = NULL;
    820 			if ((i = dowait(WBLOCK|WNOFREE, NULL, &job)) == -1)
    821 			       return 128 + lastsig();
    822 
    823 			if (job == NULL)	/* an interloper */
    824 				continue;
    825 
    826 			/*
    827 			 * one of the job's processes exited,
    828 			 * but there are more
    829 			 */
    830 			if (job->state == JOBRUNNING)
    831 				continue;
    832 		} else
    833 			job = jp;	/* we want this, and it is done */
    834 
    835 		if (job->flags & JOBWANTED) {
    836 			int rv;
    837 
    838 			job->flags &= ~JOBWANTED;	/* got it */
    839 			rv = jobstatus(job, 0);
    840 			VTRACE(DBG_WAIT, (
    841 			    "wanted %d (%s) done: st=%d", i,
    842 			    job->ref ? job->ref : "", rv));
    843 			if (any || job == last) {
    844 				retval = rv;
    845 				fpid = job->ref;
    846 
    847 				VTRACE(DBG_WAIT, (" save"));
    848 				if (pid) {
    849 				   /*
    850 				    * don't need fpid unless we are going
    851 				    * to return it.
    852 				    */
    853 				   if (fpid == NULL) {
    854 					/*
    855 					 * this only happens with "wait -n"
    856 					 * (that is, no pid args)
    857 					 */
    858 					snprintf(idstring, sizeof idstring,
    859 					    "%d", job->ps[ job->nprocs ?
    860 						    job->nprocs-1 :
    861 						    0 ].pid);
    862 					fpid = idstring;
    863 				    }
    864 				    VTRACE(DBG_WAIT, (" (for %s)", fpid));
    865 				}
    866 			}
    867 
    868 			if (job->state == JOBDONE) {
    869 				VTRACE(DBG_WAIT, (" free"));
    870 				freejob(job);
    871 			}
    872 
    873 			if (any || (found > 0 && --found == 0)) {
    874 				if (pid && fpid)
    875 					setvar(pid, fpid, 0);
    876 				VTRACE(DBG_WAIT, (" return %d\n", retval));
    877 				return retval;
    878 			}
    879 			VTRACE(DBG_WAIT, ("\n"));
    880 			continue;
    881 		}
    882 
    883 		/* this is to handle "wait" (no args) */
    884 		if (found == 0 && job->state == JOBDONE) {
    885 			VTRACE(DBG_JOBS|DBG_WAIT, ("Cleanup: %d\n", i));
    886 			freejob(job);
    887 		}
    888 	}
    889 }
    890 
    891 
    892 int
    893 jobidcmd(int argc, char **argv)
    894 {
    895 	struct job *jp;
    896 	int i;
    897 	int pg = 0, onep = 0, job = 0;
    898 
    899 	while ((i = nextopt("gjp"))) {
    900 		switch (i) {
    901 		case 'g':	pg = 1;		break;
    902 		case 'j':	job = 1;	break;
    903 		case 'p':	onep = 1;	break;
    904 		}
    905 	}
    906 	CTRACE(DBG_JOBS, ("jobidcmd%s%s%s%s %s\n", pg ? " -g" : "",
    907 	    onep ? " -p" : "", job ? " -j" : "", jobs_invalid ? " [inv]" : "",
    908 	    *argptr ? *argptr : "<implicit %%>"));
    909 	if (pg + onep + job > 1)
    910 		error("-g -j and -p options cannot be combined");
    911 
    912 	if (argptr[0] && argptr[1])
    913 		error("usage: jobid [-g|-p|-r] jobid");
    914 
    915 	jp = getjob(*argptr, 0);
    916 	if (job) {
    917 		out1fmt("%%%zu\n", (size_t)(jp - jobtab + 1));
    918 		return 0;
    919 	}
    920 	if (pg) {
    921 		if (jp->pgrp != 0) {
    922 			out1fmt("%ld\n", (long)jp->pgrp);
    923 			return 0;
    924 		}
    925 		return 1;
    926 	}
    927 	if (onep) {
    928 		i = jp->nprocs - 1;
    929 		if (i < 0)
    930 			return 1;
    931 		out1fmt("%ld\n", (long)jp->ps[i].pid);
    932 		return 0;
    933 	}
    934 	for (i = 0 ; i < jp->nprocs ; ) {
    935 		out1fmt("%ld", (long)jp->ps[i].pid);
    936 		out1c(++i < jp->nprocs ? ' ' : '\n');
    937 	}
    938 	return 0;
    939 }
    940 
    941 int
    942 getjobpgrp(const char *name)
    943 {
    944 	struct job *jp;
    945 
    946 	if (jobs_invalid)
    947 		error("No such job: %s", name);
    948 	jp = getjob(name, 1);
    949 	if (jp == 0)
    950 		return 0;
    951 	return -jp->ps[0].pid;
    952 }
    953 
    954 /*
    955  * Convert a job name to a job structure.
    956  */
    957 
    958 STATIC struct job *
    959 getjob(const char *name, int noerror)
    960 {
    961 	int jobno = -1;
    962 	struct job *jp;
    963 	int pid;
    964 	int i;
    965 	const char *err_msg = "No such job: %s";
    966 
    967 	if (name == NULL) {
    968 #if JOBS
    969 		jobno = curjob;
    970 #endif
    971 		err_msg = "No current job";
    972 	} else if (name[0] == '%') {
    973 		if (is_number(name + 1)) {
    974 			jobno = number(name + 1) - 1;
    975 		} else if (!name[1] || !name[2]) {
    976 			switch (name[1]) {
    977 #if JOBS
    978 			case 0:
    979 			case '+':
    980 			case '%':
    981 				jobno = curjob;
    982 				err_msg = "No current job";
    983 				break;
    984 			case '-':
    985 				jobno = curjob;
    986 				if (jobno != -1)
    987 					jobno = jobtab[jobno].prev_job;
    988 				err_msg = "No previous job";
    989 				break;
    990 #endif
    991 			default:
    992 				goto check_pattern;
    993 			}
    994 		} else {
    995 			struct job *found;
    996     check_pattern:
    997 			found = NULL;
    998 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    999 				if (!jp->used || jp->nprocs <= 0)
   1000 					continue;
   1001 				if ((name[1] == '?'
   1002 					&& strstr(jp->ps[0].cmd, name + 2))
   1003 				    || prefix(name + 1, jp->ps[0].cmd)) {
   1004 					if (found) {
   1005 						err_msg = "%s: ambiguous";
   1006 						found = 0;
   1007 						break;
   1008 					}
   1009 					found = jp;
   1010 				}
   1011 			}
   1012 			if (found)
   1013 				return found;
   1014 		}
   1015 
   1016 	} else if (is_number(name)) {
   1017 		pid = number(name);
   1018 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
   1019 			if (jp->used && jp->nprocs > 0
   1020 			 && jp->ps[jp->nprocs - 1].pid == pid)
   1021 				return jp;
   1022 		}
   1023 	}
   1024 
   1025 	if (jobno >= 0 && jobno < njobs) {
   1026 		jp = jobtab + jobno;
   1027 		if (jp->used)
   1028 			return jp;
   1029 	}
   1030 	if (!noerror)
   1031 		error(err_msg, name);
   1032 	return 0;
   1033 }
   1034 
   1035 
   1036 /*
   1037  * Find out if there are any running (that is, unwaited upon)
   1038  * background children of the current shell.
   1039  *
   1040  * Return 1/0 (yes, no).
   1041  *
   1042  * Needed as we cannot optimise away sub-shell creation if
   1043  * we have such a child, or a "wait" in that sub-shell would
   1044  * observe the already existing job.
   1045  */
   1046 int
   1047 anyjobs(void)
   1048 {
   1049 	struct job *jp;
   1050 	int i;
   1051 
   1052 	if (jobs_invalid)
   1053 		return 0;
   1054 
   1055 	for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
   1056 		if (jp->used)
   1057 			return 1;
   1058 	}
   1059 
   1060 	return 0;
   1061 }
   1062 
   1063 /*
   1064  * Return a new job structure,
   1065  */
   1066 
   1067 struct job *
   1068 makejob(union node *node, int nprocs)
   1069 {
   1070 	int i;
   1071 	struct job *jp;
   1072 
   1073 	if (jobs_invalid) {
   1074 		VTRACE(DBG_JOBS, ("makejob(%p, %d) clearing jobtab (%d)\n",
   1075 			(void *)node, nprocs, njobs));
   1076 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
   1077 			if (jp->used)
   1078 				freejob(jp);
   1079 		}
   1080 		jobs_invalid = 0;
   1081 	}
   1082 
   1083 	for (i = njobs, jp = jobtab ; ; jp++) {
   1084 		if (--i < 0) {
   1085 			INTOFF;
   1086 			if (njobs == 0) {
   1087 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
   1088 			} else {
   1089 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
   1090 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
   1091 				/* Relocate `ps' pointers */
   1092 				for (i = 0; i < njobs; i++)
   1093 					if (jp[i].ps == &jobtab[i].ps0)
   1094 						jp[i].ps = &jp[i].ps0;
   1095 				ckfree(jobtab);
   1096 				jobtab = jp;
   1097 			}
   1098 			jp = jobtab + njobs;
   1099 			for (i = 4 ; --i >= 0 ; njobs++) {
   1100 				jobtab[njobs].used = 0;
   1101 				jobtab[njobs].prev_job = -1;
   1102 			}
   1103 			INTON;
   1104 			break;
   1105 		}
   1106 		if (jp->used == 0)
   1107 			break;
   1108 	}
   1109 	INTOFF;
   1110 	jp->state = JOBRUNNING;
   1111 	jp->used = 1;
   1112 	jp->flags = pipefail ? JPIPEFAIL : 0;
   1113 	jp->nprocs = 0;
   1114 	jp->pgrp = 0;
   1115 #if JOBS
   1116 	jp->jobctl = jobctl;
   1117 	set_curjob(jp, 1);
   1118 #endif
   1119 	if (nprocs > 1) {
   1120 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
   1121 	} else {
   1122 		jp->ps = &jp->ps0;
   1123 	}
   1124 	INTON;
   1125 	VTRACE(DBG_JOBS, ("makejob(%p, %d)%s returns %%%d\n", (void *)node,
   1126 	    nprocs, (jp->flags&JPIPEFAIL)?" PF":"", jp - jobtab + 1));
   1127 	return jp;
   1128 }
   1129 
   1130 
   1131 /*
   1132  * Fork off a subshell.  If we are doing job control, give the subshell its
   1133  * own process group.  Jp is a job structure that the job is to be added to.
   1134  * N is the command that will be evaluated by the child.  Both jp and n may
   1135  * be NULL.  The mode parameter can be one of the following:
   1136  *	FORK_FG - Fork off a foreground process.
   1137  *	FORK_BG - Fork off a background process.
   1138  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
   1139  *		     process group even if job control is on.
   1140  *
   1141  * When job control is turned off, background processes have their standard
   1142  * input redirected to /dev/null (except for the second and later processes
   1143  * in a pipeline).
   1144  */
   1145 
   1146 int
   1147 forkshell(struct job *jp, union node *n, int mode)
   1148 {
   1149 	pid_t pid;
   1150 	int serrno;
   1151 
   1152 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
   1153 	    jp - jobtab, n, mode));
   1154 
   1155 	switch ((pid = fork())) {
   1156 	case -1:
   1157 		serrno = errno;
   1158 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
   1159 		error("Cannot fork (%s)", strerror(serrno));
   1160 		break;
   1161 	case 0:
   1162 		SHELL_FORKED();
   1163 		forkchild(jp, n, mode, 0);
   1164 		return 0;
   1165 	default:
   1166 		return forkparent(jp, n, mode, pid);
   1167 	}
   1168 }
   1169 
   1170 int
   1171 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
   1172 {
   1173 	int pgrp;
   1174 
   1175 	if (rootshell && mode != FORK_NOJOB && mflag) {
   1176 		if (jp == NULL || jp->nprocs == 0)
   1177 			pgrp = pid;
   1178 		else
   1179 			pgrp = jp->ps[0].pid;
   1180 		jp->pgrp = pgrp;
   1181 		/* This can fail because we are doing it in the child also */
   1182 		(void)setpgid(pid, pgrp);
   1183 	}
   1184 	if (mode == FORK_BG)
   1185 		backgndpid = pid;		/* set $! */
   1186 	if (jp) {
   1187 		struct procstat *ps = &jp->ps[jp->nprocs++];
   1188 		ps->pid = pid;
   1189 		ps->status = -1;
   1190 		ps->cmd[0] = 0;
   1191 		if (/* iflag && rootshell && */ n)
   1192 			commandtext(ps, n);
   1193 	}
   1194 	CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
   1195 	return pid;
   1196 }
   1197 
   1198 void
   1199 forkchild(struct job *jp, union node *n, int mode, int vforked)
   1200 {
   1201 	int wasroot;
   1202 	int pgrp;
   1203 	const char *devnull = _PATH_DEVNULL;
   1204 	const char *nullerr = "Can't open %s";
   1205 
   1206 	wasroot = rootshell;
   1207 	CTRACE(DBG_JOBS, ("Child shell %d %sforked from %d (mode %d)\n",
   1208 	    getpid(), vforked?"v":"", getppid(), mode));
   1209 
   1210 	if (!vforked) {
   1211 		rootshell = 0;
   1212 		handler = &main_handler;
   1213 	}
   1214 
   1215 	closescript(vforked);
   1216 	clear_traps(vforked);
   1217 #if JOBS
   1218 	if (!vforked)
   1219 		jobctl = 0;		/* do job control only in root shell */
   1220 	if (wasroot && mode != FORK_NOJOB && mflag) {
   1221 		if (jp == NULL || jp->nprocs == 0)
   1222 			pgrp = getpid();
   1223 		else
   1224 			pgrp = jp->ps[0].pid;
   1225 		/* This can fail because we are doing it in the parent also */
   1226 		(void)setpgid(0, pgrp);
   1227 		if (mode == FORK_FG) {
   1228 			if (tcsetpgrp(ttyfd, pgrp) == -1)
   1229 				error("Cannot set tty process group (%s) at %d",
   1230 				    strerror(errno), __LINE__);
   1231 		}
   1232 		setsignal(SIGTSTP, vforked);
   1233 		setsignal(SIGTTOU, vforked);
   1234 	} else if (mode == FORK_BG) {
   1235 		ignoresig(SIGINT, vforked);
   1236 		ignoresig(SIGQUIT, vforked);
   1237 		if ((jp == NULL || jp->nprocs == 0) &&
   1238 		    ! fd0_redirected_p ()) {
   1239 			close(0);
   1240 			if (open(devnull, O_RDONLY) != 0)
   1241 				error(nullerr, devnull);
   1242 		}
   1243 	}
   1244 #else
   1245 	if (mode == FORK_BG) {
   1246 		ignoresig(SIGINT, vforked);
   1247 		ignoresig(SIGQUIT, vforked);
   1248 		if ((jp == NULL || jp->nprocs == 0) &&
   1249 		    ! fd0_redirected_p ()) {
   1250 			close(0);
   1251 			if (open(devnull, O_RDONLY) != 0)
   1252 				error(nullerr, devnull);
   1253 		}
   1254 	}
   1255 #endif
   1256 	if (wasroot && iflag) {
   1257 		setsignal(SIGINT, vforked);
   1258 		setsignal(SIGQUIT, vforked);
   1259 		setsignal(SIGTERM, vforked);
   1260 	}
   1261 
   1262 	if (!vforked)
   1263 		jobs_invalid = 1;
   1264 }
   1265 
   1266 /*
   1267  * Wait for job to finish.
   1268  *
   1269  * Under job control we have the problem that while a child process is
   1270  * running interrupts generated by the user are sent to the child but not
   1271  * to the shell.  This means that an infinite loop started by an inter-
   1272  * active user may be hard to kill.  With job control turned off, an
   1273  * interactive user may place an interactive program inside a loop.  If
   1274  * the interactive program catches interrupts, the user doesn't want
   1275  * these interrupts to also abort the loop.  The approach we take here
   1276  * is to have the shell ignore interrupt signals while waiting for a
   1277  * forground process to terminate, and then send itself an interrupt
   1278  * signal if the child process was terminated by an interrupt signal.
   1279  * Unfortunately, some programs want to do a bit of cleanup and then
   1280  * exit on interrupt; unless these processes terminate themselves by
   1281  * sending a signal to themselves (instead of calling exit) they will
   1282  * confuse this approach.
   1283  */
   1284 
   1285 int
   1286 waitforjob(struct job *jp)
   1287 {
   1288 #if JOBS
   1289 	int mypgrp = getpgrp();
   1290 #endif
   1291 	int status;
   1292 	int st;
   1293 
   1294 	INTOFF;
   1295 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", jp - jobtab + 1));
   1296 	while (jp->state == JOBRUNNING) {
   1297 		dowait(WBLOCK, jp, NULL);
   1298 	}
   1299 #if JOBS
   1300 	if (jp->jobctl) {
   1301 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
   1302 			error("Cannot set tty process group (%s) at %d",
   1303 			    strerror(errno), __LINE__);
   1304 	}
   1305 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
   1306 		set_curjob(jp, 2);
   1307 #endif
   1308 	status = jobstatus(jp, 1);
   1309 
   1310 	/* convert to 8 bits */
   1311 	if (WIFEXITED(status))
   1312 		st = WEXITSTATUS(status);
   1313 #if JOBS
   1314 	else if (WIFSTOPPED(status))
   1315 		st = WSTOPSIG(status) + 128;
   1316 #endif
   1317 	else
   1318 		st = WTERMSIG(status) + 128;
   1319 
   1320 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
   1321 		jp - jobtab + 1, jp->nprocs, status, st));
   1322 #if JOBS
   1323 	if (jp->jobctl) {
   1324 		/*
   1325 		 * This is truly gross.
   1326 		 * If we're doing job control, then we did a TIOCSPGRP which
   1327 		 * caused us (the shell) to no longer be in the controlling
   1328 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
   1329 		 * intuit from the subprocess exit status whether a SIGINT
   1330 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
   1331 		 */
   1332 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
   1333 			raise(SIGINT);
   1334 	}
   1335 #endif
   1336 	if (! JOBS || jp->state == JOBDONE)
   1337 		freejob(jp);
   1338 	INTON;
   1339 	return st;
   1340 }
   1341 
   1342 
   1343 
   1344 /*
   1345  * Wait for a process to terminate.
   1346  */
   1347 
   1348 STATIC int
   1349 dowait(int flags, struct job *job, struct job **changed)
   1350 {
   1351 	int pid;
   1352 	int status;
   1353 	struct procstat *sp;
   1354 	struct job *jp;
   1355 	struct job *thisjob;
   1356 	int done;
   1357 	int stopped;
   1358 
   1359 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called\n", flags));
   1360 
   1361 	if (changed != NULL)
   1362 		*changed = NULL;
   1363 
   1364 	do {
   1365 		pid = waitproc(flags & WBLOCK, job, &status);
   1366 		VTRACE(DBG_JOBS|DBG_PROCS, ("wait returns pid %d, status %#x\n",
   1367 		    pid, status));
   1368 	} while (pid == -1 && errno == EINTR && pendingsigs == 0);
   1369 	if (pid <= 0)
   1370 		return pid;
   1371 	INTOFF;
   1372 	thisjob = NULL;
   1373 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
   1374 		if (jp->used) {
   1375 			done = 1;
   1376 			stopped = 1;
   1377 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
   1378 				if (sp->pid == -1)
   1379 					continue;
   1380 				if (sp->pid == pid &&
   1381 				  (sp->status==-1 || WIFSTOPPED(sp->status))) {
   1382 					VTRACE(DBG_JOBS | DBG_PROCS,
   1383 			("Job %d: changing status of proc %d from %#x to %#x\n",
   1384 						jp - jobtab + 1, pid,
   1385 						sp->status, status));
   1386 					if (WIFCONTINUED(status)) {
   1387 						if (sp->status != -1)
   1388 							jp->flags |= JOBCHANGED;
   1389 						sp->status = -1;
   1390 						jp->state = 0;
   1391 					} else
   1392 						sp->status = status;
   1393 					thisjob = jp;
   1394 					if (changed != NULL)
   1395 						*changed = jp;
   1396 				}
   1397 				if (sp->status == -1)
   1398 					stopped = 0;
   1399 				else if (WIFSTOPPED(sp->status))
   1400 					done = 0;
   1401 			}
   1402 			if (stopped) {		/* stopped or done */
   1403 				int state = done ? JOBDONE : JOBSTOPPED;
   1404 
   1405 				if (jp->state != state) {
   1406 					VTRACE(DBG_JOBS,
   1407 				("Job %d: changing state from %d to %d\n",
   1408 					    jp - jobtab + 1, jp->state, state));
   1409 					jp->state = state;
   1410 #if JOBS
   1411 					if (done)
   1412 						set_curjob(jp, 0);
   1413 #endif
   1414 				}
   1415 			}
   1416 		}
   1417 	}
   1418 
   1419 	if (thisjob &&
   1420 	    (thisjob->state != JOBRUNNING || thisjob->flags & JOBCHANGED)) {
   1421 		int mode = 0;
   1422 
   1423 		if (!rootshell || !iflag)
   1424 			mode = SHOW_SIGNALLED;
   1425 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
   1426 		    job != thisjob)
   1427 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
   1428 		if (mode && (flags & WSILENT) == 0)
   1429 			showjob(out2, thisjob, mode);
   1430 		else {
   1431 			VTRACE(DBG_JOBS,
   1432 			    ("Not printing status, rootshell=%d, job=%p\n",
   1433 			    rootshell, job));
   1434 			thisjob->flags |= JOBCHANGED;
   1435 		}
   1436 	}
   1437 
   1438 	INTON;
   1439 	return pid;
   1440 }
   1441 
   1442 
   1443 
   1444 /*
   1445  * Do a wait system call.  If job control is compiled in, we accept
   1446  * stopped processes.  If block is zero, we return a value of zero
   1447  * rather than blocking.
   1448  *
   1449  * System V doesn't have a non-blocking wait system call.  It does
   1450  * have a SIGCLD signal that is sent to a process when one of its
   1451  * children dies.  The obvious way to use SIGCLD would be to install
   1452  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
   1453  * was received, and have waitproc bump another counter when it got
   1454  * the status of a process.  Waitproc would then know that a wait
   1455  * system call would not block if the two counters were different.
   1456  * This approach doesn't work because if a process has children that
   1457  * have not been waited for, System V will send it a SIGCLD when it
   1458  * installs a signal handler for SIGCLD.  What this means is that when
   1459  * a child exits, the shell will be sent SIGCLD signals continuously
   1460  * until is runs out of stack space, unless it does a wait call before
   1461  * restoring the signal handler.  The code below takes advantage of
   1462  * this (mis)feature by installing a signal handler for SIGCLD and
   1463  * then checking to see whether it was called.  If there are any
   1464  * children to be waited for, it will be.
   1465  *
   1466  * If neither SYSV nor BSD is defined, we don't implement nonblocking
   1467  * waits at all.  In this case, the user will not be informed when
   1468  * a background process until the next time she runs a real program
   1469  * (as opposed to running a builtin command or just typing return),
   1470  * and the jobs command may give out of date information.
   1471  */
   1472 
   1473 #ifdef SYSV
   1474 STATIC int gotsigchild;
   1475 
   1476 STATIC int onsigchild() {
   1477 	gotsigchild = 1;
   1478 }
   1479 #endif
   1480 
   1481 
   1482 STATIC int
   1483 waitproc(int block, struct job *jp, int *status)
   1484 {
   1485 #ifdef BSD
   1486 	int flags = 0;
   1487 
   1488 #if JOBS
   1489 	if (mflag || (jp != NULL && jp->jobctl))
   1490 		flags |= WUNTRACED | WCONTINUED;
   1491 #endif
   1492 	if (block == 0)
   1493 		flags |= WNOHANG;
   1494 	VTRACE(DBG_WAIT, ("waitproc: doing waitpid(flags=%#x)\n", flags));
   1495 	return waitpid(-1, status, flags);
   1496 #else
   1497 #ifdef SYSV
   1498 	int (*save)();
   1499 
   1500 	if (block == 0) {
   1501 		gotsigchild = 0;
   1502 		save = signal(SIGCLD, onsigchild);
   1503 		signal(SIGCLD, save);
   1504 		if (gotsigchild == 0)
   1505 			return 0;
   1506 	}
   1507 	return wait(status);
   1508 #else
   1509 	if (block == 0)
   1510 		return 0;
   1511 	return wait(status);
   1512 #endif
   1513 #endif
   1514 }
   1515 
   1516 /*
   1517  * return 1 if there are stopped jobs, otherwise 0
   1518  */
   1519 int job_warning = 0;
   1520 int
   1521 stoppedjobs(void)
   1522 {
   1523 	int jobno;
   1524 	struct job *jp;
   1525 
   1526 	if (job_warning || jobs_invalid)
   1527 		return (0);
   1528 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1529 		if (jp->used == 0)
   1530 			continue;
   1531 		if (jp->state == JOBSTOPPED) {
   1532 			out2str("You have stopped jobs.\n");
   1533 			job_warning = 2;
   1534 			return (1);
   1535 		}
   1536 	}
   1537 
   1538 	return (0);
   1539 }
   1540 
   1541 /*
   1542  * Return a string identifying a command (to be printed by the
   1543  * jobs command).
   1544  */
   1545 
   1546 STATIC char *cmdnextc;
   1547 STATIC int cmdnleft;
   1548 
   1549 void
   1550 commandtext(struct procstat *ps, union node *n)
   1551 {
   1552 	int len;
   1553 
   1554 	cmdnextc = ps->cmd;
   1555 	if (iflag || mflag || sizeof(ps->cmd) <= 60)
   1556 		len = sizeof(ps->cmd);
   1557 	else if (sizeof ps->cmd <= 400)
   1558 		len = 50;
   1559 	else if (sizeof ps->cmd <= 800)
   1560 		len = 80;
   1561 	else
   1562 		len = sizeof(ps->cmd) / 10;
   1563 	cmdnleft = len;
   1564 	cmdtxt(n);
   1565 	if (cmdnleft <= 0) {
   1566 		char *p = ps->cmd + len - 4;
   1567 		p[0] = '.';
   1568 		p[1] = '.';
   1569 		p[2] = '.';
   1570 		p[3] = 0;
   1571 	} else
   1572 		*cmdnextc = '\0';
   1573 
   1574 	VTRACE(DBG_JOBS,
   1575 	    ("commandtext: ps->cmd %p, end %p, left %d\n\t\"%s\"\n",
   1576 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
   1577 }
   1578 
   1579 
   1580 STATIC void
   1581 cmdtxt(union node *n)
   1582 {
   1583 	union node *np;
   1584 	struct nodelist *lp;
   1585 	const char *p;
   1586 	int i;
   1587 
   1588 	if (n == NULL || cmdnleft <= 0)
   1589 		return;
   1590 	switch (n->type) {
   1591 	case NSEMI:
   1592 		cmdtxt(n->nbinary.ch1);
   1593 		cmdputs("; ");
   1594 		cmdtxt(n->nbinary.ch2);
   1595 		break;
   1596 	case NAND:
   1597 		cmdtxt(n->nbinary.ch1);
   1598 		cmdputs(" && ");
   1599 		cmdtxt(n->nbinary.ch2);
   1600 		break;
   1601 	case NOR:
   1602 		cmdtxt(n->nbinary.ch1);
   1603 		cmdputs(" || ");
   1604 		cmdtxt(n->nbinary.ch2);
   1605 		break;
   1606 	case NDNOT:
   1607 		cmdputs("! ");
   1608 		/* FALLTHROUGH */
   1609 	case NNOT:
   1610 		cmdputs("! ");
   1611 		cmdtxt(n->nnot.com);
   1612 		break;
   1613 	case NPIPE:
   1614 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1615 			cmdtxt(lp->n);
   1616 			if (lp->next)
   1617 				cmdputs(" | ");
   1618 		}
   1619 		if (n->npipe.backgnd)
   1620 			cmdputs(" &");
   1621 		break;
   1622 	case NSUBSHELL:
   1623 		cmdputs("(");
   1624 		cmdtxt(n->nredir.n);
   1625 		cmdputs(")");
   1626 		break;
   1627 	case NREDIR:
   1628 	case NBACKGND:
   1629 		cmdtxt(n->nredir.n);
   1630 		break;
   1631 	case NIF:
   1632 		cmdputs("if ");
   1633 		cmdtxt(n->nif.test);
   1634 		cmdputs("; then ");
   1635 		cmdtxt(n->nif.ifpart);
   1636 		if (n->nif.elsepart) {
   1637 			cmdputs("; else ");
   1638 			cmdtxt(n->nif.elsepart);
   1639 		}
   1640 		cmdputs("; fi");
   1641 		break;
   1642 	case NWHILE:
   1643 		cmdputs("while ");
   1644 		goto until;
   1645 	case NUNTIL:
   1646 		cmdputs("until ");
   1647  until:
   1648 		cmdtxt(n->nbinary.ch1);
   1649 		cmdputs("; do ");
   1650 		cmdtxt(n->nbinary.ch2);
   1651 		cmdputs("; done");
   1652 		break;
   1653 	case NFOR:
   1654 		cmdputs("for ");
   1655 		cmdputs(n->nfor.var);
   1656 		cmdputs(" in ");
   1657 		cmdlist(n->nfor.args, 1);
   1658 		cmdputs("; do ");
   1659 		cmdtxt(n->nfor.body);
   1660 		cmdputs("; done");
   1661 		break;
   1662 	case NCASE:
   1663 		cmdputs("case ");
   1664 		cmdputs(n->ncase.expr->narg.text);
   1665 		cmdputs(" in ");
   1666 		for (np = n->ncase.cases; np; np = np->nclist.next) {
   1667 			cmdtxt(np->nclist.pattern);
   1668 			cmdputs(") ");
   1669 			cmdtxt(np->nclist.body);
   1670 			switch (n->type) {	/* switch (not if) for later */
   1671 			case NCLISTCONT:
   1672 				cmdputs(";& ");
   1673 				break;
   1674 			default:
   1675 				cmdputs(";; ");
   1676 				break;
   1677 			}
   1678 		}
   1679 		cmdputs("esac");
   1680 		break;
   1681 	case NDEFUN:
   1682 		cmdputs(n->narg.text);
   1683 		cmdputs("() { ... }");
   1684 		break;
   1685 	case NCMD:
   1686 		cmdlist(n->ncmd.args, 1);
   1687 		cmdlist(n->ncmd.redirect, 0);
   1688 		if (n->ncmd.backgnd)
   1689 			cmdputs(" &");
   1690 		break;
   1691 	case NARG:
   1692 		cmdputs(n->narg.text);
   1693 		break;
   1694 	case NTO:
   1695 		p = ">";  i = 1;  goto redir;
   1696 	case NCLOBBER:
   1697 		p = ">|";  i = 1;  goto redir;
   1698 	case NAPPEND:
   1699 		p = ">>";  i = 1;  goto redir;
   1700 	case NTOFD:
   1701 		p = ">&";  i = 1;  goto redir;
   1702 	case NFROM:
   1703 		p = "<";  i = 0;  goto redir;
   1704 	case NFROMFD:
   1705 		p = "<&";  i = 0;  goto redir;
   1706 	case NFROMTO:
   1707 		p = "<>";  i = 0;  goto redir;
   1708  redir:
   1709 		if (n->nfile.fd != i)
   1710 			cmdputi(n->nfile.fd);
   1711 		cmdputs(p);
   1712 		if (n->type == NTOFD || n->type == NFROMFD) {
   1713 			if (n->ndup.dupfd < 0)
   1714 				cmdputs("-");
   1715 			else
   1716 				cmdputi(n->ndup.dupfd);
   1717 		} else {
   1718 			cmdtxt(n->nfile.fname);
   1719 		}
   1720 		break;
   1721 	case NHERE:
   1722 	case NXHERE:
   1723 		cmdputs("<<...");
   1724 		break;
   1725 	default:
   1726 		cmdputs("???");
   1727 		break;
   1728 	}
   1729 }
   1730 
   1731 STATIC void
   1732 cmdlist(union node *np, int sep)
   1733 {
   1734 	for (; np; np = np->narg.next) {
   1735 		if (!sep)
   1736 			cmdputs(" ");
   1737 		cmdtxt(np);
   1738 		if (sep && np->narg.next)
   1739 			cmdputs(" ");
   1740 	}
   1741 }
   1742 
   1743 
   1744 STATIC void
   1745 cmdputs(const char *s)
   1746 {
   1747 	const char *p, *str = 0;
   1748 	char c, cc[2] = " ";
   1749 	char *nextc;
   1750 	int nleft;
   1751 	int subtype = 0;
   1752 	int quoted = 0;
   1753 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
   1754 					"#", "##", "%", "%%", "}" };
   1755 
   1756 	p = s;
   1757 	nextc = cmdnextc;
   1758 	nleft = cmdnleft;
   1759 	while (nleft > 0 && (c = *p++) != 0) {
   1760 		switch (c) {
   1761 		case CTLNONL:
   1762 			c = '\0';
   1763 			break;
   1764 		case CTLESC:
   1765 			c = *p++;
   1766 			break;
   1767 		case CTLVAR:
   1768 			subtype = *p++;
   1769 			if (subtype & VSLINENO) {	/* undo LINENO hack */
   1770 				if ((subtype & VSTYPE) == VSLENGTH)
   1771 					str = "${#LINENO";	/*}*/
   1772 				else
   1773 					str = "${LINENO";	/*}*/
   1774 				while (is_digit(*p))
   1775 					p++;
   1776 			} else if ((subtype & VSTYPE) == VSLENGTH)
   1777 				str = "${#"; /*}*/
   1778 			else
   1779 				str = "${"; /*}*/
   1780 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
   1781 				quoted ^= 1;
   1782 				c = '"';
   1783 			} else {
   1784 				c = *str++;
   1785 			}
   1786 			break;
   1787 		case CTLENDVAR:		/*{*/
   1788 			c = '}';
   1789 			if (quoted & 1)
   1790 				str = "\"";
   1791 			quoted >>= 1;
   1792 			subtype = 0;
   1793 			break;
   1794 		case CTLBACKQ:
   1795 			c = '$';
   1796 			str = "(...)";
   1797 			break;
   1798 		case CTLBACKQ+CTLQUOTE:
   1799 			c = '"';
   1800 			str = "$(...)\"";
   1801 			break;
   1802 		case CTLARI:
   1803 			c = '$';
   1804 			if (*p == ' ')
   1805 				p++;
   1806 			str = "((";	/*))*/
   1807 			break;
   1808 		case CTLENDARI:		/*((*/
   1809 			c = ')';
   1810 			str = ")";
   1811 			break;
   1812 		case CTLQUOTEMARK:
   1813 			quoted ^= 1;
   1814 			c = '"';
   1815 			break;
   1816 		case CTLQUOTEEND:
   1817 			quoted >>= 1;
   1818 			c = '"';
   1819 			break;
   1820 		case '=':
   1821 			if (subtype == 0)
   1822 				break;
   1823 			str = vstype[subtype & VSTYPE];
   1824 			if (subtype & VSNUL)
   1825 				c = ':';
   1826 			else
   1827 				c = *str++;		/*{*/
   1828 			if (c != '}')
   1829 				quoted <<= 1;
   1830 			else if (*p == CTLENDVAR)
   1831 				c = *str++;
   1832 			subtype = 0;
   1833 			break;
   1834 		case '\'':
   1835 		case '\\':
   1836 		case '"':
   1837 		case '$':
   1838 			/* These can only happen inside quotes */
   1839 			cc[0] = c;
   1840 			str = cc;
   1841 			c = '\\';
   1842 			break;
   1843 		default:
   1844 			break;
   1845 		}
   1846 		if (c != '\0') do {	/* c == 0 implies nothing in str */
   1847 			*nextc++ = c;
   1848 		} while (--nleft > 0 && str && (c = *str++));
   1849 		str = 0;
   1850 	}
   1851 	if ((quoted & 1) && nleft) {
   1852 		*nextc++ = '"';
   1853 		nleft--;
   1854 	}
   1855 	cmdnleft = nleft;
   1856 	cmdnextc = nextc;
   1857 }
   1858