11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: releng/11.0/bin/sh/jobs.c 296326 2016-03-02 21:24:46Z jilles $");
401556Srgrimes
41213775Sjhb#include <sys/ioctl.h>
42213775Sjhb#include <sys/param.h>
43213775Sjhb#include <sys/resource.h>
44213775Sjhb#include <sys/time.h>
45213775Sjhb#include <sys/wait.h>
46213775Sjhb#include <errno.h>
4717987Speter#include <fcntl.h>
48213775Sjhb#include <paths.h>
4917987Speter#include <signal.h>
50213925Sjilles#include <stddef.h>
51213775Sjhb#include <stdlib.h>
5217987Speter#include <unistd.h>
5317987Speter
541556Srgrimes#include "shell.h"
551556Srgrimes#if JOBS
5617987Speter#include <termios.h>
571556Srgrimes#undef CEOF			/* syntax.h redefines this */
581556Srgrimes#endif
5917987Speter#include "redir.h"
60230998Sjilles#include "exec.h"
6117987Speter#include "show.h"
621556Srgrimes#include "main.h"
631556Srgrimes#include "parser.h"
641556Srgrimes#include "nodes.h"
651556Srgrimes#include "jobs.h"
661556Srgrimes#include "options.h"
671556Srgrimes#include "trap.h"
681556Srgrimes#include "syntax.h"
691556Srgrimes#include "input.h"
701556Srgrimes#include "output.h"
711556Srgrimes#include "memalloc.h"
721556Srgrimes#include "error.h"
731556Srgrimes#include "mystring.h"
74223024Sjilles#include "var.h"
75223060Sjilles#include "builtins.h"
761556Srgrimes
771556Srgrimes
78213760Sobrienstatic struct job *jobtab;	/* array of jobs */
79213760Sobrienstatic int njobs;		/* size of array */
80253658Sjillesstatic pid_t backgndpid = -1;	/* pid of last background process */
81253658Sjillesstatic struct job *bgjob = NULL; /* last background process */
821556Srgrimes#if JOBS
83213760Sobrienstatic struct job *jobmru;	/* most recently used job list */
84213760Sobrienstatic pid_t initialpgrp;	/* pgrp of shell on invocation */
851556Srgrimes#endif
8699762Stjrstatic int ttyfd = -1;
871556Srgrimes
88238888Sjilles/* mode flags for dowait */
89238888Sjilles#define DOWAIT_BLOCK	0x1 /* wait until a child exits */
90277973Sjilles#define DOWAIT_SIG	0x2 /* if DOWAIT_BLOCK, abort on signal */
91277973Sjilles#define DOWAIT_SIG_TRAP	0x4 /* if DOWAIT_SIG, abort on trapped signal only */
92238888Sjilles
9320425Ssteve#if JOBS
94213811Sobrienstatic void restartjob(struct job *);
9520425Ssteve#endif
96213811Sobrienstatic void freejob(struct job *);
97251429Sjillesstatic int waitcmdloop(struct job *);
98263195Sjillesstatic struct job *getjob_nonotfound(const char *);
99263195Sjillesstatic struct job *getjob(const char *);
100263206Sjillespid_t killjob(const char *, int);
101213811Sobrienstatic pid_t dowait(int, struct job *);
102213811Sobrienstatic void checkzombies(void);
103213811Sobrienstatic void cmdtxt(union node *);
104213811Sobrienstatic void cmdputs(const char *);
10597659Stjr#if JOBS
106213811Sobrienstatic void setcurjob(struct job *);
107213811Sobrienstatic void deljob(struct job *);
108213811Sobrienstatic struct job *getcurjob(struct job *);
10997659Stjr#endif
110216217Sjillesstatic void printjobcmd(struct job *);
111216217Sjillesstatic void showjob(struct job *, int);
1121556Srgrimes
1131556Srgrimes
1141556Srgrimes/*
1151556Srgrimes * Turn job control on and off.
1161556Srgrimes */
1171556Srgrimes
118253658Sjillesstatic int jobctl;
1191556Srgrimes
12020425Ssteve#if JOBS
121271144Sjillesstatic void
122271144Sjillesjobctl_notty(void)
123271144Sjilles{
124271144Sjilles	if (ttyfd >= 0) {
125271144Sjilles		close(ttyfd);
126271144Sjilles		ttyfd = -1;
127271144Sjilles	}
128271144Sjilles	if (!iflag) {
129271144Sjilles		setsignal(SIGTSTP);
130271144Sjilles		setsignal(SIGTTOU);
131271144Sjilles		setsignal(SIGTTIN);
132271144Sjilles		jobctl = 1;
133271144Sjilles		return;
134271144Sjilles	}
135271144Sjilles	out2fmt_flush("sh: can't access tty; job control turned off\n");
136271144Sjilles	mflag = 0;
137271144Sjilles}
138271144Sjilles
1391556Srgrimesvoid
14090111Simpsetjobctl(int on)
14117987Speter{
14299762Stjr	int i;
1431556Srgrimes
1441556Srgrimes	if (on == jobctl || rootshell == 0)
1451556Srgrimes		return;
1461556Srgrimes	if (on) {
14799762Stjr		if (ttyfd != -1)
14899762Stjr			close(ttyfd);
149250267Sjilles		if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) < 0) {
15099762Stjr			i = 0;
15199762Stjr			while (i <= 2 && !isatty(i))
15299762Stjr				i++;
153250267Sjilles			if (i > 2 ||
154271144Sjilles			    (ttyfd = fcntl(i, F_DUPFD_CLOEXEC, 10)) < 0) {
155271144Sjilles				jobctl_notty();
156271144Sjilles				return;
157271144Sjilles			}
15899762Stjr		}
159109927Stjr		if (ttyfd < 10) {
160109927Stjr			/*
161109927Stjr			 * Keep our TTY file descriptor out of the way of
162109927Stjr			 * the user's redirections.
163109927Stjr			 */
164250267Sjilles			if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) {
165271144Sjilles				jobctl_notty();
166271144Sjilles				return;
167109927Stjr			}
168109927Stjr			close(ttyfd);
169109927Stjr			ttyfd = i;
170109927Stjr		}
1711556Srgrimes		do { /* while we are in the background */
17299762Stjr			initialpgrp = tcgetpgrp(ttyfd);
17320425Ssteve			if (initialpgrp < 0) {
174271144Sjilles				jobctl_notty();
1751556Srgrimes				return;
1761556Srgrimes			}
177216400Sjilles			if (initialpgrp != getpgrp()) {
178271144Sjilles				if (!iflag) {
179271144Sjilles					initialpgrp = -1;
180271144Sjilles					jobctl_notty();
181271144Sjilles					return;
182271144Sjilles				}
183216400Sjilles				kill(0, SIGTTIN);
1841556Srgrimes				continue;
1851556Srgrimes			}
1861556Srgrimes		} while (0);
1871556Srgrimes		setsignal(SIGTSTP);
1881556Srgrimes		setsignal(SIGTTOU);
1891556Srgrimes		setsignal(SIGTTIN);
19017987Speter		setpgid(0, rootpid);
19199762Stjr		tcsetpgrp(ttyfd, rootpid);
1921556Srgrimes	} else { /* turning job control off */
19317987Speter		setpgid(0, initialpgrp);
194271144Sjilles		if (ttyfd >= 0) {
195271144Sjilles			tcsetpgrp(ttyfd, initialpgrp);
196271144Sjilles			close(ttyfd);
197271144Sjilles			ttyfd = -1;
198271144Sjilles		}
1991556Srgrimes		setsignal(SIGTSTP);
2001556Srgrimes		setsignal(SIGTTOU);
2011556Srgrimes		setsignal(SIGTTIN);
2021556Srgrimes	}
2031556Srgrimes	jobctl = on;
2041556Srgrimes}
20520425Ssteve#endif
2061556Srgrimes
2071556Srgrimes
2081556Srgrimes#if JOBS
20917987Speterint
210254413Sjillesfgcmd(int argc __unused, char **argv __unused)
21117987Speter{
2121556Srgrimes	struct job *jp;
213100308Stjr	pid_t pgrp;
2141556Srgrimes	int status;
2151556Srgrimes
216254413Sjilles	nextopt("");
217254413Sjilles	jp = getjob(*argptr);
2181556Srgrimes	if (jp->jobctl == 0)
2191556Srgrimes		error("job not created under job control");
220216217Sjilles	printjobcmd(jp);
22196933Stjr	flushout(&output);
2221556Srgrimes	pgrp = jp->ps[0].pid;
223271144Sjilles	if (ttyfd >= 0)
224271144Sjilles		tcsetpgrp(ttyfd, pgrp);
2251556Srgrimes	restartjob(jp);
226100305Stjr	jp->foreground = 1;
2271556Srgrimes	INTOFF;
22845916Scracauer	status = waitforjob(jp, (int *)NULL);
2291556Srgrimes	INTON;
2301556Srgrimes	return status;
2311556Srgrimes}
2321556Srgrimes
2331556Srgrimes
23417987Speterint
235279508Sjillesbgcmd(int argc __unused, char **argv __unused)
23617987Speter{
2371556Srgrimes	struct job *jp;
2381556Srgrimes
239254413Sjilles	nextopt("");
2401556Srgrimes	do {
241254413Sjilles		jp = getjob(*argptr);
2421556Srgrimes		if (jp->jobctl == 0)
2431556Srgrimes			error("job not created under job control");
24496933Stjr		if (jp->state == JOBDONE)
24596933Stjr			continue;
2461556Srgrimes		restartjob(jp);
247100305Stjr		jp->foreground = 0;
248216400Sjilles		out1fmt("[%td] ", jp - jobtab + 1);
249216217Sjilles		printjobcmd(jp);
250254413Sjilles	} while (*argptr != NULL && *++argptr != NULL);
2511556Srgrimes	return 0;
2521556Srgrimes}
2531556Srgrimes
2541556Srgrimes
255213811Sobrienstatic void
25690111Simprestartjob(struct job *jp)
25717987Speter{
2581556Srgrimes	struct procstat *ps;
2591556Srgrimes	int i;
2601556Srgrimes
2611556Srgrimes	if (jp->state == JOBDONE)
2621556Srgrimes		return;
26397660Stjr	setcurjob(jp);
2641556Srgrimes	INTOFF;
265216400Sjilles	kill(-jp->ps[0].pid, SIGCONT);
2661556Srgrimes	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
26726104Ssteve		if (WIFSTOPPED(ps->status)) {
2681556Srgrimes			ps->status = -1;
2691556Srgrimes			jp->state = 0;
2701556Srgrimes		}
2711556Srgrimes	}
2721556Srgrimes	INTON;
2731556Srgrimes}
2741556Srgrimes#endif
2751556Srgrimes
2761556Srgrimes
2771556Srgrimesint
278240541Sjillesjobscmd(int argc __unused, char *argv[] __unused)
27917987Speter{
28097669Stjr	char *id;
281163085Sstefanf	int ch, mode;
28297669Stjr
283163085Sstefanf	mode = SHOWJOBS_DEFAULT;
284240541Sjilles	while ((ch = nextopt("lps")) != '\0') {
28597669Stjr		switch (ch) {
28697669Stjr		case 'l':
287163085Sstefanf			mode = SHOWJOBS_VERBOSE;
28897669Stjr			break;
289163085Sstefanf		case 'p':
290163085Sstefanf			mode = SHOWJOBS_PGIDS;
291163085Sstefanf			break;
29297669Stjr		case 's':
293163085Sstefanf			mode = SHOWJOBS_PIDS;
29497669Stjr			break;
29597669Stjr		}
29697669Stjr	}
29797669Stjr
298240541Sjilles	if (*argptr == NULL)
299163085Sstefanf		showjobs(0, mode);
30097669Stjr	else
301240541Sjilles		while ((id = *argptr++) != NULL)
302216217Sjilles			showjob(getjob(id), mode);
30397669Stjr
30497669Stjr	return (0);
3051556Srgrimes}
3061556Srgrimes
307213811Sobrienstatic void
308216217Sjillesprintjobcmd(struct job *jp)
30997663Stjr{
310216217Sjilles	struct procstat *ps;
311216217Sjilles	int i;
312216217Sjilles
313216217Sjilles	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
314216217Sjilles		out1str(ps->cmd);
315216217Sjilles		if (i > 0)
316216217Sjilles			out1str(" | ");
317216217Sjilles	}
318216217Sjilles	out1c('\n');
319216217Sjilles}
320216217Sjilles
321216217Sjillesstatic void
322216217Sjillesshowjob(struct job *jp, int mode)
323216217Sjilles{
32497663Stjr	char s[64];
325296326Sjilles	char statebuf[16];
326296326Sjilles	const char *statestr, *coredump;
32797663Stjr	struct procstat *ps;
32897669Stjr	struct job *j;
32997669Stjr	int col, curr, i, jobno, prev, procno;
33097669Stjr	char c;
3311556Srgrimes
332163085Sstefanf	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
33397663Stjr	jobno = jp - jobtab + 1;
33497669Stjr	curr = prev = 0;
33597669Stjr#if JOBS
33697669Stjr	if ((j = getcurjob(NULL)) != NULL) {
33797669Stjr		curr = j - jobtab + 1;
33897669Stjr		if ((j = getcurjob(j)) != NULL)
33997669Stjr			prev = j - jobtab + 1;
34097669Stjr	}
34197669Stjr#endif
342296326Sjilles	coredump = "";
343216217Sjilles	ps = jp->ps + jp->nprocs - 1;
344216217Sjilles	if (jp->state == 0) {
345296326Sjilles		statestr = "Running";
346216217Sjilles#if JOBS
347216217Sjilles	} else if (jp->state == JOBSTOPPED) {
348216217Sjilles		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
349216217Sjilles			ps--;
350216217Sjilles		if (WIFSTOPPED(ps->status))
351216217Sjilles			i = WSTOPSIG(ps->status);
352216217Sjilles		else
353216217Sjilles			i = -1;
354296326Sjilles		statestr = strsignal(i);
355296326Sjilles		if (statestr == NULL)
356296326Sjilles			statestr = "Suspended";
357216217Sjilles#endif
358216217Sjilles	} else if (WIFEXITED(ps->status)) {
359216217Sjilles		if (WEXITSTATUS(ps->status) == 0)
360296326Sjilles			statestr = "Done";
361296326Sjilles		else {
362296326Sjilles			fmtstr(statebuf, sizeof(statebuf), "Done(%d)",
363216217Sjilles			    WEXITSTATUS(ps->status));
364296326Sjilles			statestr = statebuf;
365296326Sjilles		}
366216217Sjilles	} else {
367216217Sjilles		i = WTERMSIG(ps->status);
368296326Sjilles		statestr = strsignal(i);
369296326Sjilles		if (statestr == NULL)
370296326Sjilles			statestr = "Unknown signal";
371216217Sjilles		if (WCOREDUMP(ps->status))
372296326Sjilles			coredump = " (core dumped)";
373216217Sjilles	}
374216217Sjilles
375272575Sjilles	for (ps = jp->ps ; procno > 0 ; ps++, procno--) { /* for each process */
376163085Sstefanf		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
377216199Sjilles			out1fmt("%d\n", (int)ps->pid);
378272575Sjilles			continue;
37997669Stjr		}
380216217Sjilles		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
381272575Sjilles			continue;
38297819Stjr		if (jobno == curr && ps == jp->ps)
38397669Stjr			c = '+';
38497819Stjr		else if (jobno == prev && ps == jp->ps)
38597669Stjr			c = '-';
38697669Stjr		else
38797669Stjr			c = ' ';
38897663Stjr		if (ps == jp->ps)
38997669Stjr			fmtstr(s, 64, "[%d] %c ", jobno, c);
39097663Stjr		else
39197816Stjr			fmtstr(s, 64, "    %c ", c);
39297663Stjr		out1str(s);
39397663Stjr		col = strlen(s);
394163085Sstefanf		if (mode == SHOWJOBS_VERBOSE) {
395100308Stjr			fmtstr(s, 64, "%d ", (int)ps->pid);
39697669Stjr			out1str(s);
39797669Stjr			col += strlen(s);
39897669Stjr		}
399216217Sjilles		if (ps == jp->ps) {
400216217Sjilles			out1str(statestr);
401296326Sjilles			out1str(coredump);
402296326Sjilles			col += strlen(statestr) + strlen(coredump);
40397663Stjr		}
40497663Stjr		do {
40597663Stjr			out1c(' ');
40697663Stjr			col++;
40797663Stjr		} while (col < 30);
408216217Sjilles		if (mode == SHOWJOBS_VERBOSE) {
409216217Sjilles			out1str(ps->cmd);
410216217Sjilles			out1c('\n');
411216217Sjilles		} else
412216217Sjilles			printjobcmd(jp);
41397663Stjr	}
41497663Stjr}
41597663Stjr
4161556Srgrimes/*
4171556Srgrimes * Print a list of jobs.  If "change" is nonzero, only print jobs whose
4181556Srgrimes * statuses have changed since the last call to showjobs.
4191556Srgrimes *
4201556Srgrimes * If the shell is interrupted in the process of creating a job, the
4211556Srgrimes * result may be a job structure containing zero processes.  Such structures
4221556Srgrimes * will be freed here.
4231556Srgrimes */
4241556Srgrimes
4251556Srgrimesvoid
426163085Sstefanfshowjobs(int change, int mode)
42717987Speter{
4281556Srgrimes	int jobno;
4291556Srgrimes	struct job *jp;
4301556Srgrimes
4311556Srgrimes	TRACE(("showjobs(%d) called\n", change));
432208489Sjilles	checkzombies();
4331556Srgrimes	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
4341556Srgrimes		if (! jp->used)
4351556Srgrimes			continue;
4361556Srgrimes		if (jp->nprocs == 0) {
4371556Srgrimes			freejob(jp);
4381556Srgrimes			continue;
4391556Srgrimes		}
4401556Srgrimes		if (change && ! jp->changed)
4411556Srgrimes			continue;
442216217Sjilles		showjob(jp, mode);
443249984Sjilles		if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
444249984Sjilles			jp->changed = 0;
445249984Sjilles			/* Hack: discard jobs for which $! has not been
446249984Sjilles			 * referenced in interactive mode when they terminate.
447249984Sjilles			 */
448249984Sjilles			if (jp->state == JOBDONE && !jp->remembered &&
449249984Sjilles					(iflag || jp != bgjob)) {
450249984Sjilles				freejob(jp);
451249984Sjilles			}
4521556Srgrimes		}
4531556Srgrimes	}
4541556Srgrimes}
4551556Srgrimes
4561556Srgrimes
4571556Srgrimes/*
4581556Srgrimes * Mark a job structure as unused.
4591556Srgrimes */
4601556Srgrimes
461213811Sobrienstatic void
46290111Simpfreejob(struct job *jp)
46390111Simp{
4641556Srgrimes	struct procstat *ps;
4651556Srgrimes	int i;
4661556Srgrimes
4671556Srgrimes	INTOFF;
468209600Sjilles	if (bgjob == jp)
469209600Sjilles		bgjob = NULL;
4701556Srgrimes	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
4711556Srgrimes		if (ps->cmd != nullstr)
4721556Srgrimes			ckfree(ps->cmd);
4731556Srgrimes	}
4741556Srgrimes	if (jp->ps != &jp->ps0)
4751556Srgrimes		ckfree(jp->ps);
4761556Srgrimes	jp->used = 0;
4771556Srgrimes#if JOBS
47897659Stjr	deljob(jp);
4791556Srgrimes#endif
4801556Srgrimes	INTON;
4811556Srgrimes}
4821556Srgrimes
4831556Srgrimes
4841556Srgrimes
4851556Srgrimesint
486248349Sjilleswaitcmd(int argc __unused, char **argv __unused)
48717987Speter{
4881556Srgrimes	struct job *job;
489251429Sjilles	int retval;
4901556Srgrimes
491248349Sjilles	nextopt("");
492251429Sjilles	if (*argptr == NULL)
493251429Sjilles		return (waitcmdloop(NULL));
494251429Sjilles
495251429Sjilles	do {
496251430Sjilles		job = getjob_nonotfound(*argptr);
497251430Sjilles		if (job == NULL)
498251430Sjilles			retval = 127;
499251430Sjilles		else
500251430Sjilles			retval = waitcmdloop(job);
501251429Sjilles		argptr++;
502251429Sjilles	} while (*argptr != NULL);
50338536Scracauer
504251429Sjilles	return (retval);
505251429Sjilles}
506251429Sjilles
507251429Sjillesstatic int
508251429Sjilleswaitcmdloop(struct job *job)
509251429Sjilles{
510255157Sjilles	int status, retval, sig;
511251429Sjilles	struct job *jp;
512251429Sjilles
51338536Scracauer	/*
51438536Scracauer	 * Loop until a process is terminated or stopped, or a SIGINT is
51538536Scracauer	 * received.
51638536Scracauer	 */
51738536Scracauer
51838536Scracauer	do {
5191556Srgrimes		if (job != NULL) {
520254767Sjilles			if (job->state == JOBDONE) {
5211556Srgrimes				status = job->ps[job->nprocs - 1].status;
52226104Ssteve				if (WIFEXITED(status))
52326104Ssteve					retval = WEXITSTATUS(status);
5241556Srgrimes				else
52526104Ssteve					retval = WTERMSIG(status) + 128;
526209600Sjilles				if (! iflag || ! job->changed)
5271556Srgrimes					freejob(job);
528209600Sjilles				else {
529209600Sjilles					job->remembered = 0;
530209600Sjilles					if (job == bgjob)
531209600Sjilles						bgjob = NULL;
532209600Sjilles				}
53326104Ssteve				return retval;
5341556Srgrimes			}
5351556Srgrimes		} else {
536209600Sjilles			for (jp = jobtab ; jp < jobtab + njobs; jp++)
537209600Sjilles				if (jp->used && jp->state == JOBDONE) {
538209600Sjilles					if (! iflag || ! jp->changed)
539209600Sjilles						freejob(jp);
540209600Sjilles					else {
541209600Sjilles						jp->remembered = 0;
542209600Sjilles						if (jp == bgjob)
543209600Sjilles							bgjob = NULL;
544209600Sjilles					}
545209600Sjilles				}
5461556Srgrimes			for (jp = jobtab ; ; jp++) {
5471556Srgrimes				if (jp >= jobtab + njobs) {	/* no running procs */
5481556Srgrimes					return 0;
5491556Srgrimes				}
5501556Srgrimes				if (jp->used && jp->state == 0)
5511556Srgrimes					break;
5521556Srgrimes			}
5531556Srgrimes		}
554238888Sjilles	} while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, (struct job *)NULL) != -1);
55538521Scracauer
556255157Sjilles	sig = pendingsig_waitcmd;
557255157Sjilles	pendingsig_waitcmd = 0;
558255157Sjilles	return sig + 128;
5591556Srgrimes}
5601556Srgrimes
5611556Srgrimes
5621556Srgrimes
56317987Speterint
564254413Sjillesjobidcmd(int argc __unused, char **argv __unused)
56517987Speter{
5661556Srgrimes	struct job *jp;
5671556Srgrimes	int i;
5681556Srgrimes
569254413Sjilles	nextopt("");
570254413Sjilles	jp = getjob(*argptr);
5711556Srgrimes	for (i = 0 ; i < jp->nprocs ; ) {
572100308Stjr		out1fmt("%d", (int)jp->ps[i].pid);
5731556Srgrimes		out1c(++i < jp->nprocs? ' ' : '\n');
5741556Srgrimes	}
5751556Srgrimes	return 0;
5761556Srgrimes}
5771556Srgrimes
5781556Srgrimes
5791556Srgrimes
5801556Srgrimes/*
5811556Srgrimes * Convert a job name to a job structure.
5821556Srgrimes */
5831556Srgrimes
584213811Sobrienstatic struct job *
585263195Sjillesgetjob_nonotfound(const char *name)
58690111Simp{
5871556Srgrimes	int jobno;
58897688Stjr	struct job *found, *jp;
589268920Sjilles	size_t namelen;
590100308Stjr	pid_t pid;
5911556Srgrimes	int i;
5921556Srgrimes
5931556Srgrimes	if (name == NULL) {
5941556Srgrimes#if JOBS
595273152Sjilles		name = "%+";
5961556Srgrimes#else
5971556Srgrimes		error("No current job");
5981556Srgrimes#endif
599273152Sjilles	}
600273152Sjilles	if (name[0] == '%') {
6011556Srgrimes		if (is_digit(name[1])) {
6021556Srgrimes			jobno = number(name + 1);
6031556Srgrimes			if (jobno > 0 && jobno <= njobs
6041556Srgrimes			 && jobtab[jobno - 1].used != 0)
6051556Srgrimes				return &jobtab[jobno - 1];
6061556Srgrimes#if JOBS
607273152Sjilles		} else if ((name[1] == '%' || name[1] == '+') &&
608273152Sjilles		    name[2] == '\0') {
609273152Sjilles			if ((jp = getcurjob(NULL)) == NULL)
610273152Sjilles				error("No current job");
611273152Sjilles			return (jp);
61297688Stjr		} else if (name[1] == '-' && name[2] == '\0') {
61397688Stjr			if ((jp = getcurjob(NULL)) == NULL ||
61497688Stjr			    (jp = getcurjob(jp)) == NULL)
61597688Stjr				error("No previous job");
61697688Stjr			return (jp);
6171556Srgrimes#endif
61897688Stjr		} else if (name[1] == '?') {
61997688Stjr			found = NULL;
62097688Stjr			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
62197688Stjr				if (jp->used && jp->nprocs > 0
62297688Stjr				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
62397688Stjr					if (found)
62497688Stjr						error("%s: ambiguous", name);
62597688Stjr					found = jp;
62697688Stjr				}
62797688Stjr			}
62897688Stjr			if (found != NULL)
62997688Stjr				return (found);
6301556Srgrimes		} else {
631268920Sjilles			namelen = strlen(name);
63297688Stjr			found = NULL;
6331556Srgrimes			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6341556Srgrimes				if (jp->used && jp->nprocs > 0
635268920Sjilles				 && strncmp(jp->ps[0].cmd, name + 1,
636268920Sjilles				 namelen - 1) == 0) {
6371556Srgrimes					if (found)
6381556Srgrimes						error("%s: ambiguous", name);
6391556Srgrimes					found = jp;
6401556Srgrimes				}
6411556Srgrimes			}
6421556Srgrimes			if (found)
6431556Srgrimes				return found;
6441556Srgrimes		}
6451556Srgrimes	} else if (is_number(name)) {
646100308Stjr		pid = (pid_t)number(name);
6471556Srgrimes		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6481556Srgrimes			if (jp->used && jp->nprocs > 0
6491556Srgrimes			 && jp->ps[jp->nprocs - 1].pid == pid)
6501556Srgrimes				return jp;
6511556Srgrimes		}
6521556Srgrimes	}
65317987Speter	return NULL;
6541556Srgrimes}
6551556Srgrimes
6561556Srgrimes
657251430Sjillesstatic struct job *
658263195Sjillesgetjob(const char *name)
659251430Sjilles{
660251430Sjilles	struct job *jp;
661251430Sjilles
662251430Sjilles	jp = getjob_nonotfound(name);
663251430Sjilles	if (jp == NULL)
664251430Sjilles		error("No such job: %s", name);
665251430Sjilles	return (jp);
666251430Sjilles}
667251430Sjilles
668251430Sjilles
669263206Sjillesint
670263206Sjilleskilljob(const char *name, int sig)
671216629Sjilles{
672216629Sjilles	struct job *jp;
673263206Sjilles	int i, ret;
6741556Srgrimes
675216629Sjilles	jp = getjob(name);
676262931Sjilles	if (jp->state == JOBDONE)
677262931Sjilles		return 0;
678263206Sjilles	if (jp->jobctl)
679263206Sjilles		return kill(-jp->ps[0].pid, sig);
680263206Sjilles	ret = -1;
681263206Sjilles	errno = ESRCH;
682263206Sjilles	for (i = 0; i < jp->nprocs; i++)
683263206Sjilles		if (jp->ps[i].status == -1 || WIFSTOPPED(jp->ps[i].status)) {
684263206Sjilles			if (kill(jp->ps[i].pid, sig) == 0)
685263206Sjilles				ret = 0;
686263206Sjilles		} else
687263206Sjilles			ret = 0;
688263206Sjilles	return ret;
689216629Sjilles}
690216629Sjilles
6911556Srgrimes/*
6921556Srgrimes * Return a new job structure,
6931556Srgrimes */
6941556Srgrimes
6951556Srgrimesstruct job *
69690111Simpmakejob(union node *node __unused, int nprocs)
69717987Speter{
6981556Srgrimes	int i;
6991556Srgrimes	struct job *jp;
7001556Srgrimes
7011556Srgrimes	for (i = njobs, jp = jobtab ; ; jp++) {
7021556Srgrimes		if (--i < 0) {
7031556Srgrimes			INTOFF;
7041556Srgrimes			if (njobs == 0) {
7051556Srgrimes				jobtab = ckmalloc(4 * sizeof jobtab[0]);
70697664Stjr#if JOBS
70797659Stjr				jobmru = NULL;
70897664Stjr#endif
7091556Srgrimes			} else {
7101556Srgrimes				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
71117987Speter				memcpy(jp, jobtab, njobs * sizeof jp[0]);
71297659Stjr#if JOBS
71397659Stjr				/* Relocate `next' pointers and list head */
71499760Stjr				if (jobmru != NULL)
71599760Stjr					jobmru = &jp[jobmru - jobtab];
71697659Stjr				for (i = 0; i < njobs; i++)
71797659Stjr					if (jp[i].next != NULL)
71897659Stjr						jp[i].next = &jp[jp[i].next -
71997659Stjr						    jobtab];
72097659Stjr#endif
721209600Sjilles				if (bgjob != NULL)
722209600Sjilles					bgjob = &jp[bgjob - jobtab];
72320425Ssteve				/* Relocate `ps' pointers */
72420425Ssteve				for (i = 0; i < njobs; i++)
72520425Ssteve					if (jp[i].ps == &jobtab[i].ps0)
72620425Ssteve						jp[i].ps = &jp[i].ps0;
7271556Srgrimes				ckfree(jobtab);
7281556Srgrimes				jobtab = jp;
7291556Srgrimes			}
7301556Srgrimes			jp = jobtab + njobs;
731248980Sjilles			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
732248980Sjilles				;
7331556Srgrimes			INTON;
7341556Srgrimes			break;
7351556Srgrimes		}
7361556Srgrimes		if (jp->used == 0)
7371556Srgrimes			break;
7381556Srgrimes	}
7391556Srgrimes	INTOFF;
7401556Srgrimes	jp->state = 0;
7411556Srgrimes	jp->used = 1;
7421556Srgrimes	jp->changed = 0;
7431556Srgrimes	jp->nprocs = 0;
744100305Stjr	jp->foreground = 0;
745209600Sjilles	jp->remembered = 0;
7461556Srgrimes#if JOBS
7471556Srgrimes	jp->jobctl = jobctl;
74897659Stjr	jp->next = NULL;
7491556Srgrimes#endif
7501556Srgrimes	if (nprocs > 1) {
7511556Srgrimes		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
7521556Srgrimes	} else {
7531556Srgrimes		jp->ps = &jp->ps0;
7541556Srgrimes	}
7551556Srgrimes	INTON;
756213775Sjhb	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
75717987Speter	    jp - jobtab + 1));
7581556Srgrimes	return jp;
7598855Srgrimes}
7601556Srgrimes
76197659Stjr#if JOBS
762213811Sobrienstatic void
76397659Stjrsetcurjob(struct job *cj)
76497659Stjr{
76597659Stjr	struct job *jp, *prev;
7661556Srgrimes
76797659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
76897659Stjr		if (jp == cj) {
76997659Stjr			if (prev != NULL)
77097659Stjr				prev->next = jp->next;
77197659Stjr			else
77297659Stjr				jobmru = jp->next;
77397659Stjr			jp->next = jobmru;
77497659Stjr			jobmru = cj;
77597659Stjr			return;
77697659Stjr		}
77797659Stjr	}
77897659Stjr	cj->next = jobmru;
77997659Stjr	jobmru = cj;
78097659Stjr}
78197659Stjr
782213811Sobrienstatic void
78397659Stjrdeljob(struct job *j)
78497659Stjr{
78597659Stjr	struct job *jp, *prev;
78697659Stjr
78797659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
78897659Stjr		if (jp == j) {
78997659Stjr			if (prev != NULL)
79097659Stjr				prev->next = jp->next;
79197659Stjr			else
79297659Stjr				jobmru = jp->next;
79397659Stjr			return;
79497659Stjr		}
79597659Stjr	}
79697659Stjr}
79797659Stjr
7981556Srgrimes/*
79997659Stjr * Return the most recently used job that isn't `nj', and preferably one
80097659Stjr * that is stopped.
80197659Stjr */
802213811Sobrienstatic struct job *
80397659Stjrgetcurjob(struct job *nj)
80497659Stjr{
80597659Stjr	struct job *jp;
80697659Stjr
80797659Stjr	/* Try to find a stopped one.. */
80897659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
80997659Stjr		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
81097659Stjr			return (jp);
81197659Stjr	/* Otherwise the most recently used job that isn't `nj' */
81297659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
81397659Stjr		if (jp->used && jp != nj)
81497659Stjr			return (jp);
81597659Stjr
81697659Stjr	return (NULL);
81797659Stjr}
81897659Stjr
81997659Stjr#endif
82097659Stjr
82197659Stjr/*
8221556Srgrimes * Fork of a subshell.  If we are doing job control, give the subshell its
8231556Srgrimes * own process group.  Jp is a job structure that the job is to be added to.
8241556Srgrimes * N is the command that will be evaluated by the child.  Both jp and n may
8251556Srgrimes * be NULL.  The mode parameter can be one of the following:
8261556Srgrimes *	FORK_FG - Fork off a foreground process.
8271556Srgrimes *	FORK_BG - Fork off a background process.
8281556Srgrimes *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
8291556Srgrimes *		     process group even if job control is on.
8301556Srgrimes *
8311556Srgrimes * When job control is turned off, background processes have their standard
8321556Srgrimes * input redirected to /dev/null (except for the second and later processes
8331556Srgrimes * in a pipeline).
8341556Srgrimes */
8351556Srgrimes
836100308Stjrpid_t
83790111Simpforkshell(struct job *jp, union node *n, int mode)
83817987Speter{
839100308Stjr	pid_t pid;
840100308Stjr	pid_t pgrp;
8411556Srgrimes
842213775Sjhb	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
84317987Speter	    mode));
8441556Srgrimes	INTOFF;
845216208Sjilles	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
846208489Sjilles		checkzombies();
847112341Stjr	flushall();
8481556Srgrimes	pid = fork();
8491556Srgrimes	if (pid == -1) {
8501556Srgrimes		TRACE(("Fork failed, errno=%d\n", errno));
8511556Srgrimes		INTON;
85253891Scracauer		error("Cannot fork: %s", strerror(errno));
8531556Srgrimes	}
8541556Srgrimes	if (pid == 0) {
8551556Srgrimes		struct job *p;
8561556Srgrimes		int wasroot;
8571556Srgrimes		int i;
8581556Srgrimes
859100308Stjr		TRACE(("Child shell %d\n", (int)getpid()));
8601556Srgrimes		wasroot = rootshell;
8611556Srgrimes		rootshell = 0;
862200998Sjilles		handler = &main_handler;
8631556Srgrimes		closescript();
8641556Srgrimes		INTON;
865223024Sjilles		forcelocal = 0;
8661556Srgrimes		clear_traps();
8671556Srgrimes#if JOBS
8681556Srgrimes		jobctl = 0;		/* do job control only in root shell */
8691556Srgrimes		if (wasroot && mode != FORK_NOJOB && mflag) {
8701556Srgrimes			if (jp == NULL || jp->nprocs == 0)
8711556Srgrimes				pgrp = getpid();
8721556Srgrimes			else
8731556Srgrimes				pgrp = jp->ps[0].pid;
874271144Sjilles			if (setpgid(0, pgrp) == 0 && mode == FORK_FG &&
875271144Sjilles			    ttyfd >= 0) {
8761556Srgrimes				/*** this causes superfluous TIOCSPGRPS ***/
87799762Stjr				if (tcsetpgrp(ttyfd, pgrp) < 0)
87820425Ssteve					error("tcsetpgrp failed, errno=%d", errno);
8791556Srgrimes			}
8801556Srgrimes			setsignal(SIGTSTP);
8811556Srgrimes			setsignal(SIGTTOU);
8821556Srgrimes		} else if (mode == FORK_BG) {
8831556Srgrimes			ignoresig(SIGINT);
8841556Srgrimes			ignoresig(SIGQUIT);
8851556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8861556Srgrimes			    ! fd0_redirected_p ()) {
8871556Srgrimes				close(0);
88869793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
889222684Sjilles					error("cannot open %s: %s",
89069793Sobrien					    _PATH_DEVNULL, strerror(errno));
8911556Srgrimes			}
8921556Srgrimes		}
8931556Srgrimes#else
8941556Srgrimes		if (mode == FORK_BG) {
8951556Srgrimes			ignoresig(SIGINT);
8961556Srgrimes			ignoresig(SIGQUIT);
8971556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8981556Srgrimes			    ! fd0_redirected_p ()) {
8991556Srgrimes				close(0);
90069793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
901222684Sjilles					error("cannot open %s: %s",
90269793Sobrien					    _PATH_DEVNULL, strerror(errno));
9031556Srgrimes			}
9041556Srgrimes		}
9051556Srgrimes#endif
906102051Stjr		INTOFF;
907102051Stjr		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
908102051Stjr			if (p->used)
909102051Stjr				freejob(p);
910102051Stjr		INTON;
9111556Srgrimes		if (wasroot && iflag) {
9121556Srgrimes			setsignal(SIGINT);
9131556Srgrimes			setsignal(SIGQUIT);
9141556Srgrimes			setsignal(SIGTERM);
9151556Srgrimes		}
9161556Srgrimes		return pid;
9171556Srgrimes	}
9181556Srgrimes	if (rootshell && mode != FORK_NOJOB && mflag) {
9191556Srgrimes		if (jp == NULL || jp->nprocs == 0)
9201556Srgrimes			pgrp = pid;
9211556Srgrimes		else
9221556Srgrimes			pgrp = jp->ps[0].pid;
92317987Speter		setpgid(pid, pgrp);
9241556Srgrimes	}
925209600Sjilles	if (mode == FORK_BG) {
926209600Sjilles		if (bgjob != NULL && bgjob->state == JOBDONE &&
927209600Sjilles		    !bgjob->remembered && !iflag)
928209600Sjilles			freejob(bgjob);
9291556Srgrimes		backgndpid = pid;		/* set $! */
930209600Sjilles		bgjob = jp;
931209600Sjilles	}
9321556Srgrimes	if (jp) {
9331556Srgrimes		struct procstat *ps = &jp->ps[jp->nprocs++];
9341556Srgrimes		ps->pid = pid;
9351556Srgrimes		ps->status = -1;
9361556Srgrimes		ps->cmd = nullstr;
9371556Srgrimes		if (iflag && rootshell && n)
9381556Srgrimes			ps->cmd = commandtext(n);
939100305Stjr		jp->foreground = mode == FORK_FG;
94097659Stjr#if JOBS
94197659Stjr		setcurjob(jp);
94297659Stjr#endif
9431556Srgrimes	}
9441556Srgrimes	INTON;
945100308Stjr	TRACE(("In parent shell:  child = %d\n", (int)pid));
9461556Srgrimes	return pid;
9471556Srgrimes}
9481556Srgrimes
9491556Srgrimes
950230998Sjillespid_t
951230998Sjillesvforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
952230998Sjilles{
953230998Sjilles	pid_t pid;
954230998Sjilles	struct jmploc jmploc;
955230998Sjilles	struct jmploc *savehandler;
9561556Srgrimes
957233792Sjilles	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
958233792Sjilles	    (void *)pip));
959230998Sjilles	INTOFF;
960230998Sjilles	flushall();
961230998Sjilles	savehandler = handler;
962230998Sjilles	pid = vfork();
963230998Sjilles	if (pid == -1) {
964230998Sjilles		TRACE(("Vfork failed, errno=%d\n", errno));
965230998Sjilles		INTON;
966230998Sjilles		error("Cannot fork: %s", strerror(errno));
967230998Sjilles	}
968230998Sjilles	if (pid == 0) {
969230998Sjilles		TRACE(("Child shell %d\n", (int)getpid()));
970230998Sjilles		if (setjmp(jmploc.loc))
971230998Sjilles			_exit(exception == EXEXEC ? exerrno : 2);
972230998Sjilles		if (pip != NULL) {
973230998Sjilles			close(pip[0]);
974230998Sjilles			if (pip[1] != 1) {
975230998Sjilles				dup2(pip[1], 1);
976230998Sjilles				close(pip[1]);
977230998Sjilles			}
978230998Sjilles		}
979230998Sjilles		handler = &jmploc;
980230998Sjilles		shellexec(argv, envp, path, idx);
981230998Sjilles	}
982230998Sjilles	handler = savehandler;
983230998Sjilles	if (jp) {
984230998Sjilles		struct procstat *ps = &jp->ps[jp->nprocs++];
985230998Sjilles		ps->pid = pid;
986230998Sjilles		ps->status = -1;
987230998Sjilles		ps->cmd = nullstr;
988230998Sjilles		jp->foreground = 1;
989230998Sjilles#if JOBS
990230998Sjilles		setcurjob(jp);
991230998Sjilles#endif
992230998Sjilles	}
993230998Sjilles	INTON;
994230998Sjilles	TRACE(("In parent shell:  child = %d\n", (int)pid));
995230998Sjilles	return pid;
996230998Sjilles}
997230998Sjilles
998230998Sjilles
9991556Srgrimes/*
10001556Srgrimes * Wait for job to finish.
10011556Srgrimes *
10021556Srgrimes * Under job control we have the problem that while a child process is
10031556Srgrimes * running interrupts generated by the user are sent to the child but not
10041556Srgrimes * to the shell.  This means that an infinite loop started by an inter-
10051556Srgrimes * active user may be hard to kill.  With job control turned off, an
10061556Srgrimes * interactive user may place an interactive program inside a loop.  If
10071556Srgrimes * the interactive program catches interrupts, the user doesn't want
10081556Srgrimes * these interrupts to also abort the loop.  The approach we take here
10091556Srgrimes * is to have the shell ignore interrupt signals while waiting for a
101046684Skris * foreground process to terminate, and then send itself an interrupt
10111556Srgrimes * signal if the child process was terminated by an interrupt signal.
10121556Srgrimes * Unfortunately, some programs want to do a bit of cleanup and then
10131556Srgrimes * exit on interrupt; unless these processes terminate themselves by
10141556Srgrimes * sending a signal to themselves (instead of calling exit) they will
10151556Srgrimes * confuse this approach.
10161556Srgrimes */
10171556Srgrimes
10181556Srgrimesint
101990111Simpwaitforjob(struct job *jp, int *origstatus)
102045916Scracauer{
10211556Srgrimes#if JOBS
1022208881Sjilles	int propagate_int = jp->jobctl && jp->foreground;
10231556Srgrimes#endif
10241556Srgrimes	int status;
10251556Srgrimes	int st;
10261556Srgrimes
10271556Srgrimes	INTOFF;
1028213775Sjhb	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
102938950Scracauer	while (jp->state == 0)
1030255157Sjilles		if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
1031277973Sjilles		    DOWAIT_SIG_TRAP : 0), jp) == -1)
103238950Scracauer			dotrap();
10331556Srgrimes#if JOBS
10341556Srgrimes	if (jp->jobctl) {
1035271144Sjilles		if (ttyfd >= 0 && tcsetpgrp(ttyfd, rootpid) < 0)
103620425Ssteve			error("tcsetpgrp failed, errno=%d\n", errno);
10371556Srgrimes	}
10381556Srgrimes	if (jp->state == JOBSTOPPED)
103997659Stjr		setcurjob(jp);
10401556Srgrimes#endif
10411556Srgrimes	status = jp->ps[jp->nprocs - 1].status;
104245916Scracauer	if (origstatus != NULL)
104345916Scracauer		*origstatus = status;
10441556Srgrimes	/* convert to 8 bits */
104526104Ssteve	if (WIFEXITED(status))
104626104Ssteve		st = WEXITSTATUS(status);
10471556Srgrimes#if JOBS
104826104Ssteve	else if (WIFSTOPPED(status))
104926104Ssteve		st = WSTOPSIG(status) + 128;
10501556Srgrimes#endif
10511556Srgrimes	else
105226104Ssteve		st = WTERMSIG(status) + 128;
10531556Srgrimes	if (! JOBS || jp->state == JOBDONE)
10541556Srgrimes		freejob(jp);
105538521Scracauer	if (int_pending()) {
1056216400Sjilles		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
105738521Scracauer			CLEAR_PENDING_INT;
105838521Scracauer	}
1059208881Sjilles#if JOBS
1060281982Sjilles	else if (rootshell && propagate_int &&
1061208881Sjilles			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1062208881Sjilles		kill(getpid(), SIGINT);
1063208881Sjilles#endif
10641556Srgrimes	INTON;
10651556Srgrimes	return st;
10661556Srgrimes}
10671556Srgrimes
10681556Srgrimes
1069238888Sjillesstatic void
1070248980Sjillesdummy_handler(int sig __unused)
1071238888Sjilles{
1072238888Sjilles}
10731556Srgrimes
10741556Srgrimes/*
10751556Srgrimes * Wait for a process to terminate.
10761556Srgrimes */
10771556Srgrimes
1078213811Sobrienstatic pid_t
1079238888Sjillesdowait(int mode, struct job *job)
108017987Speter{
1081238888Sjilles	struct sigaction sa, osa;
1082238888Sjilles	sigset_t mask, omask;
1083100308Stjr	pid_t pid;
10841556Srgrimes	int status;
10851556Srgrimes	struct procstat *sp;
10861556Srgrimes	struct job *jp;
10871556Srgrimes	struct job *thisjob;
1088244682Sjilles	const char *sigstr;
10891556Srgrimes	int done;
10901556Srgrimes	int stopped;
109126104Ssteve	int sig;
1092216217Sjilles	int coredump;
1093238866Sjilles	int wflags;
1094238888Sjilles	int restore_sigchld;
10951556Srgrimes
1096246495Sdelphij	TRACE(("dowait(%d, %p) called\n", mode, job));
1097238888Sjilles	restore_sigchld = 0;
1098238888Sjilles	if ((mode & DOWAIT_SIG) != 0) {
1099238888Sjilles		sigfillset(&mask);
1100238888Sjilles		sigprocmask(SIG_BLOCK, &mask, &omask);
1101238888Sjilles		INTOFF;
1102238888Sjilles		if (!issigchldtrapped()) {
1103238888Sjilles			restore_sigchld = 1;
1104238888Sjilles			sa.sa_handler = dummy_handler;
1105238888Sjilles			sa.sa_flags = 0;
1106238888Sjilles			sigemptyset(&sa.sa_mask);
1107238888Sjilles			sigaction(SIGCHLD, &sa, &osa);
1108238888Sjilles		}
1109238888Sjilles	}
11101556Srgrimes	do {
1111238866Sjilles#if JOBS
1112238867Sjilles		if (iflag)
1113238867Sjilles			wflags = WUNTRACED | WCONTINUED;
1114238867Sjilles		else
1115238866Sjilles#endif
1116238867Sjilles			wflags = 0;
1117238888Sjilles		if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1118238866Sjilles			wflags |= WNOHANG;
1119238866Sjilles		pid = wait3(&status, wflags, (struct rusage *)NULL);
1120100308Stjr		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1121238888Sjilles		if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1122255157Sjilles			pid = -1;
1123277973Sjilles			if (((mode & DOWAIT_SIG_TRAP) != 0 ?
1124255157Sjilles			    pendingsig : pendingsig_waitcmd) != 0) {
1125255157Sjilles				errno = EINTR;
1126255157Sjilles				break;
1127255157Sjilles			}
1128238888Sjilles			sigsuspend(&omask);
1129238888Sjilles			if (int_pending())
1130238888Sjilles				break;
1131238888Sjilles		}
1132255157Sjilles	} while (pid == -1 && errno == EINTR);
1133153417Smaxim	if (pid == -1 && errno == ECHILD && job != NULL)
1134153417Smaxim		job->state = JOBDONE;
1135238888Sjilles	if ((mode & DOWAIT_SIG) != 0) {
1136238888Sjilles		if (restore_sigchld)
1137238888Sjilles			sigaction(SIGCHLD, &osa, NULL);
1138238888Sjilles		sigprocmask(SIG_SETMASK, &omask, NULL);
1139238888Sjilles		INTON;
1140238888Sjilles	}
11411556Srgrimes	if (pid <= 0)
11421556Srgrimes		return pid;
11431556Srgrimes	INTOFF;
11441556Srgrimes	thisjob = NULL;
11451556Srgrimes	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1146216208Sjilles		if (jp->used && jp->nprocs > 0) {
11471556Srgrimes			done = 1;
11481556Srgrimes			stopped = 1;
11491556Srgrimes			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
11501556Srgrimes				if (sp->pid == -1)
11511556Srgrimes					continue;
1152263453Sjilles				if (sp->pid == pid && (sp->status == -1 ||
1153263453Sjilles				    WIFSTOPPED(sp->status))) {
115426104Ssteve					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1155100308Stjr						   (int)pid, sp->status,
1156100308Stjr						   status));
1157238865Sjilles					if (WIFCONTINUED(status)) {
1158238865Sjilles						sp->status = -1;
1159238865Sjilles						jp->state = 0;
1160238865Sjilles					} else
1161238865Sjilles						sp->status = status;
11621556Srgrimes					thisjob = jp;
11631556Srgrimes				}
11641556Srgrimes				if (sp->status == -1)
11651556Srgrimes					stopped = 0;
116626104Ssteve				else if (WIFSTOPPED(sp->status))
11671556Srgrimes					done = 0;
11681556Srgrimes			}
11691556Srgrimes			if (stopped) {		/* stopped or done */
11701556Srgrimes				int state = done? JOBDONE : JOBSTOPPED;
11711556Srgrimes				if (jp->state != state) {
1172213775Sjhb					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
11731556Srgrimes					jp->state = state;
1174209600Sjilles					if (jp != job) {
1175209600Sjilles						if (done && !jp->remembered &&
1176209600Sjilles						    !iflag && jp != bgjob)
1177209600Sjilles							freejob(jp);
11781556Srgrimes#if JOBS
1179209600Sjilles						else if (done)
1180209600Sjilles							deljob(jp);
11811556Srgrimes#endif
1182209600Sjilles					}
11831556Srgrimes				}
11841556Srgrimes			}
11851556Srgrimes		}
11861556Srgrimes	}
11871556Srgrimes	INTON;
1188216217Sjilles	if (!thisjob || thisjob->state == 0)
1189216217Sjilles		;
1190216217Sjilles	else if ((!rootshell || !iflag || thisjob == job) &&
1191216217Sjilles	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1192216217Sjilles		sig = 0;
1193216217Sjilles		coredump = 0;
1194216217Sjilles		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1195216217Sjilles			if (WIFSIGNALED(sp->status)) {
1196216217Sjilles				sig = WTERMSIG(sp->status);
1197216217Sjilles				coredump = WCOREDUMP(sp->status);
1198216217Sjilles			}
1199216217Sjilles		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1200244682Sjilles			sigstr = strsignal(sig);
1201244682Sjilles			if (sigstr != NULL)
1202244682Sjilles				out2str(sigstr);
120326104Ssteve			else
1204244682Sjilles				out2str("Unknown signal");
1205216217Sjilles			if (coredump)
1206218105Sjilles				out2str(" (core dumped)");
1207218105Sjilles			out2c('\n');
1208218105Sjilles			flushout(out2);
12091556Srgrimes		}
12101556Srgrimes	} else {
1211109627Stjr		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1212216217Sjilles		thisjob->changed = 1;
12131556Srgrimes	}
12141556Srgrimes	return pid;
12151556Srgrimes}
12161556Srgrimes
12171556Srgrimes
12181556Srgrimes
12191556Srgrimes/*
12201556Srgrimes * return 1 if there are stopped jobs, otherwise 0
12211556Srgrimes */
12221556Srgrimesint job_warning = 0;
12231556Srgrimesint
122490111Simpstoppedjobs(void)
12251556Srgrimes{
122625222Ssteve	int jobno;
122725222Ssteve	struct job *jp;
12281556Srgrimes
12291556Srgrimes	if (job_warning)
12301556Srgrimes		return (0);
12311556Srgrimes	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
12321556Srgrimes		if (jp->used == 0)
12331556Srgrimes			continue;
12341556Srgrimes		if (jp->state == JOBSTOPPED) {
1235199629Sjilles			out2fmt_flush("You have stopped jobs.\n");
12361556Srgrimes			job_warning = 2;
12371556Srgrimes			return (1);
12381556Srgrimes		}
12391556Srgrimes	}
12401556Srgrimes
12411556Srgrimes	return (0);
12421556Srgrimes}
12431556Srgrimes
1244208489Sjilles
1245213811Sobrienstatic void
1246208489Sjillescheckzombies(void)
1247208489Sjilles{
1248208489Sjilles	while (njobs > 0 && dowait(0, NULL) > 0)
1249208489Sjilles		;
1250208489Sjilles}
1251208489Sjilles
1252208489Sjilles
1253209600Sjillesint
1254209600Sjillesbackgndpidset(void)
1255209600Sjilles{
1256209600Sjilles	return backgndpid != -1;
1257209600Sjilles}
1258209600Sjilles
1259209600Sjilles
1260209600Sjillespid_t
1261209600Sjillesbackgndpidval(void)
1262209600Sjilles{
1263223024Sjilles	if (bgjob != NULL && !forcelocal)
1264209600Sjilles		bgjob->remembered = 1;
1265209600Sjilles	return backgndpid;
1266209600Sjilles}
1267209600Sjilles
12681556Srgrimes/*
12691556Srgrimes * Return a string identifying a command (to be printed by the
12701556Srgrimes * jobs command.
12711556Srgrimes */
12721556Srgrimes
1273213760Sobrienstatic char *cmdnextc;
1274213760Sobrienstatic int cmdnleft;
12751556Srgrimes#define MAXCMDTEXT	200
12761556Srgrimes
12771556Srgrimeschar *
127890111Simpcommandtext(union node *n)
127990111Simp{
12801556Srgrimes	char *name;
12811556Srgrimes
12821556Srgrimes	cmdnextc = name = ckmalloc(MAXCMDTEXT);
12831556Srgrimes	cmdnleft = MAXCMDTEXT - 4;
12841556Srgrimes	cmdtxt(n);
12851556Srgrimes	*cmdnextc = '\0';
12861556Srgrimes	return name;
12871556Srgrimes}
12881556Srgrimes
12891556Srgrimes
1290213811Sobrienstatic void
1291273152Sjillescmdtxtdogroup(union node *n)
1292273152Sjilles{
1293273152Sjilles	cmdputs("; do ");
1294273152Sjilles	cmdtxt(n);
1295273152Sjilles	cmdputs("; done");
1296273152Sjilles}
1297273152Sjilles
1298273152Sjilles
1299273152Sjillesstatic void
1300273152Sjillescmdtxtredir(union node *n, const char *op, int deffd)
1301273152Sjilles{
1302273152Sjilles	char s[2];
1303273152Sjilles
1304273152Sjilles	if (n->nfile.fd != deffd) {
1305273152Sjilles		s[0] = n->nfile.fd + '0';
1306273152Sjilles		s[1] = '\0';
1307273152Sjilles		cmdputs(s);
1308273152Sjilles	}
1309273152Sjilles	cmdputs(op);
1310273152Sjilles	if (n->type == NTOFD || n->type == NFROMFD) {
1311273152Sjilles		if (n->ndup.dupfd >= 0)
1312273152Sjilles			s[0] = n->ndup.dupfd + '0';
1313273152Sjilles		else
1314273152Sjilles			s[0] = '-';
1315273152Sjilles		s[1] = '\0';
1316273152Sjilles		cmdputs(s);
1317273152Sjilles	} else {
1318273152Sjilles		cmdtxt(n->nfile.fname);
1319273152Sjilles	}
1320273152Sjilles}
1321273152Sjilles
1322273152Sjilles
1323273152Sjillesstatic void
132490111Simpcmdtxt(union node *n)
132590111Simp{
13261556Srgrimes	union node *np;
13271556Srgrimes	struct nodelist *lp;
13281556Srgrimes
13291556Srgrimes	if (n == NULL)
13301556Srgrimes		return;
13311556Srgrimes	switch (n->type) {
13321556Srgrimes	case NSEMI:
13331556Srgrimes		cmdtxt(n->nbinary.ch1);
13341556Srgrimes		cmdputs("; ");
13351556Srgrimes		cmdtxt(n->nbinary.ch2);
13361556Srgrimes		break;
13371556Srgrimes	case NAND:
13381556Srgrimes		cmdtxt(n->nbinary.ch1);
13391556Srgrimes		cmdputs(" && ");
13401556Srgrimes		cmdtxt(n->nbinary.ch2);
13411556Srgrimes		break;
13421556Srgrimes	case NOR:
13431556Srgrimes		cmdtxt(n->nbinary.ch1);
13441556Srgrimes		cmdputs(" || ");
13451556Srgrimes		cmdtxt(n->nbinary.ch2);
13461556Srgrimes		break;
13471556Srgrimes	case NPIPE:
13481556Srgrimes		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
13491556Srgrimes			cmdtxt(lp->n);
13501556Srgrimes			if (lp->next)
13511556Srgrimes				cmdputs(" | ");
13521556Srgrimes		}
13531556Srgrimes		break;
13541556Srgrimes	case NSUBSHELL:
13551556Srgrimes		cmdputs("(");
13561556Srgrimes		cmdtxt(n->nredir.n);
13571556Srgrimes		cmdputs(")");
13581556Srgrimes		break;
13591556Srgrimes	case NREDIR:
13601556Srgrimes	case NBACKGND:
13611556Srgrimes		cmdtxt(n->nredir.n);
13621556Srgrimes		break;
13631556Srgrimes	case NIF:
13641556Srgrimes		cmdputs("if ");
13651556Srgrimes		cmdtxt(n->nif.test);
13661556Srgrimes		cmdputs("; then ");
13671556Srgrimes		cmdtxt(n->nif.ifpart);
13681556Srgrimes		cmdputs("...");
13691556Srgrimes		break;
13701556Srgrimes	case NWHILE:
13711556Srgrimes		cmdputs("while ");
1372273152Sjilles		cmdtxt(n->nbinary.ch1);
1373273152Sjilles		cmdtxtdogroup(n->nbinary.ch2);
1374273152Sjilles		break;
13751556Srgrimes	case NUNTIL:
13761556Srgrimes		cmdputs("until ");
13771556Srgrimes		cmdtxt(n->nbinary.ch1);
1378273152Sjilles		cmdtxtdogroup(n->nbinary.ch2);
13791556Srgrimes		break;
13801556Srgrimes	case NFOR:
13811556Srgrimes		cmdputs("for ");
13821556Srgrimes		cmdputs(n->nfor.var);
13831556Srgrimes		cmdputs(" in ...");
13841556Srgrimes		break;
13851556Srgrimes	case NCASE:
13861556Srgrimes		cmdputs("case ");
13871556Srgrimes		cmdputs(n->ncase.expr->narg.text);
13881556Srgrimes		cmdputs(" in ...");
13891556Srgrimes		break;
13901556Srgrimes	case NDEFUN:
13911556Srgrimes		cmdputs(n->narg.text);
13921556Srgrimes		cmdputs("() ...");
13931556Srgrimes		break;
1394246162Sjilles	case NNOT:
1395246162Sjilles		cmdputs("! ");
1396246162Sjilles		cmdtxt(n->nnot.com);
1397246162Sjilles		break;
13981556Srgrimes	case NCMD:
13991556Srgrimes		for (np = n->ncmd.args ; np ; np = np->narg.next) {
14001556Srgrimes			cmdtxt(np);
14011556Srgrimes			if (np->narg.next)
14021556Srgrimes				cmdputs(" ");
14031556Srgrimes		}
14041556Srgrimes		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
14051556Srgrimes			cmdputs(" ");
14061556Srgrimes			cmdtxt(np);
14071556Srgrimes		}
14081556Srgrimes		break;
14091556Srgrimes	case NARG:
14101556Srgrimes		cmdputs(n->narg.text);
14111556Srgrimes		break;
14121556Srgrimes	case NTO:
1413273152Sjilles		cmdtxtredir(n, ">", 1);
1414273152Sjilles		break;
14151556Srgrimes	case NAPPEND:
1416273152Sjilles		cmdtxtredir(n, ">>", 1);
1417273152Sjilles		break;
14181556Srgrimes	case NTOFD:
1419273152Sjilles		cmdtxtredir(n, ">&", 1);
1420273152Sjilles		break;
142196922Stjr	case NCLOBBER:
1422273152Sjilles		cmdtxtredir(n, ">|", 1);
1423273152Sjilles		break;
14241556Srgrimes	case NFROM:
1425273152Sjilles		cmdtxtredir(n, "<", 0);
1426273152Sjilles		break;
142766612Sbrian	case NFROMTO:
1428273152Sjilles		cmdtxtredir(n, "<>", 0);
1429273152Sjilles		break;
14301556Srgrimes	case NFROMFD:
1431273152Sjilles		cmdtxtredir(n, "<&", 0);
14321556Srgrimes		break;
14331556Srgrimes	case NHERE:
14341556Srgrimes	case NXHERE:
14351556Srgrimes		cmdputs("<<...");
14361556Srgrimes		break;
14371556Srgrimes	default:
14381556Srgrimes		cmdputs("???");
14391556Srgrimes		break;
14401556Srgrimes	}
14411556Srgrimes}
14421556Srgrimes
14431556Srgrimes
14441556Srgrimes
1445213811Sobrienstatic void
1446201053Sjillescmdputs(const char *s)
144790111Simp{
1448201053Sjilles	const char *p;
1449201053Sjilles	char *q;
145025222Ssteve	char c;
14511556Srgrimes	int subtype = 0;
14521556Srgrimes
14531556Srgrimes	if (cmdnleft <= 0)
14541556Srgrimes		return;
14551556Srgrimes	p = s;
14561556Srgrimes	q = cmdnextc;
14571556Srgrimes	while ((c = *p++) != '\0') {
14581556Srgrimes		if (c == CTLESC)
14591556Srgrimes			*q++ = *p++;
14601556Srgrimes		else if (c == CTLVAR) {
14611556Srgrimes			*q++ = '$';
14621556Srgrimes			if (--cmdnleft > 0)
14631556Srgrimes				*q++ = '{';
14641556Srgrimes			subtype = *p++;
1465216246Sjilles			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1466216246Sjilles				*q++ = '#';
14671556Srgrimes		} else if (c == '=' && subtype != 0) {
1468216246Sjilles			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1469216246Sjilles			if (*q)
1470216246Sjilles				q++;
1471216246Sjilles			else
1472216246Sjilles				cmdnleft++;
1473216246Sjilles			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1474216246Sjilles			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1475216246Sjilles			    --cmdnleft > 0)
1476216246Sjilles				*q = q[-1], q++;
14771556Srgrimes			subtype = 0;
14781556Srgrimes		} else if (c == CTLENDVAR) {
14791556Srgrimes			*q++ = '}';
1480216246Sjilles		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1481216246Sjilles			cmdnleft -= 5;
1482216246Sjilles			if (cmdnleft > 0) {
1483216246Sjilles				*q++ = '$';
1484216246Sjilles				*q++ = '(';
1485216246Sjilles				*q++ = '.';
1486216246Sjilles				*q++ = '.';
1487216246Sjilles				*q++ = '.';
1488216246Sjilles				*q++ = ')';
1489216246Sjilles			}
1490216246Sjilles		} else if (c == CTLARI) {
1491216246Sjilles			cmdnleft -= 2;
1492216246Sjilles			if (cmdnleft > 0) {
1493216246Sjilles				*q++ = '$';
1494216246Sjilles				*q++ = '(';
1495216246Sjilles				*q++ = '(';
1496216246Sjilles			}
1497216246Sjilles			p++;
1498216246Sjilles		} else if (c == CTLENDARI) {
1499216246Sjilles			if (--cmdnleft > 0) {
1500216246Sjilles				*q++ = ')';
1501216246Sjilles				*q++ = ')';
1502216246Sjilles			}
1503216246Sjilles		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1504216246Sjilles			cmdnleft++; /* ignore */
15051556Srgrimes		else
15061556Srgrimes			*q++ = c;
15071556Srgrimes		if (--cmdnleft <= 0) {
15081556Srgrimes			*q++ = '.';
15091556Srgrimes			*q++ = '.';
15101556Srgrimes			*q++ = '.';
15111556Srgrimes			break;
15121556Srgrimes		}
15131556Srgrimes	}
15141556Srgrimes	cmdnextc = q;
15151556Srgrimes}
1516