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