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