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