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