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$");
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"
60249242Sjilles#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 */
8028346SsteveMKINIT pid_t backgndpid = -1;	/* pid of last background process */
81209600SjillesMKINIT 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
8638536Scracauerint in_waitcmd = 0;		/* are we in waitcmd()? */
8738950Scracauerint in_dowait = 0;		/* are we in dowait()? */
8838536Scracauervolatile sig_atomic_t breakwaitcmd = 0;	/* should wait be terminated? */
8999762Stjrstatic int ttyfd = -1;
901556Srgrimes
9120425Ssteve#if JOBS
92213811Sobrienstatic void restartjob(struct job *);
9320425Ssteve#endif
94213811Sobrienstatic void freejob(struct job *);
95213811Sobrienstatic struct job *getjob(char *);
96213811Sobrienstatic pid_t dowait(int, struct job *);
97213811Sobrienstatic pid_t waitproc(int, int *);
98213811Sobrienstatic void checkzombies(void);
99213811Sobrienstatic void cmdtxt(union node *);
100213811Sobrienstatic void cmdputs(const char *);
10197659Stjr#if JOBS
102213811Sobrienstatic void setcurjob(struct job *);
103213811Sobrienstatic void deljob(struct job *);
104213811Sobrienstatic struct job *getcurjob(struct job *);
10597659Stjr#endif
106216217Sjillesstatic void printjobcmd(struct job *);
107216217Sjillesstatic void showjob(struct job *, int);
1081556Srgrimes
1091556Srgrimes
1101556Srgrimes/*
1111556Srgrimes * Turn job control on and off.
1121556Srgrimes */
1131556Srgrimes
1141556SrgrimesMKINIT int jobctl;
1151556Srgrimes
11620425Ssteve#if JOBS
1171556Srgrimesvoid
11890111Simpsetjobctl(int on)
11917987Speter{
12099762Stjr	int i;
1211556Srgrimes
1221556Srgrimes	if (on == jobctl || rootshell == 0)
1231556Srgrimes		return;
1241556Srgrimes	if (on) {
12599762Stjr		if (ttyfd != -1)
12699762Stjr			close(ttyfd);
12799762Stjr		if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
12899762Stjr			i = 0;
12999762Stjr			while (i <= 2 && !isatty(i))
13099762Stjr				i++;
131109927Stjr			if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
13299762Stjr				goto out;
13399762Stjr		}
134109927Stjr		if (ttyfd < 10) {
135109927Stjr			/*
136109927Stjr			 * Keep our TTY file descriptor out of the way of
137109927Stjr			 * the user's redirections.
138109927Stjr			 */
139109927Stjr			if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
140109927Stjr				close(ttyfd);
141109927Stjr				ttyfd = -1;
142109927Stjr				goto out;
143109927Stjr			}
144109927Stjr			close(ttyfd);
145109927Stjr			ttyfd = i;
146109927Stjr		}
147103223Snectar		if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
14899762Stjr			close(ttyfd);
14999762Stjr			ttyfd = -1;
15099762Stjr			goto out;
15199762Stjr		}
1521556Srgrimes		do { /* while we are in the background */
15399762Stjr			initialpgrp = tcgetpgrp(ttyfd);
15420425Ssteve			if (initialpgrp < 0) {
155199629Sjillesout:				out2fmt_flush("sh: can't access tty; job control turned off\n");
1561556Srgrimes				mflag = 0;
1571556Srgrimes				return;
1581556Srgrimes			}
159216400Sjilles			if (initialpgrp != getpgrp()) {
160216400Sjilles				kill(0, SIGTTIN);
1611556Srgrimes				continue;
1621556Srgrimes			}
1631556Srgrimes		} while (0);
1641556Srgrimes		setsignal(SIGTSTP);
1651556Srgrimes		setsignal(SIGTTOU);
1661556Srgrimes		setsignal(SIGTTIN);
16717987Speter		setpgid(0, rootpid);
16899762Stjr		tcsetpgrp(ttyfd, rootpid);
1691556Srgrimes	} else { /* turning job control off */
17017987Speter		setpgid(0, initialpgrp);
17199762Stjr		tcsetpgrp(ttyfd, initialpgrp);
17299762Stjr		close(ttyfd);
17399762Stjr		ttyfd = -1;
1741556Srgrimes		setsignal(SIGTSTP);
1751556Srgrimes		setsignal(SIGTTOU);
1761556Srgrimes		setsignal(SIGTTIN);
1771556Srgrimes	}
1781556Srgrimes	jobctl = on;
1791556Srgrimes}
18020425Ssteve#endif
1811556Srgrimes
1821556Srgrimes
1831556Srgrimes#if JOBS
18417987Speterint
18590111Simpfgcmd(int argc __unused, char **argv)
18617987Speter{
1871556Srgrimes	struct job *jp;
188100308Stjr	pid_t pgrp;
1891556Srgrimes	int status;
1901556Srgrimes
1911556Srgrimes	jp = getjob(argv[1]);
1921556Srgrimes	if (jp->jobctl == 0)
1931556Srgrimes		error("job not created under job control");
194216217Sjilles	printjobcmd(jp);
19596933Stjr	flushout(&output);
1961556Srgrimes	pgrp = jp->ps[0].pid;
19799762Stjr	tcsetpgrp(ttyfd, pgrp);
1981556Srgrimes	restartjob(jp);
199100305Stjr	jp->foreground = 1;
2001556Srgrimes	INTOFF;
20145916Scracauer	status = waitforjob(jp, (int *)NULL);
2021556Srgrimes	INTON;
2031556Srgrimes	return status;
2041556Srgrimes}
2051556Srgrimes
2061556Srgrimes
20717987Speterint
20890111Simpbgcmd(int argc, char **argv)
20917987Speter{
2101556Srgrimes	struct job *jp;
2111556Srgrimes
2121556Srgrimes	do {
2131556Srgrimes		jp = getjob(*++argv);
2141556Srgrimes		if (jp->jobctl == 0)
2151556Srgrimes			error("job not created under job control");
21696933Stjr		if (jp->state == JOBDONE)
21796933Stjr			continue;
2181556Srgrimes		restartjob(jp);
219100305Stjr		jp->foreground = 0;
220216400Sjilles		out1fmt("[%td] ", jp - jobtab + 1);
221216217Sjilles		printjobcmd(jp);
2221556Srgrimes	} while (--argc > 1);
2231556Srgrimes	return 0;
2241556Srgrimes}
2251556Srgrimes
2261556Srgrimes
227213811Sobrienstatic void
22890111Simprestartjob(struct job *jp)
22917987Speter{
2301556Srgrimes	struct procstat *ps;
2311556Srgrimes	int i;
2321556Srgrimes
2331556Srgrimes	if (jp->state == JOBDONE)
2341556Srgrimes		return;
23597660Stjr	setcurjob(jp);
2361556Srgrimes	INTOFF;
237216400Sjilles	kill(-jp->ps[0].pid, SIGCONT);
2381556Srgrimes	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
23926104Ssteve		if (WIFSTOPPED(ps->status)) {
2401556Srgrimes			ps->status = -1;
2411556Srgrimes			jp->state = 0;
2421556Srgrimes		}
2431556Srgrimes	}
2441556Srgrimes	INTON;
2451556Srgrimes}
2461556Srgrimes#endif
2471556Srgrimes
2481556Srgrimes
2491556Srgrimesint
25097669Stjrjobscmd(int argc, char *argv[])
25117987Speter{
25297669Stjr	char *id;
253163085Sstefanf	int ch, mode;
25497669Stjr
25597669Stjr	optind = optreset = 1;
256100663Stjr	opterr = 0;
257163085Sstefanf	mode = SHOWJOBS_DEFAULT;
258163085Sstefanf	while ((ch = getopt(argc, argv, "lps")) != -1) {
25997669Stjr		switch (ch) {
26097669Stjr		case 'l':
261163085Sstefanf			mode = SHOWJOBS_VERBOSE;
26297669Stjr			break;
263163085Sstefanf		case 'p':
264163085Sstefanf			mode = SHOWJOBS_PGIDS;
265163085Sstefanf			break;
26697669Stjr		case 's':
267163085Sstefanf			mode = SHOWJOBS_PIDS;
26897669Stjr			break;
26997669Stjr		case '?':
27097669Stjr		default:
27197669Stjr			error("unknown option: -%c", optopt);
27297669Stjr		}
27397669Stjr	}
27497669Stjr	argc -= optind;
27597669Stjr	argv += optind;
27697669Stjr
27797669Stjr	if (argc == 0)
278163085Sstefanf		showjobs(0, mode);
27997669Stjr	else
28097669Stjr		while ((id = *argv++) != NULL)
281216217Sjilles			showjob(getjob(id), mode);
28297669Stjr
28397669Stjr	return (0);
2841556Srgrimes}
2851556Srgrimes
286213811Sobrienstatic void
287216217Sjillesprintjobcmd(struct job *jp)
28897663Stjr{
289216217Sjilles	struct procstat *ps;
290216217Sjilles	int i;
291216217Sjilles
292216217Sjilles	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
293216217Sjilles		out1str(ps->cmd);
294216217Sjilles		if (i > 0)
295216217Sjilles			out1str(" | ");
296216217Sjilles	}
297216217Sjilles	out1c('\n');
298216217Sjilles}
299216217Sjilles
300216217Sjillesstatic void
301216217Sjillesshowjob(struct job *jp, int mode)
302216217Sjilles{
30397663Stjr	char s[64];
304216217Sjilles	char statestr[64];
30597663Stjr	struct procstat *ps;
30697669Stjr	struct job *j;
30797669Stjr	int col, curr, i, jobno, prev, procno;
30897669Stjr	char c;
3091556Srgrimes
310163085Sstefanf	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
31197663Stjr	jobno = jp - jobtab + 1;
31297669Stjr	curr = prev = 0;
31397669Stjr#if JOBS
31497669Stjr	if ((j = getcurjob(NULL)) != NULL) {
31597669Stjr		curr = j - jobtab + 1;
31697669Stjr		if ((j = getcurjob(j)) != NULL)
31797669Stjr			prev = j - jobtab + 1;
31897669Stjr	}
31997669Stjr#endif
320216217Sjilles	ps = jp->ps + jp->nprocs - 1;
321216217Sjilles	if (jp->state == 0) {
322216217Sjilles		strcpy(statestr, "Running");
323216217Sjilles#if JOBS
324216217Sjilles	} else if (jp->state == JOBSTOPPED) {
325216217Sjilles		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
326216217Sjilles			ps--;
327216217Sjilles		if (WIFSTOPPED(ps->status))
328216217Sjilles			i = WSTOPSIG(ps->status);
329216217Sjilles		else
330216217Sjilles			i = -1;
331216217Sjilles		if (i > 0 && i < sys_nsig && sys_siglist[i])
332216217Sjilles			strcpy(statestr, sys_siglist[i]);
333216217Sjilles		else
334216217Sjilles			strcpy(statestr, "Suspended");
335216217Sjilles#endif
336216217Sjilles	} else if (WIFEXITED(ps->status)) {
337216217Sjilles		if (WEXITSTATUS(ps->status) == 0)
338216217Sjilles			strcpy(statestr, "Done");
339216217Sjilles		else
340216220Sjilles			fmtstr(statestr, 64, "Done(%d)",
341216217Sjilles			    WEXITSTATUS(ps->status));
342216217Sjilles	} else {
343216217Sjilles		i = WTERMSIG(ps->status);
344216217Sjilles		if (i > 0 && i < sys_nsig && sys_siglist[i])
345216217Sjilles			strcpy(statestr, sys_siglist[i]);
346216217Sjilles		else
347216217Sjilles			fmtstr(statestr, 64, "Signal %d", i);
348216217Sjilles		if (WCOREDUMP(ps->status))
349216217Sjilles			strcat(statestr, " (core dumped)");
350216217Sjilles	}
351216217Sjilles
35297663Stjr	for (ps = jp->ps ; ; ps++) {	/* for each process */
353163085Sstefanf		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
354216199Sjilles			out1fmt("%d\n", (int)ps->pid);
35597669Stjr			goto skip;
35697669Stjr		}
357216217Sjilles		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
35897669Stjr			goto skip;
35997819Stjr		if (jobno == curr && ps == jp->ps)
36097669Stjr			c = '+';
36197819Stjr		else if (jobno == prev && ps == jp->ps)
36297669Stjr			c = '-';
36397669Stjr		else
36497669Stjr			c = ' ';
36597663Stjr		if (ps == jp->ps)
36697669Stjr			fmtstr(s, 64, "[%d] %c ", jobno, c);
36797663Stjr		else
36897816Stjr			fmtstr(s, 64, "    %c ", c);
36997663Stjr		out1str(s);
37097663Stjr		col = strlen(s);
371163085Sstefanf		if (mode == SHOWJOBS_VERBOSE) {
372100308Stjr			fmtstr(s, 64, "%d ", (int)ps->pid);
37397669Stjr			out1str(s);
37497669Stjr			col += strlen(s);
37597669Stjr		}
376216217Sjilles		if (ps == jp->ps) {
377216217Sjilles			out1str(statestr);
378216217Sjilles			col += strlen(statestr);
37997663Stjr		}
38097663Stjr		do {
38197663Stjr			out1c(' ');
38297663Stjr			col++;
38397663Stjr		} while (col < 30);
384216217Sjilles		if (mode == SHOWJOBS_VERBOSE) {
385216217Sjilles			out1str(ps->cmd);
386216217Sjilles			out1c('\n');
387216217Sjilles		} else
388216217Sjilles			printjobcmd(jp);
38997669Stjrskip:		if (--procno <= 0)
39097663Stjr			break;
39197663Stjr	}
39297663Stjr}
39397663Stjr
3941556Srgrimes/*
3951556Srgrimes * Print a list of jobs.  If "change" is nonzero, only print jobs whose
3961556Srgrimes * statuses have changed since the last call to showjobs.
3971556Srgrimes *
3981556Srgrimes * If the shell is interrupted in the process of creating a job, the
3991556Srgrimes * result may be a job structure containing zero processes.  Such structures
4001556Srgrimes * will be freed here.
4011556Srgrimes */
4021556Srgrimes
4031556Srgrimesvoid
404163085Sstefanfshowjobs(int change, int mode)
40517987Speter{
4061556Srgrimes	int jobno;
4071556Srgrimes	struct job *jp;
4081556Srgrimes
4091556Srgrimes	TRACE(("showjobs(%d) called\n", change));
410208489Sjilles	checkzombies();
4111556Srgrimes	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
4121556Srgrimes		if (! jp->used)
4131556Srgrimes			continue;
4141556Srgrimes		if (jp->nprocs == 0) {
4151556Srgrimes			freejob(jp);
4161556Srgrimes			continue;
4171556Srgrimes		}
4181556Srgrimes		if (change && ! jp->changed)
4191556Srgrimes			continue;
420216217Sjilles		showjob(jp, mode);
4211556Srgrimes		jp->changed = 0;
422209600Sjilles		/* Hack: discard jobs for which $! has not been referenced
423209600Sjilles		 * in interactive mode when they terminate.
424209600Sjilles		 */
425209600Sjilles		if (jp->state == JOBDONE && !jp->remembered &&
426209600Sjilles				(iflag || jp != bgjob)) {
4271556Srgrimes			freejob(jp);
4281556Srgrimes		}
4291556Srgrimes	}
4301556Srgrimes}
4311556Srgrimes
4321556Srgrimes
4331556Srgrimes/*
4341556Srgrimes * Mark a job structure as unused.
4351556Srgrimes */
4361556Srgrimes
437213811Sobrienstatic void
43890111Simpfreejob(struct job *jp)
43990111Simp{
4401556Srgrimes	struct procstat *ps;
4411556Srgrimes	int i;
4421556Srgrimes
4431556Srgrimes	INTOFF;
444209600Sjilles	if (bgjob == jp)
445209600Sjilles		bgjob = NULL;
4461556Srgrimes	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
4471556Srgrimes		if (ps->cmd != nullstr)
4481556Srgrimes			ckfree(ps->cmd);
4491556Srgrimes	}
4501556Srgrimes	if (jp->ps != &jp->ps0)
4511556Srgrimes		ckfree(jp->ps);
4521556Srgrimes	jp->used = 0;
4531556Srgrimes#if JOBS
45497659Stjr	deljob(jp);
4551556Srgrimes#endif
4561556Srgrimes	INTON;
4571556Srgrimes}
4581556Srgrimes
4591556Srgrimes
4601556Srgrimes
4611556Srgrimesint
462252617Sjilleswaitcmd(int argc __unused, char **argv __unused)
46317987Speter{
4641556Srgrimes	struct job *job;
46526104Ssteve	int status, retval;
4661556Srgrimes	struct job *jp;
4671556Srgrimes
468252617Sjilles	nextopt("");
469252617Sjilles	if (*argptr != NULL) {
470252617Sjilles		job = getjob(*argptr);
4711556Srgrimes	} else {
4721556Srgrimes		job = NULL;
4731556Srgrimes	}
47438536Scracauer
47538536Scracauer	/*
47638536Scracauer	 * Loop until a process is terminated or stopped, or a SIGINT is
47738536Scracauer	 * received.
47838536Scracauer	 */
47938536Scracauer
48038521Scracauer	in_waitcmd++;
48138536Scracauer	do {
4821556Srgrimes		if (job != NULL) {
4831556Srgrimes			if (job->state) {
4841556Srgrimes				status = job->ps[job->nprocs - 1].status;
48526104Ssteve				if (WIFEXITED(status))
48626104Ssteve					retval = WEXITSTATUS(status);
4871556Srgrimes#if JOBS
48826104Ssteve				else if (WIFSTOPPED(status))
48926104Ssteve					retval = WSTOPSIG(status) + 128;
4901556Srgrimes#endif
4911556Srgrimes				else
49226104Ssteve					retval = WTERMSIG(status) + 128;
493209600Sjilles				if (! iflag || ! job->changed)
4941556Srgrimes					freejob(job);
495209600Sjilles				else {
496209600Sjilles					job->remembered = 0;
497209600Sjilles					if (job == bgjob)
498209600Sjilles						bgjob = NULL;
499209600Sjilles				}
50038536Scracauer				in_waitcmd--;
50126104Ssteve				return retval;
5021556Srgrimes			}
5031556Srgrimes		} else {
504209600Sjilles			for (jp = jobtab ; jp < jobtab + njobs; jp++)
505209600Sjilles				if (jp->used && jp->state == JOBDONE) {
506209600Sjilles					if (! iflag || ! jp->changed)
507209600Sjilles						freejob(jp);
508209600Sjilles					else {
509209600Sjilles						jp->remembered = 0;
510209600Sjilles						if (jp == bgjob)
511209600Sjilles							bgjob = NULL;
512209600Sjilles					}
513209600Sjilles				}
5141556Srgrimes			for (jp = jobtab ; ; jp++) {
5151556Srgrimes				if (jp >= jobtab + njobs) {	/* no running procs */
51638536Scracauer					in_waitcmd--;
5171556Srgrimes					return 0;
5181556Srgrimes				}
5191556Srgrimes				if (jp->used && jp->state == 0)
5201556Srgrimes					break;
5211556Srgrimes			}
5221556Srgrimes		}
52338521Scracauer	} while (dowait(1, (struct job *)NULL) != -1);
52438521Scracauer	in_waitcmd--;
52538521Scracauer
52638521Scracauer	return 0;
5271556Srgrimes}
5281556Srgrimes
5291556Srgrimes
5301556Srgrimes
53117987Speterint
53290111Simpjobidcmd(int argc __unused, char **argv)
53317987Speter{
5341556Srgrimes	struct job *jp;
5351556Srgrimes	int i;
5361556Srgrimes
5371556Srgrimes	jp = getjob(argv[1]);
5381556Srgrimes	for (i = 0 ; i < jp->nprocs ; ) {
539100308Stjr		out1fmt("%d", (int)jp->ps[i].pid);
5401556Srgrimes		out1c(++i < jp->nprocs? ' ' : '\n');
5411556Srgrimes	}
5421556Srgrimes	return 0;
5431556Srgrimes}
5441556Srgrimes
5451556Srgrimes
5461556Srgrimes
5471556Srgrimes/*
5481556Srgrimes * Convert a job name to a job structure.
5491556Srgrimes */
5501556Srgrimes
551213811Sobrienstatic struct job *
55290111Simpgetjob(char *name)
55390111Simp{
5541556Srgrimes	int jobno;
55597688Stjr	struct job *found, *jp;
556100308Stjr	pid_t pid;
5571556Srgrimes	int i;
5581556Srgrimes
5591556Srgrimes	if (name == NULL) {
5601556Srgrimes#if JOBS
56197659Stjrcurrentjob:	if ((jp = getcurjob(NULL)) == NULL)
5621556Srgrimes			error("No current job");
56397659Stjr		return (jp);
5641556Srgrimes#else
5651556Srgrimes		error("No current job");
5661556Srgrimes#endif
5671556Srgrimes	} else if (name[0] == '%') {
5681556Srgrimes		if (is_digit(name[1])) {
5691556Srgrimes			jobno = number(name + 1);
5701556Srgrimes			if (jobno > 0 && jobno <= njobs
5711556Srgrimes			 && jobtab[jobno - 1].used != 0)
5721556Srgrimes				return &jobtab[jobno - 1];
5731556Srgrimes#if JOBS
5741556Srgrimes		} else if (name[1] == '%' && name[2] == '\0') {
5751556Srgrimes			goto currentjob;
57697688Stjr		} else if (name[1] == '+' && name[2] == '\0') {
57797688Stjr			goto currentjob;
57897688Stjr		} else if (name[1] == '-' && name[2] == '\0') {
57997688Stjr			if ((jp = getcurjob(NULL)) == NULL ||
58097688Stjr			    (jp = getcurjob(jp)) == NULL)
58197688Stjr				error("No previous job");
58297688Stjr			return (jp);
5831556Srgrimes#endif
58497688Stjr		} else if (name[1] == '?') {
58597688Stjr			found = NULL;
58697688Stjr			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
58797688Stjr				if (jp->used && jp->nprocs > 0
58897688Stjr				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
58997688Stjr					if (found)
59097688Stjr						error("%s: ambiguous", name);
59197688Stjr					found = jp;
59297688Stjr				}
59397688Stjr			}
59497688Stjr			if (found != NULL)
59597688Stjr				return (found);
5961556Srgrimes		} else {
59797688Stjr			found = NULL;
5981556Srgrimes			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
5991556Srgrimes				if (jp->used && jp->nprocs > 0
6001556Srgrimes				 && prefix(name + 1, jp->ps[0].cmd)) {
6011556Srgrimes					if (found)
6021556Srgrimes						error("%s: ambiguous", name);
6031556Srgrimes					found = jp;
6041556Srgrimes				}
6051556Srgrimes			}
6061556Srgrimes			if (found)
6071556Srgrimes				return found;
6081556Srgrimes		}
6091556Srgrimes	} else if (is_number(name)) {
610100308Stjr		pid = (pid_t)number(name);
6111556Srgrimes		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6121556Srgrimes			if (jp->used && jp->nprocs > 0
6131556Srgrimes			 && jp->ps[jp->nprocs - 1].pid == pid)
6141556Srgrimes				return jp;
6151556Srgrimes		}
6161556Srgrimes	}
6171556Srgrimes	error("No such job: %s", name);
61817987Speter	/*NOTREACHED*/
61917987Speter	return NULL;
6201556Srgrimes}
6211556Srgrimes
6221556Srgrimes
623216629Sjillespid_t
624216629Sjillesgetjobpgrp(char *name)
625216629Sjilles{
626216629Sjilles	struct job *jp;
6271556Srgrimes
628216629Sjilles	jp = getjob(name);
629216629Sjilles	return -jp->ps[0].pid;
630216629Sjilles}
631216629Sjilles
6321556Srgrimes/*
6331556Srgrimes * Return a new job structure,
6341556Srgrimes */
6351556Srgrimes
6361556Srgrimesstruct job *
63790111Simpmakejob(union node *node __unused, int nprocs)
63817987Speter{
6391556Srgrimes	int i;
6401556Srgrimes	struct job *jp;
6411556Srgrimes
6421556Srgrimes	for (i = njobs, jp = jobtab ; ; jp++) {
6431556Srgrimes		if (--i < 0) {
6441556Srgrimes			INTOFF;
6451556Srgrimes			if (njobs == 0) {
6461556Srgrimes				jobtab = ckmalloc(4 * sizeof jobtab[0]);
64797664Stjr#if JOBS
64897659Stjr				jobmru = NULL;
64997664Stjr#endif
6501556Srgrimes			} else {
6511556Srgrimes				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
65217987Speter				memcpy(jp, jobtab, njobs * sizeof jp[0]);
65397659Stjr#if JOBS
65497659Stjr				/* Relocate `next' pointers and list head */
65599760Stjr				if (jobmru != NULL)
65699760Stjr					jobmru = &jp[jobmru - jobtab];
65797659Stjr				for (i = 0; i < njobs; i++)
65897659Stjr					if (jp[i].next != NULL)
65997659Stjr						jp[i].next = &jp[jp[i].next -
66097659Stjr						    jobtab];
66197659Stjr#endif
662209600Sjilles				if (bgjob != NULL)
663209600Sjilles					bgjob = &jp[bgjob - jobtab];
66420425Ssteve				/* Relocate `ps' pointers */
66520425Ssteve				for (i = 0; i < njobs; i++)
66620425Ssteve					if (jp[i].ps == &jobtab[i].ps0)
66720425Ssteve						jp[i].ps = &jp[i].ps0;
6681556Srgrimes				ckfree(jobtab);
6691556Srgrimes				jobtab = jp;
6701556Srgrimes			}
6711556Srgrimes			jp = jobtab + njobs;
6721556Srgrimes			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6731556Srgrimes			INTON;
6741556Srgrimes			break;
6751556Srgrimes		}
6761556Srgrimes		if (jp->used == 0)
6771556Srgrimes			break;
6781556Srgrimes	}
6791556Srgrimes	INTOFF;
6801556Srgrimes	jp->state = 0;
6811556Srgrimes	jp->used = 1;
6821556Srgrimes	jp->changed = 0;
6831556Srgrimes	jp->nprocs = 0;
684100305Stjr	jp->foreground = 0;
685209600Sjilles	jp->remembered = 0;
6861556Srgrimes#if JOBS
6871556Srgrimes	jp->jobctl = jobctl;
68897659Stjr	jp->next = NULL;
6891556Srgrimes#endif
6901556Srgrimes	if (nprocs > 1) {
6911556Srgrimes		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
6921556Srgrimes	} else {
6931556Srgrimes		jp->ps = &jp->ps0;
6941556Srgrimes	}
6951556Srgrimes	INTON;
696213775Sjhb	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
69717987Speter	    jp - jobtab + 1));
6981556Srgrimes	return jp;
6998855Srgrimes}
7001556Srgrimes
70197659Stjr#if JOBS
702213811Sobrienstatic void
70397659Stjrsetcurjob(struct job *cj)
70497659Stjr{
70597659Stjr	struct job *jp, *prev;
7061556Srgrimes
70797659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
70897659Stjr		if (jp == cj) {
70997659Stjr			if (prev != NULL)
71097659Stjr				prev->next = jp->next;
71197659Stjr			else
71297659Stjr				jobmru = jp->next;
71397659Stjr			jp->next = jobmru;
71497659Stjr			jobmru = cj;
71597659Stjr			return;
71697659Stjr		}
71797659Stjr	}
71897659Stjr	cj->next = jobmru;
71997659Stjr	jobmru = cj;
72097659Stjr}
72197659Stjr
722213811Sobrienstatic void
72397659Stjrdeljob(struct job *j)
72497659Stjr{
72597659Stjr	struct job *jp, *prev;
72697659Stjr
72797659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
72897659Stjr		if (jp == j) {
72997659Stjr			if (prev != NULL)
73097659Stjr				prev->next = jp->next;
73197659Stjr			else
73297659Stjr				jobmru = jp->next;
73397659Stjr			return;
73497659Stjr		}
73597659Stjr	}
73697659Stjr}
73797659Stjr
7381556Srgrimes/*
73997659Stjr * Return the most recently used job that isn't `nj', and preferably one
74097659Stjr * that is stopped.
74197659Stjr */
742213811Sobrienstatic struct job *
74397659Stjrgetcurjob(struct job *nj)
74497659Stjr{
74597659Stjr	struct job *jp;
74697659Stjr
74797659Stjr	/* Try to find a stopped one.. */
74897659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
74997659Stjr		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
75097659Stjr			return (jp);
75197659Stjr	/* Otherwise the most recently used job that isn't `nj' */
75297659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
75397659Stjr		if (jp->used && jp != nj)
75497659Stjr			return (jp);
75597659Stjr
75697659Stjr	return (NULL);
75797659Stjr}
75897659Stjr
75997659Stjr#endif
76097659Stjr
76197659Stjr/*
7621556Srgrimes * Fork of a subshell.  If we are doing job control, give the subshell its
7631556Srgrimes * own process group.  Jp is a job structure that the job is to be added to.
7641556Srgrimes * N is the command that will be evaluated by the child.  Both jp and n may
7651556Srgrimes * be NULL.  The mode parameter can be one of the following:
7661556Srgrimes *	FORK_FG - Fork off a foreground process.
7671556Srgrimes *	FORK_BG - Fork off a background process.
7681556Srgrimes *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
7691556Srgrimes *		     process group even if job control is on.
7701556Srgrimes *
7711556Srgrimes * When job control is turned off, background processes have their standard
7721556Srgrimes * input redirected to /dev/null (except for the second and later processes
7731556Srgrimes * in a pipeline).
7741556Srgrimes */
7751556Srgrimes
776100308Stjrpid_t
77790111Simpforkshell(struct job *jp, union node *n, int mode)
77817987Speter{
779100308Stjr	pid_t pid;
780100308Stjr	pid_t pgrp;
7811556Srgrimes
782213775Sjhb	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
78317987Speter	    mode));
7841556Srgrimes	INTOFF;
785216208Sjilles	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
786208489Sjilles		checkzombies();
787112341Stjr	flushall();
7881556Srgrimes	pid = fork();
7891556Srgrimes	if (pid == -1) {
7901556Srgrimes		TRACE(("Fork failed, errno=%d\n", errno));
7911556Srgrimes		INTON;
79253891Scracauer		error("Cannot fork: %s", strerror(errno));
7931556Srgrimes	}
7941556Srgrimes	if (pid == 0) {
7951556Srgrimes		struct job *p;
7961556Srgrimes		int wasroot;
7971556Srgrimes		int i;
7981556Srgrimes
799100308Stjr		TRACE(("Child shell %d\n", (int)getpid()));
8001556Srgrimes		wasroot = rootshell;
8011556Srgrimes		rootshell = 0;
802200998Sjilles		handler = &main_handler;
8031556Srgrimes		closescript();
8041556Srgrimes		INTON;
805223024Sjilles		forcelocal = 0;
8061556Srgrimes		clear_traps();
8071556Srgrimes#if JOBS
8081556Srgrimes		jobctl = 0;		/* do job control only in root shell */
8091556Srgrimes		if (wasroot && mode != FORK_NOJOB && mflag) {
8101556Srgrimes			if (jp == NULL || jp->nprocs == 0)
8111556Srgrimes				pgrp = getpid();
8121556Srgrimes			else
8131556Srgrimes				pgrp = jp->ps[0].pid;
81421352Ssteve			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
8151556Srgrimes				/*** this causes superfluous TIOCSPGRPS ***/
81699762Stjr				if (tcsetpgrp(ttyfd, pgrp) < 0)
81720425Ssteve					error("tcsetpgrp failed, errno=%d", errno);
8181556Srgrimes			}
8191556Srgrimes			setsignal(SIGTSTP);
8201556Srgrimes			setsignal(SIGTTOU);
8211556Srgrimes		} else if (mode == FORK_BG) {
8221556Srgrimes			ignoresig(SIGINT);
8231556Srgrimes			ignoresig(SIGQUIT);
8241556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8251556Srgrimes			    ! fd0_redirected_p ()) {
8261556Srgrimes				close(0);
82769793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
828222684Sjilles					error("cannot open %s: %s",
82969793Sobrien					    _PATH_DEVNULL, strerror(errno));
8301556Srgrimes			}
8311556Srgrimes		}
8321556Srgrimes#else
8331556Srgrimes		if (mode == FORK_BG) {
8341556Srgrimes			ignoresig(SIGINT);
8351556Srgrimes			ignoresig(SIGQUIT);
8361556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8371556Srgrimes			    ! fd0_redirected_p ()) {
8381556Srgrimes				close(0);
83969793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
840222684Sjilles					error("cannot open %s: %s",
84169793Sobrien					    _PATH_DEVNULL, strerror(errno));
8421556Srgrimes			}
8431556Srgrimes		}
8441556Srgrimes#endif
845102051Stjr		INTOFF;
846102051Stjr		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
847102051Stjr			if (p->used)
848102051Stjr				freejob(p);
849102051Stjr		INTON;
8501556Srgrimes		if (wasroot && iflag) {
8511556Srgrimes			setsignal(SIGINT);
8521556Srgrimes			setsignal(SIGQUIT);
8531556Srgrimes			setsignal(SIGTERM);
8541556Srgrimes		}
8551556Srgrimes		return pid;
8561556Srgrimes	}
8571556Srgrimes	if (rootshell && mode != FORK_NOJOB && mflag) {
8581556Srgrimes		if (jp == NULL || jp->nprocs == 0)
8591556Srgrimes			pgrp = pid;
8601556Srgrimes		else
8611556Srgrimes			pgrp = jp->ps[0].pid;
86217987Speter		setpgid(pid, pgrp);
8631556Srgrimes	}
864209600Sjilles	if (mode == FORK_BG) {
865209600Sjilles		if (bgjob != NULL && bgjob->state == JOBDONE &&
866209600Sjilles		    !bgjob->remembered && !iflag)
867209600Sjilles			freejob(bgjob);
8681556Srgrimes		backgndpid = pid;		/* set $! */
869209600Sjilles		bgjob = jp;
870209600Sjilles	}
8711556Srgrimes	if (jp) {
8721556Srgrimes		struct procstat *ps = &jp->ps[jp->nprocs++];
8731556Srgrimes		ps->pid = pid;
8741556Srgrimes		ps->status = -1;
8751556Srgrimes		ps->cmd = nullstr;
8761556Srgrimes		if (iflag && rootshell && n)
8771556Srgrimes			ps->cmd = commandtext(n);
878100305Stjr		jp->foreground = mode == FORK_FG;
87997659Stjr#if JOBS
88097659Stjr		setcurjob(jp);
88197659Stjr#endif
8821556Srgrimes	}
8831556Srgrimes	INTON;
884100308Stjr	TRACE(("In parent shell:  child = %d\n", (int)pid));
8851556Srgrimes	return pid;
8861556Srgrimes}
8871556Srgrimes
8881556Srgrimes
889249242Sjillespid_t
890249242Sjillesvforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
891249242Sjilles{
892249242Sjilles	pid_t pid;
893249242Sjilles	struct jmploc jmploc;
894249242Sjilles	struct jmploc *savehandler;
8951556Srgrimes
896249242Sjilles	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
897249242Sjilles	    (void *)pip));
898249242Sjilles	INTOFF;
899249242Sjilles	flushall();
900249242Sjilles	savehandler = handler;
901249242Sjilles	pid = vfork();
902249242Sjilles	if (pid == -1) {
903249242Sjilles		TRACE(("Vfork failed, errno=%d\n", errno));
904249242Sjilles		INTON;
905249242Sjilles		error("Cannot fork: %s", strerror(errno));
906249242Sjilles	}
907249242Sjilles	if (pid == 0) {
908249242Sjilles		TRACE(("Child shell %d\n", (int)getpid()));
909249242Sjilles		if (setjmp(jmploc.loc))
910249242Sjilles			_exit(exception == EXEXEC ? exerrno : 2);
911249242Sjilles		if (pip != NULL) {
912249242Sjilles			close(pip[0]);
913249242Sjilles			if (pip[1] != 1) {
914249242Sjilles				dup2(pip[1], 1);
915249242Sjilles				close(pip[1]);
916249242Sjilles			}
917249242Sjilles		}
918249242Sjilles		handler = &jmploc;
919249242Sjilles		shellexec(argv, envp, path, idx);
920249242Sjilles	}
921249242Sjilles	handler = savehandler;
922249242Sjilles	if (jp) {
923249242Sjilles		struct procstat *ps = &jp->ps[jp->nprocs++];
924249242Sjilles		ps->pid = pid;
925249242Sjilles		ps->status = -1;
926249242Sjilles		ps->cmd = nullstr;
927249242Sjilles		jp->foreground = 1;
928249242Sjilles#if JOBS
929249242Sjilles		setcurjob(jp);
930249242Sjilles#endif
931249242Sjilles	}
932249242Sjilles	INTON;
933249242Sjilles	TRACE(("In parent shell:  child = %d\n", (int)pid));
934249242Sjilles	return pid;
935249242Sjilles}
936249242Sjilles
937249242Sjilles
9381556Srgrimes/*
9391556Srgrimes * Wait for job to finish.
9401556Srgrimes *
9411556Srgrimes * Under job control we have the problem that while a child process is
9421556Srgrimes * running interrupts generated by the user are sent to the child but not
9431556Srgrimes * to the shell.  This means that an infinite loop started by an inter-
9441556Srgrimes * active user may be hard to kill.  With job control turned off, an
9451556Srgrimes * interactive user may place an interactive program inside a loop.  If
9461556Srgrimes * the interactive program catches interrupts, the user doesn't want
9471556Srgrimes * these interrupts to also abort the loop.  The approach we take here
9481556Srgrimes * is to have the shell ignore interrupt signals while waiting for a
94946684Skris * foreground process to terminate, and then send itself an interrupt
9501556Srgrimes * signal if the child process was terminated by an interrupt signal.
9511556Srgrimes * Unfortunately, some programs want to do a bit of cleanup and then
9521556Srgrimes * exit on interrupt; unless these processes terminate themselves by
9531556Srgrimes * sending a signal to themselves (instead of calling exit) they will
9541556Srgrimes * confuse this approach.
9551556Srgrimes */
9561556Srgrimes
9571556Srgrimesint
95890111Simpwaitforjob(struct job *jp, int *origstatus)
95945916Scracauer{
9601556Srgrimes#if JOBS
961100308Stjr	pid_t mypgrp = getpgrp();
962208881Sjilles	int propagate_int = jp->jobctl && jp->foreground;
9631556Srgrimes#endif
9641556Srgrimes	int status;
9651556Srgrimes	int st;
9661556Srgrimes
9671556Srgrimes	INTOFF;
968213775Sjhb	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
96938950Scracauer	while (jp->state == 0)
97038950Scracauer		if (dowait(1, jp) == -1)
97138950Scracauer			dotrap();
9721556Srgrimes#if JOBS
9731556Srgrimes	if (jp->jobctl) {
97499762Stjr		if (tcsetpgrp(ttyfd, mypgrp) < 0)
97520425Ssteve			error("tcsetpgrp failed, errno=%d\n", errno);
9761556Srgrimes	}
9771556Srgrimes	if (jp->state == JOBSTOPPED)
97897659Stjr		setcurjob(jp);
9791556Srgrimes#endif
9801556Srgrimes	status = jp->ps[jp->nprocs - 1].status;
98145916Scracauer	if (origstatus != NULL)
98245916Scracauer		*origstatus = status;
9831556Srgrimes	/* convert to 8 bits */
98426104Ssteve	if (WIFEXITED(status))
98526104Ssteve		st = WEXITSTATUS(status);
9861556Srgrimes#if JOBS
98726104Ssteve	else if (WIFSTOPPED(status))
98826104Ssteve		st = WSTOPSIG(status) + 128;
9891556Srgrimes#endif
9901556Srgrimes	else
99126104Ssteve		st = WTERMSIG(status) + 128;
9921556Srgrimes	if (! JOBS || jp->state == JOBDONE)
9931556Srgrimes		freejob(jp);
99438521Scracauer	if (int_pending()) {
995216400Sjilles		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
99638521Scracauer			CLEAR_PENDING_INT;
99738521Scracauer	}
998208881Sjilles#if JOBS
999208881Sjilles	else if (rootshell && iflag && propagate_int &&
1000208881Sjilles			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1001208881Sjilles		kill(getpid(), SIGINT);
1002208881Sjilles#endif
10031556Srgrimes	INTON;
10041556Srgrimes	return st;
10051556Srgrimes}
10061556Srgrimes
10071556Srgrimes
10081556Srgrimes
10091556Srgrimes/*
10101556Srgrimes * Wait for a process to terminate.
10111556Srgrimes */
10121556Srgrimes
1013213811Sobrienstatic pid_t
101490111Simpdowait(int block, struct job *job)
101517987Speter{
1016100308Stjr	pid_t pid;
10171556Srgrimes	int status;
10181556Srgrimes	struct procstat *sp;
10191556Srgrimes	struct job *jp;
10201556Srgrimes	struct job *thisjob;
10211556Srgrimes	int done;
10221556Srgrimes	int stopped;
102326104Ssteve	int sig;
1024216217Sjilles	int coredump;
10251556Srgrimes
102638950Scracauer	in_dowait++;
10271556Srgrimes	TRACE(("dowait(%d) called\n", block));
10281556Srgrimes	do {
10291556Srgrimes		pid = waitproc(block, &status);
1030100308Stjr		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
103172086Scracauer	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
1032125501Scracauer		 (pid > 0 && WIFSTOPPED(status) && !iflag));
103338950Scracauer	in_dowait--;
1034153417Smaxim	if (pid == -1 && errno == ECHILD && job != NULL)
1035153417Smaxim		job->state = JOBDONE;
103638521Scracauer	if (breakwaitcmd != 0) {
103738521Scracauer		breakwaitcmd = 0;
1038138312Smaxim		if (pid <= 0)
1039138312Smaxim			return -1;
104038521Scracauer	}
10411556Srgrimes	if (pid <= 0)
10421556Srgrimes		return pid;
10431556Srgrimes	INTOFF;
10441556Srgrimes	thisjob = NULL;
10451556Srgrimes	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1046216208Sjilles		if (jp->used && jp->nprocs > 0) {
10471556Srgrimes			done = 1;
10481556Srgrimes			stopped = 1;
10491556Srgrimes			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
10501556Srgrimes				if (sp->pid == -1)
10511556Srgrimes					continue;
10521556Srgrimes				if (sp->pid == pid) {
105326104Ssteve					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1054100308Stjr						   (int)pid, sp->status,
1055100308Stjr						   status));
10561556Srgrimes					sp->status = status;
10571556Srgrimes					thisjob = jp;
10581556Srgrimes				}
10591556Srgrimes				if (sp->status == -1)
10601556Srgrimes					stopped = 0;
106126104Ssteve				else if (WIFSTOPPED(sp->status))
10621556Srgrimes					done = 0;
10631556Srgrimes			}
10641556Srgrimes			if (stopped) {		/* stopped or done */
10651556Srgrimes				int state = done? JOBDONE : JOBSTOPPED;
10661556Srgrimes				if (jp->state != state) {
1067213775Sjhb					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
10681556Srgrimes					jp->state = state;
1069209600Sjilles					if (jp != job) {
1070209600Sjilles						if (done && !jp->remembered &&
1071209600Sjilles						    !iflag && jp != bgjob)
1072209600Sjilles							freejob(jp);
10731556Srgrimes#if JOBS
1074209600Sjilles						else if (done)
1075209600Sjilles							deljob(jp);
10761556Srgrimes#endif
1077209600Sjilles					}
10781556Srgrimes				}
10791556Srgrimes			}
10801556Srgrimes		}
10811556Srgrimes	}
10821556Srgrimes	INTON;
1083216217Sjilles	if (!thisjob || thisjob->state == 0)
1084216217Sjilles		;
1085216217Sjilles	else if ((!rootshell || !iflag || thisjob == job) &&
1086216217Sjilles	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1087216217Sjilles		sig = 0;
1088216217Sjilles		coredump = 0;
1089216217Sjilles		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1090216217Sjilles			if (WIFSIGNALED(sp->status)) {
1091216217Sjilles				sig = WTERMSIG(sp->status);
1092216217Sjilles				coredump = WCOREDUMP(sp->status);
1093216217Sjilles			}
1094216217Sjilles		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1095216217Sjilles			if (sig < sys_nsig && sys_siglist[sig])
1096218105Sjilles				out2str(sys_siglist[sig]);
109726104Ssteve			else
1098218105Sjilles				outfmt(out2, "Signal %d", sig);
1099216217Sjilles			if (coredump)
1100218105Sjilles				out2str(" (core dumped)");
1101218105Sjilles			out2c('\n');
1102218105Sjilles			flushout(out2);
11031556Srgrimes		}
11041556Srgrimes	} else {
1105109627Stjr		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1106216217Sjilles		thisjob->changed = 1;
11071556Srgrimes	}
11081556Srgrimes	return pid;
11091556Srgrimes}
11101556Srgrimes
11111556Srgrimes
11121556Srgrimes
11131556Srgrimes/*
11141556Srgrimes * Do a wait system call.  If job control is compiled in, we accept
11151556Srgrimes * stopped processes.  If block is zero, we return a value of zero
11161556Srgrimes * rather than blocking.
11171556Srgrimes */
1118213811Sobrienstatic pid_t
111990111Simpwaitproc(int block, int *status)
112017987Speter{
11211556Srgrimes	int flags;
11221556Srgrimes
11231556Srgrimes#if JOBS
11241556Srgrimes	flags = WUNTRACED;
11251556Srgrimes#else
11261556Srgrimes	flags = 0;
11271556Srgrimes#endif
11281556Srgrimes	if (block == 0)
11291556Srgrimes		flags |= WNOHANG;
11301556Srgrimes	return wait3(status, flags, (struct rusage *)NULL);
11311556Srgrimes}
11321556Srgrimes
11331556Srgrimes/*
11341556Srgrimes * return 1 if there are stopped jobs, otherwise 0
11351556Srgrimes */
11361556Srgrimesint job_warning = 0;
11371556Srgrimesint
113890111Simpstoppedjobs(void)
11391556Srgrimes{
114025222Ssteve	int jobno;
114125222Ssteve	struct job *jp;
11421556Srgrimes
11431556Srgrimes	if (job_warning)
11441556Srgrimes		return (0);
11451556Srgrimes	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
11461556Srgrimes		if (jp->used == 0)
11471556Srgrimes			continue;
11481556Srgrimes		if (jp->state == JOBSTOPPED) {
1149199629Sjilles			out2fmt_flush("You have stopped jobs.\n");
11501556Srgrimes			job_warning = 2;
11511556Srgrimes			return (1);
11521556Srgrimes		}
11531556Srgrimes	}
11541556Srgrimes
11551556Srgrimes	return (0);
11561556Srgrimes}
11571556Srgrimes
1158208489Sjilles
1159213811Sobrienstatic void
1160208489Sjillescheckzombies(void)
1161208489Sjilles{
1162208489Sjilles	while (njobs > 0 && dowait(0, NULL) > 0)
1163208489Sjilles		;
1164208489Sjilles}
1165208489Sjilles
1166208489Sjilles
1167209600Sjillesint
1168209600Sjillesbackgndpidset(void)
1169209600Sjilles{
1170209600Sjilles	return backgndpid != -1;
1171209600Sjilles}
1172209600Sjilles
1173209600Sjilles
1174209600Sjillespid_t
1175209600Sjillesbackgndpidval(void)
1176209600Sjilles{
1177223024Sjilles	if (bgjob != NULL && !forcelocal)
1178209600Sjilles		bgjob->remembered = 1;
1179209600Sjilles	return backgndpid;
1180209600Sjilles}
1181209600Sjilles
11821556Srgrimes/*
11831556Srgrimes * Return a string identifying a command (to be printed by the
11841556Srgrimes * jobs command.
11851556Srgrimes */
11861556Srgrimes
1187213760Sobrienstatic char *cmdnextc;
1188213760Sobrienstatic int cmdnleft;
11891556Srgrimes#define MAXCMDTEXT	200
11901556Srgrimes
11911556Srgrimeschar *
119290111Simpcommandtext(union node *n)
119390111Simp{
11941556Srgrimes	char *name;
11951556Srgrimes
11961556Srgrimes	cmdnextc = name = ckmalloc(MAXCMDTEXT);
11971556Srgrimes	cmdnleft = MAXCMDTEXT - 4;
11981556Srgrimes	cmdtxt(n);
11991556Srgrimes	*cmdnextc = '\0';
12001556Srgrimes	return name;
12011556Srgrimes}
12021556Srgrimes
12031556Srgrimes
1204213811Sobrienstatic void
120590111Simpcmdtxt(union node *n)
120690111Simp{
12071556Srgrimes	union node *np;
12081556Srgrimes	struct nodelist *lp;
1209201053Sjilles	const char *p;
12101556Srgrimes	int i;
12111556Srgrimes	char s[2];
12121556Srgrimes
12131556Srgrimes	if (n == NULL)
12141556Srgrimes		return;
12151556Srgrimes	switch (n->type) {
12161556Srgrimes	case NSEMI:
12171556Srgrimes		cmdtxt(n->nbinary.ch1);
12181556Srgrimes		cmdputs("; ");
12191556Srgrimes		cmdtxt(n->nbinary.ch2);
12201556Srgrimes		break;
12211556Srgrimes	case NAND:
12221556Srgrimes		cmdtxt(n->nbinary.ch1);
12231556Srgrimes		cmdputs(" && ");
12241556Srgrimes		cmdtxt(n->nbinary.ch2);
12251556Srgrimes		break;
12261556Srgrimes	case NOR:
12271556Srgrimes		cmdtxt(n->nbinary.ch1);
12281556Srgrimes		cmdputs(" || ");
12291556Srgrimes		cmdtxt(n->nbinary.ch2);
12301556Srgrimes		break;
12311556Srgrimes	case NPIPE:
12321556Srgrimes		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
12331556Srgrimes			cmdtxt(lp->n);
12341556Srgrimes			if (lp->next)
12351556Srgrimes				cmdputs(" | ");
12361556Srgrimes		}
12371556Srgrimes		break;
12381556Srgrimes	case NSUBSHELL:
12391556Srgrimes		cmdputs("(");
12401556Srgrimes		cmdtxt(n->nredir.n);
12411556Srgrimes		cmdputs(")");
12421556Srgrimes		break;
12431556Srgrimes	case NREDIR:
12441556Srgrimes	case NBACKGND:
12451556Srgrimes		cmdtxt(n->nredir.n);
12461556Srgrimes		break;
12471556Srgrimes	case NIF:
12481556Srgrimes		cmdputs("if ");
12491556Srgrimes		cmdtxt(n->nif.test);
12501556Srgrimes		cmdputs("; then ");
12511556Srgrimes		cmdtxt(n->nif.ifpart);
12521556Srgrimes		cmdputs("...");
12531556Srgrimes		break;
12541556Srgrimes	case NWHILE:
12551556Srgrimes		cmdputs("while ");
12561556Srgrimes		goto until;
12571556Srgrimes	case NUNTIL:
12581556Srgrimes		cmdputs("until ");
12591556Srgrimesuntil:
12601556Srgrimes		cmdtxt(n->nbinary.ch1);
12611556Srgrimes		cmdputs("; do ");
12621556Srgrimes		cmdtxt(n->nbinary.ch2);
12631556Srgrimes		cmdputs("; done");
12641556Srgrimes		break;
12651556Srgrimes	case NFOR:
12661556Srgrimes		cmdputs("for ");
12671556Srgrimes		cmdputs(n->nfor.var);
12681556Srgrimes		cmdputs(" in ...");
12691556Srgrimes		break;
12701556Srgrimes	case NCASE:
12711556Srgrimes		cmdputs("case ");
12721556Srgrimes		cmdputs(n->ncase.expr->narg.text);
12731556Srgrimes		cmdputs(" in ...");
12741556Srgrimes		break;
12751556Srgrimes	case NDEFUN:
12761556Srgrimes		cmdputs(n->narg.text);
12771556Srgrimes		cmdputs("() ...");
12781556Srgrimes		break;
12791556Srgrimes	case NCMD:
12801556Srgrimes		for (np = n->ncmd.args ; np ; np = np->narg.next) {
12811556Srgrimes			cmdtxt(np);
12821556Srgrimes			if (np->narg.next)
12831556Srgrimes				cmdputs(" ");
12841556Srgrimes		}
12851556Srgrimes		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
12861556Srgrimes			cmdputs(" ");
12871556Srgrimes			cmdtxt(np);
12881556Srgrimes		}
12891556Srgrimes		break;
12901556Srgrimes	case NARG:
12911556Srgrimes		cmdputs(n->narg.text);
12921556Srgrimes		break;
12931556Srgrimes	case NTO:
12941556Srgrimes		p = ">";  i = 1;  goto redir;
12951556Srgrimes	case NAPPEND:
12961556Srgrimes		p = ">>";  i = 1;  goto redir;
12971556Srgrimes	case NTOFD:
12981556Srgrimes		p = ">&";  i = 1;  goto redir;
129996922Stjr	case NCLOBBER:
130096922Stjr		p = ">|"; i = 1; goto redir;
13011556Srgrimes	case NFROM:
13021556Srgrimes		p = "<";  i = 0;  goto redir;
130366612Sbrian	case NFROMTO:
130466612Sbrian		p = "<>";  i = 0;  goto redir;
13051556Srgrimes	case NFROMFD:
13061556Srgrimes		p = "<&";  i = 0;  goto redir;
13071556Srgrimesredir:
13081556Srgrimes		if (n->nfile.fd != i) {
13091556Srgrimes			s[0] = n->nfile.fd + '0';
13101556Srgrimes			s[1] = '\0';
13111556Srgrimes			cmdputs(s);
13121556Srgrimes		}
13131556Srgrimes		cmdputs(p);
13141556Srgrimes		if (n->type == NTOFD || n->type == NFROMFD) {
131599634Stjr			if (n->ndup.dupfd >= 0)
131699634Stjr				s[0] = n->ndup.dupfd + '0';
131799634Stjr			else
131899634Stjr				s[0] = '-';
13191556Srgrimes			s[1] = '\0';
13201556Srgrimes			cmdputs(s);
13211556Srgrimes		} else {
13221556Srgrimes			cmdtxt(n->nfile.fname);
13231556Srgrimes		}
13241556Srgrimes		break;
13251556Srgrimes	case NHERE:
13261556Srgrimes	case NXHERE:
13271556Srgrimes		cmdputs("<<...");
13281556Srgrimes		break;
13291556Srgrimes	default:
13301556Srgrimes		cmdputs("???");
13311556Srgrimes		break;
13321556Srgrimes	}
13331556Srgrimes}
13341556Srgrimes
13351556Srgrimes
13361556Srgrimes
1337213811Sobrienstatic void
1338201053Sjillescmdputs(const char *s)
133990111Simp{
1340201053Sjilles	const char *p;
1341201053Sjilles	char *q;
134225222Ssteve	char c;
13431556Srgrimes	int subtype = 0;
13441556Srgrimes
13451556Srgrimes	if (cmdnleft <= 0)
13461556Srgrimes		return;
13471556Srgrimes	p = s;
13481556Srgrimes	q = cmdnextc;
13491556Srgrimes	while ((c = *p++) != '\0') {
13501556Srgrimes		if (c == CTLESC)
13511556Srgrimes			*q++ = *p++;
13521556Srgrimes		else if (c == CTLVAR) {
13531556Srgrimes			*q++ = '$';
13541556Srgrimes			if (--cmdnleft > 0)
13551556Srgrimes				*q++ = '{';
13561556Srgrimes			subtype = *p++;
1357216246Sjilles			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1358216246Sjilles				*q++ = '#';
13591556Srgrimes		} else if (c == '=' && subtype != 0) {
1360216246Sjilles			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1361216246Sjilles			if (*q)
1362216246Sjilles				q++;
1363216246Sjilles			else
1364216246Sjilles				cmdnleft++;
1365216246Sjilles			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1366216246Sjilles			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1367216246Sjilles			    --cmdnleft > 0)
1368216246Sjilles				*q = q[-1], q++;
13691556Srgrimes			subtype = 0;
13701556Srgrimes		} else if (c == CTLENDVAR) {
13711556Srgrimes			*q++ = '}';
1372216246Sjilles		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1373216246Sjilles			cmdnleft -= 5;
1374216246Sjilles			if (cmdnleft > 0) {
1375216246Sjilles				*q++ = '$';
1376216246Sjilles				*q++ = '(';
1377216246Sjilles				*q++ = '.';
1378216246Sjilles				*q++ = '.';
1379216246Sjilles				*q++ = '.';
1380216246Sjilles				*q++ = ')';
1381216246Sjilles			}
1382216246Sjilles		} else if (c == CTLARI) {
1383216246Sjilles			cmdnleft -= 2;
1384216246Sjilles			if (cmdnleft > 0) {
1385216246Sjilles				*q++ = '$';
1386216246Sjilles				*q++ = '(';
1387216246Sjilles				*q++ = '(';
1388216246Sjilles			}
1389216246Sjilles			p++;
1390216246Sjilles		} else if (c == CTLENDARI) {
1391216246Sjilles			if (--cmdnleft > 0) {
1392216246Sjilles				*q++ = ')';
1393216246Sjilles				*q++ = ')';
1394216246Sjilles			}
1395216246Sjilles		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1396216246Sjilles			cmdnleft++; /* ignore */
13971556Srgrimes		else
13981556Srgrimes			*q++ = c;
13991556Srgrimes		if (--cmdnleft <= 0) {
14001556Srgrimes			*q++ = '.';
14011556Srgrimes			*q++ = '.';
14021556Srgrimes			*q++ = '.';
14031556Srgrimes			break;
14041556Srgrimes		}
14051556Srgrimes	}
14061556Srgrimes	cmdnextc = q;
14071556Srgrimes}
1408