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