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