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