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