xref: /freebsd/bin/sh/jobs.c (revision 730cecb05aaf016ac52ef7cfc691ccec3a0408cd)
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)) < 0) {
131 			i = 0;
132 			while (i <= 2 && !isatty(i))
133 				i++;
134 			if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
135 				goto out;
136 		}
137 		if (ttyfd < 10) {
138 			/*
139 			 * Keep our TTY file descriptor out of the way of
140 			 * the user's redirections.
141 			 */
142 			if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
143 				close(ttyfd);
144 				ttyfd = -1;
145 				goto out;
146 			}
147 			close(ttyfd);
148 			ttyfd = i;
149 		}
150 		if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
151 			close(ttyfd);
152 			ttyfd = -1;
153 			goto out;
154 		}
155 		do { /* while we are in the background */
156 			initialpgrp = tcgetpgrp(ttyfd);
157 			if (initialpgrp < 0) {
158 out:				out2fmt_flush("sh: can't access tty; job control turned off\n");
159 				mflag = 0;
160 				return;
161 			}
162 			if (initialpgrp != getpgrp()) {
163 				kill(0, SIGTTIN);
164 				continue;
165 			}
166 		} while (0);
167 		setsignal(SIGTSTP);
168 		setsignal(SIGTTOU);
169 		setsignal(SIGTTIN);
170 		setpgid(0, rootpid);
171 		tcsetpgrp(ttyfd, rootpid);
172 	} else { /* turning job control off */
173 		setpgid(0, initialpgrp);
174 		tcsetpgrp(ttyfd, initialpgrp);
175 		close(ttyfd);
176 		ttyfd = -1;
177 		setsignal(SIGTSTP);
178 		setsignal(SIGTTOU);
179 		setsignal(SIGTTIN);
180 	}
181 	jobctl = on;
182 }
183 #endif
184 
185 
186 #if JOBS
187 int
188 fgcmd(int argc __unused, char **argv)
189 {
190 	struct job *jp;
191 	pid_t pgrp;
192 	int status;
193 
194 	jp = getjob(argv[1]);
195 	if (jp->jobctl == 0)
196 		error("job not created under job control");
197 	printjobcmd(jp);
198 	flushout(&output);
199 	pgrp = jp->ps[0].pid;
200 	tcsetpgrp(ttyfd, pgrp);
201 	restartjob(jp);
202 	jp->foreground = 1;
203 	INTOFF;
204 	status = waitforjob(jp, (int *)NULL);
205 	INTON;
206 	return status;
207 }
208 
209 
210 int
211 bgcmd(int argc, char **argv)
212 {
213 	struct job *jp;
214 
215 	do {
216 		jp = getjob(*++argv);
217 		if (jp->jobctl == 0)
218 			error("job not created under job control");
219 		if (jp->state == JOBDONE)
220 			continue;
221 		restartjob(jp);
222 		jp->foreground = 0;
223 		out1fmt("[%td] ", jp - jobtab + 1);
224 		printjobcmd(jp);
225 	} while (--argc > 1);
226 	return 0;
227 }
228 
229 
230 static void
231 restartjob(struct job *jp)
232 {
233 	struct procstat *ps;
234 	int i;
235 
236 	if (jp->state == JOBDONE)
237 		return;
238 	setcurjob(jp);
239 	INTOFF;
240 	kill(-jp->ps[0].pid, SIGCONT);
241 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
242 		if (WIFSTOPPED(ps->status)) {
243 			ps->status = -1;
244 			jp->state = 0;
245 		}
246 	}
247 	INTON;
248 }
249 #endif
250 
251 
252 int
253 jobscmd(int argc __unused, char *argv[] __unused)
254 {
255 	char *id;
256 	int ch, mode;
257 
258 	mode = SHOWJOBS_DEFAULT;
259 	while ((ch = nextopt("lps")) != '\0') {
260 		switch (ch) {
261 		case 'l':
262 			mode = SHOWJOBS_VERBOSE;
263 			break;
264 		case 'p':
265 			mode = SHOWJOBS_PGIDS;
266 			break;
267 		case 's':
268 			mode = SHOWJOBS_PIDS;
269 			break;
270 		}
271 	}
272 
273 	if (*argptr == NULL)
274 		showjobs(0, mode);
275 	else
276 		while ((id = *argptr++) != NULL)
277 			showjob(getjob(id), mode);
278 
279 	return (0);
280 }
281 
282 static void
283 printjobcmd(struct job *jp)
284 {
285 	struct procstat *ps;
286 	int i;
287 
288 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
289 		out1str(ps->cmd);
290 		if (i > 0)
291 			out1str(" | ");
292 	}
293 	out1c('\n');
294 }
295 
296 static void
297 showjob(struct job *jp, int mode)
298 {
299 	char s[64];
300 	char statestr[64];
301 	const char *sigstr;
302 	struct procstat *ps;
303 	struct job *j;
304 	int col, curr, i, jobno, prev, procno;
305 	char c;
306 
307 	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
308 	jobno = jp - jobtab + 1;
309 	curr = prev = 0;
310 #if JOBS
311 	if ((j = getcurjob(NULL)) != NULL) {
312 		curr = j - jobtab + 1;
313 		if ((j = getcurjob(j)) != NULL)
314 			prev = j - jobtab + 1;
315 	}
316 #endif
317 	ps = jp->ps + jp->nprocs - 1;
318 	if (jp->state == 0) {
319 		strcpy(statestr, "Running");
320 #if JOBS
321 	} else if (jp->state == JOBSTOPPED) {
322 		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
323 			ps--;
324 		if (WIFSTOPPED(ps->status))
325 			i = WSTOPSIG(ps->status);
326 		else
327 			i = -1;
328 		sigstr = strsignal(i);
329 		if (sigstr != NULL)
330 			strcpy(statestr, sigstr);
331 		else
332 			strcpy(statestr, "Suspended");
333 #endif
334 	} else if (WIFEXITED(ps->status)) {
335 		if (WEXITSTATUS(ps->status) == 0)
336 			strcpy(statestr, "Done");
337 		else
338 			fmtstr(statestr, 64, "Done(%d)",
339 			    WEXITSTATUS(ps->status));
340 	} else {
341 		i = WTERMSIG(ps->status);
342 		sigstr = strsignal(i);
343 		if (sigstr != NULL)
344 			strcpy(statestr, sigstr);
345 		else
346 			strcpy(statestr, "Unknown signal");
347 		if (WCOREDUMP(ps->status))
348 			strcat(statestr, " (core dumped)");
349 	}
350 
351 	for (ps = jp->ps ; ; ps++) {	/* for each process */
352 		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
353 			out1fmt("%d\n", (int)ps->pid);
354 			goto skip;
355 		}
356 		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
357 			goto skip;
358 		if (jobno == curr && ps == jp->ps)
359 			c = '+';
360 		else if (jobno == prev && ps == jp->ps)
361 			c = '-';
362 		else
363 			c = ' ';
364 		if (ps == jp->ps)
365 			fmtstr(s, 64, "[%d] %c ", jobno, c);
366 		else
367 			fmtstr(s, 64, "    %c ", c);
368 		out1str(s);
369 		col = strlen(s);
370 		if (mode == SHOWJOBS_VERBOSE) {
371 			fmtstr(s, 64, "%d ", (int)ps->pid);
372 			out1str(s);
373 			col += strlen(s);
374 		}
375 		if (ps == jp->ps) {
376 			out1str(statestr);
377 			col += strlen(statestr);
378 		}
379 		do {
380 			out1c(' ');
381 			col++;
382 		} while (col < 30);
383 		if (mode == SHOWJOBS_VERBOSE) {
384 			out1str(ps->cmd);
385 			out1c('\n');
386 		} else
387 			printjobcmd(jp);
388 skip:		if (--procno <= 0)
389 			break;
390 	}
391 }
392 
393 /*
394  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
395  * statuses have changed since the last call to showjobs.
396  *
397  * If the shell is interrupted in the process of creating a job, the
398  * result may be a job structure containing zero processes.  Such structures
399  * will be freed here.
400  */
401 
402 void
403 showjobs(int change, int mode)
404 {
405 	int jobno;
406 	struct job *jp;
407 
408 	TRACE(("showjobs(%d) called\n", change));
409 	checkzombies();
410 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
411 		if (! jp->used)
412 			continue;
413 		if (jp->nprocs == 0) {
414 			freejob(jp);
415 			continue;
416 		}
417 		if (change && ! jp->changed)
418 			continue;
419 		showjob(jp, mode);
420 		jp->changed = 0;
421 		/* Hack: discard jobs for which $! has not been referenced
422 		 * in interactive mode when they terminate.
423 		 */
424 		if (jp->state == JOBDONE && !jp->remembered &&
425 				(iflag || jp != bgjob)) {
426 			freejob(jp);
427 		}
428 	}
429 }
430 
431 
432 /*
433  * Mark a job structure as unused.
434  */
435 
436 static void
437 freejob(struct job *jp)
438 {
439 	struct procstat *ps;
440 	int i;
441 
442 	INTOFF;
443 	if (bgjob == jp)
444 		bgjob = NULL;
445 	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
446 		if (ps->cmd != nullstr)
447 			ckfree(ps->cmd);
448 	}
449 	if (jp->ps != &jp->ps0)
450 		ckfree(jp->ps);
451 	jp->used = 0;
452 #if JOBS
453 	deljob(jp);
454 #endif
455 	INTON;
456 }
457 
458 
459 
460 int
461 waitcmd(int argc __unused, char **argv __unused)
462 {
463 	struct job *job;
464 	int status, retval;
465 	struct job *jp;
466 
467 	nextopt("");
468 	if (*argptr != NULL) {
469 		job = getjob(*argptr);
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(DOWAIT_BLOCK | DOWAIT_SIG, (struct job *)NULL) != -1);
523 	in_waitcmd--;
524 
525 	return pendingsig + 128;
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 pid_t
889 vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
890 {
891 	pid_t pid;
892 	struct jmploc jmploc;
893 	struct jmploc *savehandler;
894 
895 	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
896 	    (void *)pip));
897 	INTOFF;
898 	flushall();
899 	savehandler = handler;
900 	pid = vfork();
901 	if (pid == -1) {
902 		TRACE(("Vfork failed, errno=%d\n", errno));
903 		INTON;
904 		error("Cannot fork: %s", strerror(errno));
905 	}
906 	if (pid == 0) {
907 		TRACE(("Child shell %d\n", (int)getpid()));
908 		if (setjmp(jmploc.loc))
909 			_exit(exception == EXEXEC ? exerrno : 2);
910 		if (pip != NULL) {
911 			close(pip[0]);
912 			if (pip[1] != 1) {
913 				dup2(pip[1], 1);
914 				close(pip[1]);
915 			}
916 		}
917 		handler = &jmploc;
918 		shellexec(argv, envp, path, idx);
919 	}
920 	handler = savehandler;
921 	if (jp) {
922 		struct procstat *ps = &jp->ps[jp->nprocs++];
923 		ps->pid = pid;
924 		ps->status = -1;
925 		ps->cmd = nullstr;
926 		jp->foreground = 1;
927 #if JOBS
928 		setcurjob(jp);
929 #endif
930 	}
931 	INTON;
932 	TRACE(("In parent shell:  child = %d\n", (int)pid));
933 	return pid;
934 }
935 
936 
937 /*
938  * Wait for job to finish.
939  *
940  * Under job control we have the problem that while a child process is
941  * running interrupts generated by the user are sent to the child but not
942  * to the shell.  This means that an infinite loop started by an inter-
943  * active user may be hard to kill.  With job control turned off, an
944  * interactive user may place an interactive program inside a loop.  If
945  * the interactive program catches interrupts, the user doesn't want
946  * these interrupts to also abort the loop.  The approach we take here
947  * is to have the shell ignore interrupt signals while waiting for a
948  * foreground process to terminate, and then send itself an interrupt
949  * signal if the child process was terminated by an interrupt signal.
950  * Unfortunately, some programs want to do a bit of cleanup and then
951  * exit on interrupt; unless these processes terminate themselves by
952  * sending a signal to themselves (instead of calling exit) they will
953  * confuse this approach.
954  */
955 
956 int
957 waitforjob(struct job *jp, int *origstatus)
958 {
959 #if JOBS
960 	pid_t mypgrp = getpgrp();
961 	int propagate_int = jp->jobctl && jp->foreground;
962 #endif
963 	int status;
964 	int st;
965 
966 	INTOFF;
967 	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
968 	while (jp->state == 0)
969 		if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG : 0), jp) == -1)
970 			dotrap();
971 #if JOBS
972 	if (jp->jobctl) {
973 		if (tcsetpgrp(ttyfd, mypgrp) < 0)
974 			error("tcsetpgrp failed, errno=%d\n", errno);
975 	}
976 	if (jp->state == JOBSTOPPED)
977 		setcurjob(jp);
978 #endif
979 	status = jp->ps[jp->nprocs - 1].status;
980 	if (origstatus != NULL)
981 		*origstatus = status;
982 	/* convert to 8 bits */
983 	if (WIFEXITED(status))
984 		st = WEXITSTATUS(status);
985 #if JOBS
986 	else if (WIFSTOPPED(status))
987 		st = WSTOPSIG(status) + 128;
988 #endif
989 	else
990 		st = WTERMSIG(status) + 128;
991 	if (! JOBS || jp->state == JOBDONE)
992 		freejob(jp);
993 	if (int_pending()) {
994 		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
995 			CLEAR_PENDING_INT;
996 	}
997 #if JOBS
998 	else if (rootshell && iflag && propagate_int &&
999 			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1000 		kill(getpid(), SIGINT);
1001 #endif
1002 	INTON;
1003 	return st;
1004 }
1005 
1006 
1007 static void
1008 dummy_handler(int sig)
1009 {
1010 }
1011 
1012 /*
1013  * Wait for a process to terminate.
1014  */
1015 
1016 static pid_t
1017 dowait(int mode, struct job *job)
1018 {
1019 	struct sigaction sa, osa;
1020 	sigset_t mask, omask;
1021 	pid_t pid;
1022 	int status;
1023 	struct procstat *sp;
1024 	struct job *jp;
1025 	struct job *thisjob;
1026 	const char *sigstr;
1027 	int done;
1028 	int stopped;
1029 	int sig;
1030 	int coredump;
1031 	int wflags;
1032 	int restore_sigchld;
1033 
1034 	TRACE(("dowait(%d, %p) called\n", mode, job));
1035 	restore_sigchld = 0;
1036 	if ((mode & DOWAIT_SIG) != 0) {
1037 		sigfillset(&mask);
1038 		sigprocmask(SIG_BLOCK, &mask, &omask);
1039 		INTOFF;
1040 		if (!issigchldtrapped()) {
1041 			restore_sigchld = 1;
1042 			sa.sa_handler = dummy_handler;
1043 			sa.sa_flags = 0;
1044 			sigemptyset(&sa.sa_mask);
1045 			sigaction(SIGCHLD, &sa, &osa);
1046 		}
1047 	}
1048 	do {
1049 #if JOBS
1050 		if (iflag)
1051 			wflags = WUNTRACED | WCONTINUED;
1052 		else
1053 #endif
1054 			wflags = 0;
1055 		if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1056 			wflags |= WNOHANG;
1057 		pid = wait3(&status, wflags, (struct rusage *)NULL);
1058 		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1059 		if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1060 			sigsuspend(&omask);
1061 			pid = -1;
1062 			if (int_pending())
1063 				break;
1064 		}
1065 	} while (pid == -1 && errno == EINTR && breakwaitcmd == 0);
1066 	if (pid == -1 && errno == ECHILD && job != NULL)
1067 		job->state = JOBDONE;
1068 	if ((mode & DOWAIT_SIG) != 0) {
1069 		if (restore_sigchld)
1070 			sigaction(SIGCHLD, &osa, NULL);
1071 		sigprocmask(SIG_SETMASK, &omask, NULL);
1072 		INTON;
1073 	}
1074 	if (breakwaitcmd != 0) {
1075 		breakwaitcmd = 0;
1076 		if (pid <= 0)
1077 			return -1;
1078 	}
1079 	if (pid <= 0)
1080 		return pid;
1081 	INTOFF;
1082 	thisjob = NULL;
1083 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1084 		if (jp->used && jp->nprocs > 0) {
1085 			done = 1;
1086 			stopped = 1;
1087 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1088 				if (sp->pid == -1)
1089 					continue;
1090 				if (sp->pid == pid) {
1091 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1092 						   (int)pid, sp->status,
1093 						   status));
1094 					if (WIFCONTINUED(status)) {
1095 						sp->status = -1;
1096 						jp->state = 0;
1097 					} else
1098 						sp->status = status;
1099 					thisjob = jp;
1100 				}
1101 				if (sp->status == -1)
1102 					stopped = 0;
1103 				else if (WIFSTOPPED(sp->status))
1104 					done = 0;
1105 			}
1106 			if (stopped) {		/* stopped or done */
1107 				int state = done? JOBDONE : JOBSTOPPED;
1108 				if (jp->state != state) {
1109 					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1110 					jp->state = state;
1111 					if (jp != job) {
1112 						if (done && !jp->remembered &&
1113 						    !iflag && jp != bgjob)
1114 							freejob(jp);
1115 #if JOBS
1116 						else if (done)
1117 							deljob(jp);
1118 #endif
1119 					}
1120 				}
1121 			}
1122 		}
1123 	}
1124 	INTON;
1125 	if (!thisjob || thisjob->state == 0)
1126 		;
1127 	else if ((!rootshell || !iflag || thisjob == job) &&
1128 	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1129 		sig = 0;
1130 		coredump = 0;
1131 		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1132 			if (WIFSIGNALED(sp->status)) {
1133 				sig = WTERMSIG(sp->status);
1134 				coredump = WCOREDUMP(sp->status);
1135 			}
1136 		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1137 			sigstr = strsignal(sig);
1138 			if (sigstr != NULL)
1139 				out2str(sigstr);
1140 			else
1141 				out2str("Unknown signal");
1142 			if (coredump)
1143 				out2str(" (core dumped)");
1144 			out2c('\n');
1145 			flushout(out2);
1146 		}
1147 	} else {
1148 		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1149 		thisjob->changed = 1;
1150 	}
1151 	return pid;
1152 }
1153 
1154 
1155 
1156 /*
1157  * return 1 if there are stopped jobs, otherwise 0
1158  */
1159 int job_warning = 0;
1160 int
1161 stoppedjobs(void)
1162 {
1163 	int jobno;
1164 	struct job *jp;
1165 
1166 	if (job_warning)
1167 		return (0);
1168 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1169 		if (jp->used == 0)
1170 			continue;
1171 		if (jp->state == JOBSTOPPED) {
1172 			out2fmt_flush("You have stopped jobs.\n");
1173 			job_warning = 2;
1174 			return (1);
1175 		}
1176 	}
1177 
1178 	return (0);
1179 }
1180 
1181 
1182 static void
1183 checkzombies(void)
1184 {
1185 	while (njobs > 0 && dowait(0, NULL) > 0)
1186 		;
1187 }
1188 
1189 
1190 int
1191 backgndpidset(void)
1192 {
1193 	return backgndpid != -1;
1194 }
1195 
1196 
1197 pid_t
1198 backgndpidval(void)
1199 {
1200 	if (bgjob != NULL && !forcelocal)
1201 		bgjob->remembered = 1;
1202 	return backgndpid;
1203 }
1204 
1205 /*
1206  * Return a string identifying a command (to be printed by the
1207  * jobs command.
1208  */
1209 
1210 static char *cmdnextc;
1211 static int cmdnleft;
1212 #define MAXCMDTEXT	200
1213 
1214 char *
1215 commandtext(union node *n)
1216 {
1217 	char *name;
1218 
1219 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1220 	cmdnleft = MAXCMDTEXT - 4;
1221 	cmdtxt(n);
1222 	*cmdnextc = '\0';
1223 	return name;
1224 }
1225 
1226 
1227 static void
1228 cmdtxt(union node *n)
1229 {
1230 	union node *np;
1231 	struct nodelist *lp;
1232 	const char *p;
1233 	int i;
1234 	char s[2];
1235 
1236 	if (n == NULL)
1237 		return;
1238 	switch (n->type) {
1239 	case NSEMI:
1240 		cmdtxt(n->nbinary.ch1);
1241 		cmdputs("; ");
1242 		cmdtxt(n->nbinary.ch2);
1243 		break;
1244 	case NAND:
1245 		cmdtxt(n->nbinary.ch1);
1246 		cmdputs(" && ");
1247 		cmdtxt(n->nbinary.ch2);
1248 		break;
1249 	case NOR:
1250 		cmdtxt(n->nbinary.ch1);
1251 		cmdputs(" || ");
1252 		cmdtxt(n->nbinary.ch2);
1253 		break;
1254 	case NPIPE:
1255 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1256 			cmdtxt(lp->n);
1257 			if (lp->next)
1258 				cmdputs(" | ");
1259 		}
1260 		break;
1261 	case NSUBSHELL:
1262 		cmdputs("(");
1263 		cmdtxt(n->nredir.n);
1264 		cmdputs(")");
1265 		break;
1266 	case NREDIR:
1267 	case NBACKGND:
1268 		cmdtxt(n->nredir.n);
1269 		break;
1270 	case NIF:
1271 		cmdputs("if ");
1272 		cmdtxt(n->nif.test);
1273 		cmdputs("; then ");
1274 		cmdtxt(n->nif.ifpart);
1275 		cmdputs("...");
1276 		break;
1277 	case NWHILE:
1278 		cmdputs("while ");
1279 		goto until;
1280 	case NUNTIL:
1281 		cmdputs("until ");
1282 until:
1283 		cmdtxt(n->nbinary.ch1);
1284 		cmdputs("; do ");
1285 		cmdtxt(n->nbinary.ch2);
1286 		cmdputs("; done");
1287 		break;
1288 	case NFOR:
1289 		cmdputs("for ");
1290 		cmdputs(n->nfor.var);
1291 		cmdputs(" in ...");
1292 		break;
1293 	case NCASE:
1294 		cmdputs("case ");
1295 		cmdputs(n->ncase.expr->narg.text);
1296 		cmdputs(" in ...");
1297 		break;
1298 	case NDEFUN:
1299 		cmdputs(n->narg.text);
1300 		cmdputs("() ...");
1301 		break;
1302 	case NNOT:
1303 		cmdputs("! ");
1304 		cmdtxt(n->nnot.com);
1305 		break;
1306 	case NCMD:
1307 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1308 			cmdtxt(np);
1309 			if (np->narg.next)
1310 				cmdputs(" ");
1311 		}
1312 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1313 			cmdputs(" ");
1314 			cmdtxt(np);
1315 		}
1316 		break;
1317 	case NARG:
1318 		cmdputs(n->narg.text);
1319 		break;
1320 	case NTO:
1321 		p = ">";  i = 1;  goto redir;
1322 	case NAPPEND:
1323 		p = ">>";  i = 1;  goto redir;
1324 	case NTOFD:
1325 		p = ">&";  i = 1;  goto redir;
1326 	case NCLOBBER:
1327 		p = ">|"; i = 1; goto redir;
1328 	case NFROM:
1329 		p = "<";  i = 0;  goto redir;
1330 	case NFROMTO:
1331 		p = "<>";  i = 0;  goto redir;
1332 	case NFROMFD:
1333 		p = "<&";  i = 0;  goto redir;
1334 redir:
1335 		if (n->nfile.fd != i) {
1336 			s[0] = n->nfile.fd + '0';
1337 			s[1] = '\0';
1338 			cmdputs(s);
1339 		}
1340 		cmdputs(p);
1341 		if (n->type == NTOFD || n->type == NFROMFD) {
1342 			if (n->ndup.dupfd >= 0)
1343 				s[0] = n->ndup.dupfd + '0';
1344 			else
1345 				s[0] = '-';
1346 			s[1] = '\0';
1347 			cmdputs(s);
1348 		} else {
1349 			cmdtxt(n->nfile.fname);
1350 		}
1351 		break;
1352 	case NHERE:
1353 	case NXHERE:
1354 		cmdputs("<<...");
1355 		break;
1356 	default:
1357 		cmdputs("???");
1358 		break;
1359 	}
1360 }
1361 
1362 
1363 
1364 static void
1365 cmdputs(const char *s)
1366 {
1367 	const char *p;
1368 	char *q;
1369 	char c;
1370 	int subtype = 0;
1371 
1372 	if (cmdnleft <= 0)
1373 		return;
1374 	p = s;
1375 	q = cmdnextc;
1376 	while ((c = *p++) != '\0') {
1377 		if (c == CTLESC)
1378 			*q++ = *p++;
1379 		else if (c == CTLVAR) {
1380 			*q++ = '$';
1381 			if (--cmdnleft > 0)
1382 				*q++ = '{';
1383 			subtype = *p++;
1384 			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1385 				*q++ = '#';
1386 		} else if (c == '=' && subtype != 0) {
1387 			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1388 			if (*q)
1389 				q++;
1390 			else
1391 				cmdnleft++;
1392 			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1393 			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1394 			    --cmdnleft > 0)
1395 				*q = q[-1], q++;
1396 			subtype = 0;
1397 		} else if (c == CTLENDVAR) {
1398 			*q++ = '}';
1399 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1400 			cmdnleft -= 5;
1401 			if (cmdnleft > 0) {
1402 				*q++ = '$';
1403 				*q++ = '(';
1404 				*q++ = '.';
1405 				*q++ = '.';
1406 				*q++ = '.';
1407 				*q++ = ')';
1408 			}
1409 		} else if (c == CTLARI) {
1410 			cmdnleft -= 2;
1411 			if (cmdnleft > 0) {
1412 				*q++ = '$';
1413 				*q++ = '(';
1414 				*q++ = '(';
1415 			}
1416 			p++;
1417 		} else if (c == CTLENDARI) {
1418 			if (--cmdnleft > 0) {
1419 				*q++ = ')';
1420 				*q++ = ')';
1421 			}
1422 		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1423 			cmdnleft++; /* ignore */
1424 		else
1425 			*q++ = c;
1426 		if (--cmdnleft <= 0) {
1427 			*q++ = '.';
1428 			*q++ = '.';
1429 			*q++ = '.';
1430 			break;
1431 		}
1432 	}
1433 	cmdnextc = q;
1434 }
1435