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"
60230998Sjilles#include "exec.h"
6117987Speter#include "show.h"
621556Srgrimes#include "main.h"
631556Srgrimes#include "parser.h"
641556Srgrimes#include "nodes.h"
651556Srgrimes#include "jobs.h"
661556Srgrimes#include "options.h"
671556Srgrimes#include "trap.h"
681556Srgrimes#include "syntax.h"
691556Srgrimes#include "input.h"
701556Srgrimes#include "output.h"
711556Srgrimes#include "memalloc.h"
721556Srgrimes#include "error.h"
731556Srgrimes#include "mystring.h"
74223024Sjilles#include "var.h"
75223060Sjilles#include "builtins.h"
761556Srgrimes
771556Srgrimes
78213760Sobrienstatic struct job *jobtab;	/* array of jobs */
79213760Sobrienstatic int njobs;		/* size of array */
80253658Sjillesstatic pid_t backgndpid = -1;	/* pid of last background process */
81253658Sjillesstatic struct job *bgjob = NULL; /* last background process */
821556Srgrimes#if JOBS
83213760Sobrienstatic struct job *jobmru;	/* most recently used job list */
84213760Sobrienstatic pid_t initialpgrp;	/* pgrp of shell on invocation */
851556Srgrimes#endif
8699762Stjrstatic int ttyfd = -1;
871556Srgrimes
88238888Sjilles/* mode flags for dowait */
89238888Sjilles#define DOWAIT_BLOCK	0x1 /* wait until a child exits */
90255157Sjilles#define DOWAIT_SIG	0x2 /* if DOWAIT_BLOCK, abort on SIGINT/SIGQUIT */
91255157Sjilles#define DOWAIT_SIG_ANY	0x4 /* if DOWAIT_SIG, abort on any signal */
92238888Sjilles
9320425Ssteve#if JOBS
94213811Sobrienstatic void restartjob(struct job *);
9520425Ssteve#endif
96213811Sobrienstatic void freejob(struct job *);
97251429Sjillesstatic int waitcmdloop(struct job *);
98230530Scharnierpid_t getjobpgrp(char *);
99264168Sjillesstatic struct job *getjob_nonotfound(const char *);
100264168Sjillesstatic struct job *getjob(const char *);
101213811Sobrienstatic pid_t dowait(int, struct job *);
102213811Sobrienstatic void checkzombies(void);
103213811Sobrienstatic void cmdtxt(union node *);
104213811Sobrienstatic void cmdputs(const char *);
10597659Stjr#if JOBS
106213811Sobrienstatic void setcurjob(struct job *);
107213811Sobrienstatic void deljob(struct job *);
108213811Sobrienstatic struct job *getcurjob(struct job *);
10997659Stjr#endif
110216217Sjillesstatic void printjobcmd(struct job *);
111216217Sjillesstatic void showjob(struct job *, int);
1121556Srgrimes
1131556Srgrimes
1141556Srgrimes/*
1151556Srgrimes * Turn job control on and off.
1161556Srgrimes */
1171556Srgrimes
118253658Sjillesstatic int jobctl;
1191556Srgrimes
12020425Ssteve#if JOBS
1211556Srgrimesvoid
12290111Simpsetjobctl(int on)
12317987Speter{
12499762Stjr	int i;
1251556Srgrimes
1261556Srgrimes	if (on == jobctl || rootshell == 0)
1271556Srgrimes		return;
1281556Srgrimes	if (on) {
12999762Stjr		if (ttyfd != -1)
13099762Stjr			close(ttyfd);
131250267Sjilles		if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) < 0) {
13299762Stjr			i = 0;
13399762Stjr			while (i <= 2 && !isatty(i))
13499762Stjr				i++;
135250267Sjilles			if (i > 2 ||
136250267Sjilles			    (ttyfd = fcntl(i, F_DUPFD_CLOEXEC, 10)) < 0)
13799762Stjr				goto out;
13899762Stjr		}
139109927Stjr		if (ttyfd < 10) {
140109927Stjr			/*
141109927Stjr			 * Keep our TTY file descriptor out of the way of
142109927Stjr			 * the user's redirections.
143109927Stjr			 */
144250267Sjilles			if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) {
145109927Stjr				close(ttyfd);
146109927Stjr				ttyfd = -1;
147109927Stjr				goto out;
148109927Stjr			}
149109927Stjr			close(ttyfd);
150109927Stjr			ttyfd = i;
151109927Stjr		}
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
185254413Sjillesfgcmd(int argc __unused, char **argv __unused)
18617987Speter{
1871556Srgrimes	struct job *jp;
188100308Stjr	pid_t pgrp;
1891556Srgrimes	int status;
1901556Srgrimes
191254413Sjilles	nextopt("");
192254413Sjilles	jp = getjob(*argptr);
1931556Srgrimes	if (jp->jobctl == 0)
1941556Srgrimes		error("job not created under job control");
195216217Sjilles	printjobcmd(jp);
19696933Stjr	flushout(&output);
1971556Srgrimes	pgrp = jp->ps[0].pid;
19899762Stjr	tcsetpgrp(ttyfd, pgrp);
1991556Srgrimes	restartjob(jp);
200100305Stjr	jp->foreground = 1;
2011556Srgrimes	INTOFF;
20245916Scracauer	status = waitforjob(jp, (int *)NULL);
2031556Srgrimes	INTON;
2041556Srgrimes	return status;
2051556Srgrimes}
2061556Srgrimes
2071556Srgrimes
20817987Speterint
20990111Simpbgcmd(int argc, char **argv)
21017987Speter{
2111556Srgrimes	struct job *jp;
2121556Srgrimes
213254413Sjilles	nextopt("");
2141556Srgrimes	do {
215254413Sjilles		jp = getjob(*argptr);
2161556Srgrimes		if (jp->jobctl == 0)
2171556Srgrimes			error("job not created under job control");
21896933Stjr		if (jp->state == JOBDONE)
21996933Stjr			continue;
2201556Srgrimes		restartjob(jp);
221100305Stjr		jp->foreground = 0;
222216400Sjilles		out1fmt("[%td] ", jp - jobtab + 1);
223216217Sjilles		printjobcmd(jp);
224254413Sjilles	} while (*argptr != NULL && *++argptr != NULL);
2251556Srgrimes	return 0;
2261556Srgrimes}
2271556Srgrimes
2281556Srgrimes
229213811Sobrienstatic void
23090111Simprestartjob(struct job *jp)
23117987Speter{
2321556Srgrimes	struct procstat *ps;
2331556Srgrimes	int i;
2341556Srgrimes
2351556Srgrimes	if (jp->state == JOBDONE)
2361556Srgrimes		return;
23797660Stjr	setcurjob(jp);
2381556Srgrimes	INTOFF;
239216400Sjilles	kill(-jp->ps[0].pid, SIGCONT);
2401556Srgrimes	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
24126104Ssteve		if (WIFSTOPPED(ps->status)) {
2421556Srgrimes			ps->status = -1;
2431556Srgrimes			jp->state = 0;
2441556Srgrimes		}
2451556Srgrimes	}
2461556Srgrimes	INTON;
2471556Srgrimes}
2481556Srgrimes#endif
2491556Srgrimes
2501556Srgrimes
2511556Srgrimesint
252240541Sjillesjobscmd(int argc __unused, char *argv[] __unused)
25317987Speter{
25497669Stjr	char *id;
255163085Sstefanf	int ch, mode;
25697669Stjr
257163085Sstefanf	mode = SHOWJOBS_DEFAULT;
258240541Sjilles	while ((ch = nextopt("lps")) != '\0') {
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		}
27097669Stjr	}
27197669Stjr
272240541Sjilles	if (*argptr == NULL)
273163085Sstefanf		showjobs(0, mode);
27497669Stjr	else
275240541Sjilles		while ((id = *argptr++) != NULL)
276216217Sjilles			showjob(getjob(id), mode);
27797669Stjr
27897669Stjr	return (0);
2791556Srgrimes}
2801556Srgrimes
281213811Sobrienstatic void
282216217Sjillesprintjobcmd(struct job *jp)
28397663Stjr{
284216217Sjilles	struct procstat *ps;
285216217Sjilles	int i;
286216217Sjilles
287216217Sjilles	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
288216217Sjilles		out1str(ps->cmd);
289216217Sjilles		if (i > 0)
290216217Sjilles			out1str(" | ");
291216217Sjilles	}
292216217Sjilles	out1c('\n');
293216217Sjilles}
294216217Sjilles
295216217Sjillesstatic void
296216217Sjillesshowjob(struct job *jp, int mode)
297216217Sjilles{
29897663Stjr	char s[64];
299216217Sjilles	char statestr[64];
300244682Sjilles	const char *sigstr;
30197663Stjr	struct procstat *ps;
30297669Stjr	struct job *j;
30397669Stjr	int col, curr, i, jobno, prev, procno;
30497669Stjr	char c;
3051556Srgrimes
306163085Sstefanf	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
30797663Stjr	jobno = jp - jobtab + 1;
30897669Stjr	curr = prev = 0;
30997669Stjr#if JOBS
31097669Stjr	if ((j = getcurjob(NULL)) != NULL) {
31197669Stjr		curr = j - jobtab + 1;
31297669Stjr		if ((j = getcurjob(j)) != NULL)
31397669Stjr			prev = j - jobtab + 1;
31497669Stjr	}
31597669Stjr#endif
316216217Sjilles	ps = jp->ps + jp->nprocs - 1;
317216217Sjilles	if (jp->state == 0) {
318216217Sjilles		strcpy(statestr, "Running");
319216217Sjilles#if JOBS
320216217Sjilles	} else if (jp->state == JOBSTOPPED) {
321216217Sjilles		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
322216217Sjilles			ps--;
323216217Sjilles		if (WIFSTOPPED(ps->status))
324216217Sjilles			i = WSTOPSIG(ps->status);
325216217Sjilles		else
326216217Sjilles			i = -1;
327244682Sjilles		sigstr = strsignal(i);
328244682Sjilles		if (sigstr != NULL)
329244682Sjilles			strcpy(statestr, sigstr);
330216217Sjilles		else
331216217Sjilles			strcpy(statestr, "Suspended");
332216217Sjilles#endif
333216217Sjilles	} else if (WIFEXITED(ps->status)) {
334216217Sjilles		if (WEXITSTATUS(ps->status) == 0)
335216217Sjilles			strcpy(statestr, "Done");
336216217Sjilles		else
337216220Sjilles			fmtstr(statestr, 64, "Done(%d)",
338216217Sjilles			    WEXITSTATUS(ps->status));
339216217Sjilles	} else {
340216217Sjilles		i = WTERMSIG(ps->status);
341244682Sjilles		sigstr = strsignal(i);
342244682Sjilles		if (sigstr != NULL)
343244682Sjilles			strcpy(statestr, sigstr);
344216217Sjilles		else
345244682Sjilles			strcpy(statestr, "Unknown signal");
346216217Sjilles		if (WCOREDUMP(ps->status))
347216217Sjilles			strcat(statestr, " (core dumped)");
348216217Sjilles	}
349216217Sjilles
35097663Stjr	for (ps = jp->ps ; ; ps++) {	/* for each process */
351163085Sstefanf		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
352216199Sjilles			out1fmt("%d\n", (int)ps->pid);
35397669Stjr			goto skip;
35497669Stjr		}
355216217Sjilles		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
35697669Stjr			goto skip;
35797819Stjr		if (jobno == curr && ps == jp->ps)
35897669Stjr			c = '+';
35997819Stjr		else if (jobno == prev && ps == jp->ps)
36097669Stjr			c = '-';
36197669Stjr		else
36297669Stjr			c = ' ';
36397663Stjr		if (ps == jp->ps)
36497669Stjr			fmtstr(s, 64, "[%d] %c ", jobno, c);
36597663Stjr		else
36697816Stjr			fmtstr(s, 64, "    %c ", c);
36797663Stjr		out1str(s);
36897663Stjr		col = strlen(s);
369163085Sstefanf		if (mode == SHOWJOBS_VERBOSE) {
370100308Stjr			fmtstr(s, 64, "%d ", (int)ps->pid);
37197669Stjr			out1str(s);
37297669Stjr			col += strlen(s);
37397669Stjr		}
374216217Sjilles		if (ps == jp->ps) {
375216217Sjilles			out1str(statestr);
376216217Sjilles			col += strlen(statestr);
37797663Stjr		}
37897663Stjr		do {
37997663Stjr			out1c(' ');
38097663Stjr			col++;
38197663Stjr		} while (col < 30);
382216217Sjilles		if (mode == SHOWJOBS_VERBOSE) {
383216217Sjilles			out1str(ps->cmd);
384216217Sjilles			out1c('\n');
385216217Sjilles		} else
386216217Sjilles			printjobcmd(jp);
38797669Stjrskip:		if (--procno <= 0)
38897663Stjr			break;
38997663Stjr	}
39097663Stjr}
39197663Stjr
3921556Srgrimes/*
3931556Srgrimes * Print a list of jobs.  If "change" is nonzero, only print jobs whose
3941556Srgrimes * statuses have changed since the last call to showjobs.
3951556Srgrimes *
3961556Srgrimes * If the shell is interrupted in the process of creating a job, the
3971556Srgrimes * result may be a job structure containing zero processes.  Such structures
3981556Srgrimes * will be freed here.
3991556Srgrimes */
4001556Srgrimes
4011556Srgrimesvoid
402163085Sstefanfshowjobs(int change, int mode)
40317987Speter{
4041556Srgrimes	int jobno;
4051556Srgrimes	struct job *jp;
4061556Srgrimes
4071556Srgrimes	TRACE(("showjobs(%d) called\n", change));
408208489Sjilles	checkzombies();
4091556Srgrimes	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
4101556Srgrimes		if (! jp->used)
4111556Srgrimes			continue;
4121556Srgrimes		if (jp->nprocs == 0) {
4131556Srgrimes			freejob(jp);
4141556Srgrimes			continue;
4151556Srgrimes		}
4161556Srgrimes		if (change && ! jp->changed)
4171556Srgrimes			continue;
418216217Sjilles		showjob(jp, mode);
419249984Sjilles		if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
420249984Sjilles			jp->changed = 0;
421249984Sjilles			/* Hack: discard jobs for which $! has not been
422249984Sjilles			 * referenced in interactive mode when they terminate.
423249984Sjilles			 */
424249984Sjilles			if (jp->state == JOBDONE && !jp->remembered &&
425249984Sjilles					(iflag || jp != bgjob)) {
426249984Sjilles				freejob(jp);
427249984Sjilles			}
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
462248349Sjilleswaitcmd(int argc __unused, char **argv __unused)
46317987Speter{
4641556Srgrimes	struct job *job;
465251429Sjilles	int retval;
4661556Srgrimes
467248349Sjilles	nextopt("");
468251429Sjilles	if (*argptr == NULL)
469251429Sjilles		return (waitcmdloop(NULL));
470251429Sjilles
471251429Sjilles	do {
472251430Sjilles		job = getjob_nonotfound(*argptr);
473251430Sjilles		if (job == NULL)
474251430Sjilles			retval = 127;
475251430Sjilles		else
476251430Sjilles			retval = waitcmdloop(job);
477251429Sjilles		argptr++;
478251429Sjilles	} while (*argptr != NULL);
47938536Scracauer
480251429Sjilles	return (retval);
481251429Sjilles}
482251429Sjilles
483251429Sjillesstatic int
484251429Sjilleswaitcmdloop(struct job *job)
485251429Sjilles{
486255157Sjilles	int status, retval, sig;
487251429Sjilles	struct job *jp;
488251429Sjilles
48938536Scracauer	/*
49038536Scracauer	 * Loop until a process is terminated or stopped, or a SIGINT is
49138536Scracauer	 * received.
49238536Scracauer	 */
49338536Scracauer
49438536Scracauer	do {
4951556Srgrimes		if (job != NULL) {
496254767Sjilles			if (job->state == JOBDONE) {
4971556Srgrimes				status = job->ps[job->nprocs - 1].status;
49826104Ssteve				if (WIFEXITED(status))
49926104Ssteve					retval = WEXITSTATUS(status);
5001556Srgrimes				else
50126104Ssteve					retval = WTERMSIG(status) + 128;
502209600Sjilles				if (! iflag || ! job->changed)
5031556Srgrimes					freejob(job);
504209600Sjilles				else {
505209600Sjilles					job->remembered = 0;
506209600Sjilles					if (job == bgjob)
507209600Sjilles						bgjob = NULL;
508209600Sjilles				}
50926104Ssteve				return retval;
5101556Srgrimes			}
5111556Srgrimes		} else {
512209600Sjilles			for (jp = jobtab ; jp < jobtab + njobs; jp++)
513209600Sjilles				if (jp->used && jp->state == JOBDONE) {
514209600Sjilles					if (! iflag || ! jp->changed)
515209600Sjilles						freejob(jp);
516209600Sjilles					else {
517209600Sjilles						jp->remembered = 0;
518209600Sjilles						if (jp == bgjob)
519209600Sjilles							bgjob = NULL;
520209600Sjilles					}
521209600Sjilles				}
5221556Srgrimes			for (jp = jobtab ; ; jp++) {
5231556Srgrimes				if (jp >= jobtab + njobs) {	/* no running procs */
5241556Srgrimes					return 0;
5251556Srgrimes				}
5261556Srgrimes				if (jp->used && jp->state == 0)
5271556Srgrimes					break;
5281556Srgrimes			}
5291556Srgrimes		}
530238888Sjilles	} while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, (struct job *)NULL) != -1);
53138521Scracauer
532255157Sjilles	sig = pendingsig_waitcmd;
533255157Sjilles	pendingsig_waitcmd = 0;
534255157Sjilles	return sig + 128;
5351556Srgrimes}
5361556Srgrimes
5371556Srgrimes
5381556Srgrimes
53917987Speterint
540254413Sjillesjobidcmd(int argc __unused, char **argv __unused)
54117987Speter{
5421556Srgrimes	struct job *jp;
5431556Srgrimes	int i;
5441556Srgrimes
545254413Sjilles	nextopt("");
546254413Sjilles	jp = getjob(*argptr);
5471556Srgrimes	for (i = 0 ; i < jp->nprocs ; ) {
548100308Stjr		out1fmt("%d", (int)jp->ps[i].pid);
5491556Srgrimes		out1c(++i < jp->nprocs? ' ' : '\n');
5501556Srgrimes	}
5511556Srgrimes	return 0;
5521556Srgrimes}
5531556Srgrimes
5541556Srgrimes
5551556Srgrimes
5561556Srgrimes/*
5571556Srgrimes * Convert a job name to a job structure.
5581556Srgrimes */
5591556Srgrimes
560213811Sobrienstatic struct job *
561264168Sjillesgetjob_nonotfound(const char *name)
56290111Simp{
5631556Srgrimes	int jobno;
56497688Stjr	struct job *found, *jp;
565100308Stjr	pid_t pid;
5661556Srgrimes	int i;
5671556Srgrimes
5681556Srgrimes	if (name == NULL) {
5691556Srgrimes#if JOBS
57097659Stjrcurrentjob:	if ((jp = getcurjob(NULL)) == NULL)
5711556Srgrimes			error("No current job");
57297659Stjr		return (jp);
5731556Srgrimes#else
5741556Srgrimes		error("No current job");
5751556Srgrimes#endif
5761556Srgrimes	} else if (name[0] == '%') {
5771556Srgrimes		if (is_digit(name[1])) {
5781556Srgrimes			jobno = number(name + 1);
5791556Srgrimes			if (jobno > 0 && jobno <= njobs
5801556Srgrimes			 && jobtab[jobno - 1].used != 0)
5811556Srgrimes				return &jobtab[jobno - 1];
5821556Srgrimes#if JOBS
5831556Srgrimes		} else if (name[1] == '%' && name[2] == '\0') {
5841556Srgrimes			goto currentjob;
58597688Stjr		} else if (name[1] == '+' && name[2] == '\0') {
58697688Stjr			goto currentjob;
58797688Stjr		} else if (name[1] == '-' && name[2] == '\0') {
58897688Stjr			if ((jp = getcurjob(NULL)) == NULL ||
58997688Stjr			    (jp = getcurjob(jp)) == NULL)
59097688Stjr				error("No previous job");
59197688Stjr			return (jp);
5921556Srgrimes#endif
59397688Stjr		} else if (name[1] == '?') {
59497688Stjr			found = NULL;
59597688Stjr			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
59697688Stjr				if (jp->used && jp->nprocs > 0
59797688Stjr				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
59897688Stjr					if (found)
59997688Stjr						error("%s: ambiguous", name);
60097688Stjr					found = jp;
60197688Stjr				}
60297688Stjr			}
60397688Stjr			if (found != NULL)
60497688Stjr				return (found);
6051556Srgrimes		} else {
60697688Stjr			found = NULL;
6071556Srgrimes			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6081556Srgrimes				if (jp->used && jp->nprocs > 0
6091556Srgrimes				 && prefix(name + 1, jp->ps[0].cmd)) {
6101556Srgrimes					if (found)
6111556Srgrimes						error("%s: ambiguous", name);
6121556Srgrimes					found = jp;
6131556Srgrimes				}
6141556Srgrimes			}
6151556Srgrimes			if (found)
6161556Srgrimes				return found;
6171556Srgrimes		}
6181556Srgrimes	} else if (is_number(name)) {
619100308Stjr		pid = (pid_t)number(name);
6201556Srgrimes		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6211556Srgrimes			if (jp->used && jp->nprocs > 0
6221556Srgrimes			 && jp->ps[jp->nprocs - 1].pid == pid)
6231556Srgrimes				return jp;
6241556Srgrimes		}
6251556Srgrimes	}
62617987Speter	return NULL;
6271556Srgrimes}
6281556Srgrimes
6291556Srgrimes
630251430Sjillesstatic struct job *
631264168Sjillesgetjob(const char *name)
632251430Sjilles{
633251430Sjilles	struct job *jp;
634251430Sjilles
635251430Sjilles	jp = getjob_nonotfound(name);
636251430Sjilles	if (jp == NULL)
637251430Sjilles		error("No such job: %s", name);
638251430Sjilles	return (jp);
639251430Sjilles}
640251430Sjilles
641251430Sjilles
642216629Sjillespid_t
643216629Sjillesgetjobpgrp(char *name)
644216629Sjilles{
645216629Sjilles	struct job *jp;
6461556Srgrimes
647216629Sjilles	jp = getjob(name);
648216629Sjilles	return -jp->ps[0].pid;
649216629Sjilles}
650216629Sjilles
6511556Srgrimes/*
6521556Srgrimes * Return a new job structure,
6531556Srgrimes */
6541556Srgrimes
6551556Srgrimesstruct job *
65690111Simpmakejob(union node *node __unused, int nprocs)
65717987Speter{
6581556Srgrimes	int i;
6591556Srgrimes	struct job *jp;
6601556Srgrimes
6611556Srgrimes	for (i = njobs, jp = jobtab ; ; jp++) {
6621556Srgrimes		if (--i < 0) {
6631556Srgrimes			INTOFF;
6641556Srgrimes			if (njobs == 0) {
6651556Srgrimes				jobtab = ckmalloc(4 * sizeof jobtab[0]);
66697664Stjr#if JOBS
66797659Stjr				jobmru = NULL;
66897664Stjr#endif
6691556Srgrimes			} else {
6701556Srgrimes				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
67117987Speter				memcpy(jp, jobtab, njobs * sizeof jp[0]);
67297659Stjr#if JOBS
67397659Stjr				/* Relocate `next' pointers and list head */
67499760Stjr				if (jobmru != NULL)
67599760Stjr					jobmru = &jp[jobmru - jobtab];
67697659Stjr				for (i = 0; i < njobs; i++)
67797659Stjr					if (jp[i].next != NULL)
67897659Stjr						jp[i].next = &jp[jp[i].next -
67997659Stjr						    jobtab];
68097659Stjr#endif
681209600Sjilles				if (bgjob != NULL)
682209600Sjilles					bgjob = &jp[bgjob - jobtab];
68320425Ssteve				/* Relocate `ps' pointers */
68420425Ssteve				for (i = 0; i < njobs; i++)
68520425Ssteve					if (jp[i].ps == &jobtab[i].ps0)
68620425Ssteve						jp[i].ps = &jp[i].ps0;
6871556Srgrimes				ckfree(jobtab);
6881556Srgrimes				jobtab = jp;
6891556Srgrimes			}
6901556Srgrimes			jp = jobtab + njobs;
691248980Sjilles			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
692248980Sjilles				;
6931556Srgrimes			INTON;
6941556Srgrimes			break;
6951556Srgrimes		}
6961556Srgrimes		if (jp->used == 0)
6971556Srgrimes			break;
6981556Srgrimes	}
6991556Srgrimes	INTOFF;
7001556Srgrimes	jp->state = 0;
7011556Srgrimes	jp->used = 1;
7021556Srgrimes	jp->changed = 0;
7031556Srgrimes	jp->nprocs = 0;
704100305Stjr	jp->foreground = 0;
705209600Sjilles	jp->remembered = 0;
7061556Srgrimes#if JOBS
7071556Srgrimes	jp->jobctl = jobctl;
70897659Stjr	jp->next = NULL;
7091556Srgrimes#endif
7101556Srgrimes	if (nprocs > 1) {
7111556Srgrimes		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
7121556Srgrimes	} else {
7131556Srgrimes		jp->ps = &jp->ps0;
7141556Srgrimes	}
7151556Srgrimes	INTON;
716213775Sjhb	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
71717987Speter	    jp - jobtab + 1));
7181556Srgrimes	return jp;
7198855Srgrimes}
7201556Srgrimes
72197659Stjr#if JOBS
722213811Sobrienstatic void
72397659Stjrsetcurjob(struct job *cj)
72497659Stjr{
72597659Stjr	struct job *jp, *prev;
7261556Srgrimes
72797659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
72897659Stjr		if (jp == cj) {
72997659Stjr			if (prev != NULL)
73097659Stjr				prev->next = jp->next;
73197659Stjr			else
73297659Stjr				jobmru = jp->next;
73397659Stjr			jp->next = jobmru;
73497659Stjr			jobmru = cj;
73597659Stjr			return;
73697659Stjr		}
73797659Stjr	}
73897659Stjr	cj->next = jobmru;
73997659Stjr	jobmru = cj;
74097659Stjr}
74197659Stjr
742213811Sobrienstatic void
74397659Stjrdeljob(struct job *j)
74497659Stjr{
74597659Stjr	struct job *jp, *prev;
74697659Stjr
74797659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
74897659Stjr		if (jp == j) {
74997659Stjr			if (prev != NULL)
75097659Stjr				prev->next = jp->next;
75197659Stjr			else
75297659Stjr				jobmru = jp->next;
75397659Stjr			return;
75497659Stjr		}
75597659Stjr	}
75697659Stjr}
75797659Stjr
7581556Srgrimes/*
75997659Stjr * Return the most recently used job that isn't `nj', and preferably one
76097659Stjr * that is stopped.
76197659Stjr */
762213811Sobrienstatic struct job *
76397659Stjrgetcurjob(struct job *nj)
76497659Stjr{
76597659Stjr	struct job *jp;
76697659Stjr
76797659Stjr	/* Try to find a stopped one.. */
76897659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
76997659Stjr		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
77097659Stjr			return (jp);
77197659Stjr	/* Otherwise the most recently used job that isn't `nj' */
77297659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
77397659Stjr		if (jp->used && jp != nj)
77497659Stjr			return (jp);
77597659Stjr
77697659Stjr	return (NULL);
77797659Stjr}
77897659Stjr
77997659Stjr#endif
78097659Stjr
78197659Stjr/*
7821556Srgrimes * Fork of a subshell.  If we are doing job control, give the subshell its
7831556Srgrimes * own process group.  Jp is a job structure that the job is to be added to.
7841556Srgrimes * N is the command that will be evaluated by the child.  Both jp and n may
7851556Srgrimes * be NULL.  The mode parameter can be one of the following:
7861556Srgrimes *	FORK_FG - Fork off a foreground process.
7871556Srgrimes *	FORK_BG - Fork off a background process.
7881556Srgrimes *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
7891556Srgrimes *		     process group even if job control is on.
7901556Srgrimes *
7911556Srgrimes * When job control is turned off, background processes have their standard
7921556Srgrimes * input redirected to /dev/null (except for the second and later processes
7931556Srgrimes * in a pipeline).
7941556Srgrimes */
7951556Srgrimes
796100308Stjrpid_t
79790111Simpforkshell(struct job *jp, union node *n, int mode)
79817987Speter{
799100308Stjr	pid_t pid;
800100308Stjr	pid_t pgrp;
8011556Srgrimes
802213775Sjhb	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
80317987Speter	    mode));
8041556Srgrimes	INTOFF;
805216208Sjilles	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
806208489Sjilles		checkzombies();
807112341Stjr	flushall();
8081556Srgrimes	pid = fork();
8091556Srgrimes	if (pid == -1) {
8101556Srgrimes		TRACE(("Fork failed, errno=%d\n", errno));
8111556Srgrimes		INTON;
81253891Scracauer		error("Cannot fork: %s", strerror(errno));
8131556Srgrimes	}
8141556Srgrimes	if (pid == 0) {
8151556Srgrimes		struct job *p;
8161556Srgrimes		int wasroot;
8171556Srgrimes		int i;
8181556Srgrimes
819100308Stjr		TRACE(("Child shell %d\n", (int)getpid()));
8201556Srgrimes		wasroot = rootshell;
8211556Srgrimes		rootshell = 0;
822200998Sjilles		handler = &main_handler;
8231556Srgrimes		closescript();
8241556Srgrimes		INTON;
825223024Sjilles		forcelocal = 0;
8261556Srgrimes		clear_traps();
8271556Srgrimes#if JOBS
8281556Srgrimes		jobctl = 0;		/* do job control only in root shell */
8291556Srgrimes		if (wasroot && mode != FORK_NOJOB && mflag) {
8301556Srgrimes			if (jp == NULL || jp->nprocs == 0)
8311556Srgrimes				pgrp = getpid();
8321556Srgrimes			else
8331556Srgrimes				pgrp = jp->ps[0].pid;
83421352Ssteve			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
8351556Srgrimes				/*** this causes superfluous TIOCSPGRPS ***/
83699762Stjr				if (tcsetpgrp(ttyfd, pgrp) < 0)
83720425Ssteve					error("tcsetpgrp failed, errno=%d", errno);
8381556Srgrimes			}
8391556Srgrimes			setsignal(SIGTSTP);
8401556Srgrimes			setsignal(SIGTTOU);
8411556Srgrimes		} else if (mode == FORK_BG) {
8421556Srgrimes			ignoresig(SIGINT);
8431556Srgrimes			ignoresig(SIGQUIT);
8441556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8451556Srgrimes			    ! fd0_redirected_p ()) {
8461556Srgrimes				close(0);
84769793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
848222684Sjilles					error("cannot open %s: %s",
84969793Sobrien					    _PATH_DEVNULL, strerror(errno));
8501556Srgrimes			}
8511556Srgrimes		}
8521556Srgrimes#else
8531556Srgrimes		if (mode == FORK_BG) {
8541556Srgrimes			ignoresig(SIGINT);
8551556Srgrimes			ignoresig(SIGQUIT);
8561556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8571556Srgrimes			    ! fd0_redirected_p ()) {
8581556Srgrimes				close(0);
85969793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
860222684Sjilles					error("cannot open %s: %s",
86169793Sobrien					    _PATH_DEVNULL, strerror(errno));
8621556Srgrimes			}
8631556Srgrimes		}
8641556Srgrimes#endif
865102051Stjr		INTOFF;
866102051Stjr		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
867102051Stjr			if (p->used)
868102051Stjr				freejob(p);
869102051Stjr		INTON;
8701556Srgrimes		if (wasroot && iflag) {
8711556Srgrimes			setsignal(SIGINT);
8721556Srgrimes			setsignal(SIGQUIT);
8731556Srgrimes			setsignal(SIGTERM);
8741556Srgrimes		}
8751556Srgrimes		return pid;
8761556Srgrimes	}
8771556Srgrimes	if (rootshell && mode != FORK_NOJOB && mflag) {
8781556Srgrimes		if (jp == NULL || jp->nprocs == 0)
8791556Srgrimes			pgrp = pid;
8801556Srgrimes		else
8811556Srgrimes			pgrp = jp->ps[0].pid;
88217987Speter		setpgid(pid, pgrp);
8831556Srgrimes	}
884209600Sjilles	if (mode == FORK_BG) {
885209600Sjilles		if (bgjob != NULL && bgjob->state == JOBDONE &&
886209600Sjilles		    !bgjob->remembered && !iflag)
887209600Sjilles			freejob(bgjob);
8881556Srgrimes		backgndpid = pid;		/* set $! */
889209600Sjilles		bgjob = jp;
890209600Sjilles	}
8911556Srgrimes	if (jp) {
8921556Srgrimes		struct procstat *ps = &jp->ps[jp->nprocs++];
8931556Srgrimes		ps->pid = pid;
8941556Srgrimes		ps->status = -1;
8951556Srgrimes		ps->cmd = nullstr;
8961556Srgrimes		if (iflag && rootshell && n)
8971556Srgrimes			ps->cmd = commandtext(n);
898100305Stjr		jp->foreground = mode == FORK_FG;
89997659Stjr#if JOBS
90097659Stjr		setcurjob(jp);
90197659Stjr#endif
9021556Srgrimes	}
9031556Srgrimes	INTON;
904100308Stjr	TRACE(("In parent shell:  child = %d\n", (int)pid));
9051556Srgrimes	return pid;
9061556Srgrimes}
9071556Srgrimes
9081556Srgrimes
909230998Sjillespid_t
910230998Sjillesvforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
911230998Sjilles{
912230998Sjilles	pid_t pid;
913230998Sjilles	struct jmploc jmploc;
914230998Sjilles	struct jmploc *savehandler;
9151556Srgrimes
916233792Sjilles	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
917233792Sjilles	    (void *)pip));
918230998Sjilles	INTOFF;
919230998Sjilles	flushall();
920230998Sjilles	savehandler = handler;
921230998Sjilles	pid = vfork();
922230998Sjilles	if (pid == -1) {
923230998Sjilles		TRACE(("Vfork failed, errno=%d\n", errno));
924230998Sjilles		INTON;
925230998Sjilles		error("Cannot fork: %s", strerror(errno));
926230998Sjilles	}
927230998Sjilles	if (pid == 0) {
928230998Sjilles		TRACE(("Child shell %d\n", (int)getpid()));
929230998Sjilles		if (setjmp(jmploc.loc))
930230998Sjilles			_exit(exception == EXEXEC ? exerrno : 2);
931230998Sjilles		if (pip != NULL) {
932230998Sjilles			close(pip[0]);
933230998Sjilles			if (pip[1] != 1) {
934230998Sjilles				dup2(pip[1], 1);
935230998Sjilles				close(pip[1]);
936230998Sjilles			}
937230998Sjilles		}
938230998Sjilles		handler = &jmploc;
939230998Sjilles		shellexec(argv, envp, path, idx);
940230998Sjilles	}
941230998Sjilles	handler = savehandler;
942230998Sjilles	if (jp) {
943230998Sjilles		struct procstat *ps = &jp->ps[jp->nprocs++];
944230998Sjilles		ps->pid = pid;
945230998Sjilles		ps->status = -1;
946230998Sjilles		ps->cmd = nullstr;
947230998Sjilles		jp->foreground = 1;
948230998Sjilles#if JOBS
949230998Sjilles		setcurjob(jp);
950230998Sjilles#endif
951230998Sjilles	}
952230998Sjilles	INTON;
953230998Sjilles	TRACE(("In parent shell:  child = %d\n", (int)pid));
954230998Sjilles	return pid;
955230998Sjilles}
956230998Sjilles
957230998Sjilles
9581556Srgrimes/*
9591556Srgrimes * Wait for job to finish.
9601556Srgrimes *
9611556Srgrimes * Under job control we have the problem that while a child process is
9621556Srgrimes * running interrupts generated by the user are sent to the child but not
9631556Srgrimes * to the shell.  This means that an infinite loop started by an inter-
9641556Srgrimes * active user may be hard to kill.  With job control turned off, an
9651556Srgrimes * interactive user may place an interactive program inside a loop.  If
9661556Srgrimes * the interactive program catches interrupts, the user doesn't want
9671556Srgrimes * these interrupts to also abort the loop.  The approach we take here
9681556Srgrimes * is to have the shell ignore interrupt signals while waiting for a
96946684Skris * foreground process to terminate, and then send itself an interrupt
9701556Srgrimes * signal if the child process was terminated by an interrupt signal.
9711556Srgrimes * Unfortunately, some programs want to do a bit of cleanup and then
9721556Srgrimes * exit on interrupt; unless these processes terminate themselves by
9731556Srgrimes * sending a signal to themselves (instead of calling exit) they will
9741556Srgrimes * confuse this approach.
9751556Srgrimes */
9761556Srgrimes
9771556Srgrimesint
97890111Simpwaitforjob(struct job *jp, int *origstatus)
97945916Scracauer{
9801556Srgrimes#if JOBS
981208881Sjilles	int propagate_int = jp->jobctl && jp->foreground;
9821556Srgrimes#endif
9831556Srgrimes	int status;
9841556Srgrimes	int st;
9851556Srgrimes
9861556Srgrimes	INTOFF;
987213775Sjhb	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
98838950Scracauer	while (jp->state == 0)
989255157Sjilles		if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
990255157Sjilles		    DOWAIT_SIG_ANY : 0), jp) == -1)
99138950Scracauer			dotrap();
9921556Srgrimes#if JOBS
9931556Srgrimes	if (jp->jobctl) {
994262951Sjmmv		if (tcsetpgrp(ttyfd, rootpid) < 0)
99520425Ssteve			error("tcsetpgrp failed, errno=%d\n", errno);
9961556Srgrimes	}
9971556Srgrimes	if (jp->state == JOBSTOPPED)
99897659Stjr		setcurjob(jp);
9991556Srgrimes#endif
10001556Srgrimes	status = jp->ps[jp->nprocs - 1].status;
100145916Scracauer	if (origstatus != NULL)
100245916Scracauer		*origstatus = status;
10031556Srgrimes	/* convert to 8 bits */
100426104Ssteve	if (WIFEXITED(status))
100526104Ssteve		st = WEXITSTATUS(status);
10061556Srgrimes#if JOBS
100726104Ssteve	else if (WIFSTOPPED(status))
100826104Ssteve		st = WSTOPSIG(status) + 128;
10091556Srgrimes#endif
10101556Srgrimes	else
101126104Ssteve		st = WTERMSIG(status) + 128;
10121556Srgrimes	if (! JOBS || jp->state == JOBDONE)
10131556Srgrimes		freejob(jp);
101438521Scracauer	if (int_pending()) {
1015216400Sjilles		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
101638521Scracauer			CLEAR_PENDING_INT;
101738521Scracauer	}
1018208881Sjilles#if JOBS
1019208881Sjilles	else if (rootshell && iflag && propagate_int &&
1020208881Sjilles			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1021208881Sjilles		kill(getpid(), SIGINT);
1022208881Sjilles#endif
10231556Srgrimes	INTON;
10241556Srgrimes	return st;
10251556Srgrimes}
10261556Srgrimes
10271556Srgrimes
1028238888Sjillesstatic void
1029248980Sjillesdummy_handler(int sig __unused)
1030238888Sjilles{
1031238888Sjilles}
10321556Srgrimes
10331556Srgrimes/*
10341556Srgrimes * Wait for a process to terminate.
10351556Srgrimes */
10361556Srgrimes
1037213811Sobrienstatic pid_t
1038238888Sjillesdowait(int mode, struct job *job)
103917987Speter{
1040238888Sjilles	struct sigaction sa, osa;
1041238888Sjilles	sigset_t mask, omask;
1042100308Stjr	pid_t pid;
10431556Srgrimes	int status;
10441556Srgrimes	struct procstat *sp;
10451556Srgrimes	struct job *jp;
10461556Srgrimes	struct job *thisjob;
1047244682Sjilles	const char *sigstr;
10481556Srgrimes	int done;
10491556Srgrimes	int stopped;
105026104Ssteve	int sig;
1051216217Sjilles	int coredump;
1052238866Sjilles	int wflags;
1053238888Sjilles	int restore_sigchld;
10541556Srgrimes
1055246495Sdelphij	TRACE(("dowait(%d, %p) called\n", mode, job));
1056238888Sjilles	restore_sigchld = 0;
1057238888Sjilles	if ((mode & DOWAIT_SIG) != 0) {
1058238888Sjilles		sigfillset(&mask);
1059238888Sjilles		sigprocmask(SIG_BLOCK, &mask, &omask);
1060238888Sjilles		INTOFF;
1061238888Sjilles		if (!issigchldtrapped()) {
1062238888Sjilles			restore_sigchld = 1;
1063238888Sjilles			sa.sa_handler = dummy_handler;
1064238888Sjilles			sa.sa_flags = 0;
1065238888Sjilles			sigemptyset(&sa.sa_mask);
1066238888Sjilles			sigaction(SIGCHLD, &sa, &osa);
1067238888Sjilles		}
1068238888Sjilles	}
10691556Srgrimes	do {
1070238866Sjilles#if JOBS
1071238867Sjilles		if (iflag)
1072238867Sjilles			wflags = WUNTRACED | WCONTINUED;
1073238867Sjilles		else
1074238866Sjilles#endif
1075238867Sjilles			wflags = 0;
1076238888Sjilles		if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1077238866Sjilles			wflags |= WNOHANG;
1078238866Sjilles		pid = wait3(&status, wflags, (struct rusage *)NULL);
1079100308Stjr		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1080238888Sjilles		if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1081255157Sjilles			pid = -1;
1082255157Sjilles			if (((mode & DOWAIT_SIG_ANY) != 0 ?
1083255157Sjilles			    pendingsig : pendingsig_waitcmd) != 0) {
1084255157Sjilles				errno = EINTR;
1085255157Sjilles				break;
1086255157Sjilles			}
1087238888Sjilles			sigsuspend(&omask);
1088238888Sjilles			if (int_pending())
1089238888Sjilles				break;
1090238888Sjilles		}
1091255157Sjilles	} while (pid == -1 && errno == EINTR);
1092153417Smaxim	if (pid == -1 && errno == ECHILD && job != NULL)
1093153417Smaxim		job->state = JOBDONE;
1094238888Sjilles	if ((mode & DOWAIT_SIG) != 0) {
1095238888Sjilles		if (restore_sigchld)
1096238888Sjilles			sigaction(SIGCHLD, &osa, NULL);
1097238888Sjilles		sigprocmask(SIG_SETMASK, &omask, NULL);
1098238888Sjilles		INTON;
1099238888Sjilles	}
11001556Srgrimes	if (pid <= 0)
11011556Srgrimes		return pid;
11021556Srgrimes	INTOFF;
11031556Srgrimes	thisjob = NULL;
11041556Srgrimes	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1105216208Sjilles		if (jp->used && jp->nprocs > 0) {
11061556Srgrimes			done = 1;
11071556Srgrimes			stopped = 1;
11081556Srgrimes			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
11091556Srgrimes				if (sp->pid == -1)
11101556Srgrimes					continue;
11111556Srgrimes				if (sp->pid == pid) {
111226104Ssteve					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1113100308Stjr						   (int)pid, sp->status,
1114100308Stjr						   status));
1115238865Sjilles					if (WIFCONTINUED(status)) {
1116238865Sjilles						sp->status = -1;
1117238865Sjilles						jp->state = 0;
1118238865Sjilles					} else
1119238865Sjilles						sp->status = status;
11201556Srgrimes					thisjob = jp;
11211556Srgrimes				}
11221556Srgrimes				if (sp->status == -1)
11231556Srgrimes					stopped = 0;
112426104Ssteve				else if (WIFSTOPPED(sp->status))
11251556Srgrimes					done = 0;
11261556Srgrimes			}
11271556Srgrimes			if (stopped) {		/* stopped or done */
11281556Srgrimes				int state = done? JOBDONE : JOBSTOPPED;
11291556Srgrimes				if (jp->state != state) {
1130213775Sjhb					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
11311556Srgrimes					jp->state = state;
1132209600Sjilles					if (jp != job) {
1133209600Sjilles						if (done && !jp->remembered &&
1134209600Sjilles						    !iflag && jp != bgjob)
1135209600Sjilles							freejob(jp);
11361556Srgrimes#if JOBS
1137209600Sjilles						else if (done)
1138209600Sjilles							deljob(jp);
11391556Srgrimes#endif
1140209600Sjilles					}
11411556Srgrimes				}
11421556Srgrimes			}
11431556Srgrimes		}
11441556Srgrimes	}
11451556Srgrimes	INTON;
1146216217Sjilles	if (!thisjob || thisjob->state == 0)
1147216217Sjilles		;
1148216217Sjilles	else if ((!rootshell || !iflag || thisjob == job) &&
1149216217Sjilles	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1150216217Sjilles		sig = 0;
1151216217Sjilles		coredump = 0;
1152216217Sjilles		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1153216217Sjilles			if (WIFSIGNALED(sp->status)) {
1154216217Sjilles				sig = WTERMSIG(sp->status);
1155216217Sjilles				coredump = WCOREDUMP(sp->status);
1156216217Sjilles			}
1157216217Sjilles		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1158244682Sjilles			sigstr = strsignal(sig);
1159244682Sjilles			if (sigstr != NULL)
1160244682Sjilles				out2str(sigstr);
116126104Ssteve			else
1162244682Sjilles				out2str("Unknown signal");
1163216217Sjilles			if (coredump)
1164218105Sjilles				out2str(" (core dumped)");
1165218105Sjilles			out2c('\n');
1166218105Sjilles			flushout(out2);
11671556Srgrimes		}
11681556Srgrimes	} else {
1169109627Stjr		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1170216217Sjilles		thisjob->changed = 1;
11711556Srgrimes	}
11721556Srgrimes	return pid;
11731556Srgrimes}
11741556Srgrimes
11751556Srgrimes
11761556Srgrimes
11771556Srgrimes/*
11781556Srgrimes * return 1 if there are stopped jobs, otherwise 0
11791556Srgrimes */
11801556Srgrimesint job_warning = 0;
11811556Srgrimesint
118290111Simpstoppedjobs(void)
11831556Srgrimes{
118425222Ssteve	int jobno;
118525222Ssteve	struct job *jp;
11861556Srgrimes
11871556Srgrimes	if (job_warning)
11881556Srgrimes		return (0);
11891556Srgrimes	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
11901556Srgrimes		if (jp->used == 0)
11911556Srgrimes			continue;
11921556Srgrimes		if (jp->state == JOBSTOPPED) {
1193199629Sjilles			out2fmt_flush("You have stopped jobs.\n");
11941556Srgrimes			job_warning = 2;
11951556Srgrimes			return (1);
11961556Srgrimes		}
11971556Srgrimes	}
11981556Srgrimes
11991556Srgrimes	return (0);
12001556Srgrimes}
12011556Srgrimes
1202208489Sjilles
1203213811Sobrienstatic void
1204208489Sjillescheckzombies(void)
1205208489Sjilles{
1206208489Sjilles	while (njobs > 0 && dowait(0, NULL) > 0)
1207208489Sjilles		;
1208208489Sjilles}
1209208489Sjilles
1210208489Sjilles
1211209600Sjillesint
1212209600Sjillesbackgndpidset(void)
1213209600Sjilles{
1214209600Sjilles	return backgndpid != -1;
1215209600Sjilles}
1216209600Sjilles
1217209600Sjilles
1218209600Sjillespid_t
1219209600Sjillesbackgndpidval(void)
1220209600Sjilles{
1221223024Sjilles	if (bgjob != NULL && !forcelocal)
1222209600Sjilles		bgjob->remembered = 1;
1223209600Sjilles	return backgndpid;
1224209600Sjilles}
1225209600Sjilles
12261556Srgrimes/*
12271556Srgrimes * Return a string identifying a command (to be printed by the
12281556Srgrimes * jobs command.
12291556Srgrimes */
12301556Srgrimes
1231213760Sobrienstatic char *cmdnextc;
1232213760Sobrienstatic int cmdnleft;
12331556Srgrimes#define MAXCMDTEXT	200
12341556Srgrimes
12351556Srgrimeschar *
123690111Simpcommandtext(union node *n)
123790111Simp{
12381556Srgrimes	char *name;
12391556Srgrimes
12401556Srgrimes	cmdnextc = name = ckmalloc(MAXCMDTEXT);
12411556Srgrimes	cmdnleft = MAXCMDTEXT - 4;
12421556Srgrimes	cmdtxt(n);
12431556Srgrimes	*cmdnextc = '\0';
12441556Srgrimes	return name;
12451556Srgrimes}
12461556Srgrimes
12471556Srgrimes
1248213811Sobrienstatic void
124990111Simpcmdtxt(union node *n)
125090111Simp{
12511556Srgrimes	union node *np;
12521556Srgrimes	struct nodelist *lp;
1253201053Sjilles	const char *p;
12541556Srgrimes	int i;
12551556Srgrimes	char s[2];
12561556Srgrimes
12571556Srgrimes	if (n == NULL)
12581556Srgrimes		return;
12591556Srgrimes	switch (n->type) {
12601556Srgrimes	case NSEMI:
12611556Srgrimes		cmdtxt(n->nbinary.ch1);
12621556Srgrimes		cmdputs("; ");
12631556Srgrimes		cmdtxt(n->nbinary.ch2);
12641556Srgrimes		break;
12651556Srgrimes	case NAND:
12661556Srgrimes		cmdtxt(n->nbinary.ch1);
12671556Srgrimes		cmdputs(" && ");
12681556Srgrimes		cmdtxt(n->nbinary.ch2);
12691556Srgrimes		break;
12701556Srgrimes	case NOR:
12711556Srgrimes		cmdtxt(n->nbinary.ch1);
12721556Srgrimes		cmdputs(" || ");
12731556Srgrimes		cmdtxt(n->nbinary.ch2);
12741556Srgrimes		break;
12751556Srgrimes	case NPIPE:
12761556Srgrimes		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
12771556Srgrimes			cmdtxt(lp->n);
12781556Srgrimes			if (lp->next)
12791556Srgrimes				cmdputs(" | ");
12801556Srgrimes		}
12811556Srgrimes		break;
12821556Srgrimes	case NSUBSHELL:
12831556Srgrimes		cmdputs("(");
12841556Srgrimes		cmdtxt(n->nredir.n);
12851556Srgrimes		cmdputs(")");
12861556Srgrimes		break;
12871556Srgrimes	case NREDIR:
12881556Srgrimes	case NBACKGND:
12891556Srgrimes		cmdtxt(n->nredir.n);
12901556Srgrimes		break;
12911556Srgrimes	case NIF:
12921556Srgrimes		cmdputs("if ");
12931556Srgrimes		cmdtxt(n->nif.test);
12941556Srgrimes		cmdputs("; then ");
12951556Srgrimes		cmdtxt(n->nif.ifpart);
12961556Srgrimes		cmdputs("...");
12971556Srgrimes		break;
12981556Srgrimes	case NWHILE:
12991556Srgrimes		cmdputs("while ");
13001556Srgrimes		goto until;
13011556Srgrimes	case NUNTIL:
13021556Srgrimes		cmdputs("until ");
13031556Srgrimesuntil:
13041556Srgrimes		cmdtxt(n->nbinary.ch1);
13051556Srgrimes		cmdputs("; do ");
13061556Srgrimes		cmdtxt(n->nbinary.ch2);
13071556Srgrimes		cmdputs("; done");
13081556Srgrimes		break;
13091556Srgrimes	case NFOR:
13101556Srgrimes		cmdputs("for ");
13111556Srgrimes		cmdputs(n->nfor.var);
13121556Srgrimes		cmdputs(" in ...");
13131556Srgrimes		break;
13141556Srgrimes	case NCASE:
13151556Srgrimes		cmdputs("case ");
13161556Srgrimes		cmdputs(n->ncase.expr->narg.text);
13171556Srgrimes		cmdputs(" in ...");
13181556Srgrimes		break;
13191556Srgrimes	case NDEFUN:
13201556Srgrimes		cmdputs(n->narg.text);
13211556Srgrimes		cmdputs("() ...");
13221556Srgrimes		break;
1323246162Sjilles	case NNOT:
1324246162Sjilles		cmdputs("! ");
1325246162Sjilles		cmdtxt(n->nnot.com);
1326246162Sjilles		break;
13271556Srgrimes	case NCMD:
13281556Srgrimes		for (np = n->ncmd.args ; np ; np = np->narg.next) {
13291556Srgrimes			cmdtxt(np);
13301556Srgrimes			if (np->narg.next)
13311556Srgrimes				cmdputs(" ");
13321556Srgrimes		}
13331556Srgrimes		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
13341556Srgrimes			cmdputs(" ");
13351556Srgrimes			cmdtxt(np);
13361556Srgrimes		}
13371556Srgrimes		break;
13381556Srgrimes	case NARG:
13391556Srgrimes		cmdputs(n->narg.text);
13401556Srgrimes		break;
13411556Srgrimes	case NTO:
13421556Srgrimes		p = ">";  i = 1;  goto redir;
13431556Srgrimes	case NAPPEND:
13441556Srgrimes		p = ">>";  i = 1;  goto redir;
13451556Srgrimes	case NTOFD:
13461556Srgrimes		p = ">&";  i = 1;  goto redir;
134796922Stjr	case NCLOBBER:
134896922Stjr		p = ">|"; i = 1; goto redir;
13491556Srgrimes	case NFROM:
13501556Srgrimes		p = "<";  i = 0;  goto redir;
135166612Sbrian	case NFROMTO:
135266612Sbrian		p = "<>";  i = 0;  goto redir;
13531556Srgrimes	case NFROMFD:
13541556Srgrimes		p = "<&";  i = 0;  goto redir;
13551556Srgrimesredir:
13561556Srgrimes		if (n->nfile.fd != i) {
13571556Srgrimes			s[0] = n->nfile.fd + '0';
13581556Srgrimes			s[1] = '\0';
13591556Srgrimes			cmdputs(s);
13601556Srgrimes		}
13611556Srgrimes		cmdputs(p);
13621556Srgrimes		if (n->type == NTOFD || n->type == NFROMFD) {
136399634Stjr			if (n->ndup.dupfd >= 0)
136499634Stjr				s[0] = n->ndup.dupfd + '0';
136599634Stjr			else
136699634Stjr				s[0] = '-';
13671556Srgrimes			s[1] = '\0';
13681556Srgrimes			cmdputs(s);
13691556Srgrimes		} else {
13701556Srgrimes			cmdtxt(n->nfile.fname);
13711556Srgrimes		}
13721556Srgrimes		break;
13731556Srgrimes	case NHERE:
13741556Srgrimes	case NXHERE:
13751556Srgrimes		cmdputs("<<...");
13761556Srgrimes		break;
13771556Srgrimes	default:
13781556Srgrimes		cmdputs("???");
13791556Srgrimes		break;
13801556Srgrimes	}
13811556Srgrimes}
13821556Srgrimes
13831556Srgrimes
13841556Srgrimes
1385213811Sobrienstatic void
1386201053Sjillescmdputs(const char *s)
138790111Simp{
1388201053Sjilles	const char *p;
1389201053Sjilles	char *q;
139025222Ssteve	char c;
13911556Srgrimes	int subtype = 0;
13921556Srgrimes
13931556Srgrimes	if (cmdnleft <= 0)
13941556Srgrimes		return;
13951556Srgrimes	p = s;
13961556Srgrimes	q = cmdnextc;
13971556Srgrimes	while ((c = *p++) != '\0') {
13981556Srgrimes		if (c == CTLESC)
13991556Srgrimes			*q++ = *p++;
14001556Srgrimes		else if (c == CTLVAR) {
14011556Srgrimes			*q++ = '$';
14021556Srgrimes			if (--cmdnleft > 0)
14031556Srgrimes				*q++ = '{';
14041556Srgrimes			subtype = *p++;
1405216246Sjilles			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1406216246Sjilles				*q++ = '#';
14071556Srgrimes		} else if (c == '=' && subtype != 0) {
1408216246Sjilles			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1409216246Sjilles			if (*q)
1410216246Sjilles				q++;
1411216246Sjilles			else
1412216246Sjilles				cmdnleft++;
1413216246Sjilles			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1414216246Sjilles			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1415216246Sjilles			    --cmdnleft > 0)
1416216246Sjilles				*q = q[-1], q++;
14171556Srgrimes			subtype = 0;
14181556Srgrimes		} else if (c == CTLENDVAR) {
14191556Srgrimes			*q++ = '}';
1420216246Sjilles		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1421216246Sjilles			cmdnleft -= 5;
1422216246Sjilles			if (cmdnleft > 0) {
1423216246Sjilles				*q++ = '$';
1424216246Sjilles				*q++ = '(';
1425216246Sjilles				*q++ = '.';
1426216246Sjilles				*q++ = '.';
1427216246Sjilles				*q++ = '.';
1428216246Sjilles				*q++ = ')';
1429216246Sjilles			}
1430216246Sjilles		} else if (c == CTLARI) {
1431216246Sjilles			cmdnleft -= 2;
1432216246Sjilles			if (cmdnleft > 0) {
1433216246Sjilles				*q++ = '$';
1434216246Sjilles				*q++ = '(';
1435216246Sjilles				*q++ = '(';
1436216246Sjilles			}
1437216246Sjilles			p++;
1438216246Sjilles		} else if (c == CTLENDARI) {
1439216246Sjilles			if (--cmdnleft > 0) {
1440216246Sjilles				*q++ = ')';
1441216246Sjilles				*q++ = ')';
1442216246Sjilles			}
1443216246Sjilles		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1444216246Sjilles			cmdnleft++; /* ignore */
14451556Srgrimes		else
14461556Srgrimes			*q++ = c;
14471556Srgrimes		if (--cmdnleft <= 0) {
14481556Srgrimes			*q++ = '.';
14491556Srgrimes			*q++ = '.';
14501556Srgrimes			*q++ = '.';
14511556Srgrimes			break;
14521556Srgrimes		}
14531556Srgrimes	}
14541556Srgrimes	cmdnextc = q;
14551556Srgrimes}
1456