Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.107
      1 /*	$NetBSD: jobs.c,v 1.107 2020/02/07 02:06:12 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.107 2020/02/07 02:06:12 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 	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->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 /*
   1038  * Return a new job structure,
   1039  */
   1040 
   1041 struct job *
   1042 makejob(union node *node, int nprocs)
   1043 {
   1044 	int i;
   1045 	struct job *jp;
   1046 
   1047 	if (jobs_invalid) {
   1048 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
   1049 			if (jp->used)
   1050 				freejob(jp);
   1051 		}
   1052 		jobs_invalid = 0;
   1053 	}
   1054 
   1055 	for (i = njobs, jp = jobtab ; ; jp++) {
   1056 		if (--i < 0) {
   1057 			INTOFF;
   1058 			if (njobs == 0) {
   1059 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
   1060 			} else {
   1061 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
   1062 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
   1063 				/* Relocate `ps' pointers */
   1064 				for (i = 0; i < njobs; i++)
   1065 					if (jp[i].ps == &jobtab[i].ps0)
   1066 						jp[i].ps = &jp[i].ps0;
   1067 				ckfree(jobtab);
   1068 				jobtab = jp;
   1069 			}
   1070 			jp = jobtab + njobs;
   1071 			for (i = 4 ; --i >= 0 ; njobs++) {
   1072 				jobtab[njobs].used = 0;
   1073 				jobtab[njobs].prev_job = -1;
   1074 			}
   1075 			INTON;
   1076 			break;
   1077 		}
   1078 		if (jp->used == 0)
   1079 			break;
   1080 	}
   1081 	INTOFF;
   1082 	jp->state = JOBRUNNING;
   1083 	jp->used = 1;
   1084 	jp->flags = pipefail ? JPIPEFAIL : 0;
   1085 	jp->nprocs = 0;
   1086 	jp->pgrp = 0;
   1087 #if JOBS
   1088 	jp->jobctl = jobctl;
   1089 	set_curjob(jp, 1);
   1090 #endif
   1091 	if (nprocs > 1) {
   1092 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
   1093 	} else {
   1094 		jp->ps = &jp->ps0;
   1095 	}
   1096 	INTON;
   1097 	VTRACE(DBG_JOBS, ("makejob(%p, %d)%s returns %%%d\n", (void *)node,
   1098 	    nprocs, (jp->flags&JPIPEFAIL)?" PF":"", jp - jobtab + 1));
   1099 	return jp;
   1100 }
   1101 
   1102 
   1103 /*
   1104  * Fork off a subshell.  If we are doing job control, give the subshell its
   1105  * own process group.  Jp is a job structure that the job is to be added to.
   1106  * N is the command that will be evaluated by the child.  Both jp and n may
   1107  * be NULL.  The mode parameter can be one of the following:
   1108  *	FORK_FG - Fork off a foreground process.
   1109  *	FORK_BG - Fork off a background process.
   1110  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
   1111  *		     process group even if job control is on.
   1112  *
   1113  * When job control is turned off, background processes have their standard
   1114  * input redirected to /dev/null (except for the second and later processes
   1115  * in a pipeline).
   1116  */
   1117 
   1118 int
   1119 forkshell(struct job *jp, union node *n, int mode)
   1120 {
   1121 	pid_t pid;
   1122 	int serrno;
   1123 
   1124 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
   1125 	    jp - jobtab, n, mode));
   1126 
   1127 	switch ((pid = fork())) {
   1128 	case -1:
   1129 		serrno = errno;
   1130 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
   1131 		error("Cannot fork (%s)", strerror(serrno));
   1132 		break;
   1133 	case 0:
   1134 		SHELL_FORKED();
   1135 		forkchild(jp, n, mode, 0);
   1136 		return 0;
   1137 	default:
   1138 		return forkparent(jp, n, mode, pid);
   1139 	}
   1140 }
   1141 
   1142 int
   1143 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
   1144 {
   1145 	int pgrp;
   1146 
   1147 	if (rootshell && mode != FORK_NOJOB && mflag) {
   1148 		if (jp == NULL || jp->nprocs == 0)
   1149 			pgrp = pid;
   1150 		else
   1151 			pgrp = jp->ps[0].pid;
   1152 		jp->pgrp = pgrp;
   1153 		/* This can fail because we are doing it in the child also */
   1154 		(void)setpgid(pid, pgrp);
   1155 	}
   1156 	if (mode == FORK_BG)
   1157 		backgndpid = pid;		/* set $! */
   1158 	if (jp) {
   1159 		struct procstat *ps = &jp->ps[jp->nprocs++];
   1160 		ps->pid = pid;
   1161 		ps->status = -1;
   1162 		ps->cmd[0] = 0;
   1163 		if (/* iflag && rootshell && */ n)
   1164 			commandtext(ps, n);
   1165 	}
   1166 	CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
   1167 	return pid;
   1168 }
   1169 
   1170 void
   1171 forkchild(struct job *jp, union node *n, int mode, int vforked)
   1172 {
   1173 	int wasroot;
   1174 	int pgrp;
   1175 	const char *devnull = _PATH_DEVNULL;
   1176 	const char *nullerr = "Can't open %s";
   1177 
   1178 	wasroot = rootshell;
   1179 	CTRACE(DBG_JOBS, ("Child shell %d %sforked from %d (mode %d)\n",
   1180 	    getpid(), vforked?"v":"", getppid(), mode));
   1181 
   1182 	if (!vforked) {
   1183 		rootshell = 0;
   1184 		handler = &main_handler;
   1185 	}
   1186 
   1187 	closescript(vforked);
   1188 	clear_traps(vforked);
   1189 #if JOBS
   1190 	if (!vforked)
   1191 		jobctl = 0;		/* do job control only in root shell */
   1192 	if (wasroot && mode != FORK_NOJOB && mflag) {
   1193 		if (jp == NULL || jp->nprocs == 0)
   1194 			pgrp = getpid();
   1195 		else
   1196 			pgrp = jp->ps[0].pid;
   1197 		/* This can fail because we are doing it in the parent also */
   1198 		(void)setpgid(0, pgrp);
   1199 		if (mode == FORK_FG) {
   1200 			if (tcsetpgrp(ttyfd, pgrp) == -1)
   1201 				error("Cannot set tty process group (%s) at %d",
   1202 				    strerror(errno), __LINE__);
   1203 		}
   1204 		setsignal(SIGTSTP, vforked);
   1205 		setsignal(SIGTTOU, vforked);
   1206 	} else if (mode == FORK_BG) {
   1207 		ignoresig(SIGINT, vforked);
   1208 		ignoresig(SIGQUIT, vforked);
   1209 		if ((jp == NULL || jp->nprocs == 0) &&
   1210 		    ! fd0_redirected_p ()) {
   1211 			close(0);
   1212 			if (open(devnull, O_RDONLY) != 0)
   1213 				error(nullerr, devnull);
   1214 		}
   1215 	}
   1216 #else
   1217 	if (mode == FORK_BG) {
   1218 		ignoresig(SIGINT, vforked);
   1219 		ignoresig(SIGQUIT, vforked);
   1220 		if ((jp == NULL || jp->nprocs == 0) &&
   1221 		    ! fd0_redirected_p ()) {
   1222 			close(0);
   1223 			if (open(devnull, O_RDONLY) != 0)
   1224 				error(nullerr, devnull);
   1225 		}
   1226 	}
   1227 #endif
   1228 	if (wasroot && iflag) {
   1229 		setsignal(SIGINT, vforked);
   1230 		setsignal(SIGQUIT, vforked);
   1231 		setsignal(SIGTERM, vforked);
   1232 	}
   1233 
   1234 	if (!vforked)
   1235 		jobs_invalid = 1;
   1236 }
   1237 
   1238 /*
   1239  * Wait for job to finish.
   1240  *
   1241  * Under job control we have the problem that while a child process is
   1242  * running interrupts generated by the user are sent to the child but not
   1243  * to the shell.  This means that an infinite loop started by an inter-
   1244  * active user may be hard to kill.  With job control turned off, an
   1245  * interactive user may place an interactive program inside a loop.  If
   1246  * the interactive program catches interrupts, the user doesn't want
   1247  * these interrupts to also abort the loop.  The approach we take here
   1248  * is to have the shell ignore interrupt signals while waiting for a
   1249  * forground process to terminate, and then send itself an interrupt
   1250  * signal if the child process was terminated by an interrupt signal.
   1251  * Unfortunately, some programs want to do a bit of cleanup and then
   1252  * exit on interrupt; unless these processes terminate themselves by
   1253  * sending a signal to themselves (instead of calling exit) they will
   1254  * confuse this approach.
   1255  */
   1256 
   1257 int
   1258 waitforjob(struct job *jp)
   1259 {
   1260 #if JOBS
   1261 	int mypgrp = getpgrp();
   1262 #endif
   1263 	int status;
   1264 	int st;
   1265 
   1266 	INTOFF;
   1267 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", jp - jobtab + 1));
   1268 	while (jp->state == JOBRUNNING) {
   1269 		dowait(WBLOCK, jp, NULL);
   1270 	}
   1271 #if JOBS
   1272 	if (jp->jobctl) {
   1273 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
   1274 			error("Cannot set tty process group (%s) at %d",
   1275 			    strerror(errno), __LINE__);
   1276 	}
   1277 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
   1278 		set_curjob(jp, 2);
   1279 #endif
   1280 	status = jobstatus(jp, 1);
   1281 
   1282 	/* convert to 8 bits */
   1283 	if (WIFEXITED(status))
   1284 		st = WEXITSTATUS(status);
   1285 #if JOBS
   1286 	else if (WIFSTOPPED(status))
   1287 		st = WSTOPSIG(status) + 128;
   1288 #endif
   1289 	else
   1290 		st = WTERMSIG(status) + 128;
   1291 
   1292 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
   1293 		jp - jobtab + 1, jp->nprocs, status, st));
   1294 #if JOBS
   1295 	if (jp->jobctl) {
   1296 		/*
   1297 		 * This is truly gross.
   1298 		 * If we're doing job control, then we did a TIOCSPGRP which
   1299 		 * caused us (the shell) to no longer be in the controlling
   1300 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
   1301 		 * intuit from the subprocess exit status whether a SIGINT
   1302 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
   1303 		 */
   1304 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
   1305 			raise(SIGINT);
   1306 	}
   1307 #endif
   1308 	if (! JOBS || jp->state == JOBDONE)
   1309 		freejob(jp);
   1310 	INTON;
   1311 	return st;
   1312 }
   1313 
   1314 
   1315 
   1316 /*
   1317  * Wait for a process to terminate.
   1318  */
   1319 
   1320 STATIC int
   1321 dowait(int flags, struct job *job, struct job **changed)
   1322 {
   1323 	int pid;
   1324 	int status;
   1325 	struct procstat *sp;
   1326 	struct job *jp;
   1327 	struct job *thisjob;
   1328 	int done;
   1329 	int stopped;
   1330 
   1331 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called\n", flags));
   1332 
   1333 	if (changed != NULL)
   1334 		*changed = NULL;
   1335 
   1336 	do {
   1337 		pid = waitproc(flags & WBLOCK, job, &status);
   1338 		VTRACE(DBG_JOBS|DBG_PROCS, ("wait returns pid %d, status %#x\n",
   1339 		    pid, status));
   1340 	} while (pid == -1 && errno == EINTR && pendingsigs == 0);
   1341 	if (pid <= 0)
   1342 		return pid;
   1343 	INTOFF;
   1344 	thisjob = NULL;
   1345 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
   1346 		if (jp->used) {
   1347 			done = 1;
   1348 			stopped = 1;
   1349 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
   1350 				if (sp->pid == -1)
   1351 					continue;
   1352 				if (sp->pid == pid &&
   1353 				  (sp->status==-1 || WIFSTOPPED(sp->status))) {
   1354 					VTRACE(DBG_JOBS | DBG_PROCS,
   1355 			("Job %d: changing status of proc %d from %#x to %#x\n",
   1356 						jp - jobtab + 1, pid,
   1357 						sp->status, status));
   1358 					if (WIFCONTINUED(status)) {
   1359 						if (sp->status != -1)
   1360 							jp->flags |= JOBCHANGED;
   1361 						sp->status = -1;
   1362 						jp->state = 0;
   1363 					} else
   1364 						sp->status = status;
   1365 					thisjob = jp;
   1366 					if (changed != NULL)
   1367 						*changed = jp;
   1368 				}
   1369 				if (sp->status == -1)
   1370 					stopped = 0;
   1371 				else if (WIFSTOPPED(sp->status))
   1372 					done = 0;
   1373 			}
   1374 			if (stopped) {		/* stopped or done */
   1375 				int state = done ? JOBDONE : JOBSTOPPED;
   1376 
   1377 				if (jp->state != state) {
   1378 					VTRACE(DBG_JOBS,
   1379 				("Job %d: changing state from %d to %d\n",
   1380 					    jp - jobtab + 1, jp->state, state));
   1381 					jp->state = state;
   1382 #if JOBS
   1383 					if (done)
   1384 						set_curjob(jp, 0);
   1385 #endif
   1386 				}
   1387 			}
   1388 		}
   1389 	}
   1390 
   1391 	if (thisjob &&
   1392 	    (thisjob->state != JOBRUNNING || thisjob->flags & JOBCHANGED)) {
   1393 		int mode = 0;
   1394 
   1395 		if (!rootshell || !iflag)
   1396 			mode = SHOW_SIGNALLED;
   1397 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
   1398 		    job != thisjob)
   1399 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
   1400 		if (mode && (flags & WSILENT) == 0)
   1401 			showjob(out2, thisjob, mode);
   1402 		else {
   1403 			VTRACE(DBG_JOBS,
   1404 			    ("Not printing status, rootshell=%d, job=%p\n",
   1405 			    rootshell, job));
   1406 			thisjob->flags |= JOBCHANGED;
   1407 		}
   1408 	}
   1409 
   1410 	INTON;
   1411 	return pid;
   1412 }
   1413 
   1414 
   1415 
   1416 /*
   1417  * Do a wait system call.  If job control is compiled in, we accept
   1418  * stopped processes.  If block is zero, we return a value of zero
   1419  * rather than blocking.
   1420  *
   1421  * System V doesn't have a non-blocking wait system call.  It does
   1422  * have a SIGCLD signal that is sent to a process when one of its
   1423  * children dies.  The obvious way to use SIGCLD would be to install
   1424  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
   1425  * was received, and have waitproc bump another counter when it got
   1426  * the status of a process.  Waitproc would then know that a wait
   1427  * system call would not block if the two counters were different.
   1428  * This approach doesn't work because if a process has children that
   1429  * have not been waited for, System V will send it a SIGCLD when it
   1430  * installs a signal handler for SIGCLD.  What this means is that when
   1431  * a child exits, the shell will be sent SIGCLD signals continuously
   1432  * until is runs out of stack space, unless it does a wait call before
   1433  * restoring the signal handler.  The code below takes advantage of
   1434  * this (mis)feature by installing a signal handler for SIGCLD and
   1435  * then checking to see whether it was called.  If there are any
   1436  * children to be waited for, it will be.
   1437  *
   1438  * If neither SYSV nor BSD is defined, we don't implement nonblocking
   1439  * waits at all.  In this case, the user will not be informed when
   1440  * a background process until the next time she runs a real program
   1441  * (as opposed to running a builtin command or just typing return),
   1442  * and the jobs command may give out of date information.
   1443  */
   1444 
   1445 #ifdef SYSV
   1446 STATIC int gotsigchild;
   1447 
   1448 STATIC int onsigchild() {
   1449 	gotsigchild = 1;
   1450 }
   1451 #endif
   1452 
   1453 
   1454 STATIC int
   1455 waitproc(int block, struct job *jp, int *status)
   1456 {
   1457 #ifdef BSD
   1458 	int flags = 0;
   1459 
   1460 #if JOBS
   1461 	if (mflag || (jp != NULL && jp->jobctl))
   1462 		flags |= WUNTRACED | WCONTINUED;
   1463 #endif
   1464 	if (block == 0)
   1465 		flags |= WNOHANG;
   1466 	VTRACE(DBG_WAIT, ("waitproc: doing waitpid(flags=%#x)\n", flags));
   1467 	return waitpid(-1, status, flags);
   1468 #else
   1469 #ifdef SYSV
   1470 	int (*save)();
   1471 
   1472 	if (block == 0) {
   1473 		gotsigchild = 0;
   1474 		save = signal(SIGCLD, onsigchild);
   1475 		signal(SIGCLD, save);
   1476 		if (gotsigchild == 0)
   1477 			return 0;
   1478 	}
   1479 	return wait(status);
   1480 #else
   1481 	if (block == 0)
   1482 		return 0;
   1483 	return wait(status);
   1484 #endif
   1485 #endif
   1486 }
   1487 
   1488 /*
   1489  * return 1 if there are stopped jobs, otherwise 0
   1490  */
   1491 int job_warning = 0;
   1492 int
   1493 stoppedjobs(void)
   1494 {
   1495 	int jobno;
   1496 	struct job *jp;
   1497 
   1498 	if (job_warning || jobs_invalid)
   1499 		return (0);
   1500 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1501 		if (jp->used == 0)
   1502 			continue;
   1503 		if (jp->state == JOBSTOPPED) {
   1504 			out2str("You have stopped jobs.\n");
   1505 			job_warning = 2;
   1506 			return (1);
   1507 		}
   1508 	}
   1509 
   1510 	return (0);
   1511 }
   1512 
   1513 /*
   1514  * Return a string identifying a command (to be printed by the
   1515  * jobs command).
   1516  */
   1517 
   1518 STATIC char *cmdnextc;
   1519 STATIC int cmdnleft;
   1520 
   1521 void
   1522 commandtext(struct procstat *ps, union node *n)
   1523 {
   1524 	int len;
   1525 
   1526 	cmdnextc = ps->cmd;
   1527 	if (iflag || mflag || sizeof(ps->cmd) <= 60)
   1528 		len = sizeof(ps->cmd);
   1529 	else if (sizeof ps->cmd <= 400)
   1530 		len = 50;
   1531 	else if (sizeof ps->cmd <= 800)
   1532 		len = 80;
   1533 	else
   1534 		len = sizeof(ps->cmd) / 10;
   1535 	cmdnleft = len;
   1536 	cmdtxt(n);
   1537 	if (cmdnleft <= 0) {
   1538 		char *p = ps->cmd + len - 4;
   1539 		p[0] = '.';
   1540 		p[1] = '.';
   1541 		p[2] = '.';
   1542 		p[3] = 0;
   1543 	} else
   1544 		*cmdnextc = '\0';
   1545 
   1546 	VTRACE(DBG_JOBS,
   1547 	    ("commandtext: ps->cmd %p, end %p, left %d\n\t\"%s\"\n",
   1548 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
   1549 }
   1550 
   1551 
   1552 STATIC void
   1553 cmdtxt(union node *n)
   1554 {
   1555 	union node *np;
   1556 	struct nodelist *lp;
   1557 	const char *p;
   1558 	int i;
   1559 
   1560 	if (n == NULL || cmdnleft <= 0)
   1561 		return;
   1562 	switch (n->type) {
   1563 	case NSEMI:
   1564 		cmdtxt(n->nbinary.ch1);
   1565 		cmdputs("; ");
   1566 		cmdtxt(n->nbinary.ch2);
   1567 		break;
   1568 	case NAND:
   1569 		cmdtxt(n->nbinary.ch1);
   1570 		cmdputs(" && ");
   1571 		cmdtxt(n->nbinary.ch2);
   1572 		break;
   1573 	case NOR:
   1574 		cmdtxt(n->nbinary.ch1);
   1575 		cmdputs(" || ");
   1576 		cmdtxt(n->nbinary.ch2);
   1577 		break;
   1578 	case NDNOT:
   1579 		cmdputs("! ");
   1580 		/* FALLTHROUGH */
   1581 	case NNOT:
   1582 		cmdputs("! ");
   1583 		cmdtxt(n->nnot.com);
   1584 		break;
   1585 	case NPIPE:
   1586 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1587 			cmdtxt(lp->n);
   1588 			if (lp->next)
   1589 				cmdputs(" | ");
   1590 		}
   1591 		if (n->npipe.backgnd)
   1592 			cmdputs(" &");
   1593 		break;
   1594 	case NSUBSHELL:
   1595 		cmdputs("(");
   1596 		cmdtxt(n->nredir.n);
   1597 		cmdputs(")");
   1598 		break;
   1599 	case NREDIR:
   1600 	case NBACKGND:
   1601 		cmdtxt(n->nredir.n);
   1602 		break;
   1603 	case NIF:
   1604 		cmdputs("if ");
   1605 		cmdtxt(n->nif.test);
   1606 		cmdputs("; then ");
   1607 		cmdtxt(n->nif.ifpart);
   1608 		if (n->nif.elsepart) {
   1609 			cmdputs("; else ");
   1610 			cmdtxt(n->nif.elsepart);
   1611 		}
   1612 		cmdputs("; fi");
   1613 		break;
   1614 	case NWHILE:
   1615 		cmdputs("while ");
   1616 		goto until;
   1617 	case NUNTIL:
   1618 		cmdputs("until ");
   1619  until:
   1620 		cmdtxt(n->nbinary.ch1);
   1621 		cmdputs("; do ");
   1622 		cmdtxt(n->nbinary.ch2);
   1623 		cmdputs("; done");
   1624 		break;
   1625 	case NFOR:
   1626 		cmdputs("for ");
   1627 		cmdputs(n->nfor.var);
   1628 		cmdputs(" in ");
   1629 		cmdlist(n->nfor.args, 1);
   1630 		cmdputs("; do ");
   1631 		cmdtxt(n->nfor.body);
   1632 		cmdputs("; done");
   1633 		break;
   1634 	case NCASE:
   1635 		cmdputs("case ");
   1636 		cmdputs(n->ncase.expr->narg.text);
   1637 		cmdputs(" in ");
   1638 		for (np = n->ncase.cases; np; np = np->nclist.next) {
   1639 			cmdtxt(np->nclist.pattern);
   1640 			cmdputs(") ");
   1641 			cmdtxt(np->nclist.body);
   1642 			switch (n->type) {	/* switch (not if) for later */
   1643 			case NCLISTCONT:
   1644 				cmdputs(";& ");
   1645 				break;
   1646 			default:
   1647 				cmdputs(";; ");
   1648 				break;
   1649 			}
   1650 		}
   1651 		cmdputs("esac");
   1652 		break;
   1653 	case NDEFUN:
   1654 		cmdputs(n->narg.text);
   1655 		cmdputs("() { ... }");
   1656 		break;
   1657 	case NCMD:
   1658 		cmdlist(n->ncmd.args, 1);
   1659 		cmdlist(n->ncmd.redirect, 0);
   1660 		if (n->ncmd.backgnd)
   1661 			cmdputs(" &");
   1662 		break;
   1663 	case NARG:
   1664 		cmdputs(n->narg.text);
   1665 		break;
   1666 	case NTO:
   1667 		p = ">";  i = 1;  goto redir;
   1668 	case NCLOBBER:
   1669 		p = ">|";  i = 1;  goto redir;
   1670 	case NAPPEND:
   1671 		p = ">>";  i = 1;  goto redir;
   1672 	case NTOFD:
   1673 		p = ">&";  i = 1;  goto redir;
   1674 	case NFROM:
   1675 		p = "<";  i = 0;  goto redir;
   1676 	case NFROMFD:
   1677 		p = "<&";  i = 0;  goto redir;
   1678 	case NFROMTO:
   1679 		p = "<>";  i = 0;  goto redir;
   1680  redir:
   1681 		if (n->nfile.fd != i)
   1682 			cmdputi(n->nfile.fd);
   1683 		cmdputs(p);
   1684 		if (n->type == NTOFD || n->type == NFROMFD) {
   1685 			if (n->ndup.dupfd < 0)
   1686 				cmdputs("-");
   1687 			else
   1688 				cmdputi(n->ndup.dupfd);
   1689 		} else {
   1690 			cmdtxt(n->nfile.fname);
   1691 		}
   1692 		break;
   1693 	case NHERE:
   1694 	case NXHERE:
   1695 		cmdputs("<<...");
   1696 		break;
   1697 	default:
   1698 		cmdputs("???");
   1699 		break;
   1700 	}
   1701 }
   1702 
   1703 STATIC void
   1704 cmdlist(union node *np, int sep)
   1705 {
   1706 	for (; np; np = np->narg.next) {
   1707 		if (!sep)
   1708 			cmdputs(" ");
   1709 		cmdtxt(np);
   1710 		if (sep && np->narg.next)
   1711 			cmdputs(" ");
   1712 	}
   1713 }
   1714 
   1715 
   1716 STATIC void
   1717 cmdputs(const char *s)
   1718 {
   1719 	const char *p, *str = 0;
   1720 	char c, cc[2] = " ";
   1721 	char *nextc;
   1722 	int nleft;
   1723 	int subtype = 0;
   1724 	int quoted = 0;
   1725 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
   1726 					"#", "##", "%", "%%", "}" };
   1727 
   1728 	p = s;
   1729 	nextc = cmdnextc;
   1730 	nleft = cmdnleft;
   1731 	while (nleft > 0 && (c = *p++) != 0) {
   1732 		switch (c) {
   1733 		case CTLNONL:
   1734 			c = '\0';
   1735 			break;
   1736 		case CTLESC:
   1737 			c = *p++;
   1738 			break;
   1739 		case CTLVAR:
   1740 			subtype = *p++;
   1741 			if (subtype & VSLINENO) {	/* undo LINENO hack */
   1742 				if ((subtype & VSTYPE) == VSLENGTH)
   1743 					str = "${#LINENO";	/*}*/
   1744 				else
   1745 					str = "${LINENO";	/*}*/
   1746 				while (is_digit(*p))
   1747 					p++;
   1748 			} else if ((subtype & VSTYPE) == VSLENGTH)
   1749 				str = "${#"; /*}*/
   1750 			else
   1751 				str = "${"; /*}*/
   1752 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
   1753 				quoted ^= 1;
   1754 				c = '"';
   1755 			} else {
   1756 				c = *str++;
   1757 			}
   1758 			break;
   1759 		case CTLENDVAR:		/*{*/
   1760 			c = '}';
   1761 			if (quoted & 1)
   1762 				str = "\"";
   1763 			quoted >>= 1;
   1764 			subtype = 0;
   1765 			break;
   1766 		case CTLBACKQ:
   1767 			c = '$';
   1768 			str = "(...)";
   1769 			break;
   1770 		case CTLBACKQ+CTLQUOTE:
   1771 			c = '"';
   1772 			str = "$(...)\"";
   1773 			break;
   1774 		case CTLARI:
   1775 			c = '$';
   1776 			if (*p == ' ')
   1777 				p++;
   1778 			str = "((";	/*))*/
   1779 			break;
   1780 		case CTLENDARI:		/*((*/
   1781 			c = ')';
   1782 			str = ")";
   1783 			break;
   1784 		case CTLQUOTEMARK:
   1785 			quoted ^= 1;
   1786 			c = '"';
   1787 			break;
   1788 		case CTLQUOTEEND:
   1789 			quoted >>= 1;
   1790 			c = '"';
   1791 			break;
   1792 		case '=':
   1793 			if (subtype == 0)
   1794 				break;
   1795 			str = vstype[subtype & VSTYPE];
   1796 			if (subtype & VSNUL)
   1797 				c = ':';
   1798 			else
   1799 				c = *str++;		/*{*/
   1800 			if (c != '}')
   1801 				quoted <<= 1;
   1802 			else if (*p == CTLENDVAR)
   1803 				c = *str++;
   1804 			subtype = 0;
   1805 			break;
   1806 		case '\'':
   1807 		case '\\':
   1808 		case '"':
   1809 		case '$':
   1810 			/* These can only happen inside quotes */
   1811 			cc[0] = c;
   1812 			str = cc;
   1813 			c = '\\';
   1814 			break;
   1815 		default:
   1816 			break;
   1817 		}
   1818 		if (c != '\0') do {	/* c == 0 implies nothing in str */
   1819 			*nextc++ = c;
   1820 		} while (--nleft > 0 && str && (c = *str++));
   1821 		str = 0;
   1822 	}
   1823 	if ((quoted & 1) && nleft) {
   1824 		*nextc++ = '"';
   1825 		nleft--;
   1826 	}
   1827 	cmdnleft = nleft;
   1828 	cmdnextc = nextc;
   1829 }
   1830