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