xref: /freebsd/bin/sh/jobs.c (revision b52b9d56d4e96089873a75f9e29062eec19fabba)
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 		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
745 			if (p->used)
746 				freejob(p);
747 		closescript();
748 		INTON;
749 		clear_traps();
750 #if JOBS
751 		jobctl = 0;		/* do job control only in root shell */
752 		if (wasroot && mode != FORK_NOJOB && mflag) {
753 			if (jp == NULL || jp->nprocs == 0)
754 				pgrp = getpid();
755 			else
756 				pgrp = jp->ps[0].pid;
757 			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
758 				/*** this causes superfluous TIOCSPGRPS ***/
759 				if (tcsetpgrp(ttyfd, pgrp) < 0)
760 					error("tcsetpgrp failed, errno=%d", errno);
761 			}
762 			setsignal(SIGTSTP);
763 			setsignal(SIGTTOU);
764 		} else if (mode == FORK_BG) {
765 			ignoresig(SIGINT);
766 			ignoresig(SIGQUIT);
767 			if ((jp == NULL || jp->nprocs == 0) &&
768 			    ! fd0_redirected_p ()) {
769 				close(0);
770 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
771 					error("Can't open %s: %s",
772 					    _PATH_DEVNULL, strerror(errno));
773 			}
774 		}
775 #else
776 		if (mode == FORK_BG) {
777 			ignoresig(SIGINT);
778 			ignoresig(SIGQUIT);
779 			if ((jp == NULL || jp->nprocs == 0) &&
780 			    ! fd0_redirected_p ()) {
781 				close(0);
782 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
783 					error("Can't open %s: %s",
784 					    _PATH_DEVNULL, strerror(errno));
785 			}
786 		}
787 #endif
788 		if (wasroot && iflag) {
789 			setsignal(SIGINT);
790 			setsignal(SIGQUIT);
791 			setsignal(SIGTERM);
792 		}
793 		return pid;
794 	}
795 	if (rootshell && mode != FORK_NOJOB && mflag) {
796 		if (jp == NULL || jp->nprocs == 0)
797 			pgrp = pid;
798 		else
799 			pgrp = jp->ps[0].pid;
800 		setpgid(pid, pgrp);
801 	}
802 	if (mode == FORK_BG)
803 		backgndpid = pid;		/* set $! */
804 	if (jp) {
805 		struct procstat *ps = &jp->ps[jp->nprocs++];
806 		ps->pid = pid;
807 		ps->status = -1;
808 		ps->cmd = nullstr;
809 		if (iflag && rootshell && n)
810 			ps->cmd = commandtext(n);
811 		jp->foreground = mode == FORK_FG;
812 #if JOBS
813 		setcurjob(jp);
814 #endif
815 	}
816 	INTON;
817 	TRACE(("In parent shell:  child = %d\n", (int)pid));
818 	return pid;
819 }
820 
821 
822 
823 /*
824  * Wait for job to finish.
825  *
826  * Under job control we have the problem that while a child process is
827  * running interrupts generated by the user are sent to the child but not
828  * to the shell.  This means that an infinite loop started by an inter-
829  * active user may be hard to kill.  With job control turned off, an
830  * interactive user may place an interactive program inside a loop.  If
831  * the interactive program catches interrupts, the user doesn't want
832  * these interrupts to also abort the loop.  The approach we take here
833  * is to have the shell ignore interrupt signals while waiting for a
834  * foreground process to terminate, and then send itself an interrupt
835  * signal if the child process was terminated by an interrupt signal.
836  * Unfortunately, some programs want to do a bit of cleanup and then
837  * exit on interrupt; unless these processes terminate themselves by
838  * sending a signal to themselves (instead of calling exit) they will
839  * confuse this approach.
840  */
841 
842 int
843 waitforjob(struct job *jp, int *origstatus)
844 {
845 #if JOBS
846 	pid_t mypgrp = getpgrp();
847 #endif
848 	int status;
849 	int st;
850 
851 	INTOFF;
852 	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
853 	while (jp->state == 0)
854 		if (dowait(1, jp) == -1)
855 			dotrap();
856 #if JOBS
857 	if (jp->jobctl) {
858 		if (tcsetpgrp(ttyfd, mypgrp) < 0)
859 			error("tcsetpgrp failed, errno=%d\n", errno);
860 	}
861 	if (jp->state == JOBSTOPPED)
862 		setcurjob(jp);
863 #endif
864 	status = jp->ps[jp->nprocs - 1].status;
865 	if (origstatus != NULL)
866 		*origstatus = status;
867 	/* convert to 8 bits */
868 	if (WIFEXITED(status))
869 		st = WEXITSTATUS(status);
870 #if JOBS
871 	else if (WIFSTOPPED(status))
872 		st = WSTOPSIG(status) + 128;
873 #endif
874 	else
875 		st = WTERMSIG(status) + 128;
876 	if (! JOBS || jp->state == JOBDONE)
877 		freejob(jp);
878 	if (int_pending()) {
879 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
880 			kill(getpid(), SIGINT);
881 		else
882 			CLEAR_PENDING_INT;
883 	}
884 	INTON;
885 	return st;
886 }
887 
888 
889 
890 /*
891  * Wait for a process to terminate.
892  */
893 
894 STATIC pid_t
895 dowait(int block, struct job *job)
896 {
897 	pid_t pid;
898 	int status;
899 	struct procstat *sp;
900 	struct job *jp;
901 	struct job *thisjob;
902 	int done;
903 	int stopped;
904 	int sig;
905 	int i;
906 
907 	in_dowait++;
908 	TRACE(("dowait(%d) called\n", block));
909 	do {
910 		pid = waitproc(block, &status);
911 		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
912 	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
913 	    (WIFSTOPPED(status) && !iflag));
914 	in_dowait--;
915 	if (breakwaitcmd != 0) {
916 		breakwaitcmd = 0;
917 		return -1;
918 	}
919 	if (pid <= 0)
920 		return pid;
921 	INTOFF;
922 	thisjob = NULL;
923 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
924 		if (jp->used) {
925 			done = 1;
926 			stopped = 1;
927 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
928 				if (sp->pid == -1)
929 					continue;
930 				if (sp->pid == pid) {
931 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
932 						   (int)pid, sp->status,
933 						   status));
934 					sp->status = status;
935 					thisjob = jp;
936 				}
937 				if (sp->status == -1)
938 					stopped = 0;
939 				else if (WIFSTOPPED(sp->status))
940 					done = 0;
941 			}
942 			if (stopped) {		/* stopped or done */
943 				int state = done? JOBDONE : JOBSTOPPED;
944 				if (jp->state != state) {
945 					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
946 					jp->state = state;
947 #if JOBS
948 					if (done)
949 						deljob(jp);
950 #endif
951 				}
952 			}
953 		}
954 	}
955 	INTON;
956 	if (! rootshell || ! iflag || (job && thisjob == job)) {
957 #if JOBS
958 		if (WIFSTOPPED(status))
959 			sig = WSTOPSIG(status);
960 		else
961 #endif
962 		{
963 			if (WIFEXITED(status))
964 				sig = 0;
965 			else
966 				sig = WTERMSIG(status);
967 		}
968 		if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
969 			if (jp->foreground) {
970 #if JOBS
971 				if (WIFSTOPPED(status))
972 					i = WSTOPSIG(status);
973 				else
974 #endif
975 					i = WTERMSIG(status);
976 				if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
977 					out1str(sys_siglist[i & 0x7F]);
978 				else
979 					out1fmt("Signal %d", i & 0x7F);
980 				if (WCOREDUMP(status))
981 					out1str(" (core dumped)");
982 				out1c('\n');
983 			} else
984 				showjob(thisjob, pid, 0, 1);
985 		}
986 	} else {
987 		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
988 		if (thisjob)
989 			thisjob->changed = 1;
990 	}
991 	return pid;
992 }
993 
994 
995 
996 /*
997  * Do a wait system call.  If job control is compiled in, we accept
998  * stopped processes.  If block is zero, we return a value of zero
999  * rather than blocking.
1000  */
1001 STATIC pid_t
1002 waitproc(int block, int *status)
1003 {
1004 	int flags;
1005 
1006 #if JOBS
1007 	flags = WUNTRACED;
1008 #else
1009 	flags = 0;
1010 #endif
1011 	if (block == 0)
1012 		flags |= WNOHANG;
1013 	return wait3(status, flags, (struct rusage *)NULL);
1014 }
1015 
1016 /*
1017  * return 1 if there are stopped jobs, otherwise 0
1018  */
1019 int job_warning = 0;
1020 int
1021 stoppedjobs(void)
1022 {
1023 	int jobno;
1024 	struct job *jp;
1025 
1026 	if (job_warning)
1027 		return (0);
1028 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1029 		if (jp->used == 0)
1030 			continue;
1031 		if (jp->state == JOBSTOPPED) {
1032 			out2str("You have stopped jobs.\n");
1033 			job_warning = 2;
1034 			return (1);
1035 		}
1036 	}
1037 
1038 	return (0);
1039 }
1040 
1041 /*
1042  * Return a string identifying a command (to be printed by the
1043  * jobs command.
1044  */
1045 
1046 STATIC char *cmdnextc;
1047 STATIC int cmdnleft;
1048 #define MAXCMDTEXT	200
1049 
1050 char *
1051 commandtext(union node *n)
1052 {
1053 	char *name;
1054 
1055 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1056 	cmdnleft = MAXCMDTEXT - 4;
1057 	cmdtxt(n);
1058 	*cmdnextc = '\0';
1059 	return name;
1060 }
1061 
1062 
1063 STATIC void
1064 cmdtxt(union node *n)
1065 {
1066 	union node *np;
1067 	struct nodelist *lp;
1068 	char *p;
1069 	int i;
1070 	char s[2];
1071 
1072 	if (n == NULL)
1073 		return;
1074 	switch (n->type) {
1075 	case NSEMI:
1076 		cmdtxt(n->nbinary.ch1);
1077 		cmdputs("; ");
1078 		cmdtxt(n->nbinary.ch2);
1079 		break;
1080 	case NAND:
1081 		cmdtxt(n->nbinary.ch1);
1082 		cmdputs(" && ");
1083 		cmdtxt(n->nbinary.ch2);
1084 		break;
1085 	case NOR:
1086 		cmdtxt(n->nbinary.ch1);
1087 		cmdputs(" || ");
1088 		cmdtxt(n->nbinary.ch2);
1089 		break;
1090 	case NPIPE:
1091 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1092 			cmdtxt(lp->n);
1093 			if (lp->next)
1094 				cmdputs(" | ");
1095 		}
1096 		break;
1097 	case NSUBSHELL:
1098 		cmdputs("(");
1099 		cmdtxt(n->nredir.n);
1100 		cmdputs(")");
1101 		break;
1102 	case NREDIR:
1103 	case NBACKGND:
1104 		cmdtxt(n->nredir.n);
1105 		break;
1106 	case NIF:
1107 		cmdputs("if ");
1108 		cmdtxt(n->nif.test);
1109 		cmdputs("; then ");
1110 		cmdtxt(n->nif.ifpart);
1111 		cmdputs("...");
1112 		break;
1113 	case NWHILE:
1114 		cmdputs("while ");
1115 		goto until;
1116 	case NUNTIL:
1117 		cmdputs("until ");
1118 until:
1119 		cmdtxt(n->nbinary.ch1);
1120 		cmdputs("; do ");
1121 		cmdtxt(n->nbinary.ch2);
1122 		cmdputs("; done");
1123 		break;
1124 	case NFOR:
1125 		cmdputs("for ");
1126 		cmdputs(n->nfor.var);
1127 		cmdputs(" in ...");
1128 		break;
1129 	case NCASE:
1130 		cmdputs("case ");
1131 		cmdputs(n->ncase.expr->narg.text);
1132 		cmdputs(" in ...");
1133 		break;
1134 	case NDEFUN:
1135 		cmdputs(n->narg.text);
1136 		cmdputs("() ...");
1137 		break;
1138 	case NCMD:
1139 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1140 			cmdtxt(np);
1141 			if (np->narg.next)
1142 				cmdputs(" ");
1143 		}
1144 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1145 			cmdputs(" ");
1146 			cmdtxt(np);
1147 		}
1148 		break;
1149 	case NARG:
1150 		cmdputs(n->narg.text);
1151 		break;
1152 	case NTO:
1153 		p = ">";  i = 1;  goto redir;
1154 	case NAPPEND:
1155 		p = ">>";  i = 1;  goto redir;
1156 	case NTOFD:
1157 		p = ">&";  i = 1;  goto redir;
1158 	case NCLOBBER:
1159 		p = ">|"; i = 1; goto redir;
1160 	case NFROM:
1161 		p = "<";  i = 0;  goto redir;
1162 	case NFROMTO:
1163 		p = "<>";  i = 0;  goto redir;
1164 	case NFROMFD:
1165 		p = "<&";  i = 0;  goto redir;
1166 redir:
1167 		if (n->nfile.fd != i) {
1168 			s[0] = n->nfile.fd + '0';
1169 			s[1] = '\0';
1170 			cmdputs(s);
1171 		}
1172 		cmdputs(p);
1173 		if (n->type == NTOFD || n->type == NFROMFD) {
1174 			if (n->ndup.dupfd >= 0)
1175 				s[0] = n->ndup.dupfd + '0';
1176 			else
1177 				s[0] = '-';
1178 			s[1] = '\0';
1179 			cmdputs(s);
1180 		} else {
1181 			cmdtxt(n->nfile.fname);
1182 		}
1183 		break;
1184 	case NHERE:
1185 	case NXHERE:
1186 		cmdputs("<<...");
1187 		break;
1188 	default:
1189 		cmdputs("???");
1190 		break;
1191 	}
1192 }
1193 
1194 
1195 
1196 STATIC void
1197 cmdputs(char *s)
1198 {
1199 	char *p, *q;
1200 	char c;
1201 	int subtype = 0;
1202 
1203 	if (cmdnleft <= 0)
1204 		return;
1205 	p = s;
1206 	q = cmdnextc;
1207 	while ((c = *p++) != '\0') {
1208 		if (c == CTLESC)
1209 			*q++ = *p++;
1210 		else if (c == CTLVAR) {
1211 			*q++ = '$';
1212 			if (--cmdnleft > 0)
1213 				*q++ = '{';
1214 			subtype = *p++;
1215 		} else if (c == '=' && subtype != 0) {
1216 			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1217 			subtype = 0;
1218 		} else if (c == CTLENDVAR) {
1219 			*q++ = '}';
1220 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1221 			cmdnleft++;		/* ignore it */
1222 		else
1223 			*q++ = c;
1224 		if (--cmdnleft <= 0) {
1225 			*q++ = '.';
1226 			*q++ = '.';
1227 			*q++ = '.';
1228 			break;
1229 		}
1230 	}
1231 	cmdnextc = q;
1232 }
1233