Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.87
      1 /*	$NetBSD: jobs.c,v 1.87 2017/06/17 12:12:50 kre 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. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
     39 #else
     40 __RCSID("$NetBSD: jobs.c,v 1.87 2017/06/17 12:12:50 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <fcntl.h>
     45 #include <signal.h>
     46 #include <errno.h>
     47 #include <unistd.h>
     48 #include <stdlib.h>
     49 #include <paths.h>
     50 #include <sys/types.h>
     51 #include <sys/param.h>
     52 #ifdef BSD
     53 #include <sys/wait.h>
     54 #include <sys/time.h>
     55 #include <sys/resource.h>
     56 #endif
     57 #include <sys/ioctl.h>
     58 
     59 #include "shell.h"
     60 #if JOBS
     61 #if OLD_TTY_DRIVER
     62 #include "sgtty.h"
     63 #else
     64 #include <termios.h>
     65 #endif
     66 #undef CEOF			/* syntax.h redefines this */
     67 #endif
     68 #include "redir.h"
     69 #include "show.h"
     70 #include "main.h"
     71 #include "parser.h"
     72 #include "nodes.h"
     73 #include "jobs.h"
     74 #include "options.h"
     75 #include "builtins.h"
     76 #include "trap.h"
     77 #include "syntax.h"
     78 #include "input.h"
     79 #include "output.h"
     80 #include "memalloc.h"
     81 #include "error.h"
     82 #include "mystring.h"
     83 
     84 
     85 static struct job *jobtab;		/* array of jobs */
     86 static int njobs;			/* size of array */
     87 static int jobs_invalid;		/* set in child */
     88 MKINIT pid_t backgndpid = -1;	/* pid of last background process */
     89 #if JOBS
     90 int initialpgrp;		/* pgrp of shell on invocation */
     91 static int curjob = -1;		/* current job */
     92 #endif
     93 static int ttyfd = -1;
     94 
     95 STATIC void restartjob(struct job *);
     96 STATIC void freejob(struct job *);
     97 STATIC struct job *getjob(const char *, int);
     98 STATIC int dowait(int, struct job *);
     99 #define WBLOCK	1
    100 #define WNOFREE 2
    101 STATIC int waitproc(int, struct job *, int *);
    102 STATIC void cmdtxt(union node *);
    103 STATIC void cmdlist(union node *, int);
    104 STATIC void cmdputs(const char *);
    105 inline static void cmdputi(int);
    106 
    107 #ifdef SYSV
    108 STATIC int onsigchild(void);
    109 #endif
    110 
    111 #ifdef OLD_TTY_DRIVER
    112 static pid_t tcgetpgrp(int fd);
    113 static int tcsetpgrp(int fd, pid_t pgrp);
    114 
    115 static pid_t
    116 tcgetpgrp(int fd)
    117 {
    118 	pid_t pgrp;
    119 	if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
    120 		return -1;
    121 	else
    122 		return pgrp;
    123 }
    124 
    125 static int
    126 tcsetpgrp(int fd, pid_tpgrp)
    127 {
    128 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
    129 }
    130 #endif
    131 
    132 static void
    133 ttyfd_change(int from, int to)
    134 {
    135 	if (ttyfd == from)
    136 		ttyfd = to;
    137 }
    138 
    139 /*
    140  * Turn job control on and off.
    141  *
    142  * Note:  This code assumes that the third arg to ioctl is a character
    143  * pointer, which is true on Berkeley systems but not System V.  Since
    144  * System V doesn't have job control yet, this isn't a problem now.
    145  */
    146 
    147 MKINIT int jobctl;
    148 
    149 void
    150 setjobctl(int on)
    151 {
    152 #ifdef OLD_TTY_DRIVER
    153 	int ldisc;
    154 #endif
    155 
    156 	if (on == jobctl || rootshell == 0)
    157 		return;
    158 	if (on) {
    159 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
    160 		int i;
    161 
    162 		if (ttyfd != -1)
    163 			sh_close(ttyfd);
    164 		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
    165 			for (i = 0; i < 3; i++) {
    166 				if (isatty(i) && (ttyfd = dup(i)) != -1)
    167 					break;
    168 			}
    169 			if (i == 3)
    170 				goto out;
    171 		}
    172 		ttyfd = to_upper_fd(ttyfd);	/* Move to a high fd */
    173 		register_sh_fd(ttyfd, ttyfd_change);
    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, 0);
    202 		setsignal(SIGTTOU, 0);
    203 		setsignal(SIGTTIN, 0);
    204 		if (getpgrp() != rootpid && setpgid(0, rootpid) == -1)
    205 			error("Cannot set process group (%s) at %d",
    206 			    strerror(errno), __LINE__);
    207 		if (tcsetpgrp(ttyfd, rootpid) == -1)
    208 			error("Cannot set tty process group (%s) at %d",
    209 			    strerror(errno), __LINE__);
    210 	} else { /* turning job control off */
    211 		if (getpgrp() != initialpgrp && setpgid(0, initialpgrp) == -1)
    212 			error("Cannot set process group (%s) at %d",
    213 			    strerror(errno), __LINE__);
    214 		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
    215 			error("Cannot set tty process group (%s) at %d",
    216 			    strerror(errno), __LINE__);
    217 		sh_close(ttyfd);
    218 		ttyfd = -1;
    219 		setsignal(SIGTSTP, 0);
    220 		setsignal(SIGTTOU, 0);
    221 		setsignal(SIGTTIN, 0);
    222 	}
    223 	jobctl = on;
    224 }
    225 
    226 
    227 #ifdef mkinit
    228 INCLUDE <stdlib.h>
    229 
    230 SHELLPROC {
    231 	backgndpid = -1;
    232 #if JOBS
    233 	jobctl = 0;
    234 #endif
    235 }
    236 
    237 #endif
    238 
    239 
    240 
    241 #if JOBS
    242 static int
    243 do_fgcmd(const char *arg_ptr)
    244 {
    245 	struct job *jp;
    246 	int i;
    247 	int status;
    248 
    249 	jp = getjob(arg_ptr, 0);
    250 	if (jp->jobctl == 0)
    251 		error("job not created under job control");
    252 	out1fmt("%s", jp->ps[0].cmd);
    253 	for (i = 1; i < jp->nprocs; i++)
    254 		out1fmt(" | %s", jp->ps[i].cmd );
    255 	out1c('\n');
    256 	flushall();
    257 
    258 	for (i = 0; i < jp->nprocs; i++)
    259 	    if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
    260 		    break;
    261 
    262 	if (i >= jp->nprocs) {
    263 		error("Cannot set tty process group (%s) at %d",
    264 		    strerror(errno), __LINE__);
    265 	}
    266 	restartjob(jp);
    267 	INTOFF;
    268 	status = waitforjob(jp);
    269 	INTON;
    270 	return status;
    271 }
    272 
    273 int
    274 fgcmd(int argc, char **argv)
    275 {
    276 	nextopt("");
    277 	return do_fgcmd(*argptr);
    278 }
    279 
    280 int
    281 fgcmd_percent(int argc, char **argv)
    282 {
    283 	nextopt("");
    284 	return do_fgcmd(*argv);
    285 }
    286 
    287 static void
    288 set_curjob(struct job *jp, int mode)
    289 {
    290 	struct job *jp1, *jp2;
    291 	int i, ji;
    292 
    293 	ji = jp - jobtab;
    294 
    295 	/* first remove from list */
    296 	if (ji == curjob)
    297 		curjob = jp->prev_job;
    298 	else {
    299 		for (i = 0; i < njobs; i++) {
    300 			if (jobtab[i].prev_job != ji)
    301 				continue;
    302 			jobtab[i].prev_job = jp->prev_job;
    303 			break;
    304 		}
    305 	}
    306 
    307 	/* Then re-insert in correct position */
    308 	switch (mode) {
    309 	case 0:	/* job being deleted */
    310 		jp->prev_job = -1;
    311 		break;
    312 	case 1:	/* newly created job or backgrounded job,
    313 		   put after all stopped jobs. */
    314 		if (curjob != -1 && jobtab[curjob].state == JOBSTOPPED) {
    315 			for (jp1 = jobtab + curjob; ; jp1 = jp2) {
    316 				if (jp1->prev_job == -1)
    317 					break;
    318 				jp2 = jobtab + jp1->prev_job;
    319 				if (jp2->state != JOBSTOPPED)
    320 					break;
    321 			}
    322 			jp->prev_job = jp1->prev_job;
    323 			jp1->prev_job = ji;
    324 			break;
    325 		}
    326 		/* FALLTHROUGH */
    327 	case 2:	/* newly stopped job - becomes curjob */
    328 		jp->prev_job = curjob;
    329 		curjob = ji;
    330 		break;
    331 	}
    332 }
    333 
    334 int
    335 bgcmd(int argc, char **argv)
    336 {
    337 	struct job *jp;
    338 	int i;
    339 
    340 	nextopt("");
    341 	do {
    342 		jp = getjob(*argptr, 0);
    343 		if (jp->jobctl == 0)
    344 			error("job not created under job control");
    345 		set_curjob(jp, 1);
    346 		out1fmt("[%ld] %s", (long)(jp - jobtab + 1), jp->ps[0].cmd);
    347 		for (i = 1; i < jp->nprocs; i++)
    348 			out1fmt(" | %s", jp->ps[i].cmd );
    349 		out1c('\n');
    350 		flushall();
    351 		restartjob(jp);
    352 	} while (*argptr && *++argptr);
    353 	return 0;
    354 }
    355 
    356 
    357 STATIC void
    358 restartjob(struct job *jp)
    359 {
    360 	struct procstat *ps;
    361 	int i;
    362 
    363 	if (jp->state == JOBDONE)
    364 		return;
    365 	INTOFF;
    366 	for (i = 0; i < jp->nprocs; i++)
    367 		if (killpg(jp->ps[i].pid, SIGCONT) != -1)
    368 			break;
    369 	if (i >= jp->nprocs)
    370 		error("Cannot continue job (%s)", strerror(errno));
    371 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
    372 		if (WIFSTOPPED(ps->status)) {
    373 			ps->status = -1;
    374 			jp->state = JOBRUNNING;
    375 		}
    376 	}
    377 	INTON;
    378 }
    379 #endif
    380 
    381 inline static void
    382 cmdputi(int n)
    383 {
    384 	char str[20];
    385 
    386 	fmtstr(str, sizeof str, "%d", n);
    387 	cmdputs(str);
    388 }
    389 
    390 static void
    391 showjob(struct output *out, struct job *jp, int mode)
    392 {
    393 	int procno;
    394 	int st;
    395 	struct procstat *ps;
    396 	int col;
    397 	char s[64];
    398 
    399 #if JOBS
    400 	if (mode & SHOW_PGID) {
    401 		/* just output process (group) id of pipeline */
    402 		outfmt(out, "%ld\n", (long)jp->ps->pid);
    403 		return;
    404 	}
    405 #endif
    406 
    407 	procno = jp->nprocs;
    408 	if (!procno)
    409 		return;
    410 
    411 	if (mode & SHOW_PID)
    412 		mode |= SHOW_MULTILINE;
    413 
    414 	if ((procno > 1 && !(mode & SHOW_MULTILINE))
    415 	    || (mode & SHOW_SIGNALLED)) {
    416 		/* See if we have more than one status to report */
    417 		ps = jp->ps;
    418 		st = ps->status;
    419 		do {
    420 			int st1 = ps->status;
    421 			if (st1 != st)
    422 				/* yes - need multi-line output */
    423 				mode |= SHOW_MULTILINE;
    424 			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
    425 				continue;
    426 			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
    427 			    && st1 != SIGINT && st1 != SIGPIPE))
    428 				mode |= SHOW_ISSIG;
    429 
    430 		} while (ps++, --procno);
    431 		procno = jp->nprocs;
    432 	}
    433 
    434 	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
    435 		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
    436 			VTRACE(DBG_JOBS, ("showjob: freeing job %d\n",
    437 			    jp - jobtab + 1));
    438 			freejob(jp);
    439 		}
    440 		return;
    441 	}
    442 
    443 	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
    444 		if (ps == jp->ps)
    445 			fmtstr(s, 16, "[%ld] %c ",
    446 				(long)(jp - jobtab + 1),
    447 #if JOBS
    448 				jp == jobtab + curjob ? '+' :
    449 				curjob != -1 && jp == jobtab +
    450 					    jobtab[curjob].prev_job ? '-' :
    451 #endif
    452 				' ');
    453 		else
    454 			fmtstr(s, 16, "      " );
    455 		col = strlen(s);
    456 		if (mode & SHOW_PID) {
    457 			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
    458 			     col += strlen(s + col);
    459 		}
    460 		if (ps->status == -1) {
    461 			scopy("Running", s + col);
    462 		} else if (WIFEXITED(ps->status)) {
    463 			st = WEXITSTATUS(ps->status);
    464 			if (st)
    465 				fmtstr(s + col, 16, "Done(%d)", st);
    466 			else
    467 				fmtstr(s + col, 16, "Done");
    468 		} else {
    469 #if JOBS
    470 			if (WIFSTOPPED(ps->status))
    471 				st = WSTOPSIG(ps->status);
    472 			else /* WIFSIGNALED(ps->status) */
    473 #endif
    474 				st = WTERMSIG(ps->status);
    475 			st &= 0x7f;
    476 			if (st < NSIG && sys_siglist[st])
    477 				scopyn(sys_siglist[st], s + col, 32);
    478 			else
    479 				fmtstr(s + col, 16, "Signal %d", st);
    480 			if (WCOREDUMP(ps->status)) {
    481 				col += strlen(s + col);
    482 				scopyn(" (core dumped)", s + col,  64 - col);
    483 			}
    484 		}
    485 		col += strlen(s + col);
    486 		outstr(s, out);
    487 		do {
    488 			outc(' ', out);
    489 			col++;
    490 		} while (col < 30);
    491 		outstr(ps->cmd, out);
    492 		if (mode & SHOW_MULTILINE) {
    493 			if (procno > 0) {
    494 				outc(' ', out);
    495 				outc('|', out);
    496 			}
    497 		} else {
    498 			while (--procno >= 0)
    499 				outfmt(out, " | %s", (++ps)->cmd );
    500 		}
    501 		outc('\n', out);
    502 	}
    503 	flushout(out);
    504 	jp->changed = 0;
    505 	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
    506 		freejob(jp);
    507 }
    508 
    509 
    510 int
    511 jobscmd(int argc, char **argv)
    512 {
    513 	int mode, m;
    514 	int sv = jobs_invalid;
    515 
    516 	jobs_invalid = 0;
    517 	mode = 0;
    518 	while ((m = nextopt("lp")))
    519 		if (m == 'l')
    520 			mode = SHOW_PID;
    521 		else
    522 			mode = SHOW_PGID;
    523 	if (*argptr)
    524 		do
    525 			showjob(out1, getjob(*argptr,0), mode);
    526 		while (*++argptr);
    527 	else
    528 		showjobs(out1, mode);
    529 	jobs_invalid = sv;
    530 	return 0;
    531 }
    532 
    533 
    534 /*
    535  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
    536  * statuses have changed since the last call to showjobs.
    537  *
    538  * If the shell is interrupted in the process of creating a job, the
    539  * result may be a job structure containing zero processes.  Such structures
    540  * will be freed here.
    541  */
    542 
    543 void
    544 showjobs(struct output *out, int mode)
    545 {
    546 	int jobno;
    547 	struct job *jp;
    548 	int silent = 0, gotpid;
    549 
    550 	CTRACE(DBG_JOBS, ("showjobs(%x) called\n", mode));
    551 
    552 	/* If not even one one job changed, there is nothing to do */
    553 	gotpid = dowait(0, NULL);
    554 	while (dowait(0, NULL) > 0)
    555 		continue;
    556 #ifdef JOBS
    557 	/*
    558 	 * Check if we are not in our foreground group, and if not
    559 	 * put us in it.
    560 	 */
    561 	if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
    562 		if (tcsetpgrp(ttyfd, getpid()) == -1)
    563 			error("Cannot set tty process group (%s) at %d",
    564 			    strerror(errno), __LINE__);
    565 		VTRACE(DBG_JOBS|DBG_INPUT, ("repaired tty process group\n"));
    566 		silent = 1;
    567 	}
    568 #endif
    569 	if (jobs_invalid)
    570 		return;
    571 
    572 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
    573 		if (!jp->used)
    574 			continue;
    575 		if (jp->nprocs == 0) {
    576 			freejob(jp);
    577 			continue;
    578 		}
    579 		if ((mode & SHOW_CHANGED) && !jp->changed)
    580 			continue;
    581 		if (silent && jp->changed) {
    582 			jp->changed = 0;
    583 			continue;
    584 		}
    585 		showjob(out, jp, mode);
    586 	}
    587 }
    588 
    589 /*
    590  * Mark a job structure as unused.
    591  */
    592 
    593 STATIC void
    594 freejob(struct job *jp)
    595 {
    596 	INTOFF;
    597 	if (jp->ps != &jp->ps0) {
    598 		ckfree(jp->ps);
    599 		jp->ps = &jp->ps0;
    600 	}
    601 	jp->nprocs = 0;
    602 	jp->used = 0;
    603 #if JOBS
    604 	set_curjob(jp, 0);
    605 #endif
    606 	INTON;
    607 }
    608 
    609 
    610 
    611 int
    612 waitcmd(int argc, char **argv)
    613 {
    614 	struct job *job;
    615 	int status, retval;
    616 	struct job *jp;
    617 
    618 	nextopt("");
    619 
    620 	if (!*argptr) {
    621 		/* wait for all jobs */
    622 		jp = jobtab;
    623 		if (jobs_invalid)
    624 			return 0;
    625 		for (;;) {
    626 			if (jp >= jobtab + njobs) {
    627 				/* no running procs */
    628 				return 0;
    629 			}
    630 			if (!jp->used || jp->state != JOBRUNNING) {
    631 				jp++;
    632 				continue;
    633 			}
    634 			if (dowait(WBLOCK, NULL) == -1)
    635 			       return 128 + lastsig();
    636 			jp = jobtab;
    637 		}
    638 	}
    639 
    640 	retval = 127;		/* XXXGCC: -Wuninitialized */
    641 	for (; *argptr; argptr++) {
    642 		job = getjob(*argptr, 1);
    643 		if (!job) {
    644 			retval = 127;
    645 			continue;
    646 		}
    647 		/* loop until process terminated or stopped */
    648 		while (job->state == JOBRUNNING) {
    649 			if (dowait(WBLOCK|WNOFREE, job) == -1)
    650 			       return 128 + lastsig();
    651 		}
    652 		status = job->ps[job->nprocs ? job->nprocs - 1 : 0].status;
    653 		if (WIFEXITED(status))
    654 			retval = WEXITSTATUS(status);
    655 #if JOBS
    656 		else if (WIFSTOPPED(status))
    657 			retval = WSTOPSIG(status) + 128;
    658 #endif
    659 		else {
    660 			/* XXX: limits number of signals */
    661 			retval = WTERMSIG(status) + 128;
    662 		}
    663 		if (!iflag)
    664 			freejob(job);
    665 	}
    666 	return retval;
    667 }
    668 
    669 
    670 
    671 int
    672 jobidcmd(int argc, char **argv)
    673 {
    674 	struct job *jp;
    675 	int i;
    676 
    677 	nextopt("");
    678 	jp = getjob(*argptr, 0);
    679 	for (i = 0 ; i < jp->nprocs ; ) {
    680 		out1fmt("%ld", (long)jp->ps[i].pid);
    681 		out1c(++i < jp->nprocs ? ' ' : '\n');
    682 	}
    683 	return 0;
    684 }
    685 
    686 int
    687 getjobpgrp(const char *name)
    688 {
    689 	struct job *jp;
    690 
    691 	jp = getjob(name, 1);
    692 	if (jp == 0)
    693 		return 0;
    694 	return -jp->ps[0].pid;
    695 }
    696 
    697 /*
    698  * Convert a job name to a job structure.
    699  */
    700 
    701 STATIC struct job *
    702 getjob(const char *name, int noerror)
    703 {
    704 	int jobno = -1;
    705 	struct job *jp;
    706 	int pid;
    707 	int i;
    708 	const char *err_msg = "No such job: %s";
    709 
    710 	if (name == NULL) {
    711 #if JOBS
    712 		jobno = curjob;
    713 #endif
    714 		err_msg = "No current job";
    715 	} else if (name[0] == '%') {
    716 		if (is_number(name + 1)) {
    717 			jobno = number(name + 1) - 1;
    718 		} else if (!name[2]) {
    719 			switch (name[1]) {
    720 #if JOBS
    721 			case 0:
    722 			case '+':
    723 			case '%':
    724 				jobno = curjob;
    725 				err_msg = "No current job";
    726 				break;
    727 			case '-':
    728 				jobno = curjob;
    729 				if (jobno != -1)
    730 					jobno = jobtab[jobno].prev_job;
    731 				err_msg = "No previous job";
    732 				break;
    733 #endif
    734 			default:
    735 				goto check_pattern;
    736 			}
    737 		} else {
    738 			struct job *found;
    739     check_pattern:
    740 			found = NULL;
    741 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    742 				if (!jp->used || jp->nprocs <= 0)
    743 					continue;
    744 				if ((name[1] == '?'
    745 					&& strstr(jp->ps[0].cmd, name + 2))
    746 				    || prefix(name + 1, jp->ps[0].cmd)) {
    747 					if (found) {
    748 						err_msg = "%s: ambiguous";
    749 						found = 0;
    750 						break;
    751 					}
    752 					found = jp;
    753 				}
    754 			}
    755 			if (found)
    756 				return found;
    757 		}
    758 
    759 	} else if (is_number(name)) {
    760 		pid = number(name);
    761 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    762 			if (jp->used && jp->nprocs > 0
    763 			 && jp->ps[jp->nprocs - 1].pid == pid)
    764 				return jp;
    765 		}
    766 	}
    767 
    768 	if (!jobs_invalid && jobno >= 0 && jobno < njobs) {
    769 		jp = jobtab + jobno;
    770 		if (jp->used)
    771 			return jp;
    772 	}
    773 	if (!noerror)
    774 		error(err_msg, name);
    775 	return 0;
    776 }
    777 
    778 
    779 
    780 /*
    781  * Return a new job structure,
    782  */
    783 
    784 struct job *
    785 makejob(union node *node, int nprocs)
    786 {
    787 	int i;
    788 	struct job *jp;
    789 
    790 	if (jobs_invalid) {
    791 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
    792 			if (jp->used)
    793 				freejob(jp);
    794 		}
    795 		jobs_invalid = 0;
    796 	}
    797 
    798 	for (i = njobs, jp = jobtab ; ; jp++) {
    799 		if (--i < 0) {
    800 			INTOFF;
    801 			if (njobs == 0) {
    802 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
    803 			} else {
    804 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
    805 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
    806 				/* Relocate `ps' pointers */
    807 				for (i = 0; i < njobs; i++)
    808 					if (jp[i].ps == &jobtab[i].ps0)
    809 						jp[i].ps = &jp[i].ps0;
    810 				ckfree(jobtab);
    811 				jobtab = jp;
    812 			}
    813 			jp = jobtab + njobs;
    814 			for (i = 4 ; --i >= 0 ; )
    815 				jobtab[njobs++].used = 0;
    816 			INTON;
    817 			break;
    818 		}
    819 		if (jp->used == 0)
    820 			break;
    821 	}
    822 	INTOFF;
    823 	jp->state = JOBRUNNING;
    824 	jp->used = 1;
    825 	jp->changed = 0;
    826 	jp->nprocs = 0;
    827 #if JOBS
    828 	jp->jobctl = jobctl;
    829 	set_curjob(jp, 1);
    830 #endif
    831 	if (nprocs > 1) {
    832 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
    833 	} else {
    834 		jp->ps = &jp->ps0;
    835 	}
    836 	INTON;
    837 	VTRACE(DBG_JOBS, ("makejob(0x%lx, %d) returns %%%d\n",
    838 	    (long)node, nprocs, jp - jobtab + 1));
    839 	return jp;
    840 }
    841 
    842 
    843 /*
    844  * Fork off a subshell.  If we are doing job control, give the subshell its
    845  * own process group.  Jp is a job structure that the job is to be added to.
    846  * N is the command that will be evaluated by the child.  Both jp and n may
    847  * be NULL.  The mode parameter can be one of the following:
    848  *	FORK_FG - Fork off a foreground process.
    849  *	FORK_BG - Fork off a background process.
    850  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
    851  *		     process group even if job control is on.
    852  *
    853  * When job control is turned off, background processes have their standard
    854  * input redirected to /dev/null (except for the second and later processes
    855  * in a pipeline).
    856  */
    857 
    858 int
    859 forkshell(struct job *jp, union node *n, int mode)
    860 {
    861 	pid_t pid;
    862 	int serrno;
    863 
    864 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
    865 	    jp - jobtab, n, mode));
    866 
    867 	switch ((pid = fork())) {
    868 	case -1:
    869 		serrno = errno;
    870 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
    871 		INTON;
    872 		error("Cannot fork (%s)", strerror(serrno));
    873 		break;
    874 	case 0:
    875 		SHELL_FORKED();
    876 		forkchild(jp, n, mode, 0);
    877 		return 0;
    878 	default:
    879 		return forkparent(jp, n, mode, pid);
    880 	}
    881 }
    882 
    883 int
    884 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
    885 {
    886 	int pgrp;
    887 
    888 	if (rootshell && mode != FORK_NOJOB && mflag) {
    889 		if (jp == NULL || jp->nprocs == 0)
    890 			pgrp = pid;
    891 		else
    892 			pgrp = jp->ps[0].pid;
    893 		/* This can fail because we are doing it in the child also */
    894 		(void)setpgid(pid, pgrp);
    895 	}
    896 	if (mode == FORK_BG)
    897 		backgndpid = pid;		/* set $! */
    898 	if (jp) {
    899 		struct procstat *ps = &jp->ps[jp->nprocs++];
    900 		ps->pid = pid;
    901 		ps->status = -1;
    902 		ps->cmd[0] = 0;
    903 		if (/* iflag && rootshell && */ n)
    904 			commandtext(ps, n);
    905 	}
    906 	CTRACE(DBG_JOBS, ("In parent shell:  child = %d\n", pid));
    907 	return pid;
    908 }
    909 
    910 void
    911 forkchild(struct job *jp, union node *n, int mode, int vforked)
    912 {
    913 	int wasroot;
    914 	int pgrp;
    915 	const char *devnull = _PATH_DEVNULL;
    916 	const char *nullerr = "Can't open %s";
    917 
    918 	wasroot = rootshell;
    919 	CTRACE(DBG_JOBS, ("Child shell %d\n", getpid()));
    920 	if (!vforked)
    921 		rootshell = 0;
    922 
    923 	closescript(vforked);
    924 	clear_traps(vforked);
    925 #if JOBS
    926 	if (!vforked)
    927 		jobctl = 0;		/* do job control only in root shell */
    928 	if (wasroot && mode != FORK_NOJOB && mflag) {
    929 		if (jp == NULL || jp->nprocs == 0)
    930 			pgrp = getpid();
    931 		else
    932 			pgrp = jp->ps[0].pid;
    933 		/* This can fail because we are doing it in the parent also */
    934 		(void)setpgid(0, pgrp);
    935 		if (mode == FORK_FG) {
    936 			if (tcsetpgrp(ttyfd, pgrp) == -1)
    937 				error("Cannot set tty process group (%s) at %d",
    938 				    strerror(errno), __LINE__);
    939 		}
    940 		setsignal(SIGTSTP, vforked);
    941 		setsignal(SIGTTOU, vforked);
    942 	} else if (mode == FORK_BG) {
    943 		ignoresig(SIGINT, vforked);
    944 		ignoresig(SIGQUIT, vforked);
    945 		if ((jp == NULL || jp->nprocs == 0) &&
    946 		    ! fd0_redirected_p ()) {
    947 			close(0);
    948 			if (open(devnull, O_RDONLY) != 0)
    949 				error(nullerr, devnull);
    950 		}
    951 	}
    952 #else
    953 	if (mode == FORK_BG) {
    954 		ignoresig(SIGINT, vforked);
    955 		ignoresig(SIGQUIT, vforked);
    956 		if ((jp == NULL || jp->nprocs == 0) &&
    957 		    ! fd0_redirected_p ()) {
    958 			close(0);
    959 			if (open(devnull, O_RDONLY) != 0)
    960 				error(nullerr, devnull);
    961 		}
    962 	}
    963 #endif
    964 	if (wasroot && iflag) {
    965 		setsignal(SIGINT, vforked);
    966 		setsignal(SIGQUIT, vforked);
    967 		setsignal(SIGTERM, vforked);
    968 	}
    969 
    970 	if (!vforked)
    971 		jobs_invalid = 1;
    972 }
    973 
    974 /*
    975  * Wait for job to finish.
    976  *
    977  * Under job control we have the problem that while a child process is
    978  * running interrupts generated by the user are sent to the child but not
    979  * to the shell.  This means that an infinite loop started by an inter-
    980  * active user may be hard to kill.  With job control turned off, an
    981  * interactive user may place an interactive program inside a loop.  If
    982  * the interactive program catches interrupts, the user doesn't want
    983  * these interrupts to also abort the loop.  The approach we take here
    984  * is to have the shell ignore interrupt signals while waiting for a
    985  * forground process to terminate, and then send itself an interrupt
    986  * signal if the child process was terminated by an interrupt signal.
    987  * Unfortunately, some programs want to do a bit of cleanup and then
    988  * exit on interrupt; unless these processes terminate themselves by
    989  * sending a signal to themselves (instead of calling exit) they will
    990  * confuse this approach.
    991  */
    992 
    993 int
    994 waitforjob(struct job *jp)
    995 {
    996 #if JOBS
    997 	int mypgrp = getpgrp();
    998 #endif
    999 	int status;
   1000 	int st;
   1001 
   1002 	INTOFF;
   1003 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", jp - jobtab + 1));
   1004 	while (jp->state == JOBRUNNING) {
   1005 		dowait(WBLOCK, jp);
   1006 	}
   1007 #if JOBS
   1008 	if (jp->jobctl) {
   1009 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
   1010 			error("Cannot set tty process group (%s) at %d",
   1011 			    strerror(errno), __LINE__);
   1012 	}
   1013 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
   1014 		set_curjob(jp, 2);
   1015 #endif
   1016 	status = jp->ps[jp->nprocs - 1].status;
   1017 	/* convert to 8 bits */
   1018 	if (WIFEXITED(status))
   1019 		st = WEXITSTATUS(status);
   1020 #if JOBS
   1021 	else if (WIFSTOPPED(status))
   1022 		st = WSTOPSIG(status) + 128;
   1023 #endif
   1024 	else
   1025 		st = WTERMSIG(status) + 128;
   1026 
   1027 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
   1028 		jp - jobtab + 1, jp->nprocs, status, st));
   1029 #if JOBS
   1030 	if (jp->jobctl) {
   1031 		/*
   1032 		 * This is truly gross.
   1033 		 * If we're doing job control, then we did a TIOCSPGRP which
   1034 		 * caused us (the shell) to no longer be in the controlling
   1035 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
   1036 		 * intuit from the subprocess exit status whether a SIGINT
   1037 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
   1038 		 */
   1039 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
   1040 			raise(SIGINT);
   1041 	}
   1042 #endif
   1043 	if (! JOBS || jp->state == JOBDONE)
   1044 		freejob(jp);
   1045 	INTON;
   1046 	return st;
   1047 }
   1048 
   1049 
   1050 
   1051 /*
   1052  * Wait for a process to terminate.
   1053  */
   1054 
   1055 STATIC int
   1056 dowait(int flags, struct job *job)
   1057 {
   1058 	int pid;
   1059 	int status;
   1060 	struct procstat *sp;
   1061 	struct job *jp;
   1062 	struct job *thisjob;
   1063 	int done;
   1064 	int stopped;
   1065 
   1066 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called\n", flags));
   1067 	do {
   1068 		pid = waitproc(flags & WBLOCK, job, &status);
   1069 		VTRACE(DBG_JOBS|DBG_PROCS, ("wait returns pid %d, status %#x\n",
   1070 		    pid, status));
   1071 	} while (pid == -1 && errno == EINTR && pendingsigs == 0);
   1072 	if (pid <= 0)
   1073 		return pid;
   1074 	INTOFF;
   1075 	thisjob = NULL;
   1076 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
   1077 		if (jp->used) {
   1078 			done = 1;
   1079 			stopped = 1;
   1080 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
   1081 				if (sp->pid == -1)
   1082 					continue;
   1083 				if (sp->pid == pid) {
   1084 					VTRACE(DBG_JOBS | DBG_PROCS,
   1085 			("Job %d: changing status of proc %d from %#x to %#x\n",
   1086 						jp - jobtab + 1, pid,
   1087 						sp->status, status));
   1088 					sp->status = status;
   1089 					thisjob = jp;
   1090 				}
   1091 				if (sp->status == -1)
   1092 					stopped = 0;
   1093 				else if (WIFSTOPPED(sp->status))
   1094 					done = 0;
   1095 			}
   1096 			if (stopped) {		/* stopped or done */
   1097 				int state = done ? JOBDONE : JOBSTOPPED;
   1098 				if (jp->state != state) {
   1099 					VTRACE(DBG_JOBS,
   1100 				("Job %d: changing state from %d to %d\n",
   1101 					    jp - jobtab + 1, jp->state, state));
   1102 					jp->state = state;
   1103 #if JOBS
   1104 					if (done)
   1105 						set_curjob(jp, 0);
   1106 #endif
   1107 				}
   1108 			}
   1109 		}
   1110 	}
   1111 
   1112 	if (thisjob && thisjob->state != JOBRUNNING) {
   1113 		int mode = 0;
   1114 		if (!rootshell || !iflag)
   1115 			mode = SHOW_SIGNALLED;
   1116 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
   1117 		    (job != thisjob && (flags & WNOFREE) != 0))
   1118 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
   1119 		if (mode)
   1120 			showjob(out2, thisjob, mode);
   1121 		else {
   1122 			VTRACE(DBG_JOBS,
   1123 			    ("Not printing status, rootshell=%d, job=%p\n",
   1124 			    rootshell, job));
   1125 			thisjob->changed = 1;
   1126 		}
   1127 	}
   1128 
   1129 	INTON;
   1130 	return pid;
   1131 }
   1132 
   1133 
   1134 
   1135 /*
   1136  * Do a wait system call.  If job control is compiled in, we accept
   1137  * stopped processes.  If block is zero, we return a value of zero
   1138  * rather than blocking.
   1139  *
   1140  * System V doesn't have a non-blocking wait system call.  It does
   1141  * have a SIGCLD signal that is sent to a process when one of its
   1142  * children dies.  The obvious way to use SIGCLD would be to install
   1143  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
   1144  * was received, and have waitproc bump another counter when it got
   1145  * the status of a process.  Waitproc would then know that a wait
   1146  * system call would not block if the two counters were different.
   1147  * This approach doesn't work because if a process has children that
   1148  * have not been waited for, System V will send it a SIGCLD when it
   1149  * installs a signal handler for SIGCLD.  What this means is that when
   1150  * a child exits, the shell will be sent SIGCLD signals continuously
   1151  * until is runs out of stack space, unless it does a wait call before
   1152  * restoring the signal handler.  The code below takes advantage of
   1153  * this (mis)feature by installing a signal handler for SIGCLD and
   1154  * then checking to see whether it was called.  If there are any
   1155  * children to be waited for, it will be.
   1156  *
   1157  * If neither SYSV nor BSD is defined, we don't implement nonblocking
   1158  * waits at all.  In this case, the user will not be informed when
   1159  * a background process until the next time she runs a real program
   1160  * (as opposed to running a builtin command or just typing return),
   1161  * and the jobs command may give out of date information.
   1162  */
   1163 
   1164 #ifdef SYSV
   1165 STATIC int gotsigchild;
   1166 
   1167 STATIC int onsigchild() {
   1168 	gotsigchild = 1;
   1169 }
   1170 #endif
   1171 
   1172 
   1173 STATIC int
   1174 waitproc(int block, struct job *jp, int *status)
   1175 {
   1176 #ifdef BSD
   1177 	int flags = 0;
   1178 
   1179 #if JOBS
   1180 	if (jp != NULL && jp->jobctl)
   1181 		flags |= WUNTRACED;
   1182 #endif
   1183 	if (block == 0)
   1184 		flags |= WNOHANG;
   1185 	return waitpid(-1, status, flags);
   1186 #else
   1187 #ifdef SYSV
   1188 	int (*save)();
   1189 
   1190 	if (block == 0) {
   1191 		gotsigchild = 0;
   1192 		save = signal(SIGCLD, onsigchild);
   1193 		signal(SIGCLD, save);
   1194 		if (gotsigchild == 0)
   1195 			return 0;
   1196 	}
   1197 	return wait(status);
   1198 #else
   1199 	if (block == 0)
   1200 		return 0;
   1201 	return wait(status);
   1202 #endif
   1203 #endif
   1204 }
   1205 
   1206 /*
   1207  * return 1 if there are stopped jobs, otherwise 0
   1208  */
   1209 int job_warning = 0;
   1210 int
   1211 stoppedjobs(void)
   1212 {
   1213 	int jobno;
   1214 	struct job *jp;
   1215 
   1216 	if (job_warning || jobs_invalid)
   1217 		return (0);
   1218 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1219 		if (jp->used == 0)
   1220 			continue;
   1221 		if (jp->state == JOBSTOPPED) {
   1222 			out2str("You have stopped jobs.\n");
   1223 			job_warning = 2;
   1224 			return (1);
   1225 		}
   1226 	}
   1227 
   1228 	return (0);
   1229 }
   1230 
   1231 /*
   1232  * Return a string identifying a command (to be printed by the
   1233  * jobs command).
   1234  */
   1235 
   1236 STATIC char *cmdnextc;
   1237 STATIC int cmdnleft;
   1238 
   1239 void
   1240 commandtext(struct procstat *ps, union node *n)
   1241 {
   1242 	int len;
   1243 
   1244 	cmdnextc = ps->cmd;
   1245 	if (iflag || mflag || sizeof ps->cmd < 100)
   1246 		len = sizeof(ps->cmd);
   1247 	else
   1248 		len = sizeof(ps->cmd) / 10;
   1249 	cmdnleft = len;
   1250 	cmdtxt(n);
   1251 	if (cmdnleft <= 0) {
   1252 		char *p = ps->cmd + len - 4;
   1253 		p[0] = '.';
   1254 		p[1] = '.';
   1255 		p[2] = '.';
   1256 		p[3] = 0;
   1257 	} else
   1258 		*cmdnextc = '\0';
   1259 
   1260 	VTRACE(DBG_JOBS,
   1261 	    ("commandtext: ps->cmd %x, end %x, left %d\n\t\"%s\"\n",
   1262 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
   1263 }
   1264 
   1265 
   1266 STATIC void
   1267 cmdtxt(union node *n)
   1268 {
   1269 	union node *np;
   1270 	struct nodelist *lp;
   1271 	const char *p;
   1272 	int i;
   1273 
   1274 	if (n == NULL || cmdnleft <= 0)
   1275 		return;
   1276 	switch (n->type) {
   1277 	case NSEMI:
   1278 		cmdtxt(n->nbinary.ch1);
   1279 		cmdputs("; ");
   1280 		cmdtxt(n->nbinary.ch2);
   1281 		break;
   1282 	case NAND:
   1283 		cmdtxt(n->nbinary.ch1);
   1284 		cmdputs(" && ");
   1285 		cmdtxt(n->nbinary.ch2);
   1286 		break;
   1287 	case NOR:
   1288 		cmdtxt(n->nbinary.ch1);
   1289 		cmdputs(" || ");
   1290 		cmdtxt(n->nbinary.ch2);
   1291 		break;
   1292 	case NDNOT:
   1293 		cmdputs("! ");
   1294 		/* FALLTHROUGH */
   1295 	case NNOT:
   1296 		cmdputs("! ");
   1297 		cmdtxt(n->nnot.com);
   1298 		break;
   1299 	case NPIPE:
   1300 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1301 			cmdtxt(lp->n);
   1302 			if (lp->next)
   1303 				cmdputs(" | ");
   1304 		}
   1305 		if (n->npipe.backgnd)
   1306 			cmdputs(" &");
   1307 		break;
   1308 	case NSUBSHELL:
   1309 		cmdputs("(");
   1310 		cmdtxt(n->nredir.n);
   1311 		cmdputs(")");
   1312 		break;
   1313 	case NREDIR:
   1314 	case NBACKGND:
   1315 		cmdtxt(n->nredir.n);
   1316 		break;
   1317 	case NIF:
   1318 		cmdputs("if ");
   1319 		cmdtxt(n->nif.test);
   1320 		cmdputs("; then ");
   1321 		cmdtxt(n->nif.ifpart);
   1322 		if (n->nif.elsepart) {
   1323 			cmdputs("; else ");
   1324 			cmdtxt(n->nif.elsepart);
   1325 		}
   1326 		cmdputs("; fi");
   1327 		break;
   1328 	case NWHILE:
   1329 		cmdputs("while ");
   1330 		goto until;
   1331 	case NUNTIL:
   1332 		cmdputs("until ");
   1333  until:
   1334 		cmdtxt(n->nbinary.ch1);
   1335 		cmdputs("; do ");
   1336 		cmdtxt(n->nbinary.ch2);
   1337 		cmdputs("; done");
   1338 		break;
   1339 	case NFOR:
   1340 		cmdputs("for ");
   1341 		cmdputs(n->nfor.var);
   1342 		cmdputs(" in ");
   1343 		cmdlist(n->nfor.args, 1);
   1344 		cmdputs("; do ");
   1345 		cmdtxt(n->nfor.body);
   1346 		cmdputs("; done");
   1347 		break;
   1348 	case NCASE:
   1349 		cmdputs("case ");
   1350 		cmdputs(n->ncase.expr->narg.text);
   1351 		cmdputs(" in ");
   1352 		for (np = n->ncase.cases; np; np = np->nclist.next) {
   1353 			cmdtxt(np->nclist.pattern);
   1354 			cmdputs(") ");
   1355 			cmdtxt(np->nclist.body);
   1356 			switch (n->type) {	/* switch (not if) for later */
   1357 			case NCLISTCONT:
   1358 				cmdputs(";& ");
   1359 				break;
   1360 			default:
   1361 				cmdputs(";; ");
   1362 				break;
   1363 			}
   1364 		}
   1365 		cmdputs("esac");
   1366 		break;
   1367 	case NDEFUN:
   1368 		cmdputs(n->narg.text);
   1369 		cmdputs("() { ... }");
   1370 		break;
   1371 	case NCMD:
   1372 		cmdlist(n->ncmd.args, 1);
   1373 		cmdlist(n->ncmd.redirect, 0);
   1374 		if (n->ncmd.backgnd)
   1375 			cmdputs(" &");
   1376 		break;
   1377 	case NARG:
   1378 		cmdputs(n->narg.text);
   1379 		break;
   1380 	case NTO:
   1381 		p = ">";  i = 1;  goto redir;
   1382 	case NCLOBBER:
   1383 		p = ">|";  i = 1;  goto redir;
   1384 	case NAPPEND:
   1385 		p = ">>";  i = 1;  goto redir;
   1386 	case NTOFD:
   1387 		p = ">&";  i = 1;  goto redir;
   1388 	case NFROM:
   1389 		p = "<";  i = 0;  goto redir;
   1390 	case NFROMFD:
   1391 		p = "<&";  i = 0;  goto redir;
   1392 	case NFROMTO:
   1393 		p = "<>";  i = 0;  goto redir;
   1394  redir:
   1395 		if (n->nfile.fd != i)
   1396 			cmdputi(n->nfile.fd);
   1397 		cmdputs(p);
   1398 		if (n->type == NTOFD || n->type == NFROMFD) {
   1399 			if (n->ndup.dupfd < 0)
   1400 				cmdputs("-");
   1401 			else
   1402 				cmdputi(n->ndup.dupfd);
   1403 		} else {
   1404 			cmdtxt(n->nfile.fname);
   1405 		}
   1406 		break;
   1407 	case NHERE:
   1408 	case NXHERE:
   1409 		cmdputs("<<...");
   1410 		break;
   1411 	default:
   1412 		cmdputs("???");
   1413 		break;
   1414 	}
   1415 }
   1416 
   1417 STATIC void
   1418 cmdlist(union node *np, int sep)
   1419 {
   1420 	for (; np; np = np->narg.next) {
   1421 		if (!sep)
   1422 			cmdputs(" ");
   1423 		cmdtxt(np);
   1424 		if (sep && np->narg.next)
   1425 			cmdputs(" ");
   1426 	}
   1427 }
   1428 
   1429 
   1430 STATIC void
   1431 cmdputs(const char *s)
   1432 {
   1433 	const char *p, *str = 0;
   1434 	char c, cc[2] = " ";
   1435 	char *nextc;
   1436 	int nleft;
   1437 	int subtype = 0;
   1438 	int quoted = 0;
   1439 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
   1440 					"#", "##", "%", "%%", "}" };
   1441 
   1442 	p = s;
   1443 	nextc = cmdnextc;
   1444 	nleft = cmdnleft;
   1445 	while (nleft > 0 && (c = *p++) != 0) {
   1446 		switch (c) {
   1447 		case CTLNONL:
   1448 			c = '\0';
   1449 			break;
   1450 		case CTLESC:
   1451 			c = *p++;
   1452 			break;
   1453 		case CTLVAR:
   1454 			subtype = *p++;
   1455 			if (subtype & VSLINENO) {	/* undo LINENO hack */
   1456 				if ((subtype & VSTYPE) == VSLENGTH)
   1457 					str = "${#LINENO";	/*}*/
   1458 				else
   1459 					str = "${LINENO";	/*}*/
   1460 				while (is_digit(*p))
   1461 					p++;
   1462 			} else if ((subtype & VSTYPE) == VSLENGTH)
   1463 				str = "${#"; /*}*/
   1464 			else
   1465 				str = "${"; /*}*/
   1466 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
   1467 				quoted ^= 1;
   1468 				c = '"';
   1469 			} else {
   1470 				c = *str++;
   1471 			}
   1472 			break;
   1473 		case CTLENDVAR:		/*{*/
   1474 			c = '}';
   1475 			if (quoted & 1)
   1476 				str = "\"";
   1477 			quoted >>= 1;
   1478 			subtype = 0;
   1479 			break;
   1480 		case CTLBACKQ:
   1481 			c = '$';
   1482 			str = "(...)";
   1483 			break;
   1484 		case CTLBACKQ+CTLQUOTE:
   1485 			c = '"';
   1486 			str = "$(...)\"";
   1487 			break;
   1488 		case CTLARI:
   1489 			c = '$';
   1490 			if (*p == ' ')
   1491 				p++;
   1492 			str = "((";	/*))*/
   1493 			break;
   1494 		case CTLENDARI:		/*((*/
   1495 			c = ')';
   1496 			str = ")";
   1497 			break;
   1498 		case CTLQUOTEMARK:
   1499 			quoted ^= 1;
   1500 			c = '"';
   1501 			break;
   1502 		case CTLQUOTEEND:
   1503 			quoted >>= 1;
   1504 			c = '"';
   1505 			break;
   1506 		case '=':
   1507 			if (subtype == 0)
   1508 				break;
   1509 			str = vstype[subtype & VSTYPE];
   1510 			if (subtype & VSNUL)
   1511 				c = ':';
   1512 			else
   1513 				c = *str++;		/*{*/
   1514 			if (c != '}')
   1515 				quoted <<= 1;
   1516 			else if (*p == CTLENDVAR)
   1517 				c = *str++;
   1518 			subtype = 0;
   1519 			break;
   1520 		case '\'':
   1521 		case '\\':
   1522 		case '"':
   1523 		case '$':
   1524 			/* These can only happen inside quotes */
   1525 			cc[0] = c;
   1526 			str = cc;
   1527 			c = '\\';
   1528 			break;
   1529 		default:
   1530 			break;
   1531 		}
   1532 		if (c != '\0') do {	/* c == 0 implies nothing in str */
   1533 			*nextc++ = c;
   1534 		} while (--nleft > 0 && str && (c = *str++));
   1535 		str = 0;
   1536 	}
   1537 	if ((quoted & 1) && nleft) {
   1538 		*nextc++ = '"';
   1539 		nleft--;
   1540 	}
   1541 	cmdnleft = nleft;
   1542 	cmdnextc = nextc;
   1543 }
   1544