xref: /freebsd/bin/sh/jobs.c (revision bdcbfde31e8e9b343f113a1956384bdf30d1ed62)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 #endif /* not lint */
35 #include <sys/cdefs.h>
36 #include <sys/ioctl.h>
37 #include <sys/param.h>
38 #include <sys/resource.h>
39 #include <sys/time.h>
40 #include <sys/wait.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <paths.h>
44 #include <signal.h>
45 #include <stddef.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 
49 #include "shell.h"
50 #if JOBS
51 #include <termios.h>
52 #undef CEOF			/* syntax.h redefines this */
53 #endif
54 #include "redir.h"
55 #include "exec.h"
56 #include "show.h"
57 #include "main.h"
58 #include "parser.h"
59 #include "nodes.h"
60 #include "jobs.h"
61 #include "options.h"
62 #include "trap.h"
63 #include "syntax.h"
64 #include "input.h"
65 #include "output.h"
66 #include "memalloc.h"
67 #include "error.h"
68 #include "mystring.h"
69 #include "var.h"
70 #include "builtins.h"
71 #include "eval.h"
72 
73 
74 /*
75  * A job structure contains information about a job.  A job is either a
76  * single process or a set of processes contained in a pipeline.  In the
77  * latter case, pidlist will be non-NULL, and will point to a -1 terminated
78  * array of pids.
79  */
80 
81 struct procstat {
82 	pid_t pid;		/* process id */
83 	int status;		/* status flags (defined above) */
84 	char *cmd;		/* text of command being run */
85 };
86 
87 
88 /* states */
89 #define JOBSTOPPED 1		/* all procs are stopped */
90 #define JOBDONE 2		/* all procs are completed */
91 
92 
93 struct job {
94 	struct procstat ps0;	/* status of process */
95 	struct procstat *ps;	/* status or processes when more than one */
96 	short nprocs;		/* number of processes */
97 	pid_t pgrp;		/* process group of this job */
98 	char state;		/* true if job is finished */
99 	char used;		/* true if this entry is in used */
100 	char changed;		/* true if status has changed */
101 	char foreground;	/* true if running in the foreground */
102 	char remembered;	/* true if $! referenced */
103 	char pipefail;		/* pass any non-zero status */
104 #if JOBS
105 	char jobctl;		/* job running under job control */
106 	struct job *next;	/* job used after this one */
107 #endif
108 };
109 
110 
111 static struct job *jobtab;	/* array of jobs */
112 static int njobs;		/* size of array */
113 static pid_t backgndpid = -1;	/* pid of last background process */
114 static struct job *bgjob = NULL; /* last background process */
115 #if JOBS
116 static struct job *jobmru;	/* most recently used job list */
117 static pid_t initialpgrp;	/* pgrp of shell on invocation */
118 #endif
119 static int ttyfd = -1;
120 
121 /* mode flags for dowait */
122 #define DOWAIT_BLOCK	0x1 /* wait until a child exits */
123 #define DOWAIT_SIG	0x2 /* if DOWAIT_BLOCK, abort on signal */
124 #define DOWAIT_SIG_TRAP	0x4 /* if DOWAIT_SIG, abort on trapped signal only */
125 
126 #if JOBS
127 static void restartjob(struct job *);
128 #endif
129 static void freejob(struct job *);
130 static int waitcmdloop(struct job *);
131 static struct job *getjob_nonotfound(const char *);
132 static struct job *getjob(const char *);
133 pid_t killjob(const char *, int);
134 static pid_t dowait(int, struct job *);
135 static void checkzombies(void);
136 static void cmdtxt(union node *);
137 static void cmdputs(const char *);
138 #if JOBS
139 static void setcurjob(struct job *);
140 static void deljob(struct job *);
141 static struct job *getcurjob(struct job *);
142 #endif
143 static int getjobstatus(const struct job *);
144 static void printjobcmd(struct job *);
145 static void showjob(struct job *, int);
146 
147 
148 /*
149  * Turn job control on and off.
150  */
151 
152 static int jobctl;
153 
154 #if JOBS
155 static void
156 jobctl_notty(void)
157 {
158 	if (ttyfd >= 0) {
159 		close(ttyfd);
160 		ttyfd = -1;
161 	}
162 	if (!iflag) {
163 		setsignal(SIGTSTP);
164 		setsignal(SIGTTOU);
165 		setsignal(SIGTTIN);
166 		jobctl = 1;
167 		return;
168 	}
169 	out2fmt_flush("sh: can't access tty; job control turned off\n");
170 	mflag = 0;
171 }
172 
173 void
174 setjobctl(int on)
175 {
176 	int i;
177 
178 	if (on == jobctl || rootshell == 0)
179 		return;
180 	if (on) {
181 		if (ttyfd != -1)
182 			close(ttyfd);
183 		if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) < 0) {
184 			i = 0;
185 			while (i <= 2 && !isatty(i))
186 				i++;
187 			if (i > 2 ||
188 			    (ttyfd = fcntl(i, F_DUPFD_CLOEXEC, 10)) < 0) {
189 				jobctl_notty();
190 				return;
191 			}
192 		}
193 		if (ttyfd < 10) {
194 			/*
195 			 * Keep our TTY file descriptor out of the way of
196 			 * the user's redirections.
197 			 */
198 			if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) {
199 				jobctl_notty();
200 				return;
201 			}
202 			close(ttyfd);
203 			ttyfd = i;
204 		}
205 		do { /* while we are in the background */
206 			initialpgrp = tcgetpgrp(ttyfd);
207 			if (initialpgrp < 0) {
208 				jobctl_notty();
209 				return;
210 			}
211 			if (initialpgrp != getpgrp()) {
212 				if (!iflag) {
213 					initialpgrp = -1;
214 					jobctl_notty();
215 					return;
216 				}
217 				kill(0, SIGTTIN);
218 				continue;
219 			}
220 		} while (0);
221 		setsignal(SIGTSTP);
222 		setsignal(SIGTTOU);
223 		setsignal(SIGTTIN);
224 		setpgid(0, rootpid);
225 		tcsetpgrp(ttyfd, rootpid);
226 	} else { /* turning job control off */
227 		setpgid(0, initialpgrp);
228 		if (ttyfd >= 0) {
229 			tcsetpgrp(ttyfd, initialpgrp);
230 			close(ttyfd);
231 			ttyfd = -1;
232 		}
233 		setsignal(SIGTSTP);
234 		setsignal(SIGTTOU);
235 		setsignal(SIGTTIN);
236 	}
237 	jobctl = on;
238 }
239 #endif
240 
241 
242 #if JOBS
243 int
244 fgcmd(int argc __unused, char **argv __unused)
245 {
246 	struct job *jp;
247 	pid_t pgrp;
248 	int status;
249 
250 	nextopt("");
251 	jp = getjob(*argptr);
252 	if (jp->jobctl == 0)
253 		error("job not created under job control");
254 	printjobcmd(jp);
255 	flushout(&output);
256 	pgrp = jp->ps[0].pid;
257 	if (ttyfd >= 0)
258 		tcsetpgrp(ttyfd, pgrp);
259 	restartjob(jp);
260 	jp->foreground = 1;
261 	INTOFF;
262 	status = waitforjob(jp, (int *)NULL);
263 	INTON;
264 	return status;
265 }
266 
267 
268 int
269 bgcmd(int argc __unused, char **argv __unused)
270 {
271 	struct job *jp;
272 
273 	nextopt("");
274 	do {
275 		jp = getjob(*argptr);
276 		if (jp->jobctl == 0)
277 			error("job not created under job control");
278 		if (jp->state == JOBDONE)
279 			continue;
280 		restartjob(jp);
281 		jp->foreground = 0;
282 		out1fmt("[%td] ", jp - jobtab + 1);
283 		printjobcmd(jp);
284 	} while (*argptr != NULL && *++argptr != NULL);
285 	return 0;
286 }
287 
288 
289 static void
290 restartjob(struct job *jp)
291 {
292 	struct procstat *ps;
293 	int i;
294 
295 	if (jp->state == JOBDONE)
296 		return;
297 	setcurjob(jp);
298 	INTOFF;
299 	kill(-jp->ps[0].pid, SIGCONT);
300 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
301 		if (WIFSTOPPED(ps->status)) {
302 			ps->status = -1;
303 			jp->state = 0;
304 		}
305 	}
306 	INTON;
307 }
308 #endif
309 
310 
311 int
312 jobscmd(int argc __unused, char *argv[] __unused)
313 {
314 	char *id;
315 	int ch, mode;
316 
317 	mode = SHOWJOBS_DEFAULT;
318 	while ((ch = nextopt("lps")) != '\0') {
319 		switch (ch) {
320 		case 'l':
321 			mode = SHOWJOBS_VERBOSE;
322 			break;
323 		case 'p':
324 			mode = SHOWJOBS_PGIDS;
325 			break;
326 		case 's':
327 			mode = SHOWJOBS_PIDS;
328 			break;
329 		}
330 	}
331 
332 	if (*argptr == NULL)
333 		showjobs(0, mode);
334 	else
335 		while ((id = *argptr++) != NULL)
336 			showjob(getjob(id), mode);
337 
338 	return (0);
339 }
340 
341 static int getjobstatus(const struct job *jp)
342 {
343 	int i, status;
344 
345 	if (!jp->pipefail)
346 		return (jp->ps[jp->nprocs - 1].status);
347 	for (i = jp->nprocs - 1; i >= 0; i--) {
348 		status = jp->ps[i].status;
349 		if (status != 0)
350 			return (status);
351 	}
352 	return (0);
353 }
354 
355 static void
356 printjobcmd(struct job *jp)
357 {
358 	struct procstat *ps;
359 	int i;
360 
361 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
362 		out1str(ps->cmd);
363 		if (i > 0)
364 			out1str(" | ");
365 	}
366 	out1c('\n');
367 }
368 
369 static void
370 showjob(struct job *jp, int mode)
371 {
372 	char s[64];
373 	char statebuf[16];
374 	const char *statestr, *coredump;
375 	struct procstat *ps;
376 	struct job *j;
377 	int col, curr, i, jobno, prev, procno, status;
378 	char c;
379 
380 	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
381 	jobno = jp - jobtab + 1;
382 	curr = prev = 0;
383 #if JOBS
384 	if ((j = getcurjob(NULL)) != NULL) {
385 		curr = j - jobtab + 1;
386 		if ((j = getcurjob(j)) != NULL)
387 			prev = j - jobtab + 1;
388 	}
389 #endif
390 	coredump = "";
391 	status = getjobstatus(jp);
392 	if (jp->state == 0) {
393 		statestr = "Running";
394 #if JOBS
395 	} else if (jp->state == JOBSTOPPED) {
396 		ps = jp->ps + jp->nprocs - 1;
397 		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
398 			ps--;
399 		if (WIFSTOPPED(ps->status))
400 			i = WSTOPSIG(ps->status);
401 		else
402 			i = -1;
403 		statestr = strsignal(i);
404 		if (statestr == NULL)
405 			statestr = "Suspended";
406 #endif
407 	} else if (WIFEXITED(status)) {
408 		if (WEXITSTATUS(status) == 0)
409 			statestr = "Done";
410 		else {
411 			fmtstr(statebuf, sizeof(statebuf), "Done(%d)",
412 			    WEXITSTATUS(status));
413 			statestr = statebuf;
414 		}
415 	} else {
416 		i = WTERMSIG(status);
417 		statestr = strsignal(i);
418 		if (statestr == NULL)
419 			statestr = "Unknown signal";
420 		if (WCOREDUMP(status))
421 			coredump = " (core dumped)";
422 	}
423 
424 	for (ps = jp->ps ; procno > 0 ; ps++, procno--) { /* for each process */
425 		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
426 			out1fmt("%d\n", (int)ps->pid);
427 			continue;
428 		}
429 		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
430 			continue;
431 		if (jobno == curr && ps == jp->ps)
432 			c = '+';
433 		else if (jobno == prev && ps == jp->ps)
434 			c = '-';
435 		else
436 			c = ' ';
437 		if (ps == jp->ps)
438 			fmtstr(s, 64, "[%d] %c ", jobno, c);
439 		else
440 			fmtstr(s, 64, "    %c ", c);
441 		out1str(s);
442 		col = strlen(s);
443 		if (mode == SHOWJOBS_VERBOSE) {
444 			fmtstr(s, 64, "%d ", (int)ps->pid);
445 			out1str(s);
446 			col += strlen(s);
447 		}
448 		if (ps == jp->ps) {
449 			out1str(statestr);
450 			out1str(coredump);
451 			col += strlen(statestr) + strlen(coredump);
452 		}
453 		do {
454 			out1c(' ');
455 			col++;
456 		} while (col < 30);
457 		if (mode == SHOWJOBS_VERBOSE) {
458 			out1str(ps->cmd);
459 			out1c('\n');
460 		} else
461 			printjobcmd(jp);
462 	}
463 }
464 
465 /*
466  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
467  * statuses have changed since the last call to showjobs.
468  *
469  * If the shell is interrupted in the process of creating a job, the
470  * result may be a job structure containing zero processes.  Such structures
471  * will be freed here.
472  */
473 
474 void
475 showjobs(int change, int mode)
476 {
477 	int jobno;
478 	struct job *jp;
479 
480 	TRACE(("showjobs(%d) called\n", change));
481 	checkzombies();
482 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
483 		if (! jp->used)
484 			continue;
485 		if (jp->nprocs == 0) {
486 			freejob(jp);
487 			continue;
488 		}
489 		if (change && ! jp->changed)
490 			continue;
491 		showjob(jp, mode);
492 		if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
493 			jp->changed = 0;
494 			/* Hack: discard jobs for which $! has not been
495 			 * referenced in interactive mode when they terminate.
496 			 */
497 			if (jp->state == JOBDONE && !jp->remembered &&
498 					(iflag || jp != bgjob)) {
499 				freejob(jp);
500 			}
501 		}
502 	}
503 }
504 
505 
506 /*
507  * Mark a job structure as unused.
508  */
509 
510 static void
511 freejob(struct job *jp)
512 {
513 	struct procstat *ps;
514 	int i;
515 
516 	INTOFF;
517 	if (bgjob == jp)
518 		bgjob = NULL;
519 	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
520 		if (ps->cmd != nullstr)
521 			ckfree(ps->cmd);
522 	}
523 	if (jp->ps != &jp->ps0)
524 		ckfree(jp->ps);
525 	jp->used = 0;
526 #if JOBS
527 	deljob(jp);
528 #endif
529 	INTON;
530 }
531 
532 
533 
534 int
535 waitcmd(int argc __unused, char **argv __unused)
536 {
537 	struct job *job;
538 	int retval;
539 
540 	nextopt("");
541 	if (*argptr == NULL)
542 		return (waitcmdloop(NULL));
543 
544 	do {
545 		job = getjob_nonotfound(*argptr);
546 		if (job == NULL)
547 			retval = 127;
548 		else
549 			retval = waitcmdloop(job);
550 		argptr++;
551 	} while (*argptr != NULL);
552 
553 	return (retval);
554 }
555 
556 static int
557 waitcmdloop(struct job *job)
558 {
559 	int status, retval, sig;
560 	struct job *jp;
561 
562 	/*
563 	 * Loop until a process is terminated or stopped, or a SIGINT is
564 	 * received.
565 	 */
566 
567 	do {
568 		if (job != NULL) {
569 			if (job->state == JOBDONE) {
570 				status = getjobstatus(job);
571 				if (WIFEXITED(status))
572 					retval = WEXITSTATUS(status);
573 				else
574 					retval = WTERMSIG(status) + 128;
575 				if (! iflag || ! job->changed)
576 					freejob(job);
577 				else {
578 					job->remembered = 0;
579 					if (job == bgjob)
580 						bgjob = NULL;
581 				}
582 				return retval;
583 			}
584 		} else {
585 			if (njobs == 0)
586 				return 0;
587 			for (jp = jobtab ; jp < jobtab + njobs; jp++)
588 				if (jp->used && jp->state == JOBDONE) {
589 					if (! iflag || ! jp->changed)
590 						freejob(jp);
591 					else {
592 						jp->remembered = 0;
593 						if (jp == bgjob)
594 							bgjob = NULL;
595 					}
596 				}
597 			for (jp = jobtab ; ; jp++) {
598 				if (jp >= jobtab + njobs) {	/* no running procs */
599 					return 0;
600 				}
601 				if (jp->used && jp->state == 0)
602 					break;
603 			}
604 		}
605 	} while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, (struct job *)NULL) != -1);
606 
607 	sig = pendingsig_waitcmd;
608 	pendingsig_waitcmd = 0;
609 	return sig + 128;
610 }
611 
612 
613 
614 int
615 jobidcmd(int argc __unused, char **argv __unused)
616 {
617 	struct job *jp;
618 	int i;
619 
620 	nextopt("");
621 	jp = getjob(*argptr);
622 	for (i = 0 ; i < jp->nprocs ; ) {
623 		out1fmt("%d", (int)jp->ps[i].pid);
624 		out1c(++i < jp->nprocs? ' ' : '\n');
625 	}
626 	return 0;
627 }
628 
629 
630 
631 /*
632  * Convert a job name to a job structure.
633  */
634 
635 static struct job *
636 getjob_nonotfound(const char *name)
637 {
638 	int jobno;
639 	struct job *found, *jp;
640 	size_t namelen;
641 	pid_t pid;
642 	int i;
643 
644 	if (name == NULL) {
645 #if JOBS
646 		name = "%+";
647 #else
648 		error("No current job");
649 #endif
650 	}
651 	if (name[0] == '%') {
652 		if (is_digit(name[1])) {
653 			jobno = number(name + 1);
654 			if (jobno > 0 && jobno <= njobs
655 			 && jobtab[jobno - 1].used != 0)
656 				return &jobtab[jobno - 1];
657 #if JOBS
658 		} else if ((name[1] == '%' || name[1] == '+') &&
659 		    name[2] == '\0') {
660 			if ((jp = getcurjob(NULL)) == NULL)
661 				error("No current job");
662 			return (jp);
663 		} else if (name[1] == '-' && name[2] == '\0') {
664 			if ((jp = getcurjob(NULL)) == NULL ||
665 			    (jp = getcurjob(jp)) == NULL)
666 				error("No previous job");
667 			return (jp);
668 #endif
669 		} else if (name[1] == '?') {
670 			found = NULL;
671 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
672 				if (jp->used && jp->nprocs > 0
673 				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
674 					if (found)
675 						error("%s: ambiguous", name);
676 					found = jp;
677 				}
678 			}
679 			if (found != NULL)
680 				return (found);
681 		} else {
682 			namelen = strlen(name);
683 			found = NULL;
684 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
685 				if (jp->used && jp->nprocs > 0
686 				 && strncmp(jp->ps[0].cmd, name + 1,
687 				 namelen - 1) == 0) {
688 					if (found)
689 						error("%s: ambiguous", name);
690 					found = jp;
691 				}
692 			}
693 			if (found)
694 				return found;
695 		}
696 	} else if (is_number(name)) {
697 		pid = (pid_t)number(name);
698 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
699 			if (jp->used && jp->nprocs > 0
700 			 && jp->ps[jp->nprocs - 1].pid == pid)
701 				return jp;
702 		}
703 	}
704 	return NULL;
705 }
706 
707 
708 static struct job *
709 getjob(const char *name)
710 {
711 	struct job *jp;
712 
713 	jp = getjob_nonotfound(name);
714 	if (jp == NULL)
715 		error("No such job: %s", name);
716 	return (jp);
717 }
718 
719 
720 int
721 killjob(const char *name, int sig)
722 {
723 	struct job *jp;
724 	int i, ret;
725 
726 	jp = getjob(name);
727 	if (jp->state == JOBDONE)
728 		return 0;
729 	if (jp->jobctl)
730 		return kill(-jp->ps[0].pid, sig);
731 	ret = -1;
732 	errno = ESRCH;
733 	for (i = 0; i < jp->nprocs; i++)
734 		if (jp->ps[i].status == -1 || WIFSTOPPED(jp->ps[i].status)) {
735 			if (kill(jp->ps[i].pid, sig) == 0)
736 				ret = 0;
737 		} else
738 			ret = 0;
739 	return ret;
740 }
741 
742 /*
743  * Return a new job structure,
744  */
745 
746 struct job *
747 makejob(union node *node __unused, int nprocs)
748 {
749 	int i;
750 	struct job *jp;
751 
752 	for (i = njobs, jp = jobtab ; ; jp++) {
753 		if (--i < 0) {
754 			INTOFF;
755 			if (njobs == 0) {
756 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
757 #if JOBS
758 				jobmru = NULL;
759 #endif
760 			} else {
761 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
762 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
763 #if JOBS
764 				/* Relocate `next' pointers and list head */
765 				if (jobmru != NULL)
766 					jobmru = &jp[jobmru - jobtab];
767 				for (i = 0; i < njobs; i++)
768 					if (jp[i].next != NULL)
769 						jp[i].next = &jp[jp[i].next -
770 						    jobtab];
771 #endif
772 				if (bgjob != NULL)
773 					bgjob = &jp[bgjob - jobtab];
774 				/* Relocate `ps' pointers */
775 				for (i = 0; i < njobs; i++)
776 					if (jp[i].ps == &jobtab[i].ps0)
777 						jp[i].ps = &jp[i].ps0;
778 				ckfree(jobtab);
779 				jobtab = jp;
780 			}
781 			jp = jobtab + njobs;
782 			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
783 				;
784 			INTON;
785 			break;
786 		}
787 		if (jp->used == 0)
788 			break;
789 	}
790 	INTOFF;
791 	jp->state = 0;
792 	jp->used = 1;
793 	jp->changed = 0;
794 	jp->nprocs = 0;
795 	jp->foreground = 0;
796 	jp->remembered = 0;
797 	jp->pipefail = pipefailflag;
798 #if JOBS
799 	jp->jobctl = jobctl;
800 	jp->next = NULL;
801 #endif
802 	if (nprocs > 1) {
803 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
804 	} else {
805 		jp->ps = &jp->ps0;
806 	}
807 	INTON;
808 	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
809 	    jp - jobtab + 1));
810 	return jp;
811 }
812 
813 #if JOBS
814 static void
815 setcurjob(struct job *cj)
816 {
817 	struct job *jp, *prev;
818 
819 	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
820 		if (jp == cj) {
821 			if (prev != NULL)
822 				prev->next = jp->next;
823 			else
824 				jobmru = jp->next;
825 			jp->next = jobmru;
826 			jobmru = cj;
827 			return;
828 		}
829 	}
830 	cj->next = jobmru;
831 	jobmru = cj;
832 }
833 
834 static void
835 deljob(struct job *j)
836 {
837 	struct job *jp, *prev;
838 
839 	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
840 		if (jp == j) {
841 			if (prev != NULL)
842 				prev->next = jp->next;
843 			else
844 				jobmru = jp->next;
845 			return;
846 		}
847 	}
848 }
849 
850 /*
851  * Return the most recently used job that isn't `nj', and preferably one
852  * that is stopped.
853  */
854 static struct job *
855 getcurjob(struct job *nj)
856 {
857 	struct job *jp;
858 
859 	/* Try to find a stopped one.. */
860 	for (jp = jobmru; jp != NULL; jp = jp->next)
861 		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
862 			return (jp);
863 	/* Otherwise the most recently used job that isn't `nj' */
864 	for (jp = jobmru; jp != NULL; jp = jp->next)
865 		if (jp->used && jp != nj)
866 			return (jp);
867 
868 	return (NULL);
869 }
870 
871 #endif
872 
873 /*
874  * Fork of a subshell.  If we are doing job control, give the subshell its
875  * own process group.  Jp is a job structure that the job is to be added to.
876  * N is the command that will be evaluated by the child.  Both jp and n may
877  * be NULL.  The mode parameter can be one of the following:
878  *	FORK_FG - Fork off a foreground process.
879  *	FORK_BG - Fork off a background process.
880  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
881  *		     process group even if job control is on.
882  *
883  * When job control is turned off, background processes have their standard
884  * input redirected to /dev/null (except for the second and later processes
885  * in a pipeline).
886  */
887 
888 pid_t
889 forkshell(struct job *jp, union node *n, int mode)
890 {
891 	pid_t pid;
892 	pid_t pgrp;
893 
894 	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
895 	    mode));
896 	INTOFF;
897 	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
898 		checkzombies();
899 	flushall();
900 	pid = fork();
901 	if (pid == -1) {
902 		TRACE(("Fork failed, errno=%d\n", errno));
903 		INTON;
904 		error("Cannot fork: %s", strerror(errno));
905 	}
906 	if (pid == 0) {
907 		struct job *p;
908 		int wasroot;
909 		int i;
910 
911 		TRACE(("Child shell %d\n", (int)getpid()));
912 		wasroot = rootshell;
913 		rootshell = 0;
914 		handler = &main_handler;
915 		closescript();
916 		INTON;
917 		forcelocal = 0;
918 		clear_traps();
919 #if JOBS
920 		jobctl = 0;		/* do job control only in root shell */
921 		if (wasroot && mode != FORK_NOJOB && mflag) {
922 			if (jp == NULL || jp->nprocs == 0)
923 				pgrp = getpid();
924 			else
925 				pgrp = jp->ps[0].pid;
926 			if (setpgid(0, pgrp) == 0 && mode == FORK_FG &&
927 			    ttyfd >= 0) {
928 				/*
929 				 * Each process in a pipeline must have the tty
930 				 * pgrp set before running its code.
931 				 * Only for pipelines of three or more processes
932 				 * could this be reduced to two calls.
933 				 */
934 				if (tcsetpgrp(ttyfd, pgrp) < 0)
935 					error("tcsetpgrp failed, errno=%d", errno);
936 			}
937 			setsignal(SIGTSTP);
938 			setsignal(SIGTTOU);
939 		} else if (mode == FORK_BG) {
940 			ignoresig(SIGINT);
941 			ignoresig(SIGQUIT);
942 			if ((jp == NULL || jp->nprocs == 0) &&
943 			    ! fd0_redirected_p ()) {
944 				close(0);
945 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
946 					error("cannot open %s: %s",
947 					    _PATH_DEVNULL, strerror(errno));
948 			}
949 		}
950 #else
951 		if (mode == FORK_BG) {
952 			ignoresig(SIGINT);
953 			ignoresig(SIGQUIT);
954 			if ((jp == NULL || jp->nprocs == 0) &&
955 			    ! fd0_redirected_p ()) {
956 				close(0);
957 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
958 					error("cannot open %s: %s",
959 					    _PATH_DEVNULL, strerror(errno));
960 			}
961 		}
962 #endif
963 		INTOFF;
964 		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
965 			if (p->used)
966 				freejob(p);
967 		INTON;
968 		if (wasroot && iflag) {
969 			setsignal(SIGINT);
970 			setsignal(SIGQUIT);
971 			setsignal(SIGTERM);
972 		}
973 		return pid;
974 	}
975 	if (rootshell && mode != FORK_NOJOB && mflag) {
976 		if (jp == NULL || jp->nprocs == 0)
977 			pgrp = pid;
978 		else
979 			pgrp = jp->ps[0].pid;
980 		setpgid(pid, pgrp);
981 	}
982 	if (mode == FORK_BG) {
983 		if (bgjob != NULL && bgjob->state == JOBDONE &&
984 		    !bgjob->remembered && !iflag)
985 			freejob(bgjob);
986 		backgndpid = pid;		/* set $! */
987 		bgjob = jp;
988 	}
989 	if (jp) {
990 		struct procstat *ps = &jp->ps[jp->nprocs++];
991 		ps->pid = pid;
992 		ps->status = -1;
993 		ps->cmd = nullstr;
994 		if (iflag && rootshell && n)
995 			ps->cmd = commandtext(n);
996 		jp->foreground = mode == FORK_FG;
997 #if JOBS
998 		setcurjob(jp);
999 #endif
1000 	}
1001 	INTON;
1002 	TRACE(("In parent shell:  child = %d\n", (int)pid));
1003 	return pid;
1004 }
1005 
1006 
1007 pid_t
1008 vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
1009 {
1010 	pid_t pid;
1011 	struct jmploc jmploc;
1012 	struct jmploc *savehandler;
1013 	int inton;
1014 
1015 	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
1016 	    (void *)pip));
1017 	inton = is_int_on();
1018 	INTOFF;
1019 	flushall();
1020 	savehandler = handler;
1021 	pid = vfork();
1022 	if (pid == -1) {
1023 		TRACE(("Vfork failed, errno=%d\n", errno));
1024 		INTON;
1025 		error("Cannot fork: %s", strerror(errno));
1026 	}
1027 	if (pid == 0) {
1028 		TRACE(("Child shell %d\n", (int)getpid()));
1029 		if (setjmp(jmploc.loc))
1030 			_exit(exitstatus);
1031 		if (pip != NULL) {
1032 			close(pip[0]);
1033 			if (pip[1] != 1) {
1034 				dup2(pip[1], 1);
1035 				close(pip[1]);
1036 			}
1037 		}
1038 		handler = &jmploc;
1039 		shellexec(argv, envp, path, idx);
1040 	}
1041 	handler = savehandler;
1042 	if (jp) {
1043 		struct procstat *ps = &jp->ps[jp->nprocs++];
1044 		ps->pid = pid;
1045 		ps->status = -1;
1046 		ps->cmd = nullstr;
1047 		jp->foreground = 1;
1048 #if JOBS
1049 		setcurjob(jp);
1050 #endif
1051 	}
1052 	SETINTON(inton);
1053 	TRACE(("In parent shell:  child = %d\n", (int)pid));
1054 	return pid;
1055 }
1056 
1057 
1058 /*
1059  * Wait for job to finish.
1060  *
1061  * Under job control we have the problem that while a child process is
1062  * running interrupts generated by the user are sent to the child but not
1063  * to the shell.  This means that an infinite loop started by an inter-
1064  * active user may be hard to kill.  With job control turned off, an
1065  * interactive user may place an interactive program inside a loop.  If
1066  * the interactive program catches interrupts, the user doesn't want
1067  * these interrupts to also abort the loop.  The approach we take here
1068  * is to have the shell ignore interrupt signals while waiting for a
1069  * foreground process to terminate, and then send itself an interrupt
1070  * signal if the child process was terminated by an interrupt signal.
1071  * Unfortunately, some programs want to do a bit of cleanup and then
1072  * exit on interrupt; unless these processes terminate themselves by
1073  * sending a signal to themselves (instead of calling exit) they will
1074  * confuse this approach.
1075  */
1076 
1077 int
1078 waitforjob(struct job *jp, int *signaled)
1079 {
1080 #if JOBS
1081 	int propagate_int = jp->jobctl && jp->foreground;
1082 #endif
1083 	int status;
1084 	int st;
1085 
1086 	INTOFF;
1087 	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
1088 	while (jp->state == 0)
1089 		if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
1090 		    DOWAIT_SIG_TRAP : 0), jp) == -1)
1091 			dotrap();
1092 #if JOBS
1093 	if (jp->jobctl) {
1094 		if (ttyfd >= 0 && tcsetpgrp(ttyfd, rootpid) < 0)
1095 			error("tcsetpgrp failed, errno=%d\n", errno);
1096 	}
1097 	if (jp->state == JOBSTOPPED)
1098 		setcurjob(jp);
1099 #endif
1100 	status = getjobstatus(jp);
1101 	if (signaled != NULL)
1102 		*signaled = WIFSIGNALED(status);
1103 	/* convert to 8 bits */
1104 	if (WIFEXITED(status))
1105 		st = WEXITSTATUS(status);
1106 #if JOBS
1107 	else if (WIFSTOPPED(status))
1108 		st = WSTOPSIG(status) + 128;
1109 #endif
1110 	else
1111 		st = WTERMSIG(status) + 128;
1112 	if (! JOBS || jp->state == JOBDONE)
1113 		freejob(jp);
1114 	if (int_pending()) {
1115 		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
1116 			CLEAR_PENDING_INT;
1117 	}
1118 #if JOBS
1119 	else if (rootshell && propagate_int &&
1120 			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1121 		kill(getpid(), SIGINT);
1122 #endif
1123 	INTON;
1124 	return st;
1125 }
1126 
1127 
1128 static void
1129 dummy_handler(int sig __unused)
1130 {
1131 }
1132 
1133 /*
1134  * Wait for a process to terminate.
1135  */
1136 
1137 static pid_t
1138 dowait(int mode, struct job *job)
1139 {
1140 	struct sigaction sa, osa;
1141 	sigset_t mask, omask;
1142 	pid_t pid;
1143 	int status;
1144 	struct procstat *sp;
1145 	struct job *jp;
1146 	struct job *thisjob;
1147 	const char *sigstr;
1148 	int done;
1149 	int stopped;
1150 	int sig;
1151 	int coredump;
1152 	int wflags;
1153 	int restore_sigchld;
1154 
1155 	TRACE(("dowait(%d, %p) called\n", mode, job));
1156 	restore_sigchld = 0;
1157 	if ((mode & DOWAIT_SIG) != 0) {
1158 		sigfillset(&mask);
1159 		sigprocmask(SIG_BLOCK, &mask, &omask);
1160 		INTOFF;
1161 		if (!issigchldtrapped()) {
1162 			restore_sigchld = 1;
1163 			sa.sa_handler = dummy_handler;
1164 			sa.sa_flags = 0;
1165 			sigemptyset(&sa.sa_mask);
1166 			sigaction(SIGCHLD, &sa, &osa);
1167 		}
1168 	}
1169 	do {
1170 #if JOBS
1171 		if (iflag)
1172 			wflags = WUNTRACED | WCONTINUED;
1173 		else
1174 #endif
1175 			wflags = 0;
1176 		if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1177 			wflags |= WNOHANG;
1178 		pid = wait3(&status, wflags, (struct rusage *)NULL);
1179 		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1180 		if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1181 			pid = -1;
1182 			if (((mode & DOWAIT_SIG_TRAP) != 0 ?
1183 			    pendingsig : pendingsig_waitcmd) != 0) {
1184 				errno = EINTR;
1185 				break;
1186 			}
1187 			sigsuspend(&omask);
1188 			if (int_pending())
1189 				break;
1190 		}
1191 	} while (pid == -1 && errno == EINTR);
1192 	if (pid == -1 && errno == ECHILD && job != NULL)
1193 		job->state = JOBDONE;
1194 	if ((mode & DOWAIT_SIG) != 0) {
1195 		if (restore_sigchld)
1196 			sigaction(SIGCHLD, &osa, NULL);
1197 		sigprocmask(SIG_SETMASK, &omask, NULL);
1198 		INTON;
1199 	}
1200 	if (pid <= 0)
1201 		return pid;
1202 	INTOFF;
1203 	thisjob = NULL;
1204 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1205 		if (jp->used && jp->nprocs > 0) {
1206 			done = 1;
1207 			stopped = 1;
1208 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1209 				if (sp->pid == -1)
1210 					continue;
1211 				if (sp->pid == pid && (sp->status == -1 ||
1212 				    WIFSTOPPED(sp->status))) {
1213 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1214 						   (int)pid, sp->status,
1215 						   status));
1216 					if (WIFCONTINUED(status)) {
1217 						sp->status = -1;
1218 						jp->state = 0;
1219 					} else
1220 						sp->status = status;
1221 					thisjob = jp;
1222 				}
1223 				if (sp->status == -1)
1224 					stopped = 0;
1225 				else if (WIFSTOPPED(sp->status))
1226 					done = 0;
1227 			}
1228 			if (stopped) {		/* stopped or done */
1229 				int state = done? JOBDONE : JOBSTOPPED;
1230 				if (jp->state != state) {
1231 					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1232 					jp->state = state;
1233 					if (jp != job) {
1234 						if (done && !jp->remembered &&
1235 						    !iflag && jp != bgjob)
1236 							freejob(jp);
1237 #if JOBS
1238 						else if (done)
1239 							deljob(jp);
1240 #endif
1241 					}
1242 				}
1243 			}
1244 		}
1245 	}
1246 	INTON;
1247 	if (!thisjob || thisjob->state == 0)
1248 		;
1249 	else if ((!rootshell || !iflag || thisjob == job) &&
1250 	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1251 		sig = 0;
1252 		coredump = 0;
1253 		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1254 			if (WIFSIGNALED(sp->status)) {
1255 				sig = WTERMSIG(sp->status);
1256 				coredump = WCOREDUMP(sp->status);
1257 			}
1258 		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1259 			sigstr = strsignal(sig);
1260 			if (sigstr != NULL)
1261 				out2str(sigstr);
1262 			else
1263 				out2str("Unknown signal");
1264 			if (coredump)
1265 				out2str(" (core dumped)");
1266 			out2c('\n');
1267 			flushout(out2);
1268 		}
1269 	} else {
1270 		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1271 		thisjob->changed = 1;
1272 	}
1273 	return pid;
1274 }
1275 
1276 
1277 
1278 /*
1279  * return 1 if there are stopped jobs, otherwise 0
1280  */
1281 int job_warning = 0;
1282 int
1283 stoppedjobs(void)
1284 {
1285 	int jobno;
1286 	struct job *jp;
1287 
1288 	if (job_warning)
1289 		return (0);
1290 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1291 		if (jp->used == 0)
1292 			continue;
1293 		if (jp->state == JOBSTOPPED) {
1294 			out2fmt_flush("You have stopped jobs.\n");
1295 			job_warning = 2;
1296 			return (1);
1297 		}
1298 	}
1299 
1300 	return (0);
1301 }
1302 
1303 
1304 static void
1305 checkzombies(void)
1306 {
1307 	while (njobs > 0 && dowait(0, NULL) > 0)
1308 		;
1309 }
1310 
1311 
1312 int
1313 backgndpidset(void)
1314 {
1315 	return backgndpid != -1;
1316 }
1317 
1318 
1319 pid_t
1320 backgndpidval(void)
1321 {
1322 	if (bgjob != NULL && !forcelocal)
1323 		bgjob->remembered = 1;
1324 	return backgndpid;
1325 }
1326 
1327 /*
1328  * Return a string identifying a command (to be printed by the
1329  * jobs command.
1330  */
1331 
1332 static char *cmdnextc;
1333 static int cmdnleft;
1334 #define MAXCMDTEXT	200
1335 
1336 char *
1337 commandtext(union node *n)
1338 {
1339 	char *name;
1340 
1341 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1342 	cmdnleft = MAXCMDTEXT - 4;
1343 	cmdtxt(n);
1344 	*cmdnextc = '\0';
1345 	return name;
1346 }
1347 
1348 
1349 static void
1350 cmdtxtdogroup(union node *n)
1351 {
1352 	cmdputs("; do ");
1353 	cmdtxt(n);
1354 	cmdputs("; done");
1355 }
1356 
1357 
1358 static void
1359 cmdtxtredir(union node *n, const char *op, int deffd)
1360 {
1361 	char s[2];
1362 
1363 	if (n->nfile.fd != deffd) {
1364 		s[0] = n->nfile.fd + '0';
1365 		s[1] = '\0';
1366 		cmdputs(s);
1367 	}
1368 	cmdputs(op);
1369 	if (n->type == NTOFD || n->type == NFROMFD) {
1370 		if (n->ndup.dupfd >= 0)
1371 			s[0] = n->ndup.dupfd + '0';
1372 		else
1373 			s[0] = '-';
1374 		s[1] = '\0';
1375 		cmdputs(s);
1376 	} else {
1377 		cmdtxt(n->nfile.fname);
1378 	}
1379 }
1380 
1381 
1382 static void
1383 cmdtxt(union node *n)
1384 {
1385 	union node *np;
1386 	struct nodelist *lp;
1387 
1388 	if (n == NULL)
1389 		return;
1390 	switch (n->type) {
1391 	case NSEMI:
1392 		cmdtxt(n->nbinary.ch1);
1393 		cmdputs("; ");
1394 		cmdtxt(n->nbinary.ch2);
1395 		break;
1396 	case NAND:
1397 		cmdtxt(n->nbinary.ch1);
1398 		cmdputs(" && ");
1399 		cmdtxt(n->nbinary.ch2);
1400 		break;
1401 	case NOR:
1402 		cmdtxt(n->nbinary.ch1);
1403 		cmdputs(" || ");
1404 		cmdtxt(n->nbinary.ch2);
1405 		break;
1406 	case NPIPE:
1407 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1408 			cmdtxt(lp->n);
1409 			if (lp->next)
1410 				cmdputs(" | ");
1411 		}
1412 		break;
1413 	case NSUBSHELL:
1414 		cmdputs("(");
1415 		cmdtxt(n->nredir.n);
1416 		cmdputs(")");
1417 		break;
1418 	case NREDIR:
1419 	case NBACKGND:
1420 		cmdtxt(n->nredir.n);
1421 		break;
1422 	case NIF:
1423 		cmdputs("if ");
1424 		cmdtxt(n->nif.test);
1425 		cmdputs("; then ");
1426 		cmdtxt(n->nif.ifpart);
1427 		cmdputs("...");
1428 		break;
1429 	case NWHILE:
1430 		cmdputs("while ");
1431 		cmdtxt(n->nbinary.ch1);
1432 		cmdtxtdogroup(n->nbinary.ch2);
1433 		break;
1434 	case NUNTIL:
1435 		cmdputs("until ");
1436 		cmdtxt(n->nbinary.ch1);
1437 		cmdtxtdogroup(n->nbinary.ch2);
1438 		break;
1439 	case NFOR:
1440 		cmdputs("for ");
1441 		cmdputs(n->nfor.var);
1442 		cmdputs(" in ...");
1443 		break;
1444 	case NCASE:
1445 		cmdputs("case ");
1446 		cmdputs(n->ncase.expr->narg.text);
1447 		cmdputs(" in ...");
1448 		break;
1449 	case NDEFUN:
1450 		cmdputs(n->narg.text);
1451 		cmdputs("() ...");
1452 		break;
1453 	case NNOT:
1454 		cmdputs("! ");
1455 		cmdtxt(n->nnot.com);
1456 		break;
1457 	case NCMD:
1458 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1459 			cmdtxt(np);
1460 			if (np->narg.next)
1461 				cmdputs(" ");
1462 		}
1463 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1464 			cmdputs(" ");
1465 			cmdtxt(np);
1466 		}
1467 		break;
1468 	case NARG:
1469 		cmdputs(n->narg.text);
1470 		break;
1471 	case NTO:
1472 		cmdtxtredir(n, ">", 1);
1473 		break;
1474 	case NAPPEND:
1475 		cmdtxtredir(n, ">>", 1);
1476 		break;
1477 	case NTOFD:
1478 		cmdtxtredir(n, ">&", 1);
1479 		break;
1480 	case NCLOBBER:
1481 		cmdtxtredir(n, ">|", 1);
1482 		break;
1483 	case NFROM:
1484 		cmdtxtredir(n, "<", 0);
1485 		break;
1486 	case NFROMTO:
1487 		cmdtxtredir(n, "<>", 0);
1488 		break;
1489 	case NFROMFD:
1490 		cmdtxtredir(n, "<&", 0);
1491 		break;
1492 	case NHERE:
1493 	case NXHERE:
1494 		cmdputs("<<...");
1495 		break;
1496 	default:
1497 		cmdputs("???");
1498 		break;
1499 	}
1500 }
1501 
1502 
1503 
1504 static void
1505 cmdputs(const char *s)
1506 {
1507 	const char *p;
1508 	char *q;
1509 	char c;
1510 	int subtype = 0;
1511 
1512 	if (cmdnleft <= 0)
1513 		return;
1514 	p = s;
1515 	q = cmdnextc;
1516 	while ((c = *p++) != '\0') {
1517 		if (c == CTLESC)
1518 			*q++ = *p++;
1519 		else if (c == CTLVAR) {
1520 			*q++ = '$';
1521 			if (--cmdnleft > 0)
1522 				*q++ = '{';
1523 			subtype = *p++;
1524 			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1525 				*q++ = '#';
1526 		} else if (c == '=' && subtype != 0) {
1527 			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1528 			if (*q)
1529 				q++;
1530 			else
1531 				cmdnleft++;
1532 			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1533 			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1534 			    --cmdnleft > 0)
1535 				*q = q[-1], q++;
1536 			subtype = 0;
1537 		} else if (c == CTLENDVAR) {
1538 			*q++ = '}';
1539 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1540 			cmdnleft -= 5;
1541 			if (cmdnleft > 0) {
1542 				*q++ = '$';
1543 				*q++ = '(';
1544 				*q++ = '.';
1545 				*q++ = '.';
1546 				*q++ = '.';
1547 				*q++ = ')';
1548 			}
1549 		} else if (c == CTLARI) {
1550 			cmdnleft -= 2;
1551 			if (cmdnleft > 0) {
1552 				*q++ = '$';
1553 				*q++ = '(';
1554 				*q++ = '(';
1555 			}
1556 			p++;
1557 		} else if (c == CTLENDARI) {
1558 			if (--cmdnleft > 0) {
1559 				*q++ = ')';
1560 				*q++ = ')';
1561 			}
1562 		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1563 			cmdnleft++; /* ignore */
1564 		else
1565 			*q++ = c;
1566 		if (--cmdnleft <= 0) {
1567 			*q++ = '.';
1568 			*q++ = '.';
1569 			*q++ = '.';
1570 			break;
1571 		}
1572 	}
1573 	cmdnextc = q;
1574 }
1575