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