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