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