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