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