Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.42
      1 /*	$NetBSD: jobs.c,v 1.42 2002/03/12 03:45:02 simonb 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.42 2002/03/12 03:45:02 simonb 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, struct job *, 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);
    153 		setsignal(SIGTTOU);
    154 		setsignal(SIGTTIN);
    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);
    169 		setsignal(SIGTTOU);
    170 		setsignal(SIGTTIN);
    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->ps = &jp->ps0;
    366 	}
    367 	jp->nprocs = 0;
    368 	jp->used = 0;
    369 #if JOBS
    370 	if (curjob == jp - jobtab + 1)
    371 		curjob = 0;
    372 #endif
    373 	INTON;
    374 }
    375 
    376 
    377 
    378 int
    379 waitcmd(argc, argv)
    380 	int argc;
    381 	char **argv;
    382 {
    383 	struct job *job;
    384 	int status, retval;
    385 	struct job *jp;
    386 
    387 	if (argc > 1) {
    388 		job = getjob(argv[1]);
    389 	} else {
    390 		job = NULL;
    391 	}
    392 	for (;;) {	/* loop until process terminated or stopped */
    393 		if (job != NULL) {
    394 			if (job->state) {
    395 				status = job->ps[job->nprocs - 1].status;
    396 				if (WIFEXITED(status))
    397 					retval = WEXITSTATUS(status);
    398 #if JOBS
    399 				else if (WIFSTOPPED(status))
    400 					retval = WSTOPSIG(status) + 128;
    401 #endif
    402 				else {
    403 					/* XXX: limits number of signals */
    404 					retval = WTERMSIG(status) + 128;
    405 				}
    406 				if (! iflag)
    407 					freejob(job);
    408 				return retval;
    409 			}
    410 		} else {
    411 			for (jp = jobtab ; ; jp++) {
    412 				if (jp >= jobtab + njobs) {	/* no running procs */
    413 					return 0;
    414 				}
    415 				if (jp->used && jp->state == 0)
    416 					break;
    417 			}
    418 		}
    419 		dowait(1, (struct job *)NULL);
    420 	}
    421 }
    422 
    423 
    424 
    425 int
    426 jobidcmd(argc, argv)
    427 	int argc;
    428 	char **argv;
    429 {
    430 	struct job *jp;
    431 	int i;
    432 
    433 	jp = getjob(argv[1]);
    434 	for (i = 0 ; i < jp->nprocs ; ) {
    435 		out1fmt("%ld", (long)jp->ps[i].pid);
    436 		out1c(++i < jp->nprocs? ' ' : '\n');
    437 	}
    438 	return 0;
    439 }
    440 
    441 
    442 
    443 /*
    444  * Convert a job name to a job structure.
    445  */
    446 
    447 STATIC struct job *
    448 getjob(name)
    449 	char *name;
    450 	{
    451 	int jobno;
    452 	struct job *jp;
    453 	int pid;
    454 	int i;
    455 
    456 	if (name == NULL) {
    457 #if JOBS
    458 currentjob:
    459 		if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
    460 			error("No current job");
    461 		return &jobtab[jobno - 1];
    462 #else
    463 		error("No current job");
    464 #endif
    465 	} else if (name[0] == '%') {
    466 		if (is_digit(name[1])) {
    467 			jobno = number(name + 1);
    468 			if (jobno > 0 && jobno <= njobs
    469 			 && jobtab[jobno - 1].used != 0)
    470 				return &jobtab[jobno - 1];
    471 #if JOBS
    472 		} else if (name[1] == '%' && name[2] == '\0') {
    473 			goto currentjob;
    474 #endif
    475 		} else {
    476 			struct job *found = NULL;
    477 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    478 				if (jp->used && jp->nprocs > 0
    479 				 && prefix(name + 1, jp->ps[0].cmd)) {
    480 					if (found)
    481 						error("%s: ambiguous", name);
    482 					found = jp;
    483 				}
    484 			}
    485 			if (found)
    486 				return found;
    487 		}
    488 	} else if (is_number(name)) {
    489 		pid = number(name);
    490 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    491 			if (jp->used && jp->nprocs > 0
    492 			 && jp->ps[jp->nprocs - 1].pid == pid)
    493 				return jp;
    494 		}
    495 	}
    496 	error("No such job: %s", name);
    497 	/* NOTREACHED */
    498 }
    499 
    500 
    501 
    502 /*
    503  * Return a new job structure,
    504  */
    505 
    506 struct job *
    507 makejob(node, nprocs)
    508 	union node *node;
    509 	int nprocs;
    510 {
    511 	int i;
    512 	struct job *jp;
    513 
    514 	for (i = njobs, jp = jobtab ; ; jp++) {
    515 		if (--i < 0) {
    516 			INTOFF;
    517 			if (njobs == 0) {
    518 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
    519 			} else {
    520 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
    521 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
    522 				/* Relocate `ps' pointers */
    523 				for (i = 0; i < njobs; i++)
    524 					if (jp[i].ps == &jobtab[i].ps0)
    525 						jp[i].ps = &jp[i].ps0;
    526 				ckfree(jobtab);
    527 				jobtab = jp;
    528 			}
    529 			jp = jobtab + njobs;
    530 			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
    531 			INTON;
    532 			break;
    533 		}
    534 		if (jp->used == 0)
    535 			break;
    536 	}
    537 	INTOFF;
    538 	jp->state = 0;
    539 	jp->used = 1;
    540 	jp->changed = 0;
    541 	jp->nprocs = 0;
    542 #if JOBS
    543 	jp->jobctl = jobctl;
    544 #endif
    545 	if (nprocs > 1) {
    546 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
    547 	} else {
    548 		jp->ps = &jp->ps0;
    549 	}
    550 	INTON;
    551 	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
    552 	    jp - jobtab + 1));
    553 	return jp;
    554 }
    555 
    556 
    557 /*
    558  * Fork off a subshell.  If we are doing job control, give the subshell its
    559  * own process group.  Jp is a job structure that the job is to be added to.
    560  * N is the command that will be evaluated by the child.  Both jp and n may
    561  * be NULL.  The mode parameter can be one of the following:
    562  *	FORK_FG - Fork off a foreground process.
    563  *	FORK_BG - Fork off a background process.
    564  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
    565  *		     process group even if job control is on.
    566  *
    567  * When job control is turned off, background processes have their standard
    568  * input redirected to /dev/null (except for the second and later processes
    569  * in a pipeline).
    570  */
    571 
    572 int
    573 forkshell(jp, n, mode)
    574 	union node *n;
    575 	struct job *jp;
    576 	int mode;
    577 {
    578 	int pid;
    579 	int pgrp;
    580 	const char *devnull = _PATH_DEVNULL;
    581 	const char *nullerr = "Can't open %s";
    582 
    583 	TRACE(("forkshell(%%%d, %p, %d) called\n", jp - jobtab, n, mode));
    584 	INTOFF;
    585 	pid = fork();
    586 	if (pid == -1) {
    587 		TRACE(("Fork failed, errno=%d\n", errno));
    588 		INTON;
    589 		error("Cannot fork");
    590 	}
    591 	if (pid == 0) {
    592 		struct job *p;
    593 		int wasroot;
    594 		int i;
    595 
    596 		TRACE(("Child shell %d\n", getpid()));
    597 		wasroot = rootshell;
    598 		rootshell = 0;
    599 		for (i = njobs, p = jobtab ; --i >= 0 ; p++) {
    600 			if (p == jp)
    601 				continue;	/* don't free current job */
    602 			if (p->used)
    603 				freejob(p);
    604 		}
    605 		closescript();
    606 		INTON;
    607 		clear_traps();
    608 #if JOBS
    609 		jobctl = 0;		/* do job control only in root shell */
    610 		if (wasroot && mode != FORK_NOJOB && mflag) {
    611 			if (jp == NULL || jp->nprocs == 0)
    612 				pgrp = getpid();
    613 			else
    614 				pgrp = jp->ps[0].pid;
    615 			setpgid(0, pgrp);
    616 			if (mode == FORK_FG) {
    617 				/*** this causes superfluous TIOCSPGRPS ***/
    618 #ifdef OLD_TTY_DRIVER
    619 				if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
    620 					error("TIOCSPGRP failed, errno=%d", errno);
    621 #else
    622 				if (tcsetpgrp(2, pgrp) < 0)
    623 					error("tcsetpgrp failed, errno=%d", errno);
    624 #endif
    625 			}
    626 			setsignal(SIGTSTP);
    627 			setsignal(SIGTTOU);
    628 		} else if (mode == FORK_BG) {
    629 			ignoresig(SIGINT);
    630 			ignoresig(SIGQUIT);
    631 			if ((jp == NULL || jp->nprocs == 0) &&
    632 			    ! fd0_redirected_p ()) {
    633 				close(0);
    634 				if (open(devnull, O_RDONLY) != 0)
    635 					error(nullerr, devnull);
    636 			}
    637 		}
    638 #else
    639 		if (mode == FORK_BG) {
    640 			ignoresig(SIGINT);
    641 			ignoresig(SIGQUIT);
    642 			if ((jp == NULL || jp->nprocs == 0) &&
    643 			    ! fd0_redirected_p ()) {
    644 				close(0);
    645 				if (open(devnull, O_RDONLY) != 0)
    646 					error(nullerr, devnull);
    647 			}
    648 		}
    649 #endif
    650 		if (wasroot && iflag) {
    651 			setsignal(SIGINT);
    652 			setsignal(SIGQUIT);
    653 			setsignal(SIGTERM);
    654 		}
    655 		return pid;
    656 	}
    657 	if (rootshell && mode != FORK_NOJOB && mflag) {
    658 		if (jp == NULL || jp->nprocs == 0)
    659 			pgrp = pid;
    660 		else
    661 			pgrp = jp->ps[0].pid;
    662 		setpgid(pid, pgrp);
    663 	}
    664 	if (mode == FORK_BG)
    665 		backgndpid = pid;		/* set $! */
    666 	if (jp) {
    667 		struct procstat *ps = &jp->ps[jp->nprocs++];
    668 		ps->pid = pid;
    669 		ps->status = -1;
    670 		ps->cmd = nullstr;
    671 		if (iflag && rootshell && n)
    672 			ps->cmd = commandtext(n);
    673 	}
    674 	INTON;
    675 	TRACE(("In parent shell:  child = %d\n", pid));
    676 	return pid;
    677 }
    678 
    679 
    680 
    681 /*
    682  * Wait for job to finish.
    683  *
    684  * Under job control we have the problem that while a child process is
    685  * running interrupts generated by the user are sent to the child but not
    686  * to the shell.  This means that an infinite loop started by an inter-
    687  * active user may be hard to kill.  With job control turned off, an
    688  * interactive user may place an interactive program inside a loop.  If
    689  * the interactive program catches interrupts, the user doesn't want
    690  * these interrupts to also abort the loop.  The approach we take here
    691  * is to have the shell ignore interrupt signals while waiting for a
    692  * forground process to terminate, and then send itself an interrupt
    693  * signal if the child process was terminated by an interrupt signal.
    694  * Unfortunately, some programs want to do a bit of cleanup and then
    695  * exit on interrupt; unless these processes terminate themselves by
    696  * sending a signal to themselves (instead of calling exit) they will
    697  * confuse this approach.
    698  */
    699 
    700 int
    701 waitforjob(jp)
    702 	struct job *jp;
    703 	{
    704 #if JOBS
    705 	int mypgrp = getpgrp();
    706 #endif
    707 	int status;
    708 	int st;
    709 
    710 	INTOFF;
    711 	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
    712 	while (jp->state == 0) {
    713 		dowait(1, jp);
    714 	}
    715 #if JOBS
    716 	if (jp->jobctl) {
    717 #ifdef OLD_TTY_DRIVER
    718 		if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
    719 			error("TIOCSPGRP failed, errno=%d\n", errno);
    720 #else
    721 		if (tcsetpgrp(2, mypgrp) < 0)
    722 			error("tcsetpgrp failed, errno=%d\n", errno);
    723 #endif
    724 	}
    725 	if (jp->state == JOBSTOPPED)
    726 		curjob = jp - jobtab + 1;
    727 #endif
    728 	status = jp->ps[jp->nprocs - 1].status;
    729 	/* convert to 8 bits */
    730 	if (WIFEXITED(status))
    731 		st = WEXITSTATUS(status);
    732 #if JOBS
    733 	else if (WIFSTOPPED(status))
    734 		st = WSTOPSIG(status) + 128;
    735 #endif
    736 	else
    737 		st = WTERMSIG(status) + 128;
    738 #if JOBS
    739 	if (jp->jobctl) {
    740 		/*
    741 		 * This is truly gross.
    742 		 * If we're doing job control, then we did a TIOCSPGRP which
    743 		 * caused us (the shell) to no longer be in the controlling
    744 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
    745 		 * intuit from the subprocess exit status whether a SIGINT
    746 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
    747 		 */
    748 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
    749 			raise(SIGINT);
    750 	}
    751 #endif
    752 	if (! JOBS || jp->state == JOBDONE)
    753 		freejob(jp);
    754 	INTON;
    755 	return st;
    756 }
    757 
    758 
    759 
    760 /*
    761  * Wait for a process to terminate.
    762  */
    763 
    764 STATIC int
    765 dowait(block, job)
    766 	int block;
    767 	struct job *job;
    768 {
    769 	int pid;
    770 	int status;
    771 	struct procstat *sp;
    772 	struct job *jp;
    773 	struct job *thisjob;
    774 	int done;
    775 	int stopped;
    776 	int core;
    777 	int sig;
    778 
    779 	TRACE(("dowait(%d) called\n", block));
    780 	do {
    781 		pid = waitproc(block, job, &status);
    782 		TRACE(("wait returns %d, status=%d\n", pid, status));
    783 	} while (pid == -1 && errno == EINTR);
    784 	if (pid <= 0)
    785 		return pid;
    786 	INTOFF;
    787 	thisjob = NULL;
    788 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
    789 		if (jp->used) {
    790 			done = 1;
    791 			stopped = 1;
    792 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
    793 				if (sp->pid == -1)
    794 					continue;
    795 				if (sp->pid == pid) {
    796 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
    797 					sp->status = status;
    798 					thisjob = jp;
    799 				}
    800 				if (sp->status == -1)
    801 					stopped = 0;
    802 				else if (WIFSTOPPED(sp->status))
    803 					done = 0;
    804 			}
    805 			if (stopped) {		/* stopped or done */
    806 				int state = done? JOBDONE : JOBSTOPPED;
    807 				if (jp->state != state) {
    808 					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
    809 					jp->state = state;
    810 #if JOBS
    811 					if (done && curjob == jp - jobtab + 1)
    812 						curjob = 0;		/* no current job */
    813 #endif
    814 				}
    815 			}
    816 		}
    817 	}
    818 	INTON;
    819 	if (! rootshell || ! iflag || (job && thisjob == job)) {
    820 		core = WCOREDUMP(status);
    821 #if JOBS
    822 		if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
    823 		else
    824 #endif
    825 		if (WIFEXITED(status)) sig = 0;
    826 		else sig = WTERMSIG(status);
    827 
    828 		if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
    829 			if (thisjob != job)
    830 				outfmt(out2, "%d: ", pid);
    831 #if JOBS
    832 			if (sig == SIGTSTP && rootshell && iflag)
    833 				outfmt(out2, "%%%ld ",
    834 				    (long)(job - jobtab + 1));
    835 #endif
    836 			if (sig < NSIG && sys_siglist[sig])
    837 				out2str(sys_siglist[sig]);
    838 			else
    839 				outfmt(out2, "Signal %d", sig);
    840 			if (core)
    841 				out2str(" - core dumped");
    842 			out2c('\n');
    843 			flushout(&errout);
    844 		} else {
    845 			TRACE(("Not printing status: status=%d, sig=%d\n",
    846 			       status, sig));
    847 		}
    848 	} else {
    849 		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
    850 		if (thisjob)
    851 			thisjob->changed = 1;
    852 	}
    853 	return pid;
    854 }
    855 
    856 
    857 
    858 /*
    859  * Do a wait system call.  If job control is compiled in, we accept
    860  * stopped processes.  If block is zero, we return a value of zero
    861  * rather than blocking.
    862  *
    863  * System V doesn't have a non-blocking wait system call.  It does
    864  * have a SIGCLD signal that is sent to a process when one of it's
    865  * children dies.  The obvious way to use SIGCLD would be to install
    866  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
    867  * was received, and have waitproc bump another counter when it got
    868  * the status of a process.  Waitproc would then know that a wait
    869  * system call would not block if the two counters were different.
    870  * This approach doesn't work because if a process has children that
    871  * have not been waited for, System V will send it a SIGCLD when it
    872  * installs a signal handler for SIGCLD.  What this means is that when
    873  * a child exits, the shell will be sent SIGCLD signals continuously
    874  * until is runs out of stack space, unless it does a wait call before
    875  * restoring the signal handler.  The code below takes advantage of
    876  * this (mis)feature by installing a signal handler for SIGCLD and
    877  * then checking to see whether it was called.  If there are any
    878  * children to be waited for, it will be.
    879  *
    880  * If neither SYSV nor BSD is defined, we don't implement nonblocking
    881  * waits at all.  In this case, the user will not be informed when
    882  * a background process until the next time she runs a real program
    883  * (as opposed to running a builtin command or just typing return),
    884  * and the jobs command may give out of date information.
    885  */
    886 
    887 #ifdef SYSV
    888 STATIC int gotsigchild;
    889 
    890 STATIC int onsigchild() {
    891 	gotsigchild = 1;
    892 }
    893 #endif
    894 
    895 
    896 STATIC int
    897 waitproc(block, jp, status)
    898 	int block;
    899 	struct job *jp;
    900 	int *status;
    901 {
    902 #ifdef BSD
    903 	int flags = 0;
    904 
    905 #if JOBS
    906 	if (jp != NULL && jp->jobctl)
    907 		flags |= WUNTRACED;
    908 #endif
    909 	if (block == 0)
    910 		flags |= WNOHANG;
    911 	return wait3(status, flags, (struct rusage *)NULL);
    912 #else
    913 #ifdef SYSV
    914 	int (*save)();
    915 
    916 	if (block == 0) {
    917 		gotsigchild = 0;
    918 		save = signal(SIGCLD, onsigchild);
    919 		signal(SIGCLD, save);
    920 		if (gotsigchild == 0)
    921 			return 0;
    922 	}
    923 	return wait(status);
    924 #else
    925 	if (block == 0)
    926 		return 0;
    927 	return wait(status);
    928 #endif
    929 #endif
    930 }
    931 
    932 /*
    933  * return 1 if there are stopped jobs, otherwise 0
    934  */
    935 int job_warning = 0;
    936 int
    937 stoppedjobs()
    938 {
    939 	int jobno;
    940 	struct job *jp;
    941 
    942 	if (job_warning)
    943 		return (0);
    944 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
    945 		if (jp->used == 0)
    946 			continue;
    947 		if (jp->state == JOBSTOPPED) {
    948 			out2str("You have stopped jobs.\n");
    949 			job_warning = 2;
    950 			return (1);
    951 		}
    952 	}
    953 
    954 	return (0);
    955 }
    956 
    957 /*
    958  * Return a string identifying a command (to be printed by the
    959  * jobs command.
    960  */
    961 
    962 STATIC char *cmdnextc;
    963 STATIC int cmdnleft;
    964 #define MAXCMDTEXT	200
    965 
    966 char *
    967 commandtext(n)
    968 	union node *n;
    969 	{
    970 	char *name;
    971 
    972 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
    973 	cmdnleft = MAXCMDTEXT - 4;
    974 	cmdtxt(n);
    975 	*cmdnextc = '\0';
    976 	return name;
    977 }
    978 
    979 
    980 STATIC void
    981 cmdtxt(n)
    982 	union node *n;
    983 	{
    984 	union node *np;
    985 	struct nodelist *lp;
    986 	const char *p;
    987 	int i;
    988 	char s[2];
    989 
    990 	if (n == NULL)
    991 		return;
    992 	switch (n->type) {
    993 	case NSEMI:
    994 		cmdtxt(n->nbinary.ch1);
    995 		cmdputs("; ");
    996 		cmdtxt(n->nbinary.ch2);
    997 		break;
    998 	case NAND:
    999 		cmdtxt(n->nbinary.ch1);
   1000 		cmdputs(" && ");
   1001 		cmdtxt(n->nbinary.ch2);
   1002 		break;
   1003 	case NOR:
   1004 		cmdtxt(n->nbinary.ch1);
   1005 		cmdputs(" || ");
   1006 		cmdtxt(n->nbinary.ch2);
   1007 		break;
   1008 	case NPIPE:
   1009 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1010 			cmdtxt(lp->n);
   1011 			if (lp->next)
   1012 				cmdputs(" | ");
   1013 		}
   1014 		break;
   1015 	case NSUBSHELL:
   1016 		cmdputs("(");
   1017 		cmdtxt(n->nredir.n);
   1018 		cmdputs(")");
   1019 		break;
   1020 	case NREDIR:
   1021 	case NBACKGND:
   1022 		cmdtxt(n->nredir.n);
   1023 		break;
   1024 	case NIF:
   1025 		cmdputs("if ");
   1026 		cmdtxt(n->nif.test);
   1027 		cmdputs("; then ");
   1028 		cmdtxt(n->nif.ifpart);
   1029 		cmdputs("...");
   1030 		break;
   1031 	case NWHILE:
   1032 		cmdputs("while ");
   1033 		goto until;
   1034 	case NUNTIL:
   1035 		cmdputs("until ");
   1036 until:
   1037 		cmdtxt(n->nbinary.ch1);
   1038 		cmdputs("; do ");
   1039 		cmdtxt(n->nbinary.ch2);
   1040 		cmdputs("; done");
   1041 		break;
   1042 	case NFOR:
   1043 		cmdputs("for ");
   1044 		cmdputs(n->nfor.var);
   1045 		cmdputs(" in ...");
   1046 		break;
   1047 	case NCASE:
   1048 		cmdputs("case ");
   1049 		cmdputs(n->ncase.expr->narg.text);
   1050 		cmdputs(" in ...");
   1051 		break;
   1052 	case NDEFUN:
   1053 		cmdputs(n->narg.text);
   1054 		cmdputs("() ...");
   1055 		break;
   1056 	case NCMD:
   1057 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
   1058 			cmdtxt(np);
   1059 			if (np->narg.next)
   1060 				cmdputs(" ");
   1061 		}
   1062 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
   1063 			cmdputs(" ");
   1064 			cmdtxt(np);
   1065 		}
   1066 		break;
   1067 	case NARG:
   1068 		cmdputs(n->narg.text);
   1069 		break;
   1070 	case NTO:
   1071 		p = ">";  i = 1;  goto redir;
   1072 	case NAPPEND:
   1073 		p = ">>";  i = 1;  goto redir;
   1074 	case NTOFD:
   1075 		p = ">&";  i = 1;  goto redir;
   1076 	case NFROM:
   1077 		p = "<";  i = 0;  goto redir;
   1078 	case NFROMFD:
   1079 		p = "<&";  i = 0;  goto redir;
   1080 	case NFROMTO:
   1081 		p = "<>";  i = 0;  goto redir;
   1082 redir:
   1083 		if (n->nfile.fd != i) {
   1084 			s[0] = n->nfile.fd + '0';
   1085 			s[1] = '\0';
   1086 			cmdputs(s);
   1087 		}
   1088 		cmdputs(p);
   1089 		if (n->type == NTOFD || n->type == NFROMFD) {
   1090 			s[0] = n->ndup.dupfd + '0';
   1091 			s[1] = '\0';
   1092 			cmdputs(s);
   1093 		} else {
   1094 			cmdtxt(n->nfile.fname);
   1095 		}
   1096 		break;
   1097 	case NHERE:
   1098 	case NXHERE:
   1099 		cmdputs("<<...");
   1100 		break;
   1101 	default:
   1102 		cmdputs("???");
   1103 		break;
   1104 	}
   1105 }
   1106 
   1107 
   1108 
   1109 STATIC void
   1110 cmdputs(s)
   1111 	const char *s;
   1112 	{
   1113 	const char *p;
   1114 	char *q;
   1115 	char c;
   1116 	int subtype = 0;
   1117 
   1118 	if (cmdnleft <= 0)
   1119 		return;
   1120 	p = s;
   1121 	q = cmdnextc;
   1122 	while ((c = *p++) != '\0') {
   1123 		if (c == CTLESC)
   1124 			*q++ = *p++;
   1125 		else if (c == CTLVAR) {
   1126 			*q++ = '$';
   1127 			if (--cmdnleft > 0)
   1128 				*q++ = '{';
   1129 			subtype = *p++;
   1130 		} else if (c == '=' && subtype != 0) {
   1131 			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
   1132 			subtype = 0;
   1133 		} else if (c == CTLENDVAR) {
   1134 			*q++ = '}';
   1135 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
   1136 			cmdnleft++;		/* ignore it */
   1137 		else
   1138 			*q++ = c;
   1139 		if (--cmdnleft <= 0) {
   1140 			*q++ = '.';
   1141 			*q++ = '.';
   1142 			*q++ = '.';
   1143 			break;
   1144 		}
   1145 	}
   1146 	cmdnextc = q;
   1147 }
   1148