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