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