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