Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.51
      1 /*	$NetBSD: jobs.c,v 1.51 2002/09/28 01:25:01 christos 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.51 2002/09/28 01:25:01 christos 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 	int pgrp;
    684 
    685 	if (rootshell && mode != FORK_NOJOB && mflag) {
    686 		if (jp == NULL || jp->nprocs == 0)
    687 			pgrp = pid;
    688 		else
    689 			pgrp = jp->ps[0].pid;
    690 		/* This can fail because we are doing it in the child also */
    691 		(void)setpgid(pid, pgrp);
    692 	}
    693 	if (mode == FORK_BG)
    694 		backgndpid = pid;		/* set $! */
    695 	if (jp) {
    696 		struct procstat *ps = &jp->ps[jp->nprocs++];
    697 		ps->pid = pid;
    698 		ps->status = -1;
    699 		ps->cmd = nullstr;
    700 		if (iflag && rootshell && n)
    701 			ps->cmd = commandtext(n);
    702 	}
    703 	TRACE(("In parent shell:  child = %d\n", pid));
    704 	return pid;
    705 }
    706 
    707 void
    708 forkchild(jp, n, mode, vforked)
    709 	union node *n;
    710 	struct job *jp;
    711 	int mode;
    712 	int vforked;
    713 {
    714 	struct job *p;
    715 	int wasroot;
    716 	int i;
    717 	int pgrp;
    718 	const char *devnull = _PATH_DEVNULL;
    719 	const char *nullerr = "Can't open %s";
    720 
    721 	wasroot = rootshell;
    722 	TRACE(("Child shell %d\n", getpid()));
    723 	if (!vforked) {
    724 		rootshell = 0;
    725 		for (i = njobs, p = jobtab ; --i >= 0 ; p++) {
    726 			if (p == jp)
    727 				continue;
    728 			if (p->used)
    729 				freejob(p);
    730 		}
    731 	}
    732 	closescript(vforked);
    733 	clear_traps(vforked);
    734 #if JOBS
    735 	if (!vforked)
    736 		jobctl = 0;		/* do job control only in root shell */
    737 	if (wasroot && mode != FORK_NOJOB && mflag) {
    738 		if (jp == NULL || jp->nprocs == 0)
    739 			pgrp = getpid();
    740 		else
    741 			pgrp = jp->ps[0].pid;
    742 		/* This can fail because we are doing it in the parent also */
    743 		(void)setpgid(0, pgrp);
    744 		if (mode == FORK_FG) {
    745 			if (tcsetpgrp(ttyfd, pgrp) == -1)
    746 				error("Cannot set tty process group (%s) at %d",
    747 				    strerror(errno), __LINE__);
    748 		}
    749 		setsignal(SIGTSTP, vforked);
    750 		setsignal(SIGTTOU, vforked);
    751 	} else if (mode == FORK_BG) {
    752 		ignoresig(SIGINT, vforked);
    753 		ignoresig(SIGQUIT, vforked);
    754 		if ((jp == NULL || jp->nprocs == 0) &&
    755 		    ! fd0_redirected_p ()) {
    756 			close(0);
    757 			if (open(devnull, O_RDONLY) != 0)
    758 				error(nullerr, devnull);
    759 		}
    760 	}
    761 #else
    762 	if (mode == FORK_BG) {
    763 		ignoresig(SIGINT, vforked);
    764 		ignoresig(SIGQUIT, vforked);
    765 		if ((jp == NULL || jp->nprocs == 0) &&
    766 		    ! fd0_redirected_p ()) {
    767 			close(0);
    768 			if (open(devnull, O_RDONLY) != 0)
    769 				error(nullerr, devnull);
    770 		}
    771 	}
    772 #endif
    773 	if (wasroot && iflag) {
    774 		setsignal(SIGINT, vforked);
    775 		setsignal(SIGQUIT, vforked);
    776 		setsignal(SIGTERM, vforked);
    777 	}
    778 }
    779 
    780 
    781 
    782 /*
    783  * Wait for job to finish.
    784  *
    785  * Under job control we have the problem that while a child process is
    786  * running interrupts generated by the user are sent to the child but not
    787  * to the shell.  This means that an infinite loop started by an inter-
    788  * active user may be hard to kill.  With job control turned off, an
    789  * interactive user may place an interactive program inside a loop.  If
    790  * the interactive program catches interrupts, the user doesn't want
    791  * these interrupts to also abort the loop.  The approach we take here
    792  * is to have the shell ignore interrupt signals while waiting for a
    793  * forground process to terminate, and then send itself an interrupt
    794  * signal if the child process was terminated by an interrupt signal.
    795  * Unfortunately, some programs want to do a bit of cleanup and then
    796  * exit on interrupt; unless these processes terminate themselves by
    797  * sending a signal to themselves (instead of calling exit) they will
    798  * confuse this approach.
    799  */
    800 
    801 int
    802 waitforjob(jp)
    803 	struct job *jp;
    804 	{
    805 #if JOBS
    806 	int mypgrp = getpgrp();
    807 #endif
    808 	int status;
    809 	int st;
    810 
    811 	INTOFF;
    812 	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
    813 	while (jp->state == 0) {
    814 		dowait(1, jp);
    815 	}
    816 #if JOBS
    817 	if (jp->jobctl) {
    818 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
    819 			error("Cannot set tty process group (%s) at %d",
    820 			    strerror(errno), __LINE__);
    821 	}
    822 	if (jp->state == JOBSTOPPED)
    823 		curjob = jp - jobtab + 1;
    824 #endif
    825 	status = jp->ps[jp->nprocs - 1].status;
    826 	/* convert to 8 bits */
    827 	if (WIFEXITED(status))
    828 		st = WEXITSTATUS(status);
    829 #if JOBS
    830 	else if (WIFSTOPPED(status))
    831 		st = WSTOPSIG(status) + 128;
    832 #endif
    833 	else
    834 		st = WTERMSIG(status) + 128;
    835 #if JOBS
    836 	if (jp->jobctl) {
    837 		/*
    838 		 * This is truly gross.
    839 		 * If we're doing job control, then we did a TIOCSPGRP which
    840 		 * caused us (the shell) to no longer be in the controlling
    841 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
    842 		 * intuit from the subprocess exit status whether a SIGINT
    843 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
    844 		 */
    845 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
    846 			raise(SIGINT);
    847 	}
    848 #endif
    849 	if (! JOBS || jp->state == JOBDONE)
    850 		freejob(jp);
    851 	INTON;
    852 	return st;
    853 }
    854 
    855 
    856 
    857 /*
    858  * Wait for a process to terminate.
    859  */
    860 
    861 STATIC int
    862 dowait(block, job)
    863 	int block;
    864 	struct job *job;
    865 {
    866 	int pid;
    867 	int status;
    868 	struct procstat *sp;
    869 	struct job *jp;
    870 	struct job *thisjob;
    871 	int done;
    872 	int stopped;
    873 	int core;
    874 	int sig;
    875 	extern volatile char gotsig[];
    876 
    877 	TRACE(("dowait(%d) called\n", block));
    878 	do {
    879 		pid = waitproc(block, job, &status);
    880 		TRACE(("wait returns %d, status=%d\n", pid, status));
    881 	} while (pid == -1 && errno == EINTR && gotsig[SIGINT - 1] == 0);
    882 	if (pid <= 0)
    883 		return pid;
    884 	INTOFF;
    885 	thisjob = NULL;
    886 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
    887 		if (jp->used) {
    888 			done = 1;
    889 			stopped = 1;
    890 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
    891 				if (sp->pid == -1)
    892 					continue;
    893 				if (sp->pid == pid) {
    894 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
    895 					sp->status = status;
    896 					thisjob = jp;
    897 				}
    898 				if (sp->status == -1)
    899 					stopped = 0;
    900 				else if (WIFSTOPPED(sp->status))
    901 					done = 0;
    902 			}
    903 			if (stopped) {		/* stopped or done */
    904 				int state = done? JOBDONE : JOBSTOPPED;
    905 				if (jp->state != state) {
    906 					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
    907 					jp->state = state;
    908 #if JOBS
    909 					if (done && curjob == jp - jobtab + 1)
    910 						curjob = 0;		/* no current job */
    911 #endif
    912 				}
    913 			}
    914 		}
    915 	}
    916 	if (! rootshell || ! iflag || (job && thisjob == job)) {
    917 		core = WCOREDUMP(status);
    918 #if JOBS
    919 		if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
    920 		else
    921 #endif
    922 		if (WIFEXITED(status)) sig = 0;
    923 		else sig = WTERMSIG(status);
    924 
    925 		if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
    926 			if (thisjob != job)
    927 				outfmt(out2, "%d: ", pid);
    928 #if JOBS
    929 			if (sig == SIGTSTP && rootshell && iflag)
    930 				outfmt(out2, "%%%ld ",
    931 				    (long)(job - jobtab + 1));
    932 #endif
    933 			if (sig < NSIG && sys_siglist[sig])
    934 				out2str(sys_siglist[sig]);
    935 			else
    936 				outfmt(out2, "Signal %d", sig);
    937 			if (core)
    938 				out2str(" - core dumped");
    939 			out2c('\n');
    940 			flushout(&errout);
    941 		} else {
    942 			TRACE(("Not printing status: status=%d, sig=%d\n",
    943 			       status, sig));
    944 		}
    945 	} else {
    946 		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
    947 		if (thisjob)
    948 			thisjob->changed = 1;
    949 	}
    950 	INTON;
    951 	return pid;
    952 }
    953 
    954 
    955 
    956 /*
    957  * Do a wait system call.  If job control is compiled in, we accept
    958  * stopped processes.  If block is zero, we return a value of zero
    959  * rather than blocking.
    960  *
    961  * System V doesn't have a non-blocking wait system call.  It does
    962  * have a SIGCLD signal that is sent to a process when one of it's
    963  * children dies.  The obvious way to use SIGCLD would be to install
    964  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
    965  * was received, and have waitproc bump another counter when it got
    966  * the status of a process.  Waitproc would then know that a wait
    967  * system call would not block if the two counters were different.
    968  * This approach doesn't work because if a process has children that
    969  * have not been waited for, System V will send it a SIGCLD when it
    970  * installs a signal handler for SIGCLD.  What this means is that when
    971  * a child exits, the shell will be sent SIGCLD signals continuously
    972  * until is runs out of stack space, unless it does a wait call before
    973  * restoring the signal handler.  The code below takes advantage of
    974  * this (mis)feature by installing a signal handler for SIGCLD and
    975  * then checking to see whether it was called.  If there are any
    976  * children to be waited for, it will be.
    977  *
    978  * If neither SYSV nor BSD is defined, we don't implement nonblocking
    979  * waits at all.  In this case, the user will not be informed when
    980  * a background process until the next time she runs a real program
    981  * (as opposed to running a builtin command or just typing return),
    982  * and the jobs command may give out of date information.
    983  */
    984 
    985 #ifdef SYSV
    986 STATIC int gotsigchild;
    987 
    988 STATIC int onsigchild() {
    989 	gotsigchild = 1;
    990 }
    991 #endif
    992 
    993 
    994 STATIC int
    995 waitproc(block, jp, status)
    996 	int block;
    997 	struct job *jp;
    998 	int *status;
    999 {
   1000 #ifdef BSD
   1001 	int flags = 0;
   1002 
   1003 #if JOBS
   1004 	if (jp != NULL && jp->jobctl)
   1005 		flags |= WUNTRACED;
   1006 #endif
   1007 	if (block == 0)
   1008 		flags |= WNOHANG;
   1009 	return wait3(status, flags, (struct rusage *)NULL);
   1010 #else
   1011 #ifdef SYSV
   1012 	int (*save)();
   1013 
   1014 	if (block == 0) {
   1015 		gotsigchild = 0;
   1016 		save = signal(SIGCLD, onsigchild);
   1017 		signal(SIGCLD, save);
   1018 		if (gotsigchild == 0)
   1019 			return 0;
   1020 	}
   1021 	return wait(status);
   1022 #else
   1023 	if (block == 0)
   1024 		return 0;
   1025 	return wait(status);
   1026 #endif
   1027 #endif
   1028 }
   1029 
   1030 /*
   1031  * return 1 if there are stopped jobs, otherwise 0
   1032  */
   1033 int job_warning = 0;
   1034 int
   1035 stoppedjobs()
   1036 {
   1037 	int jobno;
   1038 	struct job *jp;
   1039 
   1040 	if (job_warning)
   1041 		return (0);
   1042 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1043 		if (jp->used == 0)
   1044 			continue;
   1045 		if (jp->state == JOBSTOPPED) {
   1046 			out2str("You have stopped jobs.\n");
   1047 			job_warning = 2;
   1048 			return (1);
   1049 		}
   1050 	}
   1051 
   1052 	return (0);
   1053 }
   1054 
   1055 /*
   1056  * Return a string identifying a command (to be printed by the
   1057  * jobs command.
   1058  */
   1059 
   1060 STATIC char *cmdnextc;
   1061 STATIC int cmdnleft;
   1062 #define MAXCMDTEXT	200
   1063 
   1064 char *
   1065 commandtext(n)
   1066 	union node *n;
   1067 	{
   1068 	char *name;
   1069 
   1070 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
   1071 	cmdnleft = MAXCMDTEXT - 4;
   1072 	cmdtxt(n);
   1073 	*cmdnextc = '\0';
   1074 	return name;
   1075 }
   1076 
   1077 
   1078 STATIC void
   1079 cmdtxt(n)
   1080 	union node *n;
   1081 	{
   1082 	union node *np;
   1083 	struct nodelist *lp;
   1084 	const char *p;
   1085 	int i;
   1086 	char s[2];
   1087 
   1088 	if (n == NULL)
   1089 		return;
   1090 	switch (n->type) {
   1091 	case NSEMI:
   1092 		cmdtxt(n->nbinary.ch1);
   1093 		cmdputs("; ");
   1094 		cmdtxt(n->nbinary.ch2);
   1095 		break;
   1096 	case NAND:
   1097 		cmdtxt(n->nbinary.ch1);
   1098 		cmdputs(" && ");
   1099 		cmdtxt(n->nbinary.ch2);
   1100 		break;
   1101 	case NOR:
   1102 		cmdtxt(n->nbinary.ch1);
   1103 		cmdputs(" || ");
   1104 		cmdtxt(n->nbinary.ch2);
   1105 		break;
   1106 	case NPIPE:
   1107 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1108 			cmdtxt(lp->n);
   1109 			if (lp->next)
   1110 				cmdputs(" | ");
   1111 		}
   1112 		break;
   1113 	case NSUBSHELL:
   1114 		cmdputs("(");
   1115 		cmdtxt(n->nredir.n);
   1116 		cmdputs(")");
   1117 		break;
   1118 	case NREDIR:
   1119 	case NBACKGND:
   1120 		cmdtxt(n->nredir.n);
   1121 		break;
   1122 	case NIF:
   1123 		cmdputs("if ");
   1124 		cmdtxt(n->nif.test);
   1125 		cmdputs("; then ");
   1126 		cmdtxt(n->nif.ifpart);
   1127 		cmdputs("...");
   1128 		break;
   1129 	case NWHILE:
   1130 		cmdputs("while ");
   1131 		goto until;
   1132 	case NUNTIL:
   1133 		cmdputs("until ");
   1134 until:
   1135 		cmdtxt(n->nbinary.ch1);
   1136 		cmdputs("; do ");
   1137 		cmdtxt(n->nbinary.ch2);
   1138 		cmdputs("; done");
   1139 		break;
   1140 	case NFOR:
   1141 		cmdputs("for ");
   1142 		cmdputs(n->nfor.var);
   1143 		cmdputs(" in ...");
   1144 		break;
   1145 	case NCASE:
   1146 		cmdputs("case ");
   1147 		cmdputs(n->ncase.expr->narg.text);
   1148 		cmdputs(" in ...");
   1149 		break;
   1150 	case NDEFUN:
   1151 		cmdputs(n->narg.text);
   1152 		cmdputs("() ...");
   1153 		break;
   1154 	case NCMD:
   1155 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
   1156 			cmdtxt(np);
   1157 			if (np->narg.next)
   1158 				cmdputs(" ");
   1159 		}
   1160 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
   1161 			cmdputs(" ");
   1162 			cmdtxt(np);
   1163 		}
   1164 		break;
   1165 	case NARG:
   1166 		cmdputs(n->narg.text);
   1167 		break;
   1168 	case NTO:
   1169 		p = ">";  i = 1;  goto redir;
   1170 	case NCLOBBER:
   1171 		p = ">|";  i = 1;  goto redir;
   1172 	case NAPPEND:
   1173 		p = ">>";  i = 1;  goto redir;
   1174 	case NTOFD:
   1175 		p = ">&";  i = 1;  goto redir;
   1176 	case NFROM:
   1177 		p = "<";  i = 0;  goto redir;
   1178 	case NFROMFD:
   1179 		p = "<&";  i = 0;  goto redir;
   1180 	case NFROMTO:
   1181 		p = "<>";  i = 0;  goto redir;
   1182 redir:
   1183 		if (n->nfile.fd != i) {
   1184 			s[0] = n->nfile.fd + '0';
   1185 			s[1] = '\0';
   1186 			cmdputs(s);
   1187 		}
   1188 		cmdputs(p);
   1189 		if (n->type == NTOFD || n->type == NFROMFD) {
   1190 			s[0] = n->ndup.dupfd + '0';
   1191 			s[1] = '\0';
   1192 			cmdputs(s);
   1193 		} else {
   1194 			cmdtxt(n->nfile.fname);
   1195 		}
   1196 		break;
   1197 	case NHERE:
   1198 	case NXHERE:
   1199 		cmdputs("<<...");
   1200 		break;
   1201 	default:
   1202 		cmdputs("???");
   1203 		break;
   1204 	}
   1205 }
   1206 
   1207 
   1208 
   1209 STATIC void
   1210 cmdputs(s)
   1211 	const char *s;
   1212 	{
   1213 	const char *p;
   1214 	char *q;
   1215 	char c;
   1216 	int subtype = 0;
   1217 
   1218 	if (cmdnleft <= 0)
   1219 		return;
   1220 	p = s;
   1221 	q = cmdnextc;
   1222 	while ((c = *p++) != '\0') {
   1223 		if (c == CTLESC)
   1224 			*q++ = *p++;
   1225 		else if (c == CTLVAR) {
   1226 			*q++ = '$';
   1227 			if (--cmdnleft > 0)
   1228 				*q++ = '{';
   1229 			subtype = *p++;
   1230 		} else if (c == '=' && subtype != 0) {
   1231 			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
   1232 			subtype = 0;
   1233 		} else if (c == CTLENDVAR) {
   1234 			*q++ = '}';
   1235 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
   1236 			cmdnleft++;		/* ignore it */
   1237 		else
   1238 			*q++ = c;
   1239 		if (--cmdnleft <= 0) {
   1240 			*q++ = '.';
   1241 			*q++ = '.';
   1242 			*q++ = '.';
   1243 			break;
   1244 		}
   1245 	}
   1246 	cmdnextc = q;
   1247 }
   1248