xref: /freebsd/bin/sh/jobs.c (revision d184218c18d067f8fd47203f54ab02a7b2ed9b11)
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 				;
673 			INTON;
674 			break;
675 		}
676 		if (jp->used == 0)
677 			break;
678 	}
679 	INTOFF;
680 	jp->state = 0;
681 	jp->used = 1;
682 	jp->changed = 0;
683 	jp->nprocs = 0;
684 	jp->foreground = 0;
685 	jp->remembered = 0;
686 #if JOBS
687 	jp->jobctl = jobctl;
688 	jp->next = NULL;
689 #endif
690 	if (nprocs > 1) {
691 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
692 	} else {
693 		jp->ps = &jp->ps0;
694 	}
695 	INTON;
696 	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
697 	    jp - jobtab + 1));
698 	return jp;
699 }
700 
701 #if JOBS
702 static void
703 setcurjob(struct job *cj)
704 {
705 	struct job *jp, *prev;
706 
707 	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
708 		if (jp == cj) {
709 			if (prev != NULL)
710 				prev->next = jp->next;
711 			else
712 				jobmru = jp->next;
713 			jp->next = jobmru;
714 			jobmru = cj;
715 			return;
716 		}
717 	}
718 	cj->next = jobmru;
719 	jobmru = cj;
720 }
721 
722 static void
723 deljob(struct job *j)
724 {
725 	struct job *jp, *prev;
726 
727 	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
728 		if (jp == j) {
729 			if (prev != NULL)
730 				prev->next = jp->next;
731 			else
732 				jobmru = jp->next;
733 			return;
734 		}
735 	}
736 }
737 
738 /*
739  * Return the most recently used job that isn't `nj', and preferably one
740  * that is stopped.
741  */
742 static struct job *
743 getcurjob(struct job *nj)
744 {
745 	struct job *jp;
746 
747 	/* Try to find a stopped one.. */
748 	for (jp = jobmru; jp != NULL; jp = jp->next)
749 		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
750 			return (jp);
751 	/* Otherwise the most recently used job that isn't `nj' */
752 	for (jp = jobmru; jp != NULL; jp = jp->next)
753 		if (jp->used && jp != nj)
754 			return (jp);
755 
756 	return (NULL);
757 }
758 
759 #endif
760 
761 /*
762  * Fork of a subshell.  If we are doing job control, give the subshell its
763  * own process group.  Jp is a job structure that the job is to be added to.
764  * N is the command that will be evaluated by the child.  Both jp and n may
765  * be NULL.  The mode parameter can be one of the following:
766  *	FORK_FG - Fork off a foreground process.
767  *	FORK_BG - Fork off a background process.
768  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
769  *		     process group even if job control is on.
770  *
771  * When job control is turned off, background processes have their standard
772  * input redirected to /dev/null (except for the second and later processes
773  * in a pipeline).
774  */
775 
776 pid_t
777 forkshell(struct job *jp, union node *n, int mode)
778 {
779 	pid_t pid;
780 	pid_t pgrp;
781 
782 	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
783 	    mode));
784 	INTOFF;
785 	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
786 		checkzombies();
787 	flushall();
788 	pid = fork();
789 	if (pid == -1) {
790 		TRACE(("Fork failed, errno=%d\n", errno));
791 		INTON;
792 		error("Cannot fork: %s", strerror(errno));
793 	}
794 	if (pid == 0) {
795 		struct job *p;
796 		int wasroot;
797 		int i;
798 
799 		TRACE(("Child shell %d\n", (int)getpid()));
800 		wasroot = rootshell;
801 		rootshell = 0;
802 		handler = &main_handler;
803 		closescript();
804 		INTON;
805 		forcelocal = 0;
806 		clear_traps();
807 #if JOBS
808 		jobctl = 0;		/* do job control only in root shell */
809 		if (wasroot && mode != FORK_NOJOB && mflag) {
810 			if (jp == NULL || jp->nprocs == 0)
811 				pgrp = getpid();
812 			else
813 				pgrp = jp->ps[0].pid;
814 			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
815 				/*** this causes superfluous TIOCSPGRPS ***/
816 				if (tcsetpgrp(ttyfd, pgrp) < 0)
817 					error("tcsetpgrp failed, errno=%d", errno);
818 			}
819 			setsignal(SIGTSTP);
820 			setsignal(SIGTTOU);
821 		} else if (mode == FORK_BG) {
822 			ignoresig(SIGINT);
823 			ignoresig(SIGQUIT);
824 			if ((jp == NULL || jp->nprocs == 0) &&
825 			    ! fd0_redirected_p ()) {
826 				close(0);
827 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
828 					error("cannot open %s: %s",
829 					    _PATH_DEVNULL, strerror(errno));
830 			}
831 		}
832 #else
833 		if (mode == FORK_BG) {
834 			ignoresig(SIGINT);
835 			ignoresig(SIGQUIT);
836 			if ((jp == NULL || jp->nprocs == 0) &&
837 			    ! fd0_redirected_p ()) {
838 				close(0);
839 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
840 					error("cannot open %s: %s",
841 					    _PATH_DEVNULL, strerror(errno));
842 			}
843 		}
844 #endif
845 		INTOFF;
846 		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
847 			if (p->used)
848 				freejob(p);
849 		INTON;
850 		if (wasroot && iflag) {
851 			setsignal(SIGINT);
852 			setsignal(SIGQUIT);
853 			setsignal(SIGTERM);
854 		}
855 		return pid;
856 	}
857 	if (rootshell && mode != FORK_NOJOB && mflag) {
858 		if (jp == NULL || jp->nprocs == 0)
859 			pgrp = pid;
860 		else
861 			pgrp = jp->ps[0].pid;
862 		setpgid(pid, pgrp);
863 	}
864 	if (mode == FORK_BG) {
865 		if (bgjob != NULL && bgjob->state == JOBDONE &&
866 		    !bgjob->remembered && !iflag)
867 			freejob(bgjob);
868 		backgndpid = pid;		/* set $! */
869 		bgjob = jp;
870 	}
871 	if (jp) {
872 		struct procstat *ps = &jp->ps[jp->nprocs++];
873 		ps->pid = pid;
874 		ps->status = -1;
875 		ps->cmd = nullstr;
876 		if (iflag && rootshell && n)
877 			ps->cmd = commandtext(n);
878 		jp->foreground = mode == FORK_FG;
879 #if JOBS
880 		setcurjob(jp);
881 #endif
882 	}
883 	INTON;
884 	TRACE(("In parent shell:  child = %d\n", (int)pid));
885 	return pid;
886 }
887 
888 
889 pid_t
890 vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
891 {
892 	pid_t pid;
893 	struct jmploc jmploc;
894 	struct jmploc *savehandler;
895 
896 	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
897 	    (void *)pip));
898 	INTOFF;
899 	flushall();
900 	savehandler = handler;
901 	pid = vfork();
902 	if (pid == -1) {
903 		TRACE(("Vfork failed, errno=%d\n", errno));
904 		INTON;
905 		error("Cannot fork: %s", strerror(errno));
906 	}
907 	if (pid == 0) {
908 		TRACE(("Child shell %d\n", (int)getpid()));
909 		if (setjmp(jmploc.loc))
910 			_exit(exception == EXEXEC ? exerrno : 2);
911 		if (pip != NULL) {
912 			close(pip[0]);
913 			if (pip[1] != 1) {
914 				dup2(pip[1], 1);
915 				close(pip[1]);
916 			}
917 		}
918 		handler = &jmploc;
919 		shellexec(argv, envp, path, idx);
920 	}
921 	handler = savehandler;
922 	if (jp) {
923 		struct procstat *ps = &jp->ps[jp->nprocs++];
924 		ps->pid = pid;
925 		ps->status = -1;
926 		ps->cmd = nullstr;
927 		jp->foreground = 1;
928 #if JOBS
929 		setcurjob(jp);
930 #endif
931 	}
932 	INTON;
933 	TRACE(("In parent shell:  child = %d\n", (int)pid));
934 	return pid;
935 }
936 
937 
938 /*
939  * Wait for job to finish.
940  *
941  * Under job control we have the problem that while a child process is
942  * running interrupts generated by the user are sent to the child but not
943  * to the shell.  This means that an infinite loop started by an inter-
944  * active user may be hard to kill.  With job control turned off, an
945  * interactive user may place an interactive program inside a loop.  If
946  * the interactive program catches interrupts, the user doesn't want
947  * these interrupts to also abort the loop.  The approach we take here
948  * is to have the shell ignore interrupt signals while waiting for a
949  * foreground process to terminate, and then send itself an interrupt
950  * signal if the child process was terminated by an interrupt signal.
951  * Unfortunately, some programs want to do a bit of cleanup and then
952  * exit on interrupt; unless these processes terminate themselves by
953  * sending a signal to themselves (instead of calling exit) they will
954  * confuse this approach.
955  */
956 
957 int
958 waitforjob(struct job *jp, int *origstatus)
959 {
960 #if JOBS
961 	pid_t mypgrp = getpgrp();
962 	int propagate_int = jp->jobctl && jp->foreground;
963 #endif
964 	int status;
965 	int st;
966 
967 	INTOFF;
968 	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
969 	while (jp->state == 0)
970 		if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG : 0), jp) == -1)
971 			dotrap();
972 #if JOBS
973 	if (jp->jobctl) {
974 		if (tcsetpgrp(ttyfd, mypgrp) < 0)
975 			error("tcsetpgrp failed, errno=%d\n", errno);
976 	}
977 	if (jp->state == JOBSTOPPED)
978 		setcurjob(jp);
979 #endif
980 	status = jp->ps[jp->nprocs - 1].status;
981 	if (origstatus != NULL)
982 		*origstatus = status;
983 	/* convert to 8 bits */
984 	if (WIFEXITED(status))
985 		st = WEXITSTATUS(status);
986 #if JOBS
987 	else if (WIFSTOPPED(status))
988 		st = WSTOPSIG(status) + 128;
989 #endif
990 	else
991 		st = WTERMSIG(status) + 128;
992 	if (! JOBS || jp->state == JOBDONE)
993 		freejob(jp);
994 	if (int_pending()) {
995 		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
996 			CLEAR_PENDING_INT;
997 	}
998 #if JOBS
999 	else if (rootshell && iflag && propagate_int &&
1000 			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1001 		kill(getpid(), SIGINT);
1002 #endif
1003 	INTON;
1004 	return st;
1005 }
1006 
1007 
1008 static void
1009 dummy_handler(int sig __unused)
1010 {
1011 }
1012 
1013 /*
1014  * Wait for a process to terminate.
1015  */
1016 
1017 static pid_t
1018 dowait(int mode, struct job *job)
1019 {
1020 	struct sigaction sa, osa;
1021 	sigset_t mask, omask;
1022 	pid_t pid;
1023 	int status;
1024 	struct procstat *sp;
1025 	struct job *jp;
1026 	struct job *thisjob;
1027 	const char *sigstr;
1028 	int done;
1029 	int stopped;
1030 	int sig;
1031 	int coredump;
1032 	int wflags;
1033 	int restore_sigchld;
1034 
1035 	TRACE(("dowait(%d, %p) called\n", mode, job));
1036 	restore_sigchld = 0;
1037 	if ((mode & DOWAIT_SIG) != 0) {
1038 		sigfillset(&mask);
1039 		sigprocmask(SIG_BLOCK, &mask, &omask);
1040 		INTOFF;
1041 		if (!issigchldtrapped()) {
1042 			restore_sigchld = 1;
1043 			sa.sa_handler = dummy_handler;
1044 			sa.sa_flags = 0;
1045 			sigemptyset(&sa.sa_mask);
1046 			sigaction(SIGCHLD, &sa, &osa);
1047 		}
1048 	}
1049 	do {
1050 #if JOBS
1051 		if (iflag)
1052 			wflags = WUNTRACED | WCONTINUED;
1053 		else
1054 #endif
1055 			wflags = 0;
1056 		if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1057 			wflags |= WNOHANG;
1058 		pid = wait3(&status, wflags, (struct rusage *)NULL);
1059 		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1060 		if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1061 			sigsuspend(&omask);
1062 			pid = -1;
1063 			if (int_pending())
1064 				break;
1065 		}
1066 	} while (pid == -1 && errno == EINTR && breakwaitcmd == 0);
1067 	if (pid == -1 && errno == ECHILD && job != NULL)
1068 		job->state = JOBDONE;
1069 	if ((mode & DOWAIT_SIG) != 0) {
1070 		if (restore_sigchld)
1071 			sigaction(SIGCHLD, &osa, NULL);
1072 		sigprocmask(SIG_SETMASK, &omask, NULL);
1073 		INTON;
1074 	}
1075 	if (breakwaitcmd != 0) {
1076 		breakwaitcmd = 0;
1077 		if (pid <= 0)
1078 			return -1;
1079 	}
1080 	if (pid <= 0)
1081 		return pid;
1082 	INTOFF;
1083 	thisjob = NULL;
1084 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1085 		if (jp->used && jp->nprocs > 0) {
1086 			done = 1;
1087 			stopped = 1;
1088 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1089 				if (sp->pid == -1)
1090 					continue;
1091 				if (sp->pid == pid) {
1092 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1093 						   (int)pid, sp->status,
1094 						   status));
1095 					if (WIFCONTINUED(status)) {
1096 						sp->status = -1;
1097 						jp->state = 0;
1098 					} else
1099 						sp->status = status;
1100 					thisjob = jp;
1101 				}
1102 				if (sp->status == -1)
1103 					stopped = 0;
1104 				else if (WIFSTOPPED(sp->status))
1105 					done = 0;
1106 			}
1107 			if (stopped) {		/* stopped or done */
1108 				int state = done? JOBDONE : JOBSTOPPED;
1109 				if (jp->state != state) {
1110 					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1111 					jp->state = state;
1112 					if (jp != job) {
1113 						if (done && !jp->remembered &&
1114 						    !iflag && jp != bgjob)
1115 							freejob(jp);
1116 #if JOBS
1117 						else if (done)
1118 							deljob(jp);
1119 #endif
1120 					}
1121 				}
1122 			}
1123 		}
1124 	}
1125 	INTON;
1126 	if (!thisjob || thisjob->state == 0)
1127 		;
1128 	else if ((!rootshell || !iflag || thisjob == job) &&
1129 	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1130 		sig = 0;
1131 		coredump = 0;
1132 		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1133 			if (WIFSIGNALED(sp->status)) {
1134 				sig = WTERMSIG(sp->status);
1135 				coredump = WCOREDUMP(sp->status);
1136 			}
1137 		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1138 			sigstr = strsignal(sig);
1139 			if (sigstr != NULL)
1140 				out2str(sigstr);
1141 			else
1142 				out2str("Unknown signal");
1143 			if (coredump)
1144 				out2str(" (core dumped)");
1145 			out2c('\n');
1146 			flushout(out2);
1147 		}
1148 	} else {
1149 		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1150 		thisjob->changed = 1;
1151 	}
1152 	return pid;
1153 }
1154 
1155 
1156 
1157 /*
1158  * return 1 if there are stopped jobs, otherwise 0
1159  */
1160 int job_warning = 0;
1161 int
1162 stoppedjobs(void)
1163 {
1164 	int jobno;
1165 	struct job *jp;
1166 
1167 	if (job_warning)
1168 		return (0);
1169 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1170 		if (jp->used == 0)
1171 			continue;
1172 		if (jp->state == JOBSTOPPED) {
1173 			out2fmt_flush("You have stopped jobs.\n");
1174 			job_warning = 2;
1175 			return (1);
1176 		}
1177 	}
1178 
1179 	return (0);
1180 }
1181 
1182 
1183 static void
1184 checkzombies(void)
1185 {
1186 	while (njobs > 0 && dowait(0, NULL) > 0)
1187 		;
1188 }
1189 
1190 
1191 int
1192 backgndpidset(void)
1193 {
1194 	return backgndpid != -1;
1195 }
1196 
1197 
1198 pid_t
1199 backgndpidval(void)
1200 {
1201 	if (bgjob != NULL && !forcelocal)
1202 		bgjob->remembered = 1;
1203 	return backgndpid;
1204 }
1205 
1206 /*
1207  * Return a string identifying a command (to be printed by the
1208  * jobs command.
1209  */
1210 
1211 static char *cmdnextc;
1212 static int cmdnleft;
1213 #define MAXCMDTEXT	200
1214 
1215 char *
1216 commandtext(union node *n)
1217 {
1218 	char *name;
1219 
1220 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1221 	cmdnleft = MAXCMDTEXT - 4;
1222 	cmdtxt(n);
1223 	*cmdnextc = '\0';
1224 	return name;
1225 }
1226 
1227 
1228 static void
1229 cmdtxt(union node *n)
1230 {
1231 	union node *np;
1232 	struct nodelist *lp;
1233 	const char *p;
1234 	int i;
1235 	char s[2];
1236 
1237 	if (n == NULL)
1238 		return;
1239 	switch (n->type) {
1240 	case NSEMI:
1241 		cmdtxt(n->nbinary.ch1);
1242 		cmdputs("; ");
1243 		cmdtxt(n->nbinary.ch2);
1244 		break;
1245 	case NAND:
1246 		cmdtxt(n->nbinary.ch1);
1247 		cmdputs(" && ");
1248 		cmdtxt(n->nbinary.ch2);
1249 		break;
1250 	case NOR:
1251 		cmdtxt(n->nbinary.ch1);
1252 		cmdputs(" || ");
1253 		cmdtxt(n->nbinary.ch2);
1254 		break;
1255 	case NPIPE:
1256 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1257 			cmdtxt(lp->n);
1258 			if (lp->next)
1259 				cmdputs(" | ");
1260 		}
1261 		break;
1262 	case NSUBSHELL:
1263 		cmdputs("(");
1264 		cmdtxt(n->nredir.n);
1265 		cmdputs(")");
1266 		break;
1267 	case NREDIR:
1268 	case NBACKGND:
1269 		cmdtxt(n->nredir.n);
1270 		break;
1271 	case NIF:
1272 		cmdputs("if ");
1273 		cmdtxt(n->nif.test);
1274 		cmdputs("; then ");
1275 		cmdtxt(n->nif.ifpart);
1276 		cmdputs("...");
1277 		break;
1278 	case NWHILE:
1279 		cmdputs("while ");
1280 		goto until;
1281 	case NUNTIL:
1282 		cmdputs("until ");
1283 until:
1284 		cmdtxt(n->nbinary.ch1);
1285 		cmdputs("; do ");
1286 		cmdtxt(n->nbinary.ch2);
1287 		cmdputs("; done");
1288 		break;
1289 	case NFOR:
1290 		cmdputs("for ");
1291 		cmdputs(n->nfor.var);
1292 		cmdputs(" in ...");
1293 		break;
1294 	case NCASE:
1295 		cmdputs("case ");
1296 		cmdputs(n->ncase.expr->narg.text);
1297 		cmdputs(" in ...");
1298 		break;
1299 	case NDEFUN:
1300 		cmdputs(n->narg.text);
1301 		cmdputs("() ...");
1302 		break;
1303 	case NNOT:
1304 		cmdputs("! ");
1305 		cmdtxt(n->nnot.com);
1306 		break;
1307 	case NCMD:
1308 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1309 			cmdtxt(np);
1310 			if (np->narg.next)
1311 				cmdputs(" ");
1312 		}
1313 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1314 			cmdputs(" ");
1315 			cmdtxt(np);
1316 		}
1317 		break;
1318 	case NARG:
1319 		cmdputs(n->narg.text);
1320 		break;
1321 	case NTO:
1322 		p = ">";  i = 1;  goto redir;
1323 	case NAPPEND:
1324 		p = ">>";  i = 1;  goto redir;
1325 	case NTOFD:
1326 		p = ">&";  i = 1;  goto redir;
1327 	case NCLOBBER:
1328 		p = ">|"; i = 1; goto redir;
1329 	case NFROM:
1330 		p = "<";  i = 0;  goto redir;
1331 	case NFROMTO:
1332 		p = "<>";  i = 0;  goto redir;
1333 	case NFROMFD:
1334 		p = "<&";  i = 0;  goto redir;
1335 redir:
1336 		if (n->nfile.fd != i) {
1337 			s[0] = n->nfile.fd + '0';
1338 			s[1] = '\0';
1339 			cmdputs(s);
1340 		}
1341 		cmdputs(p);
1342 		if (n->type == NTOFD || n->type == NFROMFD) {
1343 			if (n->ndup.dupfd >= 0)
1344 				s[0] = n->ndup.dupfd + '0';
1345 			else
1346 				s[0] = '-';
1347 			s[1] = '\0';
1348 			cmdputs(s);
1349 		} else {
1350 			cmdtxt(n->nfile.fname);
1351 		}
1352 		break;
1353 	case NHERE:
1354 	case NXHERE:
1355 		cmdputs("<<...");
1356 		break;
1357 	default:
1358 		cmdputs("???");
1359 		break;
1360 	}
1361 }
1362 
1363 
1364 
1365 static void
1366 cmdputs(const char *s)
1367 {
1368 	const char *p;
1369 	char *q;
1370 	char c;
1371 	int subtype = 0;
1372 
1373 	if (cmdnleft <= 0)
1374 		return;
1375 	p = s;
1376 	q = cmdnextc;
1377 	while ((c = *p++) != '\0') {
1378 		if (c == CTLESC)
1379 			*q++ = *p++;
1380 		else if (c == CTLVAR) {
1381 			*q++ = '$';
1382 			if (--cmdnleft > 0)
1383 				*q++ = '{';
1384 			subtype = *p++;
1385 			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1386 				*q++ = '#';
1387 		} else if (c == '=' && subtype != 0) {
1388 			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1389 			if (*q)
1390 				q++;
1391 			else
1392 				cmdnleft++;
1393 			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1394 			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1395 			    --cmdnleft > 0)
1396 				*q = q[-1], q++;
1397 			subtype = 0;
1398 		} else if (c == CTLENDVAR) {
1399 			*q++ = '}';
1400 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1401 			cmdnleft -= 5;
1402 			if (cmdnleft > 0) {
1403 				*q++ = '$';
1404 				*q++ = '(';
1405 				*q++ = '.';
1406 				*q++ = '.';
1407 				*q++ = '.';
1408 				*q++ = ')';
1409 			}
1410 		} else if (c == CTLARI) {
1411 			cmdnleft -= 2;
1412 			if (cmdnleft > 0) {
1413 				*q++ = '$';
1414 				*q++ = '(';
1415 				*q++ = '(';
1416 			}
1417 			p++;
1418 		} else if (c == CTLENDARI) {
1419 			if (--cmdnleft > 0) {
1420 				*q++ = ')';
1421 				*q++ = ')';
1422 			}
1423 		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1424 			cmdnleft++; /* ignore */
1425 		else
1426 			*q++ = c;
1427 		if (--cmdnleft <= 0) {
1428 			*q++ = '.';
1429 			*q++ = '.';
1430 			*q++ = '.';
1431 			break;
1432 		}
1433 	}
1434 	cmdnextc = q;
1435 }
1436