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