jobs.c revision 238866
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: head/bin/sh/jobs.c 238866 2012-07-28 14:56:50Z 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 */
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()? */
8738536Scracauervolatile sig_atomic_t breakwaitcmd = 0;	/* should wait be terminated? */
8899762Stjrstatic int ttyfd = -1;
891556Srgrimes
9020425Ssteve#if JOBS
91213811Sobrienstatic void restartjob(struct job *);
9220425Ssteve#endif
93213811Sobrienstatic void freejob(struct job *);
94213811Sobrienstatic struct job *getjob(char *);
95230530Scharnierpid_t getjobpgrp(char *);
96213811Sobrienstatic pid_t dowait(int, struct job *);
97213811Sobrienstatic void checkzombies(void);
98213811Sobrienstatic void cmdtxt(union node *);
99213811Sobrienstatic void cmdputs(const char *);
10097659Stjr#if JOBS
101213811Sobrienstatic void setcurjob(struct job *);
102213811Sobrienstatic void deljob(struct job *);
103213811Sobrienstatic struct job *getcurjob(struct job *);
10497659Stjr#endif
105216217Sjillesstatic void printjobcmd(struct job *);
106216217Sjillesstatic void showjob(struct job *, int);
1071556Srgrimes
1081556Srgrimes
1091556Srgrimes/*
1101556Srgrimes * Turn job control on and off.
1111556Srgrimes */
1121556Srgrimes
1131556SrgrimesMKINIT int jobctl;
1141556Srgrimes
11520425Ssteve#if JOBS
1161556Srgrimesvoid
11790111Simpsetjobctl(int on)
11817987Speter{
11999762Stjr	int i;
1201556Srgrimes
1211556Srgrimes	if (on == jobctl || rootshell == 0)
1221556Srgrimes		return;
1231556Srgrimes	if (on) {
12499762Stjr		if (ttyfd != -1)
12599762Stjr			close(ttyfd);
12699762Stjr		if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
12799762Stjr			i = 0;
12899762Stjr			while (i <= 2 && !isatty(i))
12999762Stjr				i++;
130109927Stjr			if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
13199762Stjr				goto out;
13299762Stjr		}
133109927Stjr		if (ttyfd < 10) {
134109927Stjr			/*
135109927Stjr			 * Keep our TTY file descriptor out of the way of
136109927Stjr			 * the user's redirections.
137109927Stjr			 */
138109927Stjr			if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
139109927Stjr				close(ttyfd);
140109927Stjr				ttyfd = -1;
141109927Stjr				goto out;
142109927Stjr			}
143109927Stjr			close(ttyfd);
144109927Stjr			ttyfd = i;
145109927Stjr		}
146103223Snectar		if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
14799762Stjr			close(ttyfd);
14899762Stjr			ttyfd = -1;
14999762Stjr			goto out;
15099762Stjr		}
1511556Srgrimes		do { /* while we are in the background */
15299762Stjr			initialpgrp = tcgetpgrp(ttyfd);
15320425Ssteve			if (initialpgrp < 0) {
154199629Sjillesout:				out2fmt_flush("sh: can't access tty; job control turned off\n");
1551556Srgrimes				mflag = 0;
1561556Srgrimes				return;
1571556Srgrimes			}
158216400Sjilles			if (initialpgrp != getpgrp()) {
159216400Sjilles				kill(0, SIGTTIN);
1601556Srgrimes				continue;
1611556Srgrimes			}
1621556Srgrimes		} while (0);
1631556Srgrimes		setsignal(SIGTSTP);
1641556Srgrimes		setsignal(SIGTTOU);
1651556Srgrimes		setsignal(SIGTTIN);
16617987Speter		setpgid(0, rootpid);
16799762Stjr		tcsetpgrp(ttyfd, rootpid);
1681556Srgrimes	} else { /* turning job control off */
16917987Speter		setpgid(0, initialpgrp);
17099762Stjr		tcsetpgrp(ttyfd, initialpgrp);
17199762Stjr		close(ttyfd);
17299762Stjr		ttyfd = -1;
1731556Srgrimes		setsignal(SIGTSTP);
1741556Srgrimes		setsignal(SIGTTOU);
1751556Srgrimes		setsignal(SIGTTIN);
1761556Srgrimes	}
1771556Srgrimes	jobctl = on;
1781556Srgrimes}
17920425Ssteve#endif
1801556Srgrimes
1811556Srgrimes
1821556Srgrimes#if JOBS
18317987Speterint
18490111Simpfgcmd(int argc __unused, char **argv)
18517987Speter{
1861556Srgrimes	struct job *jp;
187100308Stjr	pid_t pgrp;
1881556Srgrimes	int status;
1891556Srgrimes
1901556Srgrimes	jp = getjob(argv[1]);
1911556Srgrimes	if (jp->jobctl == 0)
1921556Srgrimes		error("job not created under job control");
193216217Sjilles	printjobcmd(jp);
19496933Stjr	flushout(&output);
1951556Srgrimes	pgrp = jp->ps[0].pid;
19699762Stjr	tcsetpgrp(ttyfd, pgrp);
1971556Srgrimes	restartjob(jp);
198100305Stjr	jp->foreground = 1;
1991556Srgrimes	INTOFF;
20045916Scracauer	status = waitforjob(jp, (int *)NULL);
2011556Srgrimes	INTON;
2021556Srgrimes	return status;
2031556Srgrimes}
2041556Srgrimes
2051556Srgrimes
20617987Speterint
20790111Simpbgcmd(int argc, char **argv)
20817987Speter{
2091556Srgrimes	struct job *jp;
2101556Srgrimes
2111556Srgrimes	do {
2121556Srgrimes		jp = getjob(*++argv);
2131556Srgrimes		if (jp->jobctl == 0)
2141556Srgrimes			error("job not created under job control");
21596933Stjr		if (jp->state == JOBDONE)
21696933Stjr			continue;
2171556Srgrimes		restartjob(jp);
218100305Stjr		jp->foreground = 0;
219216400Sjilles		out1fmt("[%td] ", jp - jobtab + 1);
220216217Sjilles		printjobcmd(jp);
2211556Srgrimes	} while (--argc > 1);
2221556Srgrimes	return 0;
2231556Srgrimes}
2241556Srgrimes
2251556Srgrimes
226213811Sobrienstatic void
22790111Simprestartjob(struct job *jp)
22817987Speter{
2291556Srgrimes	struct procstat *ps;
2301556Srgrimes	int i;
2311556Srgrimes
2321556Srgrimes	if (jp->state == JOBDONE)
2331556Srgrimes		return;
23497660Stjr	setcurjob(jp);
2351556Srgrimes	INTOFF;
236216400Sjilles	kill(-jp->ps[0].pid, SIGCONT);
2371556Srgrimes	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
23826104Ssteve		if (WIFSTOPPED(ps->status)) {
2391556Srgrimes			ps->status = -1;
2401556Srgrimes			jp->state = 0;
2411556Srgrimes		}
2421556Srgrimes	}
2431556Srgrimes	INTON;
2441556Srgrimes}
2451556Srgrimes#endif
2461556Srgrimes
2471556Srgrimes
2481556Srgrimesint
24997669Stjrjobscmd(int argc, char *argv[])
25017987Speter{
25197669Stjr	char *id;
252163085Sstefanf	int ch, mode;
25397669Stjr
25497669Stjr	optind = optreset = 1;
255100663Stjr	opterr = 0;
256163085Sstefanf	mode = SHOWJOBS_DEFAULT;
257163085Sstefanf	while ((ch = getopt(argc, argv, "lps")) != -1) {
25897669Stjr		switch (ch) {
25997669Stjr		case 'l':
260163085Sstefanf			mode = SHOWJOBS_VERBOSE;
26197669Stjr			break;
262163085Sstefanf		case 'p':
263163085Sstefanf			mode = SHOWJOBS_PGIDS;
264163085Sstefanf			break;
26597669Stjr		case 's':
266163085Sstefanf			mode = SHOWJOBS_PIDS;
26797669Stjr			break;
26897669Stjr		case '?':
26997669Stjr		default:
27097669Stjr			error("unknown option: -%c", optopt);
27197669Stjr		}
27297669Stjr	}
27397669Stjr	argc -= optind;
27497669Stjr	argv += optind;
27597669Stjr
27697669Stjr	if (argc == 0)
277163085Sstefanf		showjobs(0, mode);
27897669Stjr	else
27997669Stjr		while ((id = *argv++) != NULL)
280216217Sjilles			showjob(getjob(id), mode);
28197669Stjr
28297669Stjr	return (0);
2831556Srgrimes}
2841556Srgrimes
285213811Sobrienstatic void
286216217Sjillesprintjobcmd(struct job *jp)
28797663Stjr{
288216217Sjilles	struct procstat *ps;
289216217Sjilles	int i;
290216217Sjilles
291216217Sjilles	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
292216217Sjilles		out1str(ps->cmd);
293216217Sjilles		if (i > 0)
294216217Sjilles			out1str(" | ");
295216217Sjilles	}
296216217Sjilles	out1c('\n');
297216217Sjilles}
298216217Sjilles
299216217Sjillesstatic void
300216217Sjillesshowjob(struct job *jp, int mode)
301216217Sjilles{
30297663Stjr	char s[64];
303216217Sjilles	char statestr[64];
30497663Stjr	struct procstat *ps;
30597669Stjr	struct job *j;
30697669Stjr	int col, curr, i, jobno, prev, procno;
30797669Stjr	char c;
3081556Srgrimes
309163085Sstefanf	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
31097663Stjr	jobno = jp - jobtab + 1;
31197669Stjr	curr = prev = 0;
31297669Stjr#if JOBS
31397669Stjr	if ((j = getcurjob(NULL)) != NULL) {
31497669Stjr		curr = j - jobtab + 1;
31597669Stjr		if ((j = getcurjob(j)) != NULL)
31697669Stjr			prev = j - jobtab + 1;
31797669Stjr	}
31897669Stjr#endif
319216217Sjilles	ps = jp->ps + jp->nprocs - 1;
320216217Sjilles	if (jp->state == 0) {
321216217Sjilles		strcpy(statestr, "Running");
322216217Sjilles#if JOBS
323216217Sjilles	} else if (jp->state == JOBSTOPPED) {
324216217Sjilles		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
325216217Sjilles			ps--;
326216217Sjilles		if (WIFSTOPPED(ps->status))
327216217Sjilles			i = WSTOPSIG(ps->status);
328216217Sjilles		else
329216217Sjilles			i = -1;
330216217Sjilles		if (i > 0 && i < sys_nsig && sys_siglist[i])
331216217Sjilles			strcpy(statestr, sys_siglist[i]);
332216217Sjilles		else
333216217Sjilles			strcpy(statestr, "Suspended");
334216217Sjilles#endif
335216217Sjilles	} else if (WIFEXITED(ps->status)) {
336216217Sjilles		if (WEXITSTATUS(ps->status) == 0)
337216217Sjilles			strcpy(statestr, "Done");
338216217Sjilles		else
339216220Sjilles			fmtstr(statestr, 64, "Done(%d)",
340216217Sjilles			    WEXITSTATUS(ps->status));
341216217Sjilles	} else {
342216217Sjilles		i = WTERMSIG(ps->status);
343216217Sjilles		if (i > 0 && i < sys_nsig && sys_siglist[i])
344216217Sjilles			strcpy(statestr, sys_siglist[i]);
345216217Sjilles		else
346216217Sjilles			fmtstr(statestr, 64, "Signal %d", i);
347216217Sjilles		if (WCOREDUMP(ps->status))
348216217Sjilles			strcat(statestr, " (core dumped)");
349216217Sjilles	}
350216217Sjilles
35197663Stjr	for (ps = jp->ps ; ; ps++) {	/* for each process */
352163085Sstefanf		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
353216199Sjilles			out1fmt("%d\n", (int)ps->pid);
35497669Stjr			goto skip;
35597669Stjr		}
356216217Sjilles		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
35797669Stjr			goto skip;
35897819Stjr		if (jobno == curr && ps == jp->ps)
35997669Stjr			c = '+';
36097819Stjr		else if (jobno == prev && ps == jp->ps)
36197669Stjr			c = '-';
36297669Stjr		else
36397669Stjr			c = ' ';
36497663Stjr		if (ps == jp->ps)
36597669Stjr			fmtstr(s, 64, "[%d] %c ", jobno, c);
36697663Stjr		else
36797816Stjr			fmtstr(s, 64, "    %c ", c);
36897663Stjr		out1str(s);
36997663Stjr		col = strlen(s);
370163085Sstefanf		if (mode == SHOWJOBS_VERBOSE) {
371100308Stjr			fmtstr(s, 64, "%d ", (int)ps->pid);
37297669Stjr			out1str(s);
37397669Stjr			col += strlen(s);
37497669Stjr		}
375216217Sjilles		if (ps == jp->ps) {
376216217Sjilles			out1str(statestr);
377216217Sjilles			col += strlen(statestr);
37897663Stjr		}
37997663Stjr		do {
38097663Stjr			out1c(' ');
38197663Stjr			col++;
38297663Stjr		} while (col < 30);
383216217Sjilles		if (mode == SHOWJOBS_VERBOSE) {
384216217Sjilles			out1str(ps->cmd);
385216217Sjilles			out1c('\n');
386216217Sjilles		} else
387216217Sjilles			printjobcmd(jp);
38897669Stjrskip:		if (--procno <= 0)
38997663Stjr			break;
39097663Stjr	}
39197663Stjr}
39297663Stjr
3931556Srgrimes/*
3941556Srgrimes * Print a list of jobs.  If "change" is nonzero, only print jobs whose
3951556Srgrimes * statuses have changed since the last call to showjobs.
3961556Srgrimes *
3971556Srgrimes * If the shell is interrupted in the process of creating a job, the
3981556Srgrimes * result may be a job structure containing zero processes.  Such structures
3991556Srgrimes * will be freed here.
4001556Srgrimes */
4011556Srgrimes
4021556Srgrimesvoid
403163085Sstefanfshowjobs(int change, int mode)
40417987Speter{
4051556Srgrimes	int jobno;
4061556Srgrimes	struct job *jp;
4071556Srgrimes
4081556Srgrimes	TRACE(("showjobs(%d) called\n", change));
409208489Sjilles	checkzombies();
4101556Srgrimes	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
4111556Srgrimes		if (! jp->used)
4121556Srgrimes			continue;
4131556Srgrimes		if (jp->nprocs == 0) {
4141556Srgrimes			freejob(jp);
4151556Srgrimes			continue;
4161556Srgrimes		}
4171556Srgrimes		if (change && ! jp->changed)
4181556Srgrimes			continue;
419216217Sjilles		showjob(jp, mode);
4201556Srgrimes		jp->changed = 0;
421209600Sjilles		/* Hack: discard jobs for which $! has not been referenced
422209600Sjilles		 * in interactive mode when they terminate.
423209600Sjilles		 */
424209600Sjilles		if (jp->state == JOBDONE && !jp->remembered &&
425209600Sjilles				(iflag || jp != bgjob)) {
4261556Srgrimes			freejob(jp);
4271556Srgrimes		}
4281556Srgrimes	}
4291556Srgrimes}
4301556Srgrimes
4311556Srgrimes
4321556Srgrimes/*
4331556Srgrimes * Mark a job structure as unused.
4341556Srgrimes */
4351556Srgrimes
436213811Sobrienstatic void
43790111Simpfreejob(struct job *jp)
43890111Simp{
4391556Srgrimes	struct procstat *ps;
4401556Srgrimes	int i;
4411556Srgrimes
4421556Srgrimes	INTOFF;
443209600Sjilles	if (bgjob == jp)
444209600Sjilles		bgjob = NULL;
4451556Srgrimes	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
4461556Srgrimes		if (ps->cmd != nullstr)
4471556Srgrimes			ckfree(ps->cmd);
4481556Srgrimes	}
4491556Srgrimes	if (jp->ps != &jp->ps0)
4501556Srgrimes		ckfree(jp->ps);
4511556Srgrimes	jp->used = 0;
4521556Srgrimes#if JOBS
45397659Stjr	deljob(jp);
4541556Srgrimes#endif
4551556Srgrimes	INTON;
4561556Srgrimes}
4571556Srgrimes
4581556Srgrimes
4591556Srgrimes
4601556Srgrimesint
46190111Simpwaitcmd(int argc, char **argv)
46217987Speter{
4631556Srgrimes	struct job *job;
46426104Ssteve	int status, retval;
4651556Srgrimes	struct job *jp;
4661556Srgrimes
4671556Srgrimes	if (argc > 1) {
4681556Srgrimes		job = getjob(argv[1]);
4691556Srgrimes	} else {
4701556Srgrimes		job = NULL;
4711556Srgrimes	}
47238536Scracauer
47338536Scracauer	/*
47438536Scracauer	 * Loop until a process is terminated or stopped, or a SIGINT is
47538536Scracauer	 * received.
47638536Scracauer	 */
47738536Scracauer
47838521Scracauer	in_waitcmd++;
47938536Scracauer	do {
4801556Srgrimes		if (job != NULL) {
4811556Srgrimes			if (job->state) {
4821556Srgrimes				status = job->ps[job->nprocs - 1].status;
48326104Ssteve				if (WIFEXITED(status))
48426104Ssteve					retval = WEXITSTATUS(status);
4851556Srgrimes#if JOBS
48626104Ssteve				else if (WIFSTOPPED(status))
48726104Ssteve					retval = WSTOPSIG(status) + 128;
4881556Srgrimes#endif
4891556Srgrimes				else
49026104Ssteve					retval = WTERMSIG(status) + 128;
491209600Sjilles				if (! iflag || ! job->changed)
4921556Srgrimes					freejob(job);
493209600Sjilles				else {
494209600Sjilles					job->remembered = 0;
495209600Sjilles					if (job == bgjob)
496209600Sjilles						bgjob = NULL;
497209600Sjilles				}
49838536Scracauer				in_waitcmd--;
49926104Ssteve				return retval;
5001556Srgrimes			}
5011556Srgrimes		} else {
502209600Sjilles			for (jp = jobtab ; jp < jobtab + njobs; jp++)
503209600Sjilles				if (jp->used && jp->state == JOBDONE) {
504209600Sjilles					if (! iflag || ! jp->changed)
505209600Sjilles						freejob(jp);
506209600Sjilles					else {
507209600Sjilles						jp->remembered = 0;
508209600Sjilles						if (jp == bgjob)
509209600Sjilles							bgjob = NULL;
510209600Sjilles					}
511209600Sjilles				}
5121556Srgrimes			for (jp = jobtab ; ; jp++) {
5131556Srgrimes				if (jp >= jobtab + njobs) {	/* no running procs */
51438536Scracauer					in_waitcmd--;
5151556Srgrimes					return 0;
5161556Srgrimes				}
5171556Srgrimes				if (jp->used && jp->state == 0)
5181556Srgrimes					break;
5191556Srgrimes			}
5201556Srgrimes		}
52138521Scracauer	} while (dowait(1, (struct job *)NULL) != -1);
52238521Scracauer	in_waitcmd--;
52338521Scracauer
52438521Scracauer	return 0;
5251556Srgrimes}
5261556Srgrimes
5271556Srgrimes
5281556Srgrimes
52917987Speterint
53090111Simpjobidcmd(int argc __unused, char **argv)
53117987Speter{
5321556Srgrimes	struct job *jp;
5331556Srgrimes	int i;
5341556Srgrimes
5351556Srgrimes	jp = getjob(argv[1]);
5361556Srgrimes	for (i = 0 ; i < jp->nprocs ; ) {
537100308Stjr		out1fmt("%d", (int)jp->ps[i].pid);
5381556Srgrimes		out1c(++i < jp->nprocs? ' ' : '\n');
5391556Srgrimes	}
5401556Srgrimes	return 0;
5411556Srgrimes}
5421556Srgrimes
5431556Srgrimes
5441556Srgrimes
5451556Srgrimes/*
5461556Srgrimes * Convert a job name to a job structure.
5471556Srgrimes */
5481556Srgrimes
549213811Sobrienstatic struct job *
55090111Simpgetjob(char *name)
55190111Simp{
5521556Srgrimes	int jobno;
55397688Stjr	struct job *found, *jp;
554100308Stjr	pid_t pid;
5551556Srgrimes	int i;
5561556Srgrimes
5571556Srgrimes	if (name == NULL) {
5581556Srgrimes#if JOBS
55997659Stjrcurrentjob:	if ((jp = getcurjob(NULL)) == NULL)
5601556Srgrimes			error("No current job");
56197659Stjr		return (jp);
5621556Srgrimes#else
5631556Srgrimes		error("No current job");
5641556Srgrimes#endif
5651556Srgrimes	} else if (name[0] == '%') {
5661556Srgrimes		if (is_digit(name[1])) {
5671556Srgrimes			jobno = number(name + 1);
5681556Srgrimes			if (jobno > 0 && jobno <= njobs
5691556Srgrimes			 && jobtab[jobno - 1].used != 0)
5701556Srgrimes				return &jobtab[jobno - 1];
5711556Srgrimes#if JOBS
5721556Srgrimes		} else if (name[1] == '%' && name[2] == '\0') {
5731556Srgrimes			goto currentjob;
57497688Stjr		} else if (name[1] == '+' && name[2] == '\0') {
57597688Stjr			goto currentjob;
57697688Stjr		} else if (name[1] == '-' && name[2] == '\0') {
57797688Stjr			if ((jp = getcurjob(NULL)) == NULL ||
57897688Stjr			    (jp = getcurjob(jp)) == NULL)
57997688Stjr				error("No previous job");
58097688Stjr			return (jp);
5811556Srgrimes#endif
58297688Stjr		} else if (name[1] == '?') {
58397688Stjr			found = NULL;
58497688Stjr			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
58597688Stjr				if (jp->used && jp->nprocs > 0
58697688Stjr				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
58797688Stjr					if (found)
58897688Stjr						error("%s: ambiguous", name);
58997688Stjr					found = jp;
59097688Stjr				}
59197688Stjr			}
59297688Stjr			if (found != NULL)
59397688Stjr				return (found);
5941556Srgrimes		} else {
59597688Stjr			found = NULL;
5961556Srgrimes			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
5971556Srgrimes				if (jp->used && jp->nprocs > 0
5981556Srgrimes				 && prefix(name + 1, jp->ps[0].cmd)) {
5991556Srgrimes					if (found)
6001556Srgrimes						error("%s: ambiguous", name);
6011556Srgrimes					found = jp;
6021556Srgrimes				}
6031556Srgrimes			}
6041556Srgrimes			if (found)
6051556Srgrimes				return found;
6061556Srgrimes		}
6071556Srgrimes	} else if (is_number(name)) {
608100308Stjr		pid = (pid_t)number(name);
6091556Srgrimes		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6101556Srgrimes			if (jp->used && jp->nprocs > 0
6111556Srgrimes			 && jp->ps[jp->nprocs - 1].pid == pid)
6121556Srgrimes				return jp;
6131556Srgrimes		}
6141556Srgrimes	}
6151556Srgrimes	error("No such job: %s", name);
61617987Speter	/*NOTREACHED*/
61717987Speter	return NULL;
6181556Srgrimes}
6191556Srgrimes
6201556Srgrimes
621216629Sjillespid_t
622216629Sjillesgetjobpgrp(char *name)
623216629Sjilles{
624216629Sjilles	struct job *jp;
6251556Srgrimes
626216629Sjilles	jp = getjob(name);
627216629Sjilles	return -jp->ps[0].pid;
628216629Sjilles}
629216629Sjilles
6301556Srgrimes/*
6311556Srgrimes * Return a new job structure,
6321556Srgrimes */
6331556Srgrimes
6341556Srgrimesstruct job *
63590111Simpmakejob(union node *node __unused, int nprocs)
63617987Speter{
6371556Srgrimes	int i;
6381556Srgrimes	struct job *jp;
6391556Srgrimes
6401556Srgrimes	for (i = njobs, jp = jobtab ; ; jp++) {
6411556Srgrimes		if (--i < 0) {
6421556Srgrimes			INTOFF;
6431556Srgrimes			if (njobs == 0) {
6441556Srgrimes				jobtab = ckmalloc(4 * sizeof jobtab[0]);
64597664Stjr#if JOBS
64697659Stjr				jobmru = NULL;
64797664Stjr#endif
6481556Srgrimes			} else {
6491556Srgrimes				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
65017987Speter				memcpy(jp, jobtab, njobs * sizeof jp[0]);
65197659Stjr#if JOBS
65297659Stjr				/* Relocate `next' pointers and list head */
65399760Stjr				if (jobmru != NULL)
65499760Stjr					jobmru = &jp[jobmru - jobtab];
65597659Stjr				for (i = 0; i < njobs; i++)
65697659Stjr					if (jp[i].next != NULL)
65797659Stjr						jp[i].next = &jp[jp[i].next -
65897659Stjr						    jobtab];
65997659Stjr#endif
660209600Sjilles				if (bgjob != NULL)
661209600Sjilles					bgjob = &jp[bgjob - jobtab];
66220425Ssteve				/* Relocate `ps' pointers */
66320425Ssteve				for (i = 0; i < njobs; i++)
66420425Ssteve					if (jp[i].ps == &jobtab[i].ps0)
66520425Ssteve						jp[i].ps = &jp[i].ps0;
6661556Srgrimes				ckfree(jobtab);
6671556Srgrimes				jobtab = jp;
6681556Srgrimes			}
6691556Srgrimes			jp = jobtab + njobs;
6701556Srgrimes			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6711556Srgrimes			INTON;
6721556Srgrimes			break;
6731556Srgrimes		}
6741556Srgrimes		if (jp->used == 0)
6751556Srgrimes			break;
6761556Srgrimes	}
6771556Srgrimes	INTOFF;
6781556Srgrimes	jp->state = 0;
6791556Srgrimes	jp->used = 1;
6801556Srgrimes	jp->changed = 0;
6811556Srgrimes	jp->nprocs = 0;
682100305Stjr	jp->foreground = 0;
683209600Sjilles	jp->remembered = 0;
6841556Srgrimes#if JOBS
6851556Srgrimes	jp->jobctl = jobctl;
68697659Stjr	jp->next = NULL;
6871556Srgrimes#endif
6881556Srgrimes	if (nprocs > 1) {
6891556Srgrimes		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
6901556Srgrimes	} else {
6911556Srgrimes		jp->ps = &jp->ps0;
6921556Srgrimes	}
6931556Srgrimes	INTON;
694213775Sjhb	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
69517987Speter	    jp - jobtab + 1));
6961556Srgrimes	return jp;
6978855Srgrimes}
6981556Srgrimes
69997659Stjr#if JOBS
700213811Sobrienstatic void
70197659Stjrsetcurjob(struct job *cj)
70297659Stjr{
70397659Stjr	struct job *jp, *prev;
7041556Srgrimes
70597659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
70697659Stjr		if (jp == cj) {
70797659Stjr			if (prev != NULL)
70897659Stjr				prev->next = jp->next;
70997659Stjr			else
71097659Stjr				jobmru = jp->next;
71197659Stjr			jp->next = jobmru;
71297659Stjr			jobmru = cj;
71397659Stjr			return;
71497659Stjr		}
71597659Stjr	}
71697659Stjr	cj->next = jobmru;
71797659Stjr	jobmru = cj;
71897659Stjr}
71997659Stjr
720213811Sobrienstatic void
72197659Stjrdeljob(struct job *j)
72297659Stjr{
72397659Stjr	struct job *jp, *prev;
72497659Stjr
72597659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
72697659Stjr		if (jp == j) {
72797659Stjr			if (prev != NULL)
72897659Stjr				prev->next = jp->next;
72997659Stjr			else
73097659Stjr				jobmru = jp->next;
73197659Stjr			return;
73297659Stjr		}
73397659Stjr	}
73497659Stjr}
73597659Stjr
7361556Srgrimes/*
73797659Stjr * Return the most recently used job that isn't `nj', and preferably one
73897659Stjr * that is stopped.
73997659Stjr */
740213811Sobrienstatic struct job *
74197659Stjrgetcurjob(struct job *nj)
74297659Stjr{
74397659Stjr	struct job *jp;
74497659Stjr
74597659Stjr	/* Try to find a stopped one.. */
74697659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
74797659Stjr		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
74897659Stjr			return (jp);
74997659Stjr	/* Otherwise the most recently used job that isn't `nj' */
75097659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
75197659Stjr		if (jp->used && jp != nj)
75297659Stjr			return (jp);
75397659Stjr
75497659Stjr	return (NULL);
75597659Stjr}
75697659Stjr
75797659Stjr#endif
75897659Stjr
75997659Stjr/*
7601556Srgrimes * Fork of a subshell.  If we are doing job control, give the subshell its
7611556Srgrimes * own process group.  Jp is a job structure that the job is to be added to.
7621556Srgrimes * N is the command that will be evaluated by the child.  Both jp and n may
7631556Srgrimes * be NULL.  The mode parameter can be one of the following:
7641556Srgrimes *	FORK_FG - Fork off a foreground process.
7651556Srgrimes *	FORK_BG - Fork off a background process.
7661556Srgrimes *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
7671556Srgrimes *		     process group even if job control is on.
7681556Srgrimes *
7691556Srgrimes * When job control is turned off, background processes have their standard
7701556Srgrimes * input redirected to /dev/null (except for the second and later processes
7711556Srgrimes * in a pipeline).
7721556Srgrimes */
7731556Srgrimes
774100308Stjrpid_t
77590111Simpforkshell(struct job *jp, union node *n, int mode)
77617987Speter{
777100308Stjr	pid_t pid;
778100308Stjr	pid_t pgrp;
7791556Srgrimes
780213775Sjhb	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
78117987Speter	    mode));
7821556Srgrimes	INTOFF;
783216208Sjilles	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
784208489Sjilles		checkzombies();
785112341Stjr	flushall();
7861556Srgrimes	pid = fork();
7871556Srgrimes	if (pid == -1) {
7881556Srgrimes		TRACE(("Fork failed, errno=%d\n", errno));
7891556Srgrimes		INTON;
79053891Scracauer		error("Cannot fork: %s", strerror(errno));
7911556Srgrimes	}
7921556Srgrimes	if (pid == 0) {
7931556Srgrimes		struct job *p;
7941556Srgrimes		int wasroot;
7951556Srgrimes		int i;
7961556Srgrimes
797100308Stjr		TRACE(("Child shell %d\n", (int)getpid()));
7981556Srgrimes		wasroot = rootshell;
7991556Srgrimes		rootshell = 0;
800200998Sjilles		handler = &main_handler;
8011556Srgrimes		closescript();
8021556Srgrimes		INTON;
803223024Sjilles		forcelocal = 0;
8041556Srgrimes		clear_traps();
8051556Srgrimes#if JOBS
8061556Srgrimes		jobctl = 0;		/* do job control only in root shell */
8071556Srgrimes		if (wasroot && mode != FORK_NOJOB && mflag) {
8081556Srgrimes			if (jp == NULL || jp->nprocs == 0)
8091556Srgrimes				pgrp = getpid();
8101556Srgrimes			else
8111556Srgrimes				pgrp = jp->ps[0].pid;
81221352Ssteve			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
8131556Srgrimes				/*** this causes superfluous TIOCSPGRPS ***/
81499762Stjr				if (tcsetpgrp(ttyfd, pgrp) < 0)
81520425Ssteve					error("tcsetpgrp failed, errno=%d", errno);
8161556Srgrimes			}
8171556Srgrimes			setsignal(SIGTSTP);
8181556Srgrimes			setsignal(SIGTTOU);
8191556Srgrimes		} else if (mode == FORK_BG) {
8201556Srgrimes			ignoresig(SIGINT);
8211556Srgrimes			ignoresig(SIGQUIT);
8221556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8231556Srgrimes			    ! fd0_redirected_p ()) {
8241556Srgrimes				close(0);
82569793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
826222684Sjilles					error("cannot open %s: %s",
82769793Sobrien					    _PATH_DEVNULL, strerror(errno));
8281556Srgrimes			}
8291556Srgrimes		}
8301556Srgrimes#else
8311556Srgrimes		if (mode == FORK_BG) {
8321556Srgrimes			ignoresig(SIGINT);
8331556Srgrimes			ignoresig(SIGQUIT);
8341556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8351556Srgrimes			    ! fd0_redirected_p ()) {
8361556Srgrimes				close(0);
83769793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
838222684Sjilles					error("cannot open %s: %s",
83969793Sobrien					    _PATH_DEVNULL, strerror(errno));
8401556Srgrimes			}
8411556Srgrimes		}
8421556Srgrimes#endif
843102051Stjr		INTOFF;
844102051Stjr		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
845102051Stjr			if (p->used)
846102051Stjr				freejob(p);
847102051Stjr		INTON;
8481556Srgrimes		if (wasroot && iflag) {
8491556Srgrimes			setsignal(SIGINT);
8501556Srgrimes			setsignal(SIGQUIT);
8511556Srgrimes			setsignal(SIGTERM);
8521556Srgrimes		}
8531556Srgrimes		return pid;
8541556Srgrimes	}
8551556Srgrimes	if (rootshell && mode != FORK_NOJOB && mflag) {
8561556Srgrimes		if (jp == NULL || jp->nprocs == 0)
8571556Srgrimes			pgrp = pid;
8581556Srgrimes		else
8591556Srgrimes			pgrp = jp->ps[0].pid;
86017987Speter		setpgid(pid, pgrp);
8611556Srgrimes	}
862209600Sjilles	if (mode == FORK_BG) {
863209600Sjilles		if (bgjob != NULL && bgjob->state == JOBDONE &&
864209600Sjilles		    !bgjob->remembered && !iflag)
865209600Sjilles			freejob(bgjob);
8661556Srgrimes		backgndpid = pid;		/* set $! */
867209600Sjilles		bgjob = jp;
868209600Sjilles	}
8691556Srgrimes	if (jp) {
8701556Srgrimes		struct procstat *ps = &jp->ps[jp->nprocs++];
8711556Srgrimes		ps->pid = pid;
8721556Srgrimes		ps->status = -1;
8731556Srgrimes		ps->cmd = nullstr;
8741556Srgrimes		if (iflag && rootshell && n)
8751556Srgrimes			ps->cmd = commandtext(n);
876100305Stjr		jp->foreground = mode == FORK_FG;
87797659Stjr#if JOBS
87897659Stjr		setcurjob(jp);
87997659Stjr#endif
8801556Srgrimes	}
8811556Srgrimes	INTON;
882100308Stjr	TRACE(("In parent shell:  child = %d\n", (int)pid));
8831556Srgrimes	return pid;
8841556Srgrimes}
8851556Srgrimes
8861556Srgrimes
887230998Sjillespid_t
888230998Sjillesvforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
889230998Sjilles{
890230998Sjilles	pid_t pid;
891230998Sjilles	struct jmploc jmploc;
892230998Sjilles	struct jmploc *savehandler;
8931556Srgrimes
894233792Sjilles	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
895233792Sjilles	    (void *)pip));
896230998Sjilles	INTOFF;
897230998Sjilles	flushall();
898230998Sjilles	savehandler = handler;
899230998Sjilles	pid = vfork();
900230998Sjilles	if (pid == -1) {
901230998Sjilles		TRACE(("Vfork failed, errno=%d\n", errno));
902230998Sjilles		INTON;
903230998Sjilles		error("Cannot fork: %s", strerror(errno));
904230998Sjilles	}
905230998Sjilles	if (pid == 0) {
906230998Sjilles		TRACE(("Child shell %d\n", (int)getpid()));
907230998Sjilles		if (setjmp(jmploc.loc))
908230998Sjilles			_exit(exception == EXEXEC ? exerrno : 2);
909230998Sjilles		if (pip != NULL) {
910230998Sjilles			close(pip[0]);
911230998Sjilles			if (pip[1] != 1) {
912230998Sjilles				dup2(pip[1], 1);
913230998Sjilles				close(pip[1]);
914230998Sjilles			}
915230998Sjilles		}
916230998Sjilles		handler = &jmploc;
917230998Sjilles		shellexec(argv, envp, path, idx);
918230998Sjilles	}
919230998Sjilles	handler = savehandler;
920230998Sjilles	if (jp) {
921230998Sjilles		struct procstat *ps = &jp->ps[jp->nprocs++];
922230998Sjilles		ps->pid = pid;
923230998Sjilles		ps->status = -1;
924230998Sjilles		ps->cmd = nullstr;
925230998Sjilles		jp->foreground = 1;
926230998Sjilles#if JOBS
927230998Sjilles		setcurjob(jp);
928230998Sjilles#endif
929230998Sjilles	}
930230998Sjilles	INTON;
931230998Sjilles	TRACE(("In parent shell:  child = %d\n", (int)pid));
932230998Sjilles	return pid;
933230998Sjilles}
934230998Sjilles
935230998Sjilles
9361556Srgrimes/*
9371556Srgrimes * Wait for job to finish.
9381556Srgrimes *
9391556Srgrimes * Under job control we have the problem that while a child process is
9401556Srgrimes * running interrupts generated by the user are sent to the child but not
9411556Srgrimes * to the shell.  This means that an infinite loop started by an inter-
9421556Srgrimes * active user may be hard to kill.  With job control turned off, an
9431556Srgrimes * interactive user may place an interactive program inside a loop.  If
9441556Srgrimes * the interactive program catches interrupts, the user doesn't want
9451556Srgrimes * these interrupts to also abort the loop.  The approach we take here
9461556Srgrimes * is to have the shell ignore interrupt signals while waiting for a
94746684Skris * foreground process to terminate, and then send itself an interrupt
9481556Srgrimes * signal if the child process was terminated by an interrupt signal.
9491556Srgrimes * Unfortunately, some programs want to do a bit of cleanup and then
9501556Srgrimes * exit on interrupt; unless these processes terminate themselves by
9511556Srgrimes * sending a signal to themselves (instead of calling exit) they will
9521556Srgrimes * confuse this approach.
9531556Srgrimes */
9541556Srgrimes
9551556Srgrimesint
95690111Simpwaitforjob(struct job *jp, int *origstatus)
95745916Scracauer{
9581556Srgrimes#if JOBS
959100308Stjr	pid_t mypgrp = getpgrp();
960208881Sjilles	int propagate_int = jp->jobctl && jp->foreground;
9611556Srgrimes#endif
9621556Srgrimes	int status;
9631556Srgrimes	int st;
9641556Srgrimes
9651556Srgrimes	INTOFF;
966213775Sjhb	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
96738950Scracauer	while (jp->state == 0)
96838950Scracauer		if (dowait(1, jp) == -1)
96938950Scracauer			dotrap();
9701556Srgrimes#if JOBS
9711556Srgrimes	if (jp->jobctl) {
97299762Stjr		if (tcsetpgrp(ttyfd, mypgrp) < 0)
97320425Ssteve			error("tcsetpgrp failed, errno=%d\n", errno);
9741556Srgrimes	}
9751556Srgrimes	if (jp->state == JOBSTOPPED)
97697659Stjr		setcurjob(jp);
9771556Srgrimes#endif
9781556Srgrimes	status = jp->ps[jp->nprocs - 1].status;
97945916Scracauer	if (origstatus != NULL)
98045916Scracauer		*origstatus = status;
9811556Srgrimes	/* convert to 8 bits */
98226104Ssteve	if (WIFEXITED(status))
98326104Ssteve		st = WEXITSTATUS(status);
9841556Srgrimes#if JOBS
98526104Ssteve	else if (WIFSTOPPED(status))
98626104Ssteve		st = WSTOPSIG(status) + 128;
9871556Srgrimes#endif
9881556Srgrimes	else
98926104Ssteve		st = WTERMSIG(status) + 128;
9901556Srgrimes	if (! JOBS || jp->state == JOBDONE)
9911556Srgrimes		freejob(jp);
99238521Scracauer	if (int_pending()) {
993216400Sjilles		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
99438521Scracauer			CLEAR_PENDING_INT;
99538521Scracauer	}
996208881Sjilles#if JOBS
997208881Sjilles	else if (rootshell && iflag && propagate_int &&
998208881Sjilles			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
999208881Sjilles		kill(getpid(), SIGINT);
1000208881Sjilles#endif
10011556Srgrimes	INTON;
10021556Srgrimes	return st;
10031556Srgrimes}
10041556Srgrimes
10051556Srgrimes
10061556Srgrimes
10071556Srgrimes/*
10081556Srgrimes * Wait for a process to terminate.
10091556Srgrimes */
10101556Srgrimes
1011213811Sobrienstatic pid_t
101290111Simpdowait(int block, struct job *job)
101317987Speter{
1014100308Stjr	pid_t pid;
10151556Srgrimes	int status;
10161556Srgrimes	struct procstat *sp;
10171556Srgrimes	struct job *jp;
10181556Srgrimes	struct job *thisjob;
10191556Srgrimes	int done;
10201556Srgrimes	int stopped;
102126104Ssteve	int sig;
1022216217Sjilles	int coredump;
1023238866Sjilles	int wflags;
10241556Srgrimes
10251556Srgrimes	TRACE(("dowait(%d) called\n", block));
10261556Srgrimes	do {
1027238866Sjilles#if JOBS
1028238866Sjilles		wflags = WUNTRACED | WCONTINUED;
1029238866Sjilles#else
1030238866Sjilles		wflags = 0;
1031238866Sjilles#endif
1032238866Sjilles		if (block == 0)
1033238866Sjilles			wflags |= WNOHANG;
1034238866Sjilles		pid = wait3(&status, wflags, (struct rusage *)NULL);
1035100308Stjr		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
103672086Scracauer	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
1037238865Sjilles		 (pid > 0 && (WIFSTOPPED(status) || WIFCONTINUED(status)) &&
1038238865Sjilles		  !iflag));
1039153417Smaxim	if (pid == -1 && errno == ECHILD && job != NULL)
1040153417Smaxim		job->state = JOBDONE;
104138521Scracauer	if (breakwaitcmd != 0) {
104238521Scracauer		breakwaitcmd = 0;
1043138312Smaxim		if (pid <= 0)
1044138312Smaxim			return -1;
104538521Scracauer	}
10461556Srgrimes	if (pid <= 0)
10471556Srgrimes		return pid;
10481556Srgrimes	INTOFF;
10491556Srgrimes	thisjob = NULL;
10501556Srgrimes	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1051216208Sjilles		if (jp->used && jp->nprocs > 0) {
10521556Srgrimes			done = 1;
10531556Srgrimes			stopped = 1;
10541556Srgrimes			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
10551556Srgrimes				if (sp->pid == -1)
10561556Srgrimes					continue;
10571556Srgrimes				if (sp->pid == pid) {
105826104Ssteve					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1059100308Stjr						   (int)pid, sp->status,
1060100308Stjr						   status));
1061238865Sjilles					if (WIFCONTINUED(status)) {
1062238865Sjilles						sp->status = -1;
1063238865Sjilles						jp->state = 0;
1064238865Sjilles					} else
1065238865Sjilles						sp->status = status;
10661556Srgrimes					thisjob = jp;
10671556Srgrimes				}
10681556Srgrimes				if (sp->status == -1)
10691556Srgrimes					stopped = 0;
107026104Ssteve				else if (WIFSTOPPED(sp->status))
10711556Srgrimes					done = 0;
10721556Srgrimes			}
10731556Srgrimes			if (stopped) {		/* stopped or done */
10741556Srgrimes				int state = done? JOBDONE : JOBSTOPPED;
10751556Srgrimes				if (jp->state != state) {
1076213775Sjhb					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
10771556Srgrimes					jp->state = state;
1078209600Sjilles					if (jp != job) {
1079209600Sjilles						if (done && !jp->remembered &&
1080209600Sjilles						    !iflag && jp != bgjob)
1081209600Sjilles							freejob(jp);
10821556Srgrimes#if JOBS
1083209600Sjilles						else if (done)
1084209600Sjilles							deljob(jp);
10851556Srgrimes#endif
1086209600Sjilles					}
10871556Srgrimes				}
10881556Srgrimes			}
10891556Srgrimes		}
10901556Srgrimes	}
10911556Srgrimes	INTON;
1092216217Sjilles	if (!thisjob || thisjob->state == 0)
1093216217Sjilles		;
1094216217Sjilles	else if ((!rootshell || !iflag || thisjob == job) &&
1095216217Sjilles	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1096216217Sjilles		sig = 0;
1097216217Sjilles		coredump = 0;
1098216217Sjilles		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1099216217Sjilles			if (WIFSIGNALED(sp->status)) {
1100216217Sjilles				sig = WTERMSIG(sp->status);
1101216217Sjilles				coredump = WCOREDUMP(sp->status);
1102216217Sjilles			}
1103216217Sjilles		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1104216217Sjilles			if (sig < sys_nsig && sys_siglist[sig])
1105218105Sjilles				out2str(sys_siglist[sig]);
110626104Ssteve			else
1107218105Sjilles				outfmt(out2, "Signal %d", sig);
1108216217Sjilles			if (coredump)
1109218105Sjilles				out2str(" (core dumped)");
1110218105Sjilles			out2c('\n');
1111218105Sjilles			flushout(out2);
11121556Srgrimes		}
11131556Srgrimes	} else {
1114109627Stjr		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1115216217Sjilles		thisjob->changed = 1;
11161556Srgrimes	}
11171556Srgrimes	return pid;
11181556Srgrimes}
11191556Srgrimes
11201556Srgrimes
11211556Srgrimes
11221556Srgrimes/*
11231556Srgrimes * return 1 if there are stopped jobs, otherwise 0
11241556Srgrimes */
11251556Srgrimesint job_warning = 0;
11261556Srgrimesint
112790111Simpstoppedjobs(void)
11281556Srgrimes{
112925222Ssteve	int jobno;
113025222Ssteve	struct job *jp;
11311556Srgrimes
11321556Srgrimes	if (job_warning)
11331556Srgrimes		return (0);
11341556Srgrimes	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
11351556Srgrimes		if (jp->used == 0)
11361556Srgrimes			continue;
11371556Srgrimes		if (jp->state == JOBSTOPPED) {
1138199629Sjilles			out2fmt_flush("You have stopped jobs.\n");
11391556Srgrimes			job_warning = 2;
11401556Srgrimes			return (1);
11411556Srgrimes		}
11421556Srgrimes	}
11431556Srgrimes
11441556Srgrimes	return (0);
11451556Srgrimes}
11461556Srgrimes
1147208489Sjilles
1148213811Sobrienstatic void
1149208489Sjillescheckzombies(void)
1150208489Sjilles{
1151208489Sjilles	while (njobs > 0 && dowait(0, NULL) > 0)
1152208489Sjilles		;
1153208489Sjilles}
1154208489Sjilles
1155208489Sjilles
1156209600Sjillesint
1157209600Sjillesbackgndpidset(void)
1158209600Sjilles{
1159209600Sjilles	return backgndpid != -1;
1160209600Sjilles}
1161209600Sjilles
1162209600Sjilles
1163209600Sjillespid_t
1164209600Sjillesbackgndpidval(void)
1165209600Sjilles{
1166223024Sjilles	if (bgjob != NULL && !forcelocal)
1167209600Sjilles		bgjob->remembered = 1;
1168209600Sjilles	return backgndpid;
1169209600Sjilles}
1170209600Sjilles
11711556Srgrimes/*
11721556Srgrimes * Return a string identifying a command (to be printed by the
11731556Srgrimes * jobs command.
11741556Srgrimes */
11751556Srgrimes
1176213760Sobrienstatic char *cmdnextc;
1177213760Sobrienstatic int cmdnleft;
11781556Srgrimes#define MAXCMDTEXT	200
11791556Srgrimes
11801556Srgrimeschar *
118190111Simpcommandtext(union node *n)
118290111Simp{
11831556Srgrimes	char *name;
11841556Srgrimes
11851556Srgrimes	cmdnextc = name = ckmalloc(MAXCMDTEXT);
11861556Srgrimes	cmdnleft = MAXCMDTEXT - 4;
11871556Srgrimes	cmdtxt(n);
11881556Srgrimes	*cmdnextc = '\0';
11891556Srgrimes	return name;
11901556Srgrimes}
11911556Srgrimes
11921556Srgrimes
1193213811Sobrienstatic void
119490111Simpcmdtxt(union node *n)
119590111Simp{
11961556Srgrimes	union node *np;
11971556Srgrimes	struct nodelist *lp;
1198201053Sjilles	const char *p;
11991556Srgrimes	int i;
12001556Srgrimes	char s[2];
12011556Srgrimes
12021556Srgrimes	if (n == NULL)
12031556Srgrimes		return;
12041556Srgrimes	switch (n->type) {
12051556Srgrimes	case NSEMI:
12061556Srgrimes		cmdtxt(n->nbinary.ch1);
12071556Srgrimes		cmdputs("; ");
12081556Srgrimes		cmdtxt(n->nbinary.ch2);
12091556Srgrimes		break;
12101556Srgrimes	case NAND:
12111556Srgrimes		cmdtxt(n->nbinary.ch1);
12121556Srgrimes		cmdputs(" && ");
12131556Srgrimes		cmdtxt(n->nbinary.ch2);
12141556Srgrimes		break;
12151556Srgrimes	case NOR:
12161556Srgrimes		cmdtxt(n->nbinary.ch1);
12171556Srgrimes		cmdputs(" || ");
12181556Srgrimes		cmdtxt(n->nbinary.ch2);
12191556Srgrimes		break;
12201556Srgrimes	case NPIPE:
12211556Srgrimes		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
12221556Srgrimes			cmdtxt(lp->n);
12231556Srgrimes			if (lp->next)
12241556Srgrimes				cmdputs(" | ");
12251556Srgrimes		}
12261556Srgrimes		break;
12271556Srgrimes	case NSUBSHELL:
12281556Srgrimes		cmdputs("(");
12291556Srgrimes		cmdtxt(n->nredir.n);
12301556Srgrimes		cmdputs(")");
12311556Srgrimes		break;
12321556Srgrimes	case NREDIR:
12331556Srgrimes	case NBACKGND:
12341556Srgrimes		cmdtxt(n->nredir.n);
12351556Srgrimes		break;
12361556Srgrimes	case NIF:
12371556Srgrimes		cmdputs("if ");
12381556Srgrimes		cmdtxt(n->nif.test);
12391556Srgrimes		cmdputs("; then ");
12401556Srgrimes		cmdtxt(n->nif.ifpart);
12411556Srgrimes		cmdputs("...");
12421556Srgrimes		break;
12431556Srgrimes	case NWHILE:
12441556Srgrimes		cmdputs("while ");
12451556Srgrimes		goto until;
12461556Srgrimes	case NUNTIL:
12471556Srgrimes		cmdputs("until ");
12481556Srgrimesuntil:
12491556Srgrimes		cmdtxt(n->nbinary.ch1);
12501556Srgrimes		cmdputs("; do ");
12511556Srgrimes		cmdtxt(n->nbinary.ch2);
12521556Srgrimes		cmdputs("; done");
12531556Srgrimes		break;
12541556Srgrimes	case NFOR:
12551556Srgrimes		cmdputs("for ");
12561556Srgrimes		cmdputs(n->nfor.var);
12571556Srgrimes		cmdputs(" in ...");
12581556Srgrimes		break;
12591556Srgrimes	case NCASE:
12601556Srgrimes		cmdputs("case ");
12611556Srgrimes		cmdputs(n->ncase.expr->narg.text);
12621556Srgrimes		cmdputs(" in ...");
12631556Srgrimes		break;
12641556Srgrimes	case NDEFUN:
12651556Srgrimes		cmdputs(n->narg.text);
12661556Srgrimes		cmdputs("() ...");
12671556Srgrimes		break;
12681556Srgrimes	case NCMD:
12691556Srgrimes		for (np = n->ncmd.args ; np ; np = np->narg.next) {
12701556Srgrimes			cmdtxt(np);
12711556Srgrimes			if (np->narg.next)
12721556Srgrimes				cmdputs(" ");
12731556Srgrimes		}
12741556Srgrimes		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
12751556Srgrimes			cmdputs(" ");
12761556Srgrimes			cmdtxt(np);
12771556Srgrimes		}
12781556Srgrimes		break;
12791556Srgrimes	case NARG:
12801556Srgrimes		cmdputs(n->narg.text);
12811556Srgrimes		break;
12821556Srgrimes	case NTO:
12831556Srgrimes		p = ">";  i = 1;  goto redir;
12841556Srgrimes	case NAPPEND:
12851556Srgrimes		p = ">>";  i = 1;  goto redir;
12861556Srgrimes	case NTOFD:
12871556Srgrimes		p = ">&";  i = 1;  goto redir;
128896922Stjr	case NCLOBBER:
128996922Stjr		p = ">|"; i = 1; goto redir;
12901556Srgrimes	case NFROM:
12911556Srgrimes		p = "<";  i = 0;  goto redir;
129266612Sbrian	case NFROMTO:
129366612Sbrian		p = "<>";  i = 0;  goto redir;
12941556Srgrimes	case NFROMFD:
12951556Srgrimes		p = "<&";  i = 0;  goto redir;
12961556Srgrimesredir:
12971556Srgrimes		if (n->nfile.fd != i) {
12981556Srgrimes			s[0] = n->nfile.fd + '0';
12991556Srgrimes			s[1] = '\0';
13001556Srgrimes			cmdputs(s);
13011556Srgrimes		}
13021556Srgrimes		cmdputs(p);
13031556Srgrimes		if (n->type == NTOFD || n->type == NFROMFD) {
130499634Stjr			if (n->ndup.dupfd >= 0)
130599634Stjr				s[0] = n->ndup.dupfd + '0';
130699634Stjr			else
130799634Stjr				s[0] = '-';
13081556Srgrimes			s[1] = '\0';
13091556Srgrimes			cmdputs(s);
13101556Srgrimes		} else {
13111556Srgrimes			cmdtxt(n->nfile.fname);
13121556Srgrimes		}
13131556Srgrimes		break;
13141556Srgrimes	case NHERE:
13151556Srgrimes	case NXHERE:
13161556Srgrimes		cmdputs("<<...");
13171556Srgrimes		break;
13181556Srgrimes	default:
13191556Srgrimes		cmdputs("???");
13201556Srgrimes		break;
13211556Srgrimes	}
13221556Srgrimes}
13231556Srgrimes
13241556Srgrimes
13251556Srgrimes
1326213811Sobrienstatic void
1327201053Sjillescmdputs(const char *s)
132890111Simp{
1329201053Sjilles	const char *p;
1330201053Sjilles	char *q;
133125222Ssteve	char c;
13321556Srgrimes	int subtype = 0;
13331556Srgrimes
13341556Srgrimes	if (cmdnleft <= 0)
13351556Srgrimes		return;
13361556Srgrimes	p = s;
13371556Srgrimes	q = cmdnextc;
13381556Srgrimes	while ((c = *p++) != '\0') {
13391556Srgrimes		if (c == CTLESC)
13401556Srgrimes			*q++ = *p++;
13411556Srgrimes		else if (c == CTLVAR) {
13421556Srgrimes			*q++ = '$';
13431556Srgrimes			if (--cmdnleft > 0)
13441556Srgrimes				*q++ = '{';
13451556Srgrimes			subtype = *p++;
1346216246Sjilles			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1347216246Sjilles				*q++ = '#';
13481556Srgrimes		} else if (c == '=' && subtype != 0) {
1349216246Sjilles			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1350216246Sjilles			if (*q)
1351216246Sjilles				q++;
1352216246Sjilles			else
1353216246Sjilles				cmdnleft++;
1354216246Sjilles			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1355216246Sjilles			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1356216246Sjilles			    --cmdnleft > 0)
1357216246Sjilles				*q = q[-1], q++;
13581556Srgrimes			subtype = 0;
13591556Srgrimes		} else if (c == CTLENDVAR) {
13601556Srgrimes			*q++ = '}';
1361216246Sjilles		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1362216246Sjilles			cmdnleft -= 5;
1363216246Sjilles			if (cmdnleft > 0) {
1364216246Sjilles				*q++ = '$';
1365216246Sjilles				*q++ = '(';
1366216246Sjilles				*q++ = '.';
1367216246Sjilles				*q++ = '.';
1368216246Sjilles				*q++ = '.';
1369216246Sjilles				*q++ = ')';
1370216246Sjilles			}
1371216246Sjilles		} else if (c == CTLARI) {
1372216246Sjilles			cmdnleft -= 2;
1373216246Sjilles			if (cmdnleft > 0) {
1374216246Sjilles				*q++ = '$';
1375216246Sjilles				*q++ = '(';
1376216246Sjilles				*q++ = '(';
1377216246Sjilles			}
1378216246Sjilles			p++;
1379216246Sjilles		} else if (c == CTLENDARI) {
1380216246Sjilles			if (--cmdnleft > 0) {
1381216246Sjilles				*q++ = ')';
1382216246Sjilles				*q++ = ')';
1383216246Sjilles			}
1384216246Sjilles		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1385216246Sjilles			cmdnleft++; /* ignore */
13861556Srgrimes		else
13871556Srgrimes			*q++ = c;
13881556Srgrimes		if (--cmdnleft <= 0) {
13891556Srgrimes			*q++ = '.';
13901556Srgrimes			*q++ = '.';
13911556Srgrimes			*q++ = '.';
13921556Srgrimes			break;
13931556Srgrimes		}
13941556Srgrimes	}
13951556Srgrimes	cmdnextc = q;
13961556Srgrimes}
1397