Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.89
      1 /*	$NetBSD: jobs.c,v 1.89 2017/09/29 17:53:57 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.89 2017/09/29 17:53:57 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 		if (pipefail && job->nprocs) {
    653 			int i;
    654 
    655 			status = 0;
    656 			for (i = 0; i < job->nprocs; i++)
    657 				if (job->ps[i].status != 0)
    658 					status = job->ps[i].status;
    659 		} else
    660 			status =
    661 			    job->ps[job->nprocs ? job->nprocs - 1 : 0].status;
    662 
    663 		if (WIFEXITED(status))
    664 			retval = WEXITSTATUS(status);
    665 #if JOBS
    666 		else if (WIFSTOPPED(status))
    667 			retval = WSTOPSIG(status) + 128;
    668 #endif
    669 		else {
    670 			/* XXX: limits number of signals */
    671 			retval = WTERMSIG(status) + 128;
    672 		}
    673 		if (!iflag)
    674 			freejob(job);
    675 	}
    676 	return retval;
    677 }
    678 
    679 
    680 
    681 int
    682 jobidcmd(int argc, char **argv)
    683 {
    684 	struct job *jp;
    685 	int i;
    686 
    687 	nextopt("");
    688 	jp = getjob(*argptr, 0);
    689 	for (i = 0 ; i < jp->nprocs ; ) {
    690 		out1fmt("%ld", (long)jp->ps[i].pid);
    691 		out1c(++i < jp->nprocs ? ' ' : '\n');
    692 	}
    693 	return 0;
    694 }
    695 
    696 int
    697 getjobpgrp(const char *name)
    698 {
    699 	struct job *jp;
    700 
    701 	jp = getjob(name, 1);
    702 	if (jp == 0)
    703 		return 0;
    704 	return -jp->ps[0].pid;
    705 }
    706 
    707 /*
    708  * Convert a job name to a job structure.
    709  */
    710 
    711 STATIC struct job *
    712 getjob(const char *name, int noerror)
    713 {
    714 	int jobno = -1;
    715 	struct job *jp;
    716 	int pid;
    717 	int i;
    718 	const char *err_msg = "No such job: %s";
    719 
    720 	if (name == NULL) {
    721 #if JOBS
    722 		jobno = curjob;
    723 #endif
    724 		err_msg = "No current job";
    725 	} else if (name[0] == '%') {
    726 		if (is_number(name + 1)) {
    727 			jobno = number(name + 1) - 1;
    728 		} else if (!name[2]) {
    729 			switch (name[1]) {
    730 #if JOBS
    731 			case 0:
    732 			case '+':
    733 			case '%':
    734 				jobno = curjob;
    735 				err_msg = "No current job";
    736 				break;
    737 			case '-':
    738 				jobno = curjob;
    739 				if (jobno != -1)
    740 					jobno = jobtab[jobno].prev_job;
    741 				err_msg = "No previous job";
    742 				break;
    743 #endif
    744 			default:
    745 				goto check_pattern;
    746 			}
    747 		} else {
    748 			struct job *found;
    749     check_pattern:
    750 			found = NULL;
    751 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    752 				if (!jp->used || jp->nprocs <= 0)
    753 					continue;
    754 				if ((name[1] == '?'
    755 					&& strstr(jp->ps[0].cmd, name + 2))
    756 				    || prefix(name + 1, jp->ps[0].cmd)) {
    757 					if (found) {
    758 						err_msg = "%s: ambiguous";
    759 						found = 0;
    760 						break;
    761 					}
    762 					found = jp;
    763 				}
    764 			}
    765 			if (found)
    766 				return found;
    767 		}
    768 
    769 	} else if (is_number(name)) {
    770 		pid = number(name);
    771 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    772 			if (jp->used && jp->nprocs > 0
    773 			 && jp->ps[jp->nprocs - 1].pid == pid)
    774 				return jp;
    775 		}
    776 	}
    777 
    778 	if (!jobs_invalid && jobno >= 0 && jobno < njobs) {
    779 		jp = jobtab + jobno;
    780 		if (jp->used)
    781 			return jp;
    782 	}
    783 	if (!noerror)
    784 		error(err_msg, name);
    785 	return 0;
    786 }
    787 
    788 
    789 
    790 /*
    791  * Return a new job structure,
    792  */
    793 
    794 struct job *
    795 makejob(union node *node, int nprocs)
    796 {
    797 	int i;
    798 	struct job *jp;
    799 
    800 	if (jobs_invalid) {
    801 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
    802 			if (jp->used)
    803 				freejob(jp);
    804 		}
    805 		jobs_invalid = 0;
    806 	}
    807 
    808 	for (i = njobs, jp = jobtab ; ; jp++) {
    809 		if (--i < 0) {
    810 			INTOFF;
    811 			if (njobs == 0) {
    812 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
    813 			} else {
    814 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
    815 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
    816 				/* Relocate `ps' pointers */
    817 				for (i = 0; i < njobs; i++)
    818 					if (jp[i].ps == &jobtab[i].ps0)
    819 						jp[i].ps = &jp[i].ps0;
    820 				ckfree(jobtab);
    821 				jobtab = jp;
    822 			}
    823 			jp = jobtab + njobs;
    824 			for (i = 4 ; --i >= 0 ; )
    825 				jobtab[njobs++].used = 0;
    826 			INTON;
    827 			break;
    828 		}
    829 		if (jp->used == 0)
    830 			break;
    831 	}
    832 	INTOFF;
    833 	jp->state = JOBRUNNING;
    834 	jp->used = 1;
    835 	jp->changed = 0;
    836 	jp->nprocs = 0;
    837 #if JOBS
    838 	jp->jobctl = jobctl;
    839 	set_curjob(jp, 1);
    840 #endif
    841 	if (nprocs > 1) {
    842 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
    843 	} else {
    844 		jp->ps = &jp->ps0;
    845 	}
    846 	INTON;
    847 	VTRACE(DBG_JOBS, ("makejob(0x%lx, %d) returns %%%d\n",
    848 	    (long)node, nprocs, jp - jobtab + 1));
    849 	return jp;
    850 }
    851 
    852 
    853 /*
    854  * Fork off a subshell.  If we are doing job control, give the subshell its
    855  * own process group.  Jp is a job structure that the job is to be added to.
    856  * N is the command that will be evaluated by the child.  Both jp and n may
    857  * be NULL.  The mode parameter can be one of the following:
    858  *	FORK_FG - Fork off a foreground process.
    859  *	FORK_BG - Fork off a background process.
    860  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
    861  *		     process group even if job control is on.
    862  *
    863  * When job control is turned off, background processes have their standard
    864  * input redirected to /dev/null (except for the second and later processes
    865  * in a pipeline).
    866  */
    867 
    868 int
    869 forkshell(struct job *jp, union node *n, int mode)
    870 {
    871 	pid_t pid;
    872 	int serrno;
    873 
    874 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
    875 	    jp - jobtab, n, mode));
    876 
    877 	switch ((pid = fork())) {
    878 	case -1:
    879 		serrno = errno;
    880 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
    881 		INTON;
    882 		error("Cannot fork (%s)", strerror(serrno));
    883 		break;
    884 	case 0:
    885 		SHELL_FORKED();
    886 		forkchild(jp, n, mode, 0);
    887 		return 0;
    888 	default:
    889 		return forkparent(jp, n, mode, pid);
    890 	}
    891 }
    892 
    893 int
    894 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
    895 {
    896 	int pgrp;
    897 
    898 	if (rootshell && mode != FORK_NOJOB && mflag) {
    899 		if (jp == NULL || jp->nprocs == 0)
    900 			pgrp = pid;
    901 		else
    902 			pgrp = jp->ps[0].pid;
    903 		/* This can fail because we are doing it in the child also */
    904 		(void)setpgid(pid, pgrp);
    905 	}
    906 	if (mode == FORK_BG)
    907 		backgndpid = pid;		/* set $! */
    908 	if (jp) {
    909 		struct procstat *ps = &jp->ps[jp->nprocs++];
    910 		ps->pid = pid;
    911 		ps->status = -1;
    912 		ps->cmd[0] = 0;
    913 		if (/* iflag && rootshell && */ n)
    914 			commandtext(ps, n);
    915 	}
    916 	CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
    917 	return pid;
    918 }
    919 
    920 void
    921 forkchild(struct job *jp, union node *n, int mode, int vforked)
    922 {
    923 	int wasroot;
    924 	int pgrp;
    925 	const char *devnull = _PATH_DEVNULL;
    926 	const char *nullerr = "Can't open %s";
    927 
    928 	wasroot = rootshell;
    929 	CTRACE(DBG_JOBS, ("Child shell %d%s\n",getpid(),vforked?" vforked":""));
    930 	if (!vforked)
    931 		rootshell = 0;
    932 
    933 	closescript(vforked);
    934 	clear_traps(vforked);
    935 #if JOBS
    936 	if (!vforked)
    937 		jobctl = 0;		/* do job control only in root shell */
    938 	if (wasroot && mode != FORK_NOJOB && mflag) {
    939 		if (jp == NULL || jp->nprocs == 0)
    940 			pgrp = getpid();
    941 		else
    942 			pgrp = jp->ps[0].pid;
    943 		/* This can fail because we are doing it in the parent also */
    944 		(void)setpgid(0, pgrp);
    945 		if (mode == FORK_FG) {
    946 			if (tcsetpgrp(ttyfd, pgrp) == -1)
    947 				error("Cannot set tty process group (%s) at %d",
    948 				    strerror(errno), __LINE__);
    949 		}
    950 		setsignal(SIGTSTP, vforked);
    951 		setsignal(SIGTTOU, vforked);
    952 	} else if (mode == FORK_BG) {
    953 		ignoresig(SIGINT, vforked);
    954 		ignoresig(SIGQUIT, vforked);
    955 		if ((jp == NULL || jp->nprocs == 0) &&
    956 		    ! fd0_redirected_p ()) {
    957 			close(0);
    958 			if (open(devnull, O_RDONLY) != 0)
    959 				error(nullerr, devnull);
    960 		}
    961 	}
    962 #else
    963 	if (mode == FORK_BG) {
    964 		ignoresig(SIGINT, vforked);
    965 		ignoresig(SIGQUIT, vforked);
    966 		if ((jp == NULL || jp->nprocs == 0) &&
    967 		    ! fd0_redirected_p ()) {
    968 			close(0);
    969 			if (open(devnull, O_RDONLY) != 0)
    970 				error(nullerr, devnull);
    971 		}
    972 	}
    973 #endif
    974 	if (wasroot && iflag) {
    975 		setsignal(SIGINT, vforked);
    976 		setsignal(SIGQUIT, vforked);
    977 		setsignal(SIGTERM, vforked);
    978 	}
    979 
    980 	if (!vforked)
    981 		jobs_invalid = 1;
    982 }
    983 
    984 /*
    985  * Wait for job to finish.
    986  *
    987  * Under job control we have the problem that while a child process is
    988  * running interrupts generated by the user are sent to the child but not
    989  * to the shell.  This means that an infinite loop started by an inter-
    990  * active user may be hard to kill.  With job control turned off, an
    991  * interactive user may place an interactive program inside a loop.  If
    992  * the interactive program catches interrupts, the user doesn't want
    993  * these interrupts to also abort the loop.  The approach we take here
    994  * is to have the shell ignore interrupt signals while waiting for a
    995  * forground process to terminate, and then send itself an interrupt
    996  * signal if the child process was terminated by an interrupt signal.
    997  * Unfortunately, some programs want to do a bit of cleanup and then
    998  * exit on interrupt; unless these processes terminate themselves by
    999  * sending a signal to themselves (instead of calling exit) they will
   1000  * confuse this approach.
   1001  */
   1002 
   1003 int
   1004 waitforjob(struct job *jp)
   1005 {
   1006 #if JOBS
   1007 	int mypgrp = getpgrp();
   1008 #endif
   1009 	int status;
   1010 	int st;
   1011 
   1012 	INTOFF;
   1013 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", jp - jobtab + 1));
   1014 	while (jp->state == JOBRUNNING) {
   1015 		dowait(WBLOCK, jp);
   1016 	}
   1017 #if JOBS
   1018 	if (jp->jobctl) {
   1019 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
   1020 			error("Cannot set tty process group (%s) at %d",
   1021 			    strerror(errno), __LINE__);
   1022 	}
   1023 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
   1024 		set_curjob(jp, 2);
   1025 #endif
   1026 	if (pipefail) {
   1027 		status = 0;
   1028 		for (st = 0; st < jp->nprocs; st++)
   1029 			if (jp->ps[st].status != 0)
   1030 				status = jp->ps[st].status;
   1031 	} else
   1032 		status = jp->ps[jp->nprocs - 1].status;
   1033 	/* convert to 8 bits */
   1034 	if (WIFEXITED(status))
   1035 		st = WEXITSTATUS(status);
   1036 #if JOBS
   1037 	else if (WIFSTOPPED(status))
   1038 		st = WSTOPSIG(status) + 128;
   1039 #endif
   1040 	else
   1041 		st = WTERMSIG(status) + 128;
   1042 
   1043 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
   1044 		jp - jobtab + 1, jp->nprocs, status, st));
   1045 #if JOBS
   1046 	if (jp->jobctl) {
   1047 		/*
   1048 		 * This is truly gross.
   1049 		 * If we're doing job control, then we did a TIOCSPGRP which
   1050 		 * caused us (the shell) to no longer be in the controlling
   1051 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
   1052 		 * intuit from the subprocess exit status whether a SIGINT
   1053 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
   1054 		 */
   1055 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
   1056 			raise(SIGINT);
   1057 	}
   1058 #endif
   1059 	if (! JOBS || jp->state == JOBDONE)
   1060 		freejob(jp);
   1061 	INTON;
   1062 	return st;
   1063 }
   1064 
   1065 
   1066 
   1067 /*
   1068  * Wait for a process to terminate.
   1069  */
   1070 
   1071 STATIC int
   1072 dowait(int flags, struct job *job)
   1073 {
   1074 	int pid;
   1075 	int status;
   1076 	struct procstat *sp;
   1077 	struct job *jp;
   1078 	struct job *thisjob;
   1079 	int done;
   1080 	int stopped;
   1081 
   1082 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called\n", flags));
   1083 	do {
   1084 		pid = waitproc(flags & WBLOCK, job, &status);
   1085 		VTRACE(DBG_JOBS|DBG_PROCS, ("wait returns pid %d, status %#x\n",
   1086 		    pid, status));
   1087 	} while (pid == -1 && errno == EINTR && pendingsigs == 0);
   1088 	if (pid <= 0)
   1089 		return pid;
   1090 	INTOFF;
   1091 	thisjob = NULL;
   1092 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
   1093 		if (jp->used) {
   1094 			done = 1;
   1095 			stopped = 1;
   1096 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
   1097 				if (sp->pid == -1)
   1098 					continue;
   1099 				if (sp->pid == pid) {
   1100 					VTRACE(DBG_JOBS | DBG_PROCS,
   1101 			("Job %d: changing status of proc %d from %#x to %#x\n",
   1102 						jp - jobtab + 1, pid,
   1103 						sp->status, status));
   1104 					sp->status = status;
   1105 					thisjob = jp;
   1106 				}
   1107 				if (sp->status == -1)
   1108 					stopped = 0;
   1109 				else if (WIFSTOPPED(sp->status))
   1110 					done = 0;
   1111 			}
   1112 			if (stopped) {		/* stopped or done */
   1113 				int state = done ? JOBDONE : JOBSTOPPED;
   1114 				if (jp->state != state) {
   1115 					VTRACE(DBG_JOBS,
   1116 				("Job %d: changing state from %d to %d\n",
   1117 					    jp - jobtab + 1, jp->state, state));
   1118 					jp->state = state;
   1119 #if JOBS
   1120 					if (done)
   1121 						set_curjob(jp, 0);
   1122 #endif
   1123 				}
   1124 			}
   1125 		}
   1126 	}
   1127 
   1128 	if (thisjob && thisjob->state != JOBRUNNING) {
   1129 		int mode = 0;
   1130 		if (!rootshell || !iflag)
   1131 			mode = SHOW_SIGNALLED;
   1132 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
   1133 		    (job != thisjob && (flags & WNOFREE) != 0))
   1134 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
   1135 		if (mode)
   1136 			showjob(out2, thisjob, mode);
   1137 		else {
   1138 			VTRACE(DBG_JOBS,
   1139 			    ("Not printing status, rootshell=%d, job=%p\n",
   1140 			    rootshell, job));
   1141 			thisjob->changed = 1;
   1142 		}
   1143 	}
   1144 
   1145 	INTON;
   1146 	return pid;
   1147 }
   1148 
   1149 
   1150 
   1151 /*
   1152  * Do a wait system call.  If job control is compiled in, we accept
   1153  * stopped processes.  If block is zero, we return a value of zero
   1154  * rather than blocking.
   1155  *
   1156  * System V doesn't have a non-blocking wait system call.  It does
   1157  * have a SIGCLD signal that is sent to a process when one of its
   1158  * children dies.  The obvious way to use SIGCLD would be to install
   1159  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
   1160  * was received, and have waitproc bump another counter when it got
   1161  * the status of a process.  Waitproc would then know that a wait
   1162  * system call would not block if the two counters were different.
   1163  * This approach doesn't work because if a process has children that
   1164  * have not been waited for, System V will send it a SIGCLD when it
   1165  * installs a signal handler for SIGCLD.  What this means is that when
   1166  * a child exits, the shell will be sent SIGCLD signals continuously
   1167  * until is runs out of stack space, unless it does a wait call before
   1168  * restoring the signal handler.  The code below takes advantage of
   1169  * this (mis)feature by installing a signal handler for SIGCLD and
   1170  * then checking to see whether it was called.  If there are any
   1171  * children to be waited for, it will be.
   1172  *
   1173  * If neither SYSV nor BSD is defined, we don't implement nonblocking
   1174  * waits at all.  In this case, the user will not be informed when
   1175  * a background process until the next time she runs a real program
   1176  * (as opposed to running a builtin command or just typing return),
   1177  * and the jobs command may give out of date information.
   1178  */
   1179 
   1180 #ifdef SYSV
   1181 STATIC int gotsigchild;
   1182 
   1183 STATIC int onsigchild() {
   1184 	gotsigchild = 1;
   1185 }
   1186 #endif
   1187 
   1188 
   1189 STATIC int
   1190 waitproc(int block, struct job *jp, int *status)
   1191 {
   1192 #ifdef BSD
   1193 	int flags = 0;
   1194 
   1195 #if JOBS
   1196 	if (jp != NULL && jp->jobctl)
   1197 		flags |= WUNTRACED;
   1198 #endif
   1199 	if (block == 0)
   1200 		flags |= WNOHANG;
   1201 	return waitpid(-1, status, flags);
   1202 #else
   1203 #ifdef SYSV
   1204 	int (*save)();
   1205 
   1206 	if (block == 0) {
   1207 		gotsigchild = 0;
   1208 		save = signal(SIGCLD, onsigchild);
   1209 		signal(SIGCLD, save);
   1210 		if (gotsigchild == 0)
   1211 			return 0;
   1212 	}
   1213 	return wait(status);
   1214 #else
   1215 	if (block == 0)
   1216 		return 0;
   1217 	return wait(status);
   1218 #endif
   1219 #endif
   1220 }
   1221 
   1222 /*
   1223  * return 1 if there are stopped jobs, otherwise 0
   1224  */
   1225 int job_warning = 0;
   1226 int
   1227 stoppedjobs(void)
   1228 {
   1229 	int jobno;
   1230 	struct job *jp;
   1231 
   1232 	if (job_warning || jobs_invalid)
   1233 		return (0);
   1234 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1235 		if (jp->used == 0)
   1236 			continue;
   1237 		if (jp->state == JOBSTOPPED) {
   1238 			out2str("You have stopped jobs.\n");
   1239 			job_warning = 2;
   1240 			return (1);
   1241 		}
   1242 	}
   1243 
   1244 	return (0);
   1245 }
   1246 
   1247 /*
   1248  * Return a string identifying a command (to be printed by the
   1249  * jobs command).
   1250  */
   1251 
   1252 STATIC char *cmdnextc;
   1253 STATIC int cmdnleft;
   1254 
   1255 void
   1256 commandtext(struct procstat *ps, union node *n)
   1257 {
   1258 	int len;
   1259 
   1260 	cmdnextc = ps->cmd;
   1261 	if (iflag || mflag || sizeof ps->cmd < 100)
   1262 		len = sizeof(ps->cmd);
   1263 	else
   1264 		len = sizeof(ps->cmd) / 10;
   1265 	cmdnleft = len;
   1266 	cmdtxt(n);
   1267 	if (cmdnleft <= 0) {
   1268 		char *p = ps->cmd + len - 4;
   1269 		p[0] = '.';
   1270 		p[1] = '.';
   1271 		p[2] = '.';
   1272 		p[3] = 0;
   1273 	} else
   1274 		*cmdnextc = '\0';
   1275 
   1276 	VTRACE(DBG_JOBS,
   1277 	    ("commandtext: ps->cmd %x, end %x, left %d\n\t\"%s\"\n",
   1278 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
   1279 }
   1280 
   1281 
   1282 STATIC void
   1283 cmdtxt(union node *n)
   1284 {
   1285 	union node *np;
   1286 	struct nodelist *lp;
   1287 	const char *p;
   1288 	int i;
   1289 
   1290 	if (n == NULL || cmdnleft <= 0)
   1291 		return;
   1292 	switch (n->type) {
   1293 	case NSEMI:
   1294 		cmdtxt(n->nbinary.ch1);
   1295 		cmdputs("; ");
   1296 		cmdtxt(n->nbinary.ch2);
   1297 		break;
   1298 	case NAND:
   1299 		cmdtxt(n->nbinary.ch1);
   1300 		cmdputs(" && ");
   1301 		cmdtxt(n->nbinary.ch2);
   1302 		break;
   1303 	case NOR:
   1304 		cmdtxt(n->nbinary.ch1);
   1305 		cmdputs(" || ");
   1306 		cmdtxt(n->nbinary.ch2);
   1307 		break;
   1308 	case NDNOT:
   1309 		cmdputs("! ");
   1310 		/* FALLTHROUGH */
   1311 	case NNOT:
   1312 		cmdputs("! ");
   1313 		cmdtxt(n->nnot.com);
   1314 		break;
   1315 	case NPIPE:
   1316 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1317 			cmdtxt(lp->n);
   1318 			if (lp->next)
   1319 				cmdputs(" | ");
   1320 		}
   1321 		if (n->npipe.backgnd)
   1322 			cmdputs(" &");
   1323 		break;
   1324 	case NSUBSHELL:
   1325 		cmdputs("(");
   1326 		cmdtxt(n->nredir.n);
   1327 		cmdputs(")");
   1328 		break;
   1329 	case NREDIR:
   1330 	case NBACKGND:
   1331 		cmdtxt(n->nredir.n);
   1332 		break;
   1333 	case NIF:
   1334 		cmdputs("if ");
   1335 		cmdtxt(n->nif.test);
   1336 		cmdputs("; then ");
   1337 		cmdtxt(n->nif.ifpart);
   1338 		if (n->nif.elsepart) {
   1339 			cmdputs("; else ");
   1340 			cmdtxt(n->nif.elsepart);
   1341 		}
   1342 		cmdputs("; fi");
   1343 		break;
   1344 	case NWHILE:
   1345 		cmdputs("while ");
   1346 		goto until;
   1347 	case NUNTIL:
   1348 		cmdputs("until ");
   1349  until:
   1350 		cmdtxt(n->nbinary.ch1);
   1351 		cmdputs("; do ");
   1352 		cmdtxt(n->nbinary.ch2);
   1353 		cmdputs("; done");
   1354 		break;
   1355 	case NFOR:
   1356 		cmdputs("for ");
   1357 		cmdputs(n->nfor.var);
   1358 		cmdputs(" in ");
   1359 		cmdlist(n->nfor.args, 1);
   1360 		cmdputs("; do ");
   1361 		cmdtxt(n->nfor.body);
   1362 		cmdputs("; done");
   1363 		break;
   1364 	case NCASE:
   1365 		cmdputs("case ");
   1366 		cmdputs(n->ncase.expr->narg.text);
   1367 		cmdputs(" in ");
   1368 		for (np = n->ncase.cases; np; np = np->nclist.next) {
   1369 			cmdtxt(np->nclist.pattern);
   1370 			cmdputs(") ");
   1371 			cmdtxt(np->nclist.body);
   1372 			switch (n->type) {	/* switch (not if) for later */
   1373 			case NCLISTCONT:
   1374 				cmdputs(";& ");
   1375 				break;
   1376 			default:
   1377 				cmdputs(";; ");
   1378 				break;
   1379 			}
   1380 		}
   1381 		cmdputs("esac");
   1382 		break;
   1383 	case NDEFUN:
   1384 		cmdputs(n->narg.text);
   1385 		cmdputs("() { ... }");
   1386 		break;
   1387 	case NCMD:
   1388 		cmdlist(n->ncmd.args, 1);
   1389 		cmdlist(n->ncmd.redirect, 0);
   1390 		if (n->ncmd.backgnd)
   1391 			cmdputs(" &");
   1392 		break;
   1393 	case NARG:
   1394 		cmdputs(n->narg.text);
   1395 		break;
   1396 	case NTO:
   1397 		p = ">";  i = 1;  goto redir;
   1398 	case NCLOBBER:
   1399 		p = ">|";  i = 1;  goto redir;
   1400 	case NAPPEND:
   1401 		p = ">>";  i = 1;  goto redir;
   1402 	case NTOFD:
   1403 		p = ">&";  i = 1;  goto redir;
   1404 	case NFROM:
   1405 		p = "<";  i = 0;  goto redir;
   1406 	case NFROMFD:
   1407 		p = "<&";  i = 0;  goto redir;
   1408 	case NFROMTO:
   1409 		p = "<>";  i = 0;  goto redir;
   1410  redir:
   1411 		if (n->nfile.fd != i)
   1412 			cmdputi(n->nfile.fd);
   1413 		cmdputs(p);
   1414 		if (n->type == NTOFD || n->type == NFROMFD) {
   1415 			if (n->ndup.dupfd < 0)
   1416 				cmdputs("-");
   1417 			else
   1418 				cmdputi(n->ndup.dupfd);
   1419 		} else {
   1420 			cmdtxt(n->nfile.fname);
   1421 		}
   1422 		break;
   1423 	case NHERE:
   1424 	case NXHERE:
   1425 		cmdputs("<<...");
   1426 		break;
   1427 	default:
   1428 		cmdputs("???");
   1429 		break;
   1430 	}
   1431 }
   1432 
   1433 STATIC void
   1434 cmdlist(union node *np, int sep)
   1435 {
   1436 	for (; np; np = np->narg.next) {
   1437 		if (!sep)
   1438 			cmdputs(" ");
   1439 		cmdtxt(np);
   1440 		if (sep && np->narg.next)
   1441 			cmdputs(" ");
   1442 	}
   1443 }
   1444 
   1445 
   1446 STATIC void
   1447 cmdputs(const char *s)
   1448 {
   1449 	const char *p, *str = 0;
   1450 	char c, cc[2] = " ";
   1451 	char *nextc;
   1452 	int nleft;
   1453 	int subtype = 0;
   1454 	int quoted = 0;
   1455 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
   1456 					"#", "##", "%", "%%", "}" };
   1457 
   1458 	p = s;
   1459 	nextc = cmdnextc;
   1460 	nleft = cmdnleft;
   1461 	while (nleft > 0 && (c = *p++) != 0) {
   1462 		switch (c) {
   1463 		case CTLNONL:
   1464 			c = '\0';
   1465 			break;
   1466 		case CTLESC:
   1467 			c = *p++;
   1468 			break;
   1469 		case CTLVAR:
   1470 			subtype = *p++;
   1471 			if (subtype & VSLINENO) {	/* undo LINENO hack */
   1472 				if ((subtype & VSTYPE) == VSLENGTH)
   1473 					str = "${#LINENO";	/*}*/
   1474 				else
   1475 					str = "${LINENO";	/*}*/
   1476 				while (is_digit(*p))
   1477 					p++;
   1478 			} else if ((subtype & VSTYPE) == VSLENGTH)
   1479 				str = "${#"; /*}*/
   1480 			else
   1481 				str = "${"; /*}*/
   1482 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
   1483 				quoted ^= 1;
   1484 				c = '"';
   1485 			} else {
   1486 				c = *str++;
   1487 			}
   1488 			break;
   1489 		case CTLENDVAR:		/*{*/
   1490 			c = '}';
   1491 			if (quoted & 1)
   1492 				str = "\"";
   1493 			quoted >>= 1;
   1494 			subtype = 0;
   1495 			break;
   1496 		case CTLBACKQ:
   1497 			c = '$';
   1498 			str = "(...)";
   1499 			break;
   1500 		case CTLBACKQ+CTLQUOTE:
   1501 			c = '"';
   1502 			str = "$(...)\"";
   1503 			break;
   1504 		case CTLARI:
   1505 			c = '$';
   1506 			if (*p == ' ')
   1507 				p++;
   1508 			str = "((";	/*))*/
   1509 			break;
   1510 		case CTLENDARI:		/*((*/
   1511 			c = ')';
   1512 			str = ")";
   1513 			break;
   1514 		case CTLQUOTEMARK:
   1515 			quoted ^= 1;
   1516 			c = '"';
   1517 			break;
   1518 		case CTLQUOTEEND:
   1519 			quoted >>= 1;
   1520 			c = '"';
   1521 			break;
   1522 		case '=':
   1523 			if (subtype == 0)
   1524 				break;
   1525 			str = vstype[subtype & VSTYPE];
   1526 			if (subtype & VSNUL)
   1527 				c = ':';
   1528 			else
   1529 				c = *str++;		/*{*/
   1530 			if (c != '}')
   1531 				quoted <<= 1;
   1532 			else if (*p == CTLENDVAR)
   1533 				c = *str++;
   1534 			subtype = 0;
   1535 			break;
   1536 		case '\'':
   1537 		case '\\':
   1538 		case '"':
   1539 		case '$':
   1540 			/* These can only happen inside quotes */
   1541 			cc[0] = c;
   1542 			str = cc;
   1543 			c = '\\';
   1544 			break;
   1545 		default:
   1546 			break;
   1547 		}
   1548 		if (c != '\0') do {	/* c == 0 implies nothing in str */
   1549 			*nextc++ = c;
   1550 		} while (--nleft > 0 && str && (c = *str++));
   1551 		str = 0;
   1552 	}
   1553 	if ((quoted & 1) && nleft) {
   1554 		*nextc++ = '"';
   1555 		nleft--;
   1556 	}
   1557 	cmdnleft = nleft;
   1558 	cmdnextc = nextc;
   1559 }
   1560