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