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