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