Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.52
      1 /*	$NetBSD: jobs.c,v 1.52 2002/09/28 03:08:00 mycroft 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. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 #if 0
     42 static char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
     43 #else
     44 __RCSID("$NetBSD: jobs.c,v 1.52 2002/09/28 03:08:00 mycroft Exp $");
     45 #endif
     46 #endif /* not lint */
     47 
     48 #include <fcntl.h>
     49 #include <signal.h>
     50 #include <errno.h>
     51 #include <unistd.h>
     52 #include <stdlib.h>
     53 #include <paths.h>
     54 #include <sys/types.h>
     55 #include <sys/param.h>
     56 #ifdef BSD
     57 #include <sys/wait.h>
     58 #include <sys/time.h>
     59 #include <sys/resource.h>
     60 #endif
     61 #include <sys/ioctl.h>
     62 
     63 #include "shell.h"
     64 #if JOBS
     65 #if OLD_TTY_DRIVER
     66 #include "sgtty.h"
     67 #else
     68 #include <termios.h>
     69 #endif
     70 #undef CEOF			/* syntax.h redefines this */
     71 #endif
     72 #include "redir.h"
     73 #include "show.h"
     74 #include "main.h"
     75 #include "parser.h"
     76 #include "nodes.h"
     77 #include "jobs.h"
     78 #include "options.h"
     79 #include "trap.h"
     80 #include "syntax.h"
     81 #include "input.h"
     82 #include "output.h"
     83 #include "memalloc.h"
     84 #include "error.h"
     85 #include "mystring.h"
     86 
     87 
     88 struct job *jobtab;		/* array of jobs */
     89 int njobs;			/* size of array */
     90 MKINIT short backgndpid = -1;	/* pid of last background process */
     91 #if JOBS
     92 int initialpgrp;		/* pgrp of shell on invocation */
     93 short curjob;			/* current job */
     94 #endif
     95 static int ttyfd = -1;
     96 
     97 STATIC void restartjob __P((struct job *));
     98 STATIC void freejob __P((struct job *));
     99 STATIC struct job *getjob __P((char *));
    100 STATIC int dowait __P((int, struct job *));
    101 STATIC int onsigchild __P((void));
    102 STATIC int waitproc __P((int, struct job *, int *));
    103 STATIC void cmdtxt __P((union node *));
    104 STATIC void cmdputs __P((const char *));
    105 
    106 #ifdef OLD_TTY_DRIVER
    107 static pid_t tcgetpgrp __P((int fd));
    108 static int tcsetpgrp __P((int fd, pid_t pgrp));
    109 
    110 static pid_t
    111 tcgetpgrp(fd)
    112 	int fd;
    113 {
    114 	pid_t pgrp;
    115 	if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
    116 		return -1;
    117 	else
    118 		return pgrp;
    119 }
    120 
    121 static int
    122 tcsetpgrp(fd, pgrp)
    123 	int fd;
    124 	pid_t pgrp;
    125 {
    126 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
    127 }
    128 #endif
    129 
    130 /*
    131  * Turn job control on and off.
    132  *
    133  * Note:  This code assumes that the third arg to ioctl is a character
    134  * pointer, which is true on Berkeley systems but not System V.  Since
    135  * System V doesn't have job control yet, this isn't a problem now.
    136  */
    137 
    138 MKINIT int jobctl;
    139 
    140 void
    141 setjobctl(on)
    142 	int on;
    143 {
    144 #ifdef OLD_TTY_DRIVER
    145 	int ldisc;
    146 #endif
    147 
    148 	if (on == jobctl || rootshell == 0)
    149 		return;
    150 	if (on) {
    151 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
    152 		int err;
    153 		if (ttyfd != -1)
    154 			close(ttyfd);
    155 		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
    156 			int i;
    157 			for (i = 0; i < 3; i++) {
    158 				if (isatty(i) && (ttyfd = dup(i)) != -1)
    159 					break;
    160 			}
    161 			if (i == 3)
    162 				goto out;
    163 		}
    164 #ifdef FIOCLEX
    165 		err = ioctl(ttyfd, FIOCLEX, 0);
    166 #elif FD_CLOEXEC
    167 		err = fcntl(ttyfd, FD_CLOEXEC, 1);
    168 #endif
    169 		if (err == -1) {
    170 			close(ttyfd);
    171 			ttyfd = -1;
    172 			goto out;
    173 		}
    174 #else
    175 		out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
    176 		goto out;
    177 #endif
    178 		do { /* while we are in the background */
    179 			if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
    180 out:
    181 				out2str("sh: can't access tty; job control turned off\n");
    182 				mflag = 0;
    183 				return;
    184 			}
    185 			if (initialpgrp == -1)
    186 				initialpgrp = getpgrp();
    187 			else if (initialpgrp != getpgrp()) {
    188 				killpg(0, SIGTTIN);
    189 				continue;
    190 			}
    191 		} while (0);
    192 
    193 #ifdef OLD_TTY_DRIVER
    194 		if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
    195 		    || ldisc != NTTYDISC) {
    196 			out2str("sh: need new tty driver to run job control; job control turned off\n");
    197 			mflag = 0;
    198 			return;
    199 		}
    200 #endif
    201 		setsignal(SIGTSTP, 0);
    202 		setsignal(SIGTTOU, 0);
    203 		setsignal(SIGTTIN, 0);
    204 		if (getpgid(0) != rootpid && setpgid(0, rootpid) == -1)
    205 			error("Cannot set process group (%s) at %d",
    206 			    strerror(errno), __LINE__);
    207 		if (tcsetpgrp(ttyfd, rootpid) == -1)
    208 			error("Cannot set tty process group (%s) at %d",
    209 			    strerror(errno), __LINE__);
    210 	} else { /* turning job control off */
    211 		if (getpgid(0) != initialpgrp && setpgid(0, initialpgrp) == -1)
    212 			error("Cannot set process group (%s) at %d",
    213 			    strerror(errno), __LINE__);
    214 		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
    215 			error("Cannot set tty process group (%s) at %d",
    216 			    strerror(errno), __LINE__);
    217 		close(ttyfd);
    218 		ttyfd = -1;
    219 		setsignal(SIGTSTP, 0);
    220 		setsignal(SIGTTOU, 0);
    221 		setsignal(SIGTTIN, 0);
    222 	}
    223 	jobctl = on;
    224 }
    225 
    226 
    227 #ifdef mkinit
    228 INCLUDE <stdlib.h>
    229 
    230 SHELLPROC {
    231 	backgndpid = -1;
    232 #if JOBS
    233 	jobctl = 0;
    234 #endif
    235 }
    236 
    237 #endif
    238 
    239 
    240 
    241 #if JOBS
    242 int
    243 fgcmd(argc, argv)
    244 	int argc;
    245 	char **argv;
    246 {
    247 	struct job *jp;
    248 	int i;
    249 	int status;
    250 
    251 	jp = getjob(argv[1]);
    252 	if (jp->jobctl == 0)
    253 		error("job not created under job control");
    254 
    255 	for (i = 0; i < jp->nprocs; i++)
    256 	    if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
    257 		    break;
    258 
    259 	if (i >= jp->nprocs) {
    260 		error("Cannot set tty process group (%s) at %d",
    261 		    strerror(errno), __LINE__);
    262 	}
    263 	restartjob(jp);
    264 	INTOFF;
    265 	status = waitforjob(jp);
    266 	INTON;
    267 	return status;
    268 }
    269 
    270 
    271 int
    272 bgcmd(argc, argv)
    273 	int argc;
    274 	char **argv;
    275 {
    276 	struct job *jp;
    277 
    278 	do {
    279 		jp = getjob(*++argv);
    280 		if (jp->jobctl == 0)
    281 			error("job not created under job control");
    282 		restartjob(jp);
    283 	} while (--argc > 1);
    284 	return 0;
    285 }
    286 
    287 
    288 STATIC void
    289 restartjob(jp)
    290 	struct job *jp;
    291 {
    292 	struct procstat *ps;
    293 	int i;
    294 
    295 	if (jp->state == JOBDONE)
    296 		return;
    297 	INTOFF;
    298 	for (i = 0; i < jp->nprocs; i++)
    299 		if (killpg(jp->ps[i].pid, SIGCONT) != -1)
    300 			break;
    301 	if (i >= jp->nprocs)
    302 		error("Cannot continue job (%s)", strerror(errno));
    303 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
    304 		if (WIFSTOPPED(ps->status)) {
    305 			ps->status = -1;
    306 			jp->state = 0;
    307 		}
    308 	}
    309 	INTON;
    310 }
    311 #endif
    312 
    313 
    314 int
    315 jobscmd(argc, argv)
    316 	int argc;
    317 	char **argv;
    318 {
    319 	showjobs(0);
    320 	return 0;
    321 }
    322 
    323 
    324 /*
    325  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
    326  * statuses have changed since the last call to showjobs.
    327  *
    328  * If the shell is interrupted in the process of creating a job, the
    329  * result may be a job structure containing zero processes.  Such structures
    330  * will be freed here.
    331  */
    332 
    333 void
    334 showjobs(change)
    335 	int change;
    336 {
    337 	int jobno;
    338 	int procno;
    339 	int i;
    340 	struct job *jp;
    341 	struct procstat *ps;
    342 	int col;
    343 	int silent = 0, gotpid;
    344 	char s[64];
    345 
    346 	TRACE(("showjobs(%d) called\n", change));
    347 
    348 	/* If not even one one job changed, there is nothing to do */
    349 	gotpid = dowait(0, NULL);
    350 	while (dowait(0, NULL) > 0)
    351 		continue;
    352 #ifdef JOBS
    353 	/*
    354 	 * Check if we are not in our foreground group, and if not
    355 	 * put us in it.
    356 	 */
    357 	if (gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
    358 		if (tcsetpgrp(ttyfd, getpid()) == -1)
    359 			error("Cannot set tty process group (%s) at %d",
    360 			    strerror(errno), __LINE__);
    361 		TRACE(("repaired tty process group\n"));
    362 		silent = 1;
    363 	}
    364 #endif
    365 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
    366 		if (! jp->used)
    367 			continue;
    368 		if (jp->nprocs == 0) {
    369 			freejob(jp);
    370 			continue;
    371 		}
    372 		if (change && ! jp->changed)
    373 			continue;
    374 		if (silent && jp->changed) {
    375 			jp->changed = 0;
    376 			continue;
    377 		}
    378 		procno = jp->nprocs;
    379 		for (ps = jp->ps ; ; ps++) {	/* for each process */
    380 			if (ps == jp->ps)
    381 				fmtstr(s, 64, "[%d] %ld ", jobno,
    382 				    (long)ps->pid);
    383 			else
    384 				fmtstr(s, 64, "    %ld ",
    385 				    (long)ps->pid);
    386 			out1str(s);
    387 			col = strlen(s);
    388 			s[0] = '\0';
    389 			if (ps->status == -1) {
    390 				/* don't print anything */
    391 			} else if (WIFEXITED(ps->status)) {
    392 				fmtstr(s, 64, "Exit %d",
    393 				       WEXITSTATUS(ps->status));
    394 			} else {
    395 #if JOBS
    396 				if (WIFSTOPPED(ps->status))
    397 					i = WSTOPSIG(ps->status);
    398 				else /* WIFSIGNALED(ps->status) */
    399 #endif
    400 					i = WTERMSIG(ps->status);
    401 				if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
    402 					scopy(sys_siglist[i & 0x7F], s);
    403 				else
    404 					fmtstr(s, 64, "Signal %d", i & 0x7F);
    405 				if (WCOREDUMP(ps->status))
    406 					strcat(s, " (core dumped)");
    407 			}
    408 			out1str(s);
    409 			col += strlen(s);
    410 			do {
    411 				out1c(' ');
    412 				col++;
    413 			} while (col < 30);
    414 			out1str(ps->cmd);
    415 			out1c('\n');
    416 			if (--procno <= 0)
    417 				break;
    418 		}
    419 		jp->changed = 0;
    420 		if (jp->state == JOBDONE) {
    421 			freejob(jp);
    422 		}
    423 	}
    424 }
    425 
    426 
    427 /*
    428  * Mark a job structure as unused.
    429  */
    430 
    431 STATIC void
    432 freejob(jp)
    433 	struct job *jp;
    434 	{
    435 	struct procstat *ps;
    436 	int i;
    437 
    438 	INTOFF;
    439 	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
    440 		if (ps->cmd != nullstr)
    441 			ckfree(ps->cmd);
    442 	}
    443 	if (jp->ps != &jp->ps0) {
    444 		ckfree(jp->ps);
    445 		jp->ps = &jp->ps0;
    446 	}
    447 	jp->nprocs = 0;
    448 	jp->used = 0;
    449 #if JOBS
    450 	if (curjob == jp - jobtab + 1)
    451 		curjob = 0;
    452 #endif
    453 	INTON;
    454 }
    455 
    456 
    457 
    458 int
    459 waitcmd(argc, argv)
    460 	int argc;
    461 	char **argv;
    462 {
    463 	struct job *job;
    464 	int status, retval;
    465 	struct job *jp;
    466 
    467 	if (argc > 1) {
    468 		job = getjob(argv[1]);
    469 	} else {
    470 		job = NULL;
    471 	}
    472 	for (;;) {	/* loop until process terminated or stopped */
    473 		if (job != NULL) {
    474 			if (job->state) {
    475 				status = job->ps[job->nprocs - 1].status;
    476 				if (WIFEXITED(status))
    477 					retval = WEXITSTATUS(status);
    478 #if JOBS
    479 				else if (WIFSTOPPED(status))
    480 					retval = WSTOPSIG(status) + 128;
    481 #endif
    482 				else {
    483 					/* XXX: limits number of signals */
    484 					retval = WTERMSIG(status) + 128;
    485 				}
    486 				if (! iflag)
    487 					freejob(job);
    488 				return retval;
    489 			}
    490 		} else {
    491 			for (jp = jobtab ; ; jp++) {
    492 				if (jp >= jobtab + njobs) {	/* no running procs */
    493 					return 0;
    494 				}
    495 				if (jp->used && jp->state == 0)
    496 					break;
    497 			}
    498 		}
    499 		if (dowait(1, (struct job *)NULL) == -1)
    500 		       return 128 + SIGINT;
    501 	}
    502 }
    503 
    504 
    505 
    506 int
    507 jobidcmd(argc, argv)
    508 	int argc;
    509 	char **argv;
    510 {
    511 	struct job *jp;
    512 	int i;
    513 
    514 	jp = getjob(argv[1]);
    515 	for (i = 0 ; i < jp->nprocs ; ) {
    516 		out1fmt("%ld", (long)jp->ps[i].pid);
    517 		out1c(++i < jp->nprocs? ' ' : '\n');
    518 	}
    519 	return 0;
    520 }
    521 
    522 
    523 
    524 /*
    525  * Convert a job name to a job structure.
    526  */
    527 
    528 STATIC struct job *
    529 getjob(name)
    530 	char *name;
    531 	{
    532 	int jobno;
    533 	struct job *jp;
    534 	int pid;
    535 	int i;
    536 
    537 	if (name == NULL) {
    538 #if JOBS
    539 currentjob:
    540 		if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
    541 			error("No current job");
    542 		return &jobtab[jobno - 1];
    543 #else
    544 		error("No current job");
    545 #endif
    546 	} else if (name[0] == '%') {
    547 		if (is_digit(name[1])) {
    548 			jobno = number(name + 1);
    549 			if (jobno > 0 && jobno <= njobs
    550 			 && jobtab[jobno - 1].used != 0)
    551 				return &jobtab[jobno - 1];
    552 #if JOBS
    553 		} else if (name[1] == '%' && name[2] == '\0') {
    554 			goto currentjob;
    555 #endif
    556 		} else {
    557 			struct job *found = NULL;
    558 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    559 				if (jp->used && jp->nprocs > 0
    560 				 && prefix(name + 1, jp->ps[0].cmd)) {
    561 					if (found)
    562 						error("%s: ambiguous", name);
    563 					found = jp;
    564 				}
    565 			}
    566 			if (found)
    567 				return found;
    568 		}
    569 	} else if (is_number(name)) {
    570 		pid = number(name);
    571 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    572 			if (jp->used && jp->nprocs > 0
    573 			 && jp->ps[jp->nprocs - 1].pid == pid)
    574 				return jp;
    575 		}
    576 	}
    577 	error("No such job: %s", name);
    578 	/* NOTREACHED */
    579 }
    580 
    581 
    582 
    583 /*
    584  * Return a new job structure,
    585  */
    586 
    587 struct job *
    588 makejob(node, nprocs)
    589 	union node *node;
    590 	int nprocs;
    591 {
    592 	int i;
    593 	struct job *jp;
    594 
    595 	for (i = njobs, jp = jobtab ; ; jp++) {
    596 		if (--i < 0) {
    597 			INTOFF;
    598 			if (njobs == 0) {
    599 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
    600 			} else {
    601 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
    602 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
    603 				/* Relocate `ps' pointers */
    604 				for (i = 0; i < njobs; i++)
    605 					if (jp[i].ps == &jobtab[i].ps0)
    606 						jp[i].ps = &jp[i].ps0;
    607 				ckfree(jobtab);
    608 				jobtab = jp;
    609 			}
    610 			jp = jobtab + njobs;
    611 			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
    612 			INTON;
    613 			break;
    614 		}
    615 		if (jp->used == 0)
    616 			break;
    617 	}
    618 	INTOFF;
    619 	jp->state = 0;
    620 	jp->used = 1;
    621 	jp->changed = 0;
    622 	jp->nprocs = 0;
    623 #if JOBS
    624 	jp->jobctl = jobctl;
    625 #endif
    626 	if (nprocs > 1) {
    627 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
    628 	} else {
    629 		jp->ps = &jp->ps0;
    630 	}
    631 	INTON;
    632 	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
    633 	    jp - jobtab + 1));
    634 	return jp;
    635 }
    636 
    637 
    638 /*
    639  * Fork off a subshell.  If we are doing job control, give the subshell its
    640  * own process group.  Jp is a job structure that the job is to be added to.
    641  * N is the command that will be evaluated by the child.  Both jp and n may
    642  * be NULL.  The mode parameter can be one of the following:
    643  *	FORK_FG - Fork off a foreground process.
    644  *	FORK_BG - Fork off a background process.
    645  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
    646  *		     process group even if job control is on.
    647  *
    648  * When job control is turned off, background processes have their standard
    649  * input redirected to /dev/null (except for the second and later processes
    650  * in a pipeline).
    651  */
    652 
    653 int
    654 forkshell(jp, n, mode)
    655 	union node *n;
    656 	struct job *jp;
    657 	int mode;
    658 {
    659 	int pid;
    660 
    661 	TRACE(("forkshell(%%%d, %p, %d) called\n", jp - jobtab, n, mode));
    662 	switch ((pid = fork())) {
    663 	case -1:
    664 		TRACE(("Fork failed, errno=%d", errno));
    665 		INTON;
    666 		error("Cannot fork");
    667 		break;
    668 	case 0:
    669 		forkchild(jp, n, mode, 0);
    670 		return 0;
    671 	default:
    672 		return forkparent(jp, n, mode, pid);
    673 	}
    674 }
    675 
    676 int
    677 forkparent(jp, n, mode, pid)
    678 	union node *n;
    679 	struct job *jp;
    680 	int mode;
    681 	pid_t pid;
    682 {
    683 
    684 	if (mode == FORK_BG)
    685 		backgndpid = pid;		/* set $! */
    686 	if (jp) {
    687 		struct procstat *ps = &jp->ps[jp->nprocs++];
    688 		ps->pid = pid;
    689 		ps->status = -1;
    690 		ps->cmd = nullstr;
    691 		if (iflag && rootshell && n)
    692 			ps->cmd = commandtext(n);
    693 	}
    694 	TRACE(("In parent shell:  child = %d\n", pid));
    695 	return pid;
    696 }
    697 
    698 void
    699 forkchild(jp, n, mode, vforked)
    700 	union node *n;
    701 	struct job *jp;
    702 	int mode;
    703 	int vforked;
    704 {
    705 	struct job *p;
    706 	int wasroot;
    707 	int i;
    708 	int pgrp;
    709 	const char *devnull = _PATH_DEVNULL;
    710 	const char *nullerr = "Can't open %s";
    711 
    712 	wasroot = rootshell;
    713 	TRACE(("Child shell %d\n", getpid()));
    714 	if (!vforked) {
    715 		rootshell = 0;
    716 		for (i = njobs, p = jobtab ; --i >= 0 ; p++) {
    717 			if (p == jp)
    718 				continue;
    719 			if (p->used)
    720 				freejob(p);
    721 		}
    722 	}
    723 	closescript(vforked);
    724 	clear_traps(vforked);
    725 #if JOBS
    726 	if (!vforked)
    727 		jobctl = 0;		/* do job control only in root shell */
    728 	if (wasroot && mode != FORK_NOJOB && mflag) {
    729 		if (jp == NULL || jp->nprocs == 0)
    730 			pgrp = getpid();
    731 		else
    732 			pgrp = jp->ps[0].pid;
    733 		if (setpgid(0, pgrp) == -1)
    734 			error("Cannot set process group (%s) at %d",
    735 			    strerror(errno), __LINE__);
    736 		if (mode == FORK_FG) {
    737 			if (tcsetpgrp(ttyfd, pgrp) == -1)
    738 				error("Cannot set tty process group (%s) at %d",
    739 				    strerror(errno), __LINE__);
    740 		}
    741 		setsignal(SIGTSTP, vforked);
    742 		setsignal(SIGTTOU, vforked);
    743 	} else if (mode == FORK_BG) {
    744 		ignoresig(SIGINT, vforked);
    745 		ignoresig(SIGQUIT, vforked);
    746 		if ((jp == NULL || jp->nprocs == 0) &&
    747 		    ! fd0_redirected_p ()) {
    748 			close(0);
    749 			if (open(devnull, O_RDONLY) != 0)
    750 				error(nullerr, devnull);
    751 		}
    752 	}
    753 #else
    754 	if (mode == FORK_BG) {
    755 		ignoresig(SIGINT, vforked);
    756 		ignoresig(SIGQUIT, vforked);
    757 		if ((jp == NULL || jp->nprocs == 0) &&
    758 		    ! fd0_redirected_p ()) {
    759 			close(0);
    760 			if (open(devnull, O_RDONLY) != 0)
    761 				error(nullerr, devnull);
    762 		}
    763 	}
    764 #endif
    765 	if (wasroot && iflag) {
    766 		setsignal(SIGINT, vforked);
    767 		setsignal(SIGQUIT, vforked);
    768 		setsignal(SIGTERM, vforked);
    769 	}
    770 }
    771 
    772 
    773 
    774 /*
    775  * Wait for job to finish.
    776  *
    777  * Under job control we have the problem that while a child process is
    778  * running interrupts generated by the user are sent to the child but not
    779  * to the shell.  This means that an infinite loop started by an inter-
    780  * active user may be hard to kill.  With job control turned off, an
    781  * interactive user may place an interactive program inside a loop.  If
    782  * the interactive program catches interrupts, the user doesn't want
    783  * these interrupts to also abort the loop.  The approach we take here
    784  * is to have the shell ignore interrupt signals while waiting for a
    785  * forground process to terminate, and then send itself an interrupt
    786  * signal if the child process was terminated by an interrupt signal.
    787  * Unfortunately, some programs want to do a bit of cleanup and then
    788  * exit on interrupt; unless these processes terminate themselves by
    789  * sending a signal to themselves (instead of calling exit) they will
    790  * confuse this approach.
    791  */
    792 
    793 int
    794 waitforjob(jp)
    795 	struct job *jp;
    796 	{
    797 #if JOBS
    798 	int mypgrp = getpgrp();
    799 #endif
    800 	int status;
    801 	int st;
    802 
    803 	INTOFF;
    804 	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
    805 	while (jp->state == 0) {
    806 		dowait(1, jp);
    807 	}
    808 #if JOBS
    809 	if (jp->jobctl) {
    810 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
    811 			error("Cannot set tty process group (%s) at %d",
    812 			    strerror(errno), __LINE__);
    813 	}
    814 	if (jp->state == JOBSTOPPED)
    815 		curjob = jp - jobtab + 1;
    816 #endif
    817 	status = jp->ps[jp->nprocs - 1].status;
    818 	/* convert to 8 bits */
    819 	if (WIFEXITED(status))
    820 		st = WEXITSTATUS(status);
    821 #if JOBS
    822 	else if (WIFSTOPPED(status))
    823 		st = WSTOPSIG(status) + 128;
    824 #endif
    825 	else
    826 		st = WTERMSIG(status) + 128;
    827 #if JOBS
    828 	if (jp->jobctl) {
    829 		/*
    830 		 * This is truly gross.
    831 		 * If we're doing job control, then we did a TIOCSPGRP which
    832 		 * caused us (the shell) to no longer be in the controlling
    833 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
    834 		 * intuit from the subprocess exit status whether a SIGINT
    835 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
    836 		 */
    837 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
    838 			raise(SIGINT);
    839 	}
    840 #endif
    841 	if (! JOBS || jp->state == JOBDONE)
    842 		freejob(jp);
    843 	INTON;
    844 	return st;
    845 }
    846 
    847 
    848 
    849 /*
    850  * Wait for a process to terminate.
    851  */
    852 
    853 STATIC int
    854 dowait(block, job)
    855 	int block;
    856 	struct job *job;
    857 {
    858 	int pid;
    859 	int status;
    860 	struct procstat *sp;
    861 	struct job *jp;
    862 	struct job *thisjob;
    863 	int done;
    864 	int stopped;
    865 	int core;
    866 	int sig;
    867 	extern volatile char gotsig[];
    868 
    869 	TRACE(("dowait(%d) called\n", block));
    870 	do {
    871 		pid = waitproc(block, job, &status);
    872 		TRACE(("wait returns %d, status=%d\n", pid, status));
    873 	} while (pid == -1 && errno == EINTR && gotsig[SIGINT - 1] == 0);
    874 	if (pid <= 0)
    875 		return pid;
    876 	INTOFF;
    877 	thisjob = NULL;
    878 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
    879 		if (jp->used) {
    880 			done = 1;
    881 			stopped = 1;
    882 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
    883 				if (sp->pid == -1)
    884 					continue;
    885 				if (sp->pid == pid) {
    886 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
    887 					sp->status = status;
    888 					thisjob = jp;
    889 				}
    890 				if (sp->status == -1)
    891 					stopped = 0;
    892 				else if (WIFSTOPPED(sp->status))
    893 					done = 0;
    894 			}
    895 			if (stopped) {		/* stopped or done */
    896 				int state = done? JOBDONE : JOBSTOPPED;
    897 				if (jp->state != state) {
    898 					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
    899 					jp->state = state;
    900 #if JOBS
    901 					if (done && curjob == jp - jobtab + 1)
    902 						curjob = 0;		/* no current job */
    903 #endif
    904 				}
    905 			}
    906 		}
    907 	}
    908 	if (! rootshell || ! iflag || (job && thisjob == job)) {
    909 		core = WCOREDUMP(status);
    910 #if JOBS
    911 		if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
    912 		else
    913 #endif
    914 		if (WIFEXITED(status)) sig = 0;
    915 		else sig = WTERMSIG(status);
    916 
    917 		if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
    918 			if (thisjob != job)
    919 				outfmt(out2, "%d: ", pid);
    920 #if JOBS
    921 			if (sig == SIGTSTP && rootshell && iflag)
    922 				outfmt(out2, "%%%ld ",
    923 				    (long)(job - jobtab + 1));
    924 #endif
    925 			if (sig < NSIG && sys_siglist[sig])
    926 				out2str(sys_siglist[sig]);
    927 			else
    928 				outfmt(out2, "Signal %d", sig);
    929 			if (core)
    930 				out2str(" - core dumped");
    931 			out2c('\n');
    932 			flushout(&errout);
    933 		} else {
    934 			TRACE(("Not printing status: status=%d, sig=%d\n",
    935 			       status, sig));
    936 		}
    937 	} else {
    938 		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
    939 		if (thisjob)
    940 			thisjob->changed = 1;
    941 	}
    942 	INTON;
    943 	return pid;
    944 }
    945 
    946 
    947 
    948 /*
    949  * Do a wait system call.  If job control is compiled in, we accept
    950  * stopped processes.  If block is zero, we return a value of zero
    951  * rather than blocking.
    952  *
    953  * System V doesn't have a non-blocking wait system call.  It does
    954  * have a SIGCLD signal that is sent to a process when one of it's
    955  * children dies.  The obvious way to use SIGCLD would be to install
    956  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
    957  * was received, and have waitproc bump another counter when it got
    958  * the status of a process.  Waitproc would then know that a wait
    959  * system call would not block if the two counters were different.
    960  * This approach doesn't work because if a process has children that
    961  * have not been waited for, System V will send it a SIGCLD when it
    962  * installs a signal handler for SIGCLD.  What this means is that when
    963  * a child exits, the shell will be sent SIGCLD signals continuously
    964  * until is runs out of stack space, unless it does a wait call before
    965  * restoring the signal handler.  The code below takes advantage of
    966  * this (mis)feature by installing a signal handler for SIGCLD and
    967  * then checking to see whether it was called.  If there are any
    968  * children to be waited for, it will be.
    969  *
    970  * If neither SYSV nor BSD is defined, we don't implement nonblocking
    971  * waits at all.  In this case, the user will not be informed when
    972  * a background process until the next time she runs a real program
    973  * (as opposed to running a builtin command or just typing return),
    974  * and the jobs command may give out of date information.
    975  */
    976 
    977 #ifdef SYSV
    978 STATIC int gotsigchild;
    979 
    980 STATIC int onsigchild() {
    981 	gotsigchild = 1;
    982 }
    983 #endif
    984 
    985 
    986 STATIC int
    987 waitproc(block, jp, status)
    988 	int block;
    989 	struct job *jp;
    990 	int *status;
    991 {
    992 #ifdef BSD
    993 	int flags = 0;
    994 
    995 #if JOBS
    996 	if (jp != NULL && jp->jobctl)
    997 		flags |= WUNTRACED;
    998 #endif
    999 	if (block == 0)
   1000 		flags |= WNOHANG;
   1001 	return wait3(status, flags, (struct rusage *)NULL);
   1002 #else
   1003 #ifdef SYSV
   1004 	int (*save)();
   1005 
   1006 	if (block == 0) {
   1007 		gotsigchild = 0;
   1008 		save = signal(SIGCLD, onsigchild);
   1009 		signal(SIGCLD, save);
   1010 		if (gotsigchild == 0)
   1011 			return 0;
   1012 	}
   1013 	return wait(status);
   1014 #else
   1015 	if (block == 0)
   1016 		return 0;
   1017 	return wait(status);
   1018 #endif
   1019 #endif
   1020 }
   1021 
   1022 /*
   1023  * return 1 if there are stopped jobs, otherwise 0
   1024  */
   1025 int job_warning = 0;
   1026 int
   1027 stoppedjobs()
   1028 {
   1029 	int jobno;
   1030 	struct job *jp;
   1031 
   1032 	if (job_warning)
   1033 		return (0);
   1034 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1035 		if (jp->used == 0)
   1036 			continue;
   1037 		if (jp->state == JOBSTOPPED) {
   1038 			out2str("You have stopped jobs.\n");
   1039 			job_warning = 2;
   1040 			return (1);
   1041 		}
   1042 	}
   1043 
   1044 	return (0);
   1045 }
   1046 
   1047 /*
   1048  * Return a string identifying a command (to be printed by the
   1049  * jobs command.
   1050  */
   1051 
   1052 STATIC char *cmdnextc;
   1053 STATIC int cmdnleft;
   1054 #define MAXCMDTEXT	200
   1055 
   1056 char *
   1057 commandtext(n)
   1058 	union node *n;
   1059 	{
   1060 	char *name;
   1061 
   1062 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
   1063 	cmdnleft = MAXCMDTEXT - 4;
   1064 	cmdtxt(n);
   1065 	*cmdnextc = '\0';
   1066 	return name;
   1067 }
   1068 
   1069 
   1070 STATIC void
   1071 cmdtxt(n)
   1072 	union node *n;
   1073 	{
   1074 	union node *np;
   1075 	struct nodelist *lp;
   1076 	const char *p;
   1077 	int i;
   1078 	char s[2];
   1079 
   1080 	if (n == NULL)
   1081 		return;
   1082 	switch (n->type) {
   1083 	case NSEMI:
   1084 		cmdtxt(n->nbinary.ch1);
   1085 		cmdputs("; ");
   1086 		cmdtxt(n->nbinary.ch2);
   1087 		break;
   1088 	case NAND:
   1089 		cmdtxt(n->nbinary.ch1);
   1090 		cmdputs(" && ");
   1091 		cmdtxt(n->nbinary.ch2);
   1092 		break;
   1093 	case NOR:
   1094 		cmdtxt(n->nbinary.ch1);
   1095 		cmdputs(" || ");
   1096 		cmdtxt(n->nbinary.ch2);
   1097 		break;
   1098 	case NPIPE:
   1099 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1100 			cmdtxt(lp->n);
   1101 			if (lp->next)
   1102 				cmdputs(" | ");
   1103 		}
   1104 		break;
   1105 	case NSUBSHELL:
   1106 		cmdputs("(");
   1107 		cmdtxt(n->nredir.n);
   1108 		cmdputs(")");
   1109 		break;
   1110 	case NREDIR:
   1111 	case NBACKGND:
   1112 		cmdtxt(n->nredir.n);
   1113 		break;
   1114 	case NIF:
   1115 		cmdputs("if ");
   1116 		cmdtxt(n->nif.test);
   1117 		cmdputs("; then ");
   1118 		cmdtxt(n->nif.ifpart);
   1119 		cmdputs("...");
   1120 		break;
   1121 	case NWHILE:
   1122 		cmdputs("while ");
   1123 		goto until;
   1124 	case NUNTIL:
   1125 		cmdputs("until ");
   1126 until:
   1127 		cmdtxt(n->nbinary.ch1);
   1128 		cmdputs("; do ");
   1129 		cmdtxt(n->nbinary.ch2);
   1130 		cmdputs("; done");
   1131 		break;
   1132 	case NFOR:
   1133 		cmdputs("for ");
   1134 		cmdputs(n->nfor.var);
   1135 		cmdputs(" in ...");
   1136 		break;
   1137 	case NCASE:
   1138 		cmdputs("case ");
   1139 		cmdputs(n->ncase.expr->narg.text);
   1140 		cmdputs(" in ...");
   1141 		break;
   1142 	case NDEFUN:
   1143 		cmdputs(n->narg.text);
   1144 		cmdputs("() ...");
   1145 		break;
   1146 	case NCMD:
   1147 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
   1148 			cmdtxt(np);
   1149 			if (np->narg.next)
   1150 				cmdputs(" ");
   1151 		}
   1152 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
   1153 			cmdputs(" ");
   1154 			cmdtxt(np);
   1155 		}
   1156 		break;
   1157 	case NARG:
   1158 		cmdputs(n->narg.text);
   1159 		break;
   1160 	case NTO:
   1161 		p = ">";  i = 1;  goto redir;
   1162 	case NCLOBBER:
   1163 		p = ">|";  i = 1;  goto redir;
   1164 	case NAPPEND:
   1165 		p = ">>";  i = 1;  goto redir;
   1166 	case NTOFD:
   1167 		p = ">&";  i = 1;  goto redir;
   1168 	case NFROM:
   1169 		p = "<";  i = 0;  goto redir;
   1170 	case NFROMFD:
   1171 		p = "<&";  i = 0;  goto redir;
   1172 	case NFROMTO:
   1173 		p = "<>";  i = 0;  goto redir;
   1174 redir:
   1175 		if (n->nfile.fd != i) {
   1176 			s[0] = n->nfile.fd + '0';
   1177 			s[1] = '\0';
   1178 			cmdputs(s);
   1179 		}
   1180 		cmdputs(p);
   1181 		if (n->type == NTOFD || n->type == NFROMFD) {
   1182 			s[0] = n->ndup.dupfd + '0';
   1183 			s[1] = '\0';
   1184 			cmdputs(s);
   1185 		} else {
   1186 			cmdtxt(n->nfile.fname);
   1187 		}
   1188 		break;
   1189 	case NHERE:
   1190 	case NXHERE:
   1191 		cmdputs("<<...");
   1192 		break;
   1193 	default:
   1194 		cmdputs("???");
   1195 		break;
   1196 	}
   1197 }
   1198 
   1199 
   1200 
   1201 STATIC void
   1202 cmdputs(s)
   1203 	const char *s;
   1204 	{
   1205 	const char *p;
   1206 	char *q;
   1207 	char c;
   1208 	int subtype = 0;
   1209 
   1210 	if (cmdnleft <= 0)
   1211 		return;
   1212 	p = s;
   1213 	q = cmdnextc;
   1214 	while ((c = *p++) != '\0') {
   1215 		if (c == CTLESC)
   1216 			*q++ = *p++;
   1217 		else if (c == CTLVAR) {
   1218 			*q++ = '$';
   1219 			if (--cmdnleft > 0)
   1220 				*q++ = '{';
   1221 			subtype = *p++;
   1222 		} else if (c == '=' && subtype != 0) {
   1223 			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
   1224 			subtype = 0;
   1225 		} else if (c == CTLENDVAR) {
   1226 			*q++ = '}';
   1227 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
   1228 			cmdnleft++;		/* ignore it */
   1229 		else
   1230 			*q++ = c;
   1231 		if (--cmdnleft <= 0) {
   1232 			*q++ = '.';
   1233 			*q++ = '.';
   1234 			*q++ = '.';
   1235 			break;
   1236 		}
   1237 	}
   1238 	cmdnextc = q;
   1239 }
   1240