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