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