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