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