jobs.c revision 216400
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 216400 2010-12-12 22:59: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
635
636/*
637 * Return a new job structure,
638 */
639
640struct job *
641makejob(union node *node __unused, int nprocs)
642{
643	int i;
644	struct job *jp;
645
646	for (i = njobs, jp = jobtab ; ; jp++) {
647		if (--i < 0) {
648			INTOFF;
649			if (njobs == 0) {
650				jobtab = ckmalloc(4 * sizeof jobtab[0]);
651#if JOBS
652				jobmru = NULL;
653#endif
654			} else {
655				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
656				memcpy(jp, jobtab, njobs * sizeof jp[0]);
657#if JOBS
658				/* Relocate `next' pointers and list head */
659				if (jobmru != NULL)
660					jobmru = &jp[jobmru - jobtab];
661				for (i = 0; i < njobs; i++)
662					if (jp[i].next != NULL)
663						jp[i].next = &jp[jp[i].next -
664						    jobtab];
665#endif
666				if (bgjob != NULL)
667					bgjob = &jp[bgjob - jobtab];
668				/* Relocate `ps' pointers */
669				for (i = 0; i < njobs; i++)
670					if (jp[i].ps == &jobtab[i].ps0)
671						jp[i].ps = &jp[i].ps0;
672				ckfree(jobtab);
673				jobtab = jp;
674			}
675			jp = jobtab + njobs;
676			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
677			INTON;
678			break;
679		}
680		if (jp->used == 0)
681			break;
682	}
683	INTOFF;
684	jp->state = 0;
685	jp->used = 1;
686	jp->changed = 0;
687	jp->nprocs = 0;
688	jp->foreground = 0;
689	jp->remembered = 0;
690#if JOBS
691	jp->jobctl = jobctl;
692	jp->next = NULL;
693#endif
694	if (nprocs > 1) {
695		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
696	} else {
697		jp->ps = &jp->ps0;
698	}
699	INTON;
700	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
701	    jp - jobtab + 1));
702	return jp;
703}
704
705#if JOBS
706static void
707setcurjob(struct job *cj)
708{
709	struct job *jp, *prev;
710
711	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
712		if (jp == cj) {
713			if (prev != NULL)
714				prev->next = jp->next;
715			else
716				jobmru = jp->next;
717			jp->next = jobmru;
718			jobmru = cj;
719			return;
720		}
721	}
722	cj->next = jobmru;
723	jobmru = cj;
724}
725
726static void
727deljob(struct job *j)
728{
729	struct job *jp, *prev;
730
731	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
732		if (jp == j) {
733			if (prev != NULL)
734				prev->next = jp->next;
735			else
736				jobmru = jp->next;
737			return;
738		}
739	}
740}
741
742/*
743 * Return the most recently used job that isn't `nj', and preferably one
744 * that is stopped.
745 */
746static struct job *
747getcurjob(struct job *nj)
748{
749	struct job *jp;
750
751	/* Try to find a stopped one.. */
752	for (jp = jobmru; jp != NULL; jp = jp->next)
753		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
754			return (jp);
755	/* Otherwise the most recently used job that isn't `nj' */
756	for (jp = jobmru; jp != NULL; jp = jp->next)
757		if (jp->used && jp != nj)
758			return (jp);
759
760	return (NULL);
761}
762
763#endif
764
765/*
766 * Fork of a subshell.  If we are doing job control, give the subshell its
767 * own process group.  Jp is a job structure that the job is to be added to.
768 * N is the command that will be evaluated by the child.  Both jp and n may
769 * be NULL.  The mode parameter can be one of the following:
770 *	FORK_FG - Fork off a foreground process.
771 *	FORK_BG - Fork off a background process.
772 *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
773 *		     process group even if job control is on.
774 *
775 * When job control is turned off, background processes have their standard
776 * input redirected to /dev/null (except for the second and later processes
777 * in a pipeline).
778 */
779
780pid_t
781forkshell(struct job *jp, union node *n, int mode)
782{
783	pid_t pid;
784	pid_t pgrp;
785
786	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
787	    mode));
788	INTOFF;
789	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
790		checkzombies();
791	flushall();
792	pid = fork();
793	if (pid == -1) {
794		TRACE(("Fork failed, errno=%d\n", errno));
795		INTON;
796		error("Cannot fork: %s", strerror(errno));
797	}
798	if (pid == 0) {
799		struct job *p;
800		int wasroot;
801		int i;
802
803		TRACE(("Child shell %d\n", (int)getpid()));
804		wasroot = rootshell;
805		rootshell = 0;
806		handler = &main_handler;
807		closescript();
808		INTON;
809		clear_traps();
810#if JOBS
811		jobctl = 0;		/* do job control only in root shell */
812		if (wasroot && mode != FORK_NOJOB && mflag) {
813			if (jp == NULL || jp->nprocs == 0)
814				pgrp = getpid();
815			else
816				pgrp = jp->ps[0].pid;
817			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
818				/*** this causes superfluous TIOCSPGRPS ***/
819				if (tcsetpgrp(ttyfd, pgrp) < 0)
820					error("tcsetpgrp failed, errno=%d", errno);
821			}
822			setsignal(SIGTSTP);
823			setsignal(SIGTTOU);
824		} else if (mode == FORK_BG) {
825			ignoresig(SIGINT);
826			ignoresig(SIGQUIT);
827			if ((jp == NULL || jp->nprocs == 0) &&
828			    ! fd0_redirected_p ()) {
829				close(0);
830				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
831					error("Can't open %s: %s",
832					    _PATH_DEVNULL, strerror(errno));
833			}
834		}
835#else
836		if (mode == FORK_BG) {
837			ignoresig(SIGINT);
838			ignoresig(SIGQUIT);
839			if ((jp == NULL || jp->nprocs == 0) &&
840			    ! fd0_redirected_p ()) {
841				close(0);
842				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
843					error("Can't open %s: %s",
844					    _PATH_DEVNULL, strerror(errno));
845			}
846		}
847#endif
848		INTOFF;
849		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
850			if (p->used)
851				freejob(p);
852		INTON;
853		if (wasroot && iflag) {
854			setsignal(SIGINT);
855			setsignal(SIGQUIT);
856			setsignal(SIGTERM);
857		}
858		return pid;
859	}
860	if (rootshell && mode != FORK_NOJOB && mflag) {
861		if (jp == NULL || jp->nprocs == 0)
862			pgrp = pid;
863		else
864			pgrp = jp->ps[0].pid;
865		setpgid(pid, pgrp);
866	}
867	if (mode == FORK_BG) {
868		if (bgjob != NULL && bgjob->state == JOBDONE &&
869		    !bgjob->remembered && !iflag)
870			freejob(bgjob);
871		backgndpid = pid;		/* set $! */
872		bgjob = jp;
873	}
874	if (jp) {
875		struct procstat *ps = &jp->ps[jp->nprocs++];
876		ps->pid = pid;
877		ps->status = -1;
878		ps->cmd = nullstr;
879		if (iflag && rootshell && n)
880			ps->cmd = commandtext(n);
881		jp->foreground = mode == FORK_FG;
882#if JOBS
883		setcurjob(jp);
884#endif
885	}
886	INTON;
887	TRACE(("In parent shell:  child = %d\n", (int)pid));
888	return pid;
889}
890
891
892
893/*
894 * Wait for job to finish.
895 *
896 * Under job control we have the problem that while a child process is
897 * running interrupts generated by the user are sent to the child but not
898 * to the shell.  This means that an infinite loop started by an inter-
899 * active user may be hard to kill.  With job control turned off, an
900 * interactive user may place an interactive program inside a loop.  If
901 * the interactive program catches interrupts, the user doesn't want
902 * these interrupts to also abort the loop.  The approach we take here
903 * is to have the shell ignore interrupt signals while waiting for a
904 * foreground process to terminate, and then send itself an interrupt
905 * signal if the child process was terminated by an interrupt signal.
906 * Unfortunately, some programs want to do a bit of cleanup and then
907 * exit on interrupt; unless these processes terminate themselves by
908 * sending a signal to themselves (instead of calling exit) they will
909 * confuse this approach.
910 */
911
912int
913waitforjob(struct job *jp, int *origstatus)
914{
915#if JOBS
916	pid_t mypgrp = getpgrp();
917	int propagate_int = jp->jobctl && jp->foreground;
918#endif
919	int status;
920	int st;
921
922	INTOFF;
923	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
924	while (jp->state == 0)
925		if (dowait(1, jp) == -1)
926			dotrap();
927#if JOBS
928	if (jp->jobctl) {
929		if (tcsetpgrp(ttyfd, mypgrp) < 0)
930			error("tcsetpgrp failed, errno=%d\n", errno);
931	}
932	if (jp->state == JOBSTOPPED)
933		setcurjob(jp);
934#endif
935	status = jp->ps[jp->nprocs - 1].status;
936	if (origstatus != NULL)
937		*origstatus = status;
938	/* convert to 8 bits */
939	if (WIFEXITED(status))
940		st = WEXITSTATUS(status);
941#if JOBS
942	else if (WIFSTOPPED(status))
943		st = WSTOPSIG(status) + 128;
944#endif
945	else
946		st = WTERMSIG(status) + 128;
947	if (! JOBS || jp->state == JOBDONE)
948		freejob(jp);
949	if (int_pending()) {
950		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
951			CLEAR_PENDING_INT;
952	}
953#if JOBS
954	else if (rootshell && iflag && propagate_int &&
955			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
956		kill(getpid(), SIGINT);
957#endif
958	INTON;
959	return st;
960}
961
962
963
964/*
965 * Wait for a process to terminate.
966 */
967
968static pid_t
969dowait(int block, struct job *job)
970{
971	pid_t pid;
972	int status;
973	struct procstat *sp;
974	struct job *jp;
975	struct job *thisjob;
976	int done;
977	int stopped;
978	int sig;
979	int coredump;
980
981	in_dowait++;
982	TRACE(("dowait(%d) called\n", block));
983	do {
984		pid = waitproc(block, &status);
985		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
986	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
987		 (pid > 0 && WIFSTOPPED(status) && !iflag));
988	in_dowait--;
989	if (pid == -1 && errno == ECHILD && job != NULL)
990		job->state = JOBDONE;
991	if (breakwaitcmd != 0) {
992		breakwaitcmd = 0;
993		if (pid <= 0)
994			return -1;
995	}
996	if (pid <= 0)
997		return pid;
998	INTOFF;
999	thisjob = NULL;
1000	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1001		if (jp->used && jp->nprocs > 0) {
1002			done = 1;
1003			stopped = 1;
1004			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1005				if (sp->pid == -1)
1006					continue;
1007				if (sp->pid == pid) {
1008					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1009						   (int)pid, sp->status,
1010						   status));
1011					sp->status = status;
1012					thisjob = jp;
1013				}
1014				if (sp->status == -1)
1015					stopped = 0;
1016				else if (WIFSTOPPED(sp->status))
1017					done = 0;
1018			}
1019			if (stopped) {		/* stopped or done */
1020				int state = done? JOBDONE : JOBSTOPPED;
1021				if (jp->state != state) {
1022					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1023					jp->state = state;
1024					if (jp != job) {
1025						if (done && !jp->remembered &&
1026						    !iflag && jp != bgjob)
1027							freejob(jp);
1028#if JOBS
1029						else if (done)
1030							deljob(jp);
1031#endif
1032					}
1033				}
1034			}
1035		}
1036	}
1037	INTON;
1038	if (!thisjob || thisjob->state == 0)
1039		;
1040	else if ((!rootshell || !iflag || thisjob == job) &&
1041	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1042		sig = 0;
1043		coredump = 0;
1044		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1045			if (WIFSIGNALED(sp->status)) {
1046				sig = WTERMSIG(sp->status);
1047				coredump = WCOREDUMP(sp->status);
1048			}
1049		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1050			if (sig < sys_nsig && sys_siglist[sig])
1051				out1str(sys_siglist[sig]);
1052			else
1053				out1fmt("Signal %d", sig);
1054			if (coredump)
1055				out1str(" (core dumped)");
1056			out1c('\n');
1057		}
1058	} else {
1059		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1060		thisjob->changed = 1;
1061	}
1062	return pid;
1063}
1064
1065
1066
1067/*
1068 * Do a wait system call.  If job control is compiled in, we accept
1069 * stopped processes.  If block is zero, we return a value of zero
1070 * rather than blocking.
1071 */
1072static pid_t
1073waitproc(int block, int *status)
1074{
1075	int flags;
1076
1077#if JOBS
1078	flags = WUNTRACED;
1079#else
1080	flags = 0;
1081#endif
1082	if (block == 0)
1083		flags |= WNOHANG;
1084	return wait3(status, flags, (struct rusage *)NULL);
1085}
1086
1087/*
1088 * return 1 if there are stopped jobs, otherwise 0
1089 */
1090int job_warning = 0;
1091int
1092stoppedjobs(void)
1093{
1094	int jobno;
1095	struct job *jp;
1096
1097	if (job_warning)
1098		return (0);
1099	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1100		if (jp->used == 0)
1101			continue;
1102		if (jp->state == JOBSTOPPED) {
1103			out2fmt_flush("You have stopped jobs.\n");
1104			job_warning = 2;
1105			return (1);
1106		}
1107	}
1108
1109	return (0);
1110}
1111
1112
1113static void
1114checkzombies(void)
1115{
1116	while (njobs > 0 && dowait(0, NULL) > 0)
1117		;
1118}
1119
1120
1121int
1122backgndpidset(void)
1123{
1124	return backgndpid != -1;
1125}
1126
1127
1128pid_t
1129backgndpidval(void)
1130{
1131	if (bgjob != NULL)
1132		bgjob->remembered = 1;
1133	return backgndpid;
1134}
1135
1136/*
1137 * Return a string identifying a command (to be printed by the
1138 * jobs command.
1139 */
1140
1141static char *cmdnextc;
1142static int cmdnleft;
1143#define MAXCMDTEXT	200
1144
1145char *
1146commandtext(union node *n)
1147{
1148	char *name;
1149
1150	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1151	cmdnleft = MAXCMDTEXT - 4;
1152	cmdtxt(n);
1153	*cmdnextc = '\0';
1154	return name;
1155}
1156
1157
1158static void
1159cmdtxt(union node *n)
1160{
1161	union node *np;
1162	struct nodelist *lp;
1163	const char *p;
1164	int i;
1165	char s[2];
1166
1167	if (n == NULL)
1168		return;
1169	switch (n->type) {
1170	case NSEMI:
1171		cmdtxt(n->nbinary.ch1);
1172		cmdputs("; ");
1173		cmdtxt(n->nbinary.ch2);
1174		break;
1175	case NAND:
1176		cmdtxt(n->nbinary.ch1);
1177		cmdputs(" && ");
1178		cmdtxt(n->nbinary.ch2);
1179		break;
1180	case NOR:
1181		cmdtxt(n->nbinary.ch1);
1182		cmdputs(" || ");
1183		cmdtxt(n->nbinary.ch2);
1184		break;
1185	case NPIPE:
1186		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1187			cmdtxt(lp->n);
1188			if (lp->next)
1189				cmdputs(" | ");
1190		}
1191		break;
1192	case NSUBSHELL:
1193		cmdputs("(");
1194		cmdtxt(n->nredir.n);
1195		cmdputs(")");
1196		break;
1197	case NREDIR:
1198	case NBACKGND:
1199		cmdtxt(n->nredir.n);
1200		break;
1201	case NIF:
1202		cmdputs("if ");
1203		cmdtxt(n->nif.test);
1204		cmdputs("; then ");
1205		cmdtxt(n->nif.ifpart);
1206		cmdputs("...");
1207		break;
1208	case NWHILE:
1209		cmdputs("while ");
1210		goto until;
1211	case NUNTIL:
1212		cmdputs("until ");
1213until:
1214		cmdtxt(n->nbinary.ch1);
1215		cmdputs("; do ");
1216		cmdtxt(n->nbinary.ch2);
1217		cmdputs("; done");
1218		break;
1219	case NFOR:
1220		cmdputs("for ");
1221		cmdputs(n->nfor.var);
1222		cmdputs(" in ...");
1223		break;
1224	case NCASE:
1225		cmdputs("case ");
1226		cmdputs(n->ncase.expr->narg.text);
1227		cmdputs(" in ...");
1228		break;
1229	case NDEFUN:
1230		cmdputs(n->narg.text);
1231		cmdputs("() ...");
1232		break;
1233	case NCMD:
1234		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1235			cmdtxt(np);
1236			if (np->narg.next)
1237				cmdputs(" ");
1238		}
1239		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1240			cmdputs(" ");
1241			cmdtxt(np);
1242		}
1243		break;
1244	case NARG:
1245		cmdputs(n->narg.text);
1246		break;
1247	case NTO:
1248		p = ">";  i = 1;  goto redir;
1249	case NAPPEND:
1250		p = ">>";  i = 1;  goto redir;
1251	case NTOFD:
1252		p = ">&";  i = 1;  goto redir;
1253	case NCLOBBER:
1254		p = ">|"; i = 1; goto redir;
1255	case NFROM:
1256		p = "<";  i = 0;  goto redir;
1257	case NFROMTO:
1258		p = "<>";  i = 0;  goto redir;
1259	case NFROMFD:
1260		p = "<&";  i = 0;  goto redir;
1261redir:
1262		if (n->nfile.fd != i) {
1263			s[0] = n->nfile.fd + '0';
1264			s[1] = '\0';
1265			cmdputs(s);
1266		}
1267		cmdputs(p);
1268		if (n->type == NTOFD || n->type == NFROMFD) {
1269			if (n->ndup.dupfd >= 0)
1270				s[0] = n->ndup.dupfd + '0';
1271			else
1272				s[0] = '-';
1273			s[1] = '\0';
1274			cmdputs(s);
1275		} else {
1276			cmdtxt(n->nfile.fname);
1277		}
1278		break;
1279	case NHERE:
1280	case NXHERE:
1281		cmdputs("<<...");
1282		break;
1283	default:
1284		cmdputs("???");
1285		break;
1286	}
1287}
1288
1289
1290
1291static void
1292cmdputs(const char *s)
1293{
1294	const char *p;
1295	char *q;
1296	char c;
1297	int subtype = 0;
1298
1299	if (cmdnleft <= 0)
1300		return;
1301	p = s;
1302	q = cmdnextc;
1303	while ((c = *p++) != '\0') {
1304		if (c == CTLESC)
1305			*q++ = *p++;
1306		else if (c == CTLVAR) {
1307			*q++ = '$';
1308			if (--cmdnleft > 0)
1309				*q++ = '{';
1310			subtype = *p++;
1311			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1312				*q++ = '#';
1313		} else if (c == '=' && subtype != 0) {
1314			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1315			if (*q)
1316				q++;
1317			else
1318				cmdnleft++;
1319			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1320			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1321			    --cmdnleft > 0)
1322				*q = q[-1], q++;
1323			subtype = 0;
1324		} else if (c == CTLENDVAR) {
1325			*q++ = '}';
1326		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1327			cmdnleft -= 5;
1328			if (cmdnleft > 0) {
1329				*q++ = '$';
1330				*q++ = '(';
1331				*q++ = '.';
1332				*q++ = '.';
1333				*q++ = '.';
1334				*q++ = ')';
1335			}
1336		} else if (c == CTLARI) {
1337			cmdnleft -= 2;
1338			if (cmdnleft > 0) {
1339				*q++ = '$';
1340				*q++ = '(';
1341				*q++ = '(';
1342			}
1343			p++;
1344		} else if (c == CTLENDARI) {
1345			if (--cmdnleft > 0) {
1346				*q++ = ')';
1347				*q++ = ')';
1348			}
1349		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1350			cmdnleft++; /* ignore */
1351		else
1352			*q++ = c;
1353		if (--cmdnleft <= 0) {
1354			*q++ = '.';
1355			*q++ = '.';
1356			*q++ = '.';
1357			break;
1358		}
1359	}
1360	cmdnextc = q;
1361}
1362