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