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
350287750Sjilles	for (ps = jp->ps ; procno > 0 ; ps++, procno--) { /* for each process */
351163085Sstefanf		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
352216199Sjilles			out1fmt("%d\n", (int)ps->pid);
353287750Sjilles			continue;
35497669Stjr		}
355216217Sjilles		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
356287750Sjilles			continue;
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);
38797663Stjr	}
38897663Stjr}
38997663Stjr
3901556Srgrimes/*
3911556Srgrimes * Print a list of jobs.  If "change" is nonzero, only print jobs whose
3921556Srgrimes * statuses have changed since the last call to showjobs.
3931556Srgrimes *
3941556Srgrimes * If the shell is interrupted in the process of creating a job, the
3951556Srgrimes * result may be a job structure containing zero processes.  Such structures
3961556Srgrimes * will be freed here.
3971556Srgrimes */
3981556Srgrimes
3991556Srgrimesvoid
400163085Sstefanfshowjobs(int change, int mode)
40117987Speter{
4021556Srgrimes	int jobno;
4031556Srgrimes	struct job *jp;
4041556Srgrimes
4051556Srgrimes	TRACE(("showjobs(%d) called\n", change));
406208489Sjilles	checkzombies();
4071556Srgrimes	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
4081556Srgrimes		if (! jp->used)
4091556Srgrimes			continue;
4101556Srgrimes		if (jp->nprocs == 0) {
4111556Srgrimes			freejob(jp);
4121556Srgrimes			continue;
4131556Srgrimes		}
4141556Srgrimes		if (change && ! jp->changed)
4151556Srgrimes			continue;
416216217Sjilles		showjob(jp, mode);
417249984Sjilles		if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
418249984Sjilles			jp->changed = 0;
419249984Sjilles			/* Hack: discard jobs for which $! has not been
420249984Sjilles			 * referenced in interactive mode when they terminate.
421249984Sjilles			 */
422249984Sjilles			if (jp->state == JOBDONE && !jp->remembered &&
423249984Sjilles					(iflag || jp != bgjob)) {
424249984Sjilles				freejob(jp);
425249984Sjilles			}
4261556Srgrimes		}
4271556Srgrimes	}
4281556Srgrimes}
4291556Srgrimes
4301556Srgrimes
4311556Srgrimes/*
4321556Srgrimes * Mark a job structure as unused.
4331556Srgrimes */
4341556Srgrimes
435213811Sobrienstatic void
43690111Simpfreejob(struct job *jp)
43790111Simp{
4381556Srgrimes	struct procstat *ps;
4391556Srgrimes	int i;
4401556Srgrimes
4411556Srgrimes	INTOFF;
442209600Sjilles	if (bgjob == jp)
443209600Sjilles		bgjob = NULL;
4441556Srgrimes	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
4451556Srgrimes		if (ps->cmd != nullstr)
4461556Srgrimes			ckfree(ps->cmd);
4471556Srgrimes	}
4481556Srgrimes	if (jp->ps != &jp->ps0)
4491556Srgrimes		ckfree(jp->ps);
4501556Srgrimes	jp->used = 0;
4511556Srgrimes#if JOBS
45297659Stjr	deljob(jp);
4531556Srgrimes#endif
4541556Srgrimes	INTON;
4551556Srgrimes}
4561556Srgrimes
4571556Srgrimes
4581556Srgrimes
4591556Srgrimesint
460248349Sjilleswaitcmd(int argc __unused, char **argv __unused)
46117987Speter{
4621556Srgrimes	struct job *job;
463251429Sjilles	int retval;
4641556Srgrimes
465248349Sjilles	nextopt("");
466251429Sjilles	if (*argptr == NULL)
467251429Sjilles		return (waitcmdloop(NULL));
468251429Sjilles
469251429Sjilles	do {
470251430Sjilles		job = getjob_nonotfound(*argptr);
471251430Sjilles		if (job == NULL)
472251430Sjilles			retval = 127;
473251430Sjilles		else
474251430Sjilles			retval = waitcmdloop(job);
475251429Sjilles		argptr++;
476251429Sjilles	} while (*argptr != NULL);
47738536Scracauer
478251429Sjilles	return (retval);
479251429Sjilles}
480251429Sjilles
481251429Sjillesstatic int
482251429Sjilleswaitcmdloop(struct job *job)
483251429Sjilles{
484255157Sjilles	int status, retval, sig;
485251429Sjilles	struct job *jp;
486251429Sjilles
48738536Scracauer	/*
48838536Scracauer	 * Loop until a process is terminated or stopped, or a SIGINT is
48938536Scracauer	 * received.
49038536Scracauer	 */
49138536Scracauer
49238536Scracauer	do {
4931556Srgrimes		if (job != NULL) {
494254767Sjilles			if (job->state == JOBDONE) {
4951556Srgrimes				status = job->ps[job->nprocs - 1].status;
49626104Ssteve				if (WIFEXITED(status))
49726104Ssteve					retval = WEXITSTATUS(status);
4981556Srgrimes				else
49926104Ssteve					retval = WTERMSIG(status) + 128;
500209600Sjilles				if (! iflag || ! job->changed)
5011556Srgrimes					freejob(job);
502209600Sjilles				else {
503209600Sjilles					job->remembered = 0;
504209600Sjilles					if (job == bgjob)
505209600Sjilles						bgjob = NULL;
506209600Sjilles				}
50726104Ssteve				return retval;
5081556Srgrimes			}
5091556Srgrimes		} else {
510209600Sjilles			for (jp = jobtab ; jp < jobtab + njobs; jp++)
511209600Sjilles				if (jp->used && jp->state == JOBDONE) {
512209600Sjilles					if (! iflag || ! jp->changed)
513209600Sjilles						freejob(jp);
514209600Sjilles					else {
515209600Sjilles						jp->remembered = 0;
516209600Sjilles						if (jp == bgjob)
517209600Sjilles							bgjob = NULL;
518209600Sjilles					}
519209600Sjilles				}
5201556Srgrimes			for (jp = jobtab ; ; jp++) {
5211556Srgrimes				if (jp >= jobtab + njobs) {	/* no running procs */
5221556Srgrimes					return 0;
5231556Srgrimes				}
5241556Srgrimes				if (jp->used && jp->state == 0)
5251556Srgrimes					break;
5261556Srgrimes			}
5271556Srgrimes		}
528238888Sjilles	} while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, (struct job *)NULL) != -1);
52938521Scracauer
530255157Sjilles	sig = pendingsig_waitcmd;
531255157Sjilles	pendingsig_waitcmd = 0;
532255157Sjilles	return sig + 128;
5331556Srgrimes}
5341556Srgrimes
5351556Srgrimes
5361556Srgrimes
53717987Speterint
538254413Sjillesjobidcmd(int argc __unused, char **argv __unused)
53917987Speter{
5401556Srgrimes	struct job *jp;
5411556Srgrimes	int i;
5421556Srgrimes
543254413Sjilles	nextopt("");
544254413Sjilles	jp = getjob(*argptr);
5451556Srgrimes	for (i = 0 ; i < jp->nprocs ; ) {
546100308Stjr		out1fmt("%d", (int)jp->ps[i].pid);
5471556Srgrimes		out1c(++i < jp->nprocs? ' ' : '\n');
5481556Srgrimes	}
5491556Srgrimes	return 0;
5501556Srgrimes}
5511556Srgrimes
5521556Srgrimes
5531556Srgrimes
5541556Srgrimes/*
5551556Srgrimes * Convert a job name to a job structure.
5561556Srgrimes */
5571556Srgrimes
558213811Sobrienstatic struct job *
559264168Sjillesgetjob_nonotfound(const char *name)
56090111Simp{
5611556Srgrimes	int jobno;
56297688Stjr	struct job *found, *jp;
563100308Stjr	pid_t pid;
5641556Srgrimes	int i;
5651556Srgrimes
5661556Srgrimes	if (name == NULL) {
5671556Srgrimes#if JOBS
56897659Stjrcurrentjob:	if ((jp = getcurjob(NULL)) == NULL)
5691556Srgrimes			error("No current job");
57097659Stjr		return (jp);
5711556Srgrimes#else
5721556Srgrimes		error("No current job");
5731556Srgrimes#endif
5741556Srgrimes	} else if (name[0] == '%') {
5751556Srgrimes		if (is_digit(name[1])) {
5761556Srgrimes			jobno = number(name + 1);
5771556Srgrimes			if (jobno > 0 && jobno <= njobs
5781556Srgrimes			 && jobtab[jobno - 1].used != 0)
5791556Srgrimes				return &jobtab[jobno - 1];
5801556Srgrimes#if JOBS
5811556Srgrimes		} else if (name[1] == '%' && name[2] == '\0') {
5821556Srgrimes			goto currentjob;
58397688Stjr		} else if (name[1] == '+' && name[2] == '\0') {
58497688Stjr			goto currentjob;
58597688Stjr		} else if (name[1] == '-' && name[2] == '\0') {
58697688Stjr			if ((jp = getcurjob(NULL)) == NULL ||
58797688Stjr			    (jp = getcurjob(jp)) == NULL)
58897688Stjr				error("No previous job");
58997688Stjr			return (jp);
5901556Srgrimes#endif
59197688Stjr		} else if (name[1] == '?') {
59297688Stjr			found = NULL;
59397688Stjr			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
59497688Stjr				if (jp->used && jp->nprocs > 0
59597688Stjr				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
59697688Stjr					if (found)
59797688Stjr						error("%s: ambiguous", name);
59897688Stjr					found = jp;
59997688Stjr				}
60097688Stjr			}
60197688Stjr			if (found != NULL)
60297688Stjr				return (found);
6031556Srgrimes		} else {
60497688Stjr			found = NULL;
6051556Srgrimes			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6061556Srgrimes				if (jp->used && jp->nprocs > 0
6071556Srgrimes				 && prefix(name + 1, jp->ps[0].cmd)) {
6081556Srgrimes					if (found)
6091556Srgrimes						error("%s: ambiguous", name);
6101556Srgrimes					found = jp;
6111556Srgrimes				}
6121556Srgrimes			}
6131556Srgrimes			if (found)
6141556Srgrimes				return found;
6151556Srgrimes		}
6161556Srgrimes	} else if (is_number(name)) {
617100308Stjr		pid = (pid_t)number(name);
6181556Srgrimes		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6191556Srgrimes			if (jp->used && jp->nprocs > 0
6201556Srgrimes			 && jp->ps[jp->nprocs - 1].pid == pid)
6211556Srgrimes				return jp;
6221556Srgrimes		}
6231556Srgrimes	}
62417987Speter	return NULL;
6251556Srgrimes}
6261556Srgrimes
6271556Srgrimes
628251430Sjillesstatic struct job *
629264168Sjillesgetjob(const char *name)
630251430Sjilles{
631251430Sjilles	struct job *jp;
632251430Sjilles
633251430Sjilles	jp = getjob_nonotfound(name);
634251430Sjilles	if (jp == NULL)
635251430Sjilles		error("No such job: %s", name);
636251430Sjilles	return (jp);
637251430Sjilles}
638251430Sjilles
639251430Sjilles
640216629Sjillespid_t
641216629Sjillesgetjobpgrp(char *name)
642216629Sjilles{
643216629Sjilles	struct job *jp;
6441556Srgrimes
645216629Sjilles	jp = getjob(name);
646216629Sjilles	return -jp->ps[0].pid;
647216629Sjilles}
648216629Sjilles
6491556Srgrimes/*
6501556Srgrimes * Return a new job structure,
6511556Srgrimes */
6521556Srgrimes
6531556Srgrimesstruct job *
65490111Simpmakejob(union node *node __unused, int nprocs)
65517987Speter{
6561556Srgrimes	int i;
6571556Srgrimes	struct job *jp;
6581556Srgrimes
6591556Srgrimes	for (i = njobs, jp = jobtab ; ; jp++) {
6601556Srgrimes		if (--i < 0) {
6611556Srgrimes			INTOFF;
6621556Srgrimes			if (njobs == 0) {
6631556Srgrimes				jobtab = ckmalloc(4 * sizeof jobtab[0]);
66497664Stjr#if JOBS
66597659Stjr				jobmru = NULL;
66697664Stjr#endif
6671556Srgrimes			} else {
6681556Srgrimes				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
66917987Speter				memcpy(jp, jobtab, njobs * sizeof jp[0]);
67097659Stjr#if JOBS
67197659Stjr				/* Relocate `next' pointers and list head */
67299760Stjr				if (jobmru != NULL)
67399760Stjr					jobmru = &jp[jobmru - jobtab];
67497659Stjr				for (i = 0; i < njobs; i++)
67597659Stjr					if (jp[i].next != NULL)
67697659Stjr						jp[i].next = &jp[jp[i].next -
67797659Stjr						    jobtab];
67897659Stjr#endif
679209600Sjilles				if (bgjob != NULL)
680209600Sjilles					bgjob = &jp[bgjob - jobtab];
68120425Ssteve				/* Relocate `ps' pointers */
68220425Ssteve				for (i = 0; i < njobs; i++)
68320425Ssteve					if (jp[i].ps == &jobtab[i].ps0)
68420425Ssteve						jp[i].ps = &jp[i].ps0;
6851556Srgrimes				ckfree(jobtab);
6861556Srgrimes				jobtab = jp;
6871556Srgrimes			}
6881556Srgrimes			jp = jobtab + njobs;
689248980Sjilles			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
690248980Sjilles				;
6911556Srgrimes			INTON;
6921556Srgrimes			break;
6931556Srgrimes		}
6941556Srgrimes		if (jp->used == 0)
6951556Srgrimes			break;
6961556Srgrimes	}
6971556Srgrimes	INTOFF;
6981556Srgrimes	jp->state = 0;
6991556Srgrimes	jp->used = 1;
7001556Srgrimes	jp->changed = 0;
7011556Srgrimes	jp->nprocs = 0;
702100305Stjr	jp->foreground = 0;
703209600Sjilles	jp->remembered = 0;
7041556Srgrimes#if JOBS
7051556Srgrimes	jp->jobctl = jobctl;
70697659Stjr	jp->next = NULL;
7071556Srgrimes#endif
7081556Srgrimes	if (nprocs > 1) {
7091556Srgrimes		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
7101556Srgrimes	} else {
7111556Srgrimes		jp->ps = &jp->ps0;
7121556Srgrimes	}
7131556Srgrimes	INTON;
714213775Sjhb	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
71517987Speter	    jp - jobtab + 1));
7161556Srgrimes	return jp;
7178855Srgrimes}
7181556Srgrimes
71997659Stjr#if JOBS
720213811Sobrienstatic void
72197659Stjrsetcurjob(struct job *cj)
72297659Stjr{
72397659Stjr	struct job *jp, *prev;
7241556Srgrimes
72597659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
72697659Stjr		if (jp == cj) {
72797659Stjr			if (prev != NULL)
72897659Stjr				prev->next = jp->next;
72997659Stjr			else
73097659Stjr				jobmru = jp->next;
73197659Stjr			jp->next = jobmru;
73297659Stjr			jobmru = cj;
73397659Stjr			return;
73497659Stjr		}
73597659Stjr	}
73697659Stjr	cj->next = jobmru;
73797659Stjr	jobmru = cj;
73897659Stjr}
73997659Stjr
740213811Sobrienstatic void
74197659Stjrdeljob(struct job *j)
74297659Stjr{
74397659Stjr	struct job *jp, *prev;
74497659Stjr
74597659Stjr	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
74697659Stjr		if (jp == j) {
74797659Stjr			if (prev != NULL)
74897659Stjr				prev->next = jp->next;
74997659Stjr			else
75097659Stjr				jobmru = jp->next;
75197659Stjr			return;
75297659Stjr		}
75397659Stjr	}
75497659Stjr}
75597659Stjr
7561556Srgrimes/*
75797659Stjr * Return the most recently used job that isn't `nj', and preferably one
75897659Stjr * that is stopped.
75997659Stjr */
760213811Sobrienstatic struct job *
76197659Stjrgetcurjob(struct job *nj)
76297659Stjr{
76397659Stjr	struct job *jp;
76497659Stjr
76597659Stjr	/* Try to find a stopped one.. */
76697659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
76797659Stjr		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
76897659Stjr			return (jp);
76997659Stjr	/* Otherwise the most recently used job that isn't `nj' */
77097659Stjr	for (jp = jobmru; jp != NULL; jp = jp->next)
77197659Stjr		if (jp->used && jp != nj)
77297659Stjr			return (jp);
77397659Stjr
77497659Stjr	return (NULL);
77597659Stjr}
77697659Stjr
77797659Stjr#endif
77897659Stjr
77997659Stjr/*
7801556Srgrimes * Fork of a subshell.  If we are doing job control, give the subshell its
7811556Srgrimes * own process group.  Jp is a job structure that the job is to be added to.
7821556Srgrimes * N is the command that will be evaluated by the child.  Both jp and n may
7831556Srgrimes * be NULL.  The mode parameter can be one of the following:
7841556Srgrimes *	FORK_FG - Fork off a foreground process.
7851556Srgrimes *	FORK_BG - Fork off a background process.
7861556Srgrimes *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
7871556Srgrimes *		     process group even if job control is on.
7881556Srgrimes *
7891556Srgrimes * When job control is turned off, background processes have their standard
7901556Srgrimes * input redirected to /dev/null (except for the second and later processes
7911556Srgrimes * in a pipeline).
7921556Srgrimes */
7931556Srgrimes
794100308Stjrpid_t
79590111Simpforkshell(struct job *jp, union node *n, int mode)
79617987Speter{
797100308Stjr	pid_t pid;
798100308Stjr	pid_t pgrp;
7991556Srgrimes
800213775Sjhb	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
80117987Speter	    mode));
8021556Srgrimes	INTOFF;
803216208Sjilles	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
804208489Sjilles		checkzombies();
805112341Stjr	flushall();
8061556Srgrimes	pid = fork();
8071556Srgrimes	if (pid == -1) {
8081556Srgrimes		TRACE(("Fork failed, errno=%d\n", errno));
8091556Srgrimes		INTON;
81053891Scracauer		error("Cannot fork: %s", strerror(errno));
8111556Srgrimes	}
8121556Srgrimes	if (pid == 0) {
8131556Srgrimes		struct job *p;
8141556Srgrimes		int wasroot;
8151556Srgrimes		int i;
8161556Srgrimes
817100308Stjr		TRACE(("Child shell %d\n", (int)getpid()));
8181556Srgrimes		wasroot = rootshell;
8191556Srgrimes		rootshell = 0;
820200998Sjilles		handler = &main_handler;
8211556Srgrimes		closescript();
8221556Srgrimes		INTON;
823223024Sjilles		forcelocal = 0;
8241556Srgrimes		clear_traps();
8251556Srgrimes#if JOBS
8261556Srgrimes		jobctl = 0;		/* do job control only in root shell */
8271556Srgrimes		if (wasroot && mode != FORK_NOJOB && mflag) {
8281556Srgrimes			if (jp == NULL || jp->nprocs == 0)
8291556Srgrimes				pgrp = getpid();
8301556Srgrimes			else
8311556Srgrimes				pgrp = jp->ps[0].pid;
83221352Ssteve			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
8331556Srgrimes				/*** this causes superfluous TIOCSPGRPS ***/
83499762Stjr				if (tcsetpgrp(ttyfd, pgrp) < 0)
83520425Ssteve					error("tcsetpgrp failed, errno=%d", errno);
8361556Srgrimes			}
8371556Srgrimes			setsignal(SIGTSTP);
8381556Srgrimes			setsignal(SIGTTOU);
8391556Srgrimes		} else if (mode == FORK_BG) {
8401556Srgrimes			ignoresig(SIGINT);
8411556Srgrimes			ignoresig(SIGQUIT);
8421556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8431556Srgrimes			    ! fd0_redirected_p ()) {
8441556Srgrimes				close(0);
84569793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
846222684Sjilles					error("cannot open %s: %s",
84769793Sobrien					    _PATH_DEVNULL, strerror(errno));
8481556Srgrimes			}
8491556Srgrimes		}
8501556Srgrimes#else
8511556Srgrimes		if (mode == FORK_BG) {
8521556Srgrimes			ignoresig(SIGINT);
8531556Srgrimes			ignoresig(SIGQUIT);
8541556Srgrimes			if ((jp == NULL || jp->nprocs == 0) &&
8551556Srgrimes			    ! fd0_redirected_p ()) {
8561556Srgrimes				close(0);
85769793Sobrien				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
858222684Sjilles					error("cannot open %s: %s",
85969793Sobrien					    _PATH_DEVNULL, strerror(errno));
8601556Srgrimes			}
8611556Srgrimes		}
8621556Srgrimes#endif
863102051Stjr		INTOFF;
864102051Stjr		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
865102051Stjr			if (p->used)
866102051Stjr				freejob(p);
867102051Stjr		INTON;
8681556Srgrimes		if (wasroot && iflag) {
8691556Srgrimes			setsignal(SIGINT);
8701556Srgrimes			setsignal(SIGQUIT);
8711556Srgrimes			setsignal(SIGTERM);
8721556Srgrimes		}
8731556Srgrimes		return pid;
8741556Srgrimes	}
8751556Srgrimes	if (rootshell && mode != FORK_NOJOB && mflag) {
8761556Srgrimes		if (jp == NULL || jp->nprocs == 0)
8771556Srgrimes			pgrp = pid;
8781556Srgrimes		else
8791556Srgrimes			pgrp = jp->ps[0].pid;
88017987Speter		setpgid(pid, pgrp);
8811556Srgrimes	}
882209600Sjilles	if (mode == FORK_BG) {
883209600Sjilles		if (bgjob != NULL && bgjob->state == JOBDONE &&
884209600Sjilles		    !bgjob->remembered && !iflag)
885209600Sjilles			freejob(bgjob);
8861556Srgrimes		backgndpid = pid;		/* set $! */
887209600Sjilles		bgjob = jp;
888209600Sjilles	}
8891556Srgrimes	if (jp) {
8901556Srgrimes		struct procstat *ps = &jp->ps[jp->nprocs++];
8911556Srgrimes		ps->pid = pid;
8921556Srgrimes		ps->status = -1;
8931556Srgrimes		ps->cmd = nullstr;
8941556Srgrimes		if (iflag && rootshell && n)
8951556Srgrimes			ps->cmd = commandtext(n);
896100305Stjr		jp->foreground = mode == FORK_FG;
89797659Stjr#if JOBS
89897659Stjr		setcurjob(jp);
89997659Stjr#endif
9001556Srgrimes	}
9011556Srgrimes	INTON;
902100308Stjr	TRACE(("In parent shell:  child = %d\n", (int)pid));
9031556Srgrimes	return pid;
9041556Srgrimes}
9051556Srgrimes
9061556Srgrimes
907230998Sjillespid_t
908230998Sjillesvforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
909230998Sjilles{
910230998Sjilles	pid_t pid;
911230998Sjilles	struct jmploc jmploc;
912230998Sjilles	struct jmploc *savehandler;
9131556Srgrimes
914233792Sjilles	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
915233792Sjilles	    (void *)pip));
916230998Sjilles	INTOFF;
917230998Sjilles	flushall();
918230998Sjilles	savehandler = handler;
919230998Sjilles	pid = vfork();
920230998Sjilles	if (pid == -1) {
921230998Sjilles		TRACE(("Vfork failed, errno=%d\n", errno));
922230998Sjilles		INTON;
923230998Sjilles		error("Cannot fork: %s", strerror(errno));
924230998Sjilles	}
925230998Sjilles	if (pid == 0) {
926230998Sjilles		TRACE(("Child shell %d\n", (int)getpid()));
927230998Sjilles		if (setjmp(jmploc.loc))
928230998Sjilles			_exit(exception == EXEXEC ? exerrno : 2);
929230998Sjilles		if (pip != NULL) {
930230998Sjilles			close(pip[0]);
931230998Sjilles			if (pip[1] != 1) {
932230998Sjilles				dup2(pip[1], 1);
933230998Sjilles				close(pip[1]);
934230998Sjilles			}
935230998Sjilles		}
936230998Sjilles		handler = &jmploc;
937230998Sjilles		shellexec(argv, envp, path, idx);
938230998Sjilles	}
939230998Sjilles	handler = savehandler;
940230998Sjilles	if (jp) {
941230998Sjilles		struct procstat *ps = &jp->ps[jp->nprocs++];
942230998Sjilles		ps->pid = pid;
943230998Sjilles		ps->status = -1;
944230998Sjilles		ps->cmd = nullstr;
945230998Sjilles		jp->foreground = 1;
946230998Sjilles#if JOBS
947230998Sjilles		setcurjob(jp);
948230998Sjilles#endif
949230998Sjilles	}
950230998Sjilles	INTON;
951230998Sjilles	TRACE(("In parent shell:  child = %d\n", (int)pid));
952230998Sjilles	return pid;
953230998Sjilles}
954230998Sjilles
955230998Sjilles
9561556Srgrimes/*
9571556Srgrimes * Wait for job to finish.
9581556Srgrimes *
9591556Srgrimes * Under job control we have the problem that while a child process is
9601556Srgrimes * running interrupts generated by the user are sent to the child but not
9611556Srgrimes * to the shell.  This means that an infinite loop started by an inter-
9621556Srgrimes * active user may be hard to kill.  With job control turned off, an
9631556Srgrimes * interactive user may place an interactive program inside a loop.  If
9641556Srgrimes * the interactive program catches interrupts, the user doesn't want
9651556Srgrimes * these interrupts to also abort the loop.  The approach we take here
9661556Srgrimes * is to have the shell ignore interrupt signals while waiting for a
96746684Skris * foreground process to terminate, and then send itself an interrupt
9681556Srgrimes * signal if the child process was terminated by an interrupt signal.
9691556Srgrimes * Unfortunately, some programs want to do a bit of cleanup and then
9701556Srgrimes * exit on interrupt; unless these processes terminate themselves by
9711556Srgrimes * sending a signal to themselves (instead of calling exit) they will
9721556Srgrimes * confuse this approach.
9731556Srgrimes */
9741556Srgrimes
9751556Srgrimesint
97690111Simpwaitforjob(struct job *jp, int *origstatus)
97745916Scracauer{
9781556Srgrimes#if JOBS
979208881Sjilles	int propagate_int = jp->jobctl && jp->foreground;
9801556Srgrimes#endif
9811556Srgrimes	int status;
9821556Srgrimes	int st;
9831556Srgrimes
9841556Srgrimes	INTOFF;
985213775Sjhb	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
98638950Scracauer	while (jp->state == 0)
987255157Sjilles		if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
988255157Sjilles		    DOWAIT_SIG_ANY : 0), jp) == -1)
98938950Scracauer			dotrap();
9901556Srgrimes#if JOBS
9911556Srgrimes	if (jp->jobctl) {
992262951Sjmmv		if (tcsetpgrp(ttyfd, rootpid) < 0)
99320425Ssteve			error("tcsetpgrp failed, errno=%d\n", errno);
9941556Srgrimes	}
9951556Srgrimes	if (jp->state == JOBSTOPPED)
99697659Stjr		setcurjob(jp);
9971556Srgrimes#endif
9981556Srgrimes	status = jp->ps[jp->nprocs - 1].status;
99945916Scracauer	if (origstatus != NULL)
100045916Scracauer		*origstatus = status;
10011556Srgrimes	/* convert to 8 bits */
100226104Ssteve	if (WIFEXITED(status))
100326104Ssteve		st = WEXITSTATUS(status);
10041556Srgrimes#if JOBS
100526104Ssteve	else if (WIFSTOPPED(status))
100626104Ssteve		st = WSTOPSIG(status) + 128;
10071556Srgrimes#endif
10081556Srgrimes	else
100926104Ssteve		st = WTERMSIG(status) + 128;
10101556Srgrimes	if (! JOBS || jp->state == JOBDONE)
10111556Srgrimes		freejob(jp);
101238521Scracauer	if (int_pending()) {
1013216400Sjilles		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
101438521Scracauer			CLEAR_PENDING_INT;
101538521Scracauer	}
1016208881Sjilles#if JOBS
1017208881Sjilles	else if (rootshell && iflag && propagate_int &&
1018208881Sjilles			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1019208881Sjilles		kill(getpid(), SIGINT);
1020208881Sjilles#endif
10211556Srgrimes	INTON;
10221556Srgrimes	return st;
10231556Srgrimes}
10241556Srgrimes
10251556Srgrimes
1026238888Sjillesstatic void
1027248980Sjillesdummy_handler(int sig __unused)
1028238888Sjilles{
1029238888Sjilles}
10301556Srgrimes
10311556Srgrimes/*
10321556Srgrimes * Wait for a process to terminate.
10331556Srgrimes */
10341556Srgrimes
1035213811Sobrienstatic pid_t
1036238888Sjillesdowait(int mode, struct job *job)
103717987Speter{
1038238888Sjilles	struct sigaction sa, osa;
1039238888Sjilles	sigset_t mask, omask;
1040100308Stjr	pid_t pid;
10411556Srgrimes	int status;
10421556Srgrimes	struct procstat *sp;
10431556Srgrimes	struct job *jp;
10441556Srgrimes	struct job *thisjob;
1045244682Sjilles	const char *sigstr;
10461556Srgrimes	int done;
10471556Srgrimes	int stopped;
104826104Ssteve	int sig;
1049216217Sjilles	int coredump;
1050238866Sjilles	int wflags;
1051238888Sjilles	int restore_sigchld;
10521556Srgrimes
1053246495Sdelphij	TRACE(("dowait(%d, %p) called\n", mode, job));
1054238888Sjilles	restore_sigchld = 0;
1055238888Sjilles	if ((mode & DOWAIT_SIG) != 0) {
1056238888Sjilles		sigfillset(&mask);
1057238888Sjilles		sigprocmask(SIG_BLOCK, &mask, &omask);
1058238888Sjilles		INTOFF;
1059238888Sjilles		if (!issigchldtrapped()) {
1060238888Sjilles			restore_sigchld = 1;
1061238888Sjilles			sa.sa_handler = dummy_handler;
1062238888Sjilles			sa.sa_flags = 0;
1063238888Sjilles			sigemptyset(&sa.sa_mask);
1064238888Sjilles			sigaction(SIGCHLD, &sa, &osa);
1065238888Sjilles		}
1066238888Sjilles	}
10671556Srgrimes	do {
1068238866Sjilles#if JOBS
1069238867Sjilles		if (iflag)
1070238867Sjilles			wflags = WUNTRACED | WCONTINUED;
1071238867Sjilles		else
1072238866Sjilles#endif
1073238867Sjilles			wflags = 0;
1074238888Sjilles		if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1075238866Sjilles			wflags |= WNOHANG;
1076238866Sjilles		pid = wait3(&status, wflags, (struct rusage *)NULL);
1077100308Stjr		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1078238888Sjilles		if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1079255157Sjilles			pid = -1;
1080255157Sjilles			if (((mode & DOWAIT_SIG_ANY) != 0 ?
1081255157Sjilles			    pendingsig : pendingsig_waitcmd) != 0) {
1082255157Sjilles				errno = EINTR;
1083255157Sjilles				break;
1084255157Sjilles			}
1085238888Sjilles			sigsuspend(&omask);
1086238888Sjilles			if (int_pending())
1087238888Sjilles				break;
1088238888Sjilles		}
1089255157Sjilles	} while (pid == -1 && errno == EINTR);
1090153417Smaxim	if (pid == -1 && errno == ECHILD && job != NULL)
1091153417Smaxim		job->state = JOBDONE;
1092238888Sjilles	if ((mode & DOWAIT_SIG) != 0) {
1093238888Sjilles		if (restore_sigchld)
1094238888Sjilles			sigaction(SIGCHLD, &osa, NULL);
1095238888Sjilles		sigprocmask(SIG_SETMASK, &omask, NULL);
1096238888Sjilles		INTON;
1097238888Sjilles	}
10981556Srgrimes	if (pid <= 0)
10991556Srgrimes		return pid;
11001556Srgrimes	INTOFF;
11011556Srgrimes	thisjob = NULL;
11021556Srgrimes	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1103216208Sjilles		if (jp->used && jp->nprocs > 0) {
11041556Srgrimes			done = 1;
11051556Srgrimes			stopped = 1;
11061556Srgrimes			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
11071556Srgrimes				if (sp->pid == -1)
11081556Srgrimes					continue;
11091556Srgrimes				if (sp->pid == pid) {
111026104Ssteve					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1111100308Stjr						   (int)pid, sp->status,
1112100308Stjr						   status));
1113238865Sjilles					if (WIFCONTINUED(status)) {
1114238865Sjilles						sp->status = -1;
1115238865Sjilles						jp->state = 0;
1116238865Sjilles					} else
1117238865Sjilles						sp->status = status;
11181556Srgrimes					thisjob = jp;
11191556Srgrimes				}
11201556Srgrimes				if (sp->status == -1)
11211556Srgrimes					stopped = 0;
112226104Ssteve				else if (WIFSTOPPED(sp->status))
11231556Srgrimes					done = 0;
11241556Srgrimes			}
11251556Srgrimes			if (stopped) {		/* stopped or done */
11261556Srgrimes				int state = done? JOBDONE : JOBSTOPPED;
11271556Srgrimes				if (jp->state != state) {
1128213775Sjhb					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
11291556Srgrimes					jp->state = state;
1130209600Sjilles					if (jp != job) {
1131209600Sjilles						if (done && !jp->remembered &&
1132209600Sjilles						    !iflag && jp != bgjob)
1133209600Sjilles							freejob(jp);
11341556Srgrimes#if JOBS
1135209600Sjilles						else if (done)
1136209600Sjilles							deljob(jp);
11371556Srgrimes#endif
1138209600Sjilles					}
11391556Srgrimes				}
11401556Srgrimes			}
11411556Srgrimes		}
11421556Srgrimes	}
11431556Srgrimes	INTON;
1144216217Sjilles	if (!thisjob || thisjob->state == 0)
1145216217Sjilles		;
1146216217Sjilles	else if ((!rootshell || !iflag || thisjob == job) &&
1147216217Sjilles	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1148216217Sjilles		sig = 0;
1149216217Sjilles		coredump = 0;
1150216217Sjilles		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1151216217Sjilles			if (WIFSIGNALED(sp->status)) {
1152216217Sjilles				sig = WTERMSIG(sp->status);
1153216217Sjilles				coredump = WCOREDUMP(sp->status);
1154216217Sjilles			}
1155216217Sjilles		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1156244682Sjilles			sigstr = strsignal(sig);
1157244682Sjilles			if (sigstr != NULL)
1158244682Sjilles				out2str(sigstr);
115926104Ssteve			else
1160244682Sjilles				out2str("Unknown signal");
1161216217Sjilles			if (coredump)
1162218105Sjilles				out2str(" (core dumped)");
1163218105Sjilles			out2c('\n');
1164218105Sjilles			flushout(out2);
11651556Srgrimes		}
11661556Srgrimes	} else {
1167109627Stjr		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1168216217Sjilles		thisjob->changed = 1;
11691556Srgrimes	}
11701556Srgrimes	return pid;
11711556Srgrimes}
11721556Srgrimes
11731556Srgrimes
11741556Srgrimes
11751556Srgrimes/*
11761556Srgrimes * return 1 if there are stopped jobs, otherwise 0
11771556Srgrimes */
11781556Srgrimesint job_warning = 0;
11791556Srgrimesint
118090111Simpstoppedjobs(void)
11811556Srgrimes{
118225222Ssteve	int jobno;
118325222Ssteve	struct job *jp;
11841556Srgrimes
11851556Srgrimes	if (job_warning)
11861556Srgrimes		return (0);
11871556Srgrimes	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
11881556Srgrimes		if (jp->used == 0)
11891556Srgrimes			continue;
11901556Srgrimes		if (jp->state == JOBSTOPPED) {
1191199629Sjilles			out2fmt_flush("You have stopped jobs.\n");
11921556Srgrimes			job_warning = 2;
11931556Srgrimes			return (1);
11941556Srgrimes		}
11951556Srgrimes	}
11961556Srgrimes
11971556Srgrimes	return (0);
11981556Srgrimes}
11991556Srgrimes
1200208489Sjilles
1201213811Sobrienstatic void
1202208489Sjillescheckzombies(void)
1203208489Sjilles{
1204208489Sjilles	while (njobs > 0 && dowait(0, NULL) > 0)
1205208489Sjilles		;
1206208489Sjilles}
1207208489Sjilles
1208208489Sjilles
1209209600Sjillesint
1210209600Sjillesbackgndpidset(void)
1211209600Sjilles{
1212209600Sjilles	return backgndpid != -1;
1213209600Sjilles}
1214209600Sjilles
1215209600Sjilles
1216209600Sjillespid_t
1217209600Sjillesbackgndpidval(void)
1218209600Sjilles{
1219223024Sjilles	if (bgjob != NULL && !forcelocal)
1220209600Sjilles		bgjob->remembered = 1;
1221209600Sjilles	return backgndpid;
1222209600Sjilles}
1223209600Sjilles
12241556Srgrimes/*
12251556Srgrimes * Return a string identifying a command (to be printed by the
12261556Srgrimes * jobs command.
12271556Srgrimes */
12281556Srgrimes
1229213760Sobrienstatic char *cmdnextc;
1230213760Sobrienstatic int cmdnleft;
12311556Srgrimes#define MAXCMDTEXT	200
12321556Srgrimes
12331556Srgrimeschar *
123490111Simpcommandtext(union node *n)
123590111Simp{
12361556Srgrimes	char *name;
12371556Srgrimes
12381556Srgrimes	cmdnextc = name = ckmalloc(MAXCMDTEXT);
12391556Srgrimes	cmdnleft = MAXCMDTEXT - 4;
12401556Srgrimes	cmdtxt(n);
12411556Srgrimes	*cmdnextc = '\0';
12421556Srgrimes	return name;
12431556Srgrimes}
12441556Srgrimes
12451556Srgrimes
1246213811Sobrienstatic void
124790111Simpcmdtxt(union node *n)
124890111Simp{
12491556Srgrimes	union node *np;
12501556Srgrimes	struct nodelist *lp;
1251201053Sjilles	const char *p;
12521556Srgrimes	int i;
12531556Srgrimes	char s[2];
12541556Srgrimes
12551556Srgrimes	if (n == NULL)
12561556Srgrimes		return;
12571556Srgrimes	switch (n->type) {
12581556Srgrimes	case NSEMI:
12591556Srgrimes		cmdtxt(n->nbinary.ch1);
12601556Srgrimes		cmdputs("; ");
12611556Srgrimes		cmdtxt(n->nbinary.ch2);
12621556Srgrimes		break;
12631556Srgrimes	case NAND:
12641556Srgrimes		cmdtxt(n->nbinary.ch1);
12651556Srgrimes		cmdputs(" && ");
12661556Srgrimes		cmdtxt(n->nbinary.ch2);
12671556Srgrimes		break;
12681556Srgrimes	case NOR:
12691556Srgrimes		cmdtxt(n->nbinary.ch1);
12701556Srgrimes		cmdputs(" || ");
12711556Srgrimes		cmdtxt(n->nbinary.ch2);
12721556Srgrimes		break;
12731556Srgrimes	case NPIPE:
12741556Srgrimes		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
12751556Srgrimes			cmdtxt(lp->n);
12761556Srgrimes			if (lp->next)
12771556Srgrimes				cmdputs(" | ");
12781556Srgrimes		}
12791556Srgrimes		break;
12801556Srgrimes	case NSUBSHELL:
12811556Srgrimes		cmdputs("(");
12821556Srgrimes		cmdtxt(n->nredir.n);
12831556Srgrimes		cmdputs(")");
12841556Srgrimes		break;
12851556Srgrimes	case NREDIR:
12861556Srgrimes	case NBACKGND:
12871556Srgrimes		cmdtxt(n->nredir.n);
12881556Srgrimes		break;
12891556Srgrimes	case NIF:
12901556Srgrimes		cmdputs("if ");
12911556Srgrimes		cmdtxt(n->nif.test);
12921556Srgrimes		cmdputs("; then ");
12931556Srgrimes		cmdtxt(n->nif.ifpart);
12941556Srgrimes		cmdputs("...");
12951556Srgrimes		break;
12961556Srgrimes	case NWHILE:
12971556Srgrimes		cmdputs("while ");
12981556Srgrimes		goto until;
12991556Srgrimes	case NUNTIL:
13001556Srgrimes		cmdputs("until ");
13011556Srgrimesuntil:
13021556Srgrimes		cmdtxt(n->nbinary.ch1);
13031556Srgrimes		cmdputs("; do ");
13041556Srgrimes		cmdtxt(n->nbinary.ch2);
13051556Srgrimes		cmdputs("; done");
13061556Srgrimes		break;
13071556Srgrimes	case NFOR:
13081556Srgrimes		cmdputs("for ");
13091556Srgrimes		cmdputs(n->nfor.var);
13101556Srgrimes		cmdputs(" in ...");
13111556Srgrimes		break;
13121556Srgrimes	case NCASE:
13131556Srgrimes		cmdputs("case ");
13141556Srgrimes		cmdputs(n->ncase.expr->narg.text);
13151556Srgrimes		cmdputs(" in ...");
13161556Srgrimes		break;
13171556Srgrimes	case NDEFUN:
13181556Srgrimes		cmdputs(n->narg.text);
13191556Srgrimes		cmdputs("() ...");
13201556Srgrimes		break;
1321246162Sjilles	case NNOT:
1322246162Sjilles		cmdputs("! ");
1323246162Sjilles		cmdtxt(n->nnot.com);
1324246162Sjilles		break;
13251556Srgrimes	case NCMD:
13261556Srgrimes		for (np = n->ncmd.args ; np ; np = np->narg.next) {
13271556Srgrimes			cmdtxt(np);
13281556Srgrimes			if (np->narg.next)
13291556Srgrimes				cmdputs(" ");
13301556Srgrimes		}
13311556Srgrimes		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
13321556Srgrimes			cmdputs(" ");
13331556Srgrimes			cmdtxt(np);
13341556Srgrimes		}
13351556Srgrimes		break;
13361556Srgrimes	case NARG:
13371556Srgrimes		cmdputs(n->narg.text);
13381556Srgrimes		break;
13391556Srgrimes	case NTO:
13401556Srgrimes		p = ">";  i = 1;  goto redir;
13411556Srgrimes	case NAPPEND:
13421556Srgrimes		p = ">>";  i = 1;  goto redir;
13431556Srgrimes	case NTOFD:
13441556Srgrimes		p = ">&";  i = 1;  goto redir;
134596922Stjr	case NCLOBBER:
134696922Stjr		p = ">|"; i = 1; goto redir;
13471556Srgrimes	case NFROM:
13481556Srgrimes		p = "<";  i = 0;  goto redir;
134966612Sbrian	case NFROMTO:
135066612Sbrian		p = "<>";  i = 0;  goto redir;
13511556Srgrimes	case NFROMFD:
13521556Srgrimes		p = "<&";  i = 0;  goto redir;
13531556Srgrimesredir:
13541556Srgrimes		if (n->nfile.fd != i) {
13551556Srgrimes			s[0] = n->nfile.fd + '0';
13561556Srgrimes			s[1] = '\0';
13571556Srgrimes			cmdputs(s);
13581556Srgrimes		}
13591556Srgrimes		cmdputs(p);
13601556Srgrimes		if (n->type == NTOFD || n->type == NFROMFD) {
136199634Stjr			if (n->ndup.dupfd >= 0)
136299634Stjr				s[0] = n->ndup.dupfd + '0';
136399634Stjr			else
136499634Stjr				s[0] = '-';
13651556Srgrimes			s[1] = '\0';
13661556Srgrimes			cmdputs(s);
13671556Srgrimes		} else {
13681556Srgrimes			cmdtxt(n->nfile.fname);
13691556Srgrimes		}
13701556Srgrimes		break;
13711556Srgrimes	case NHERE:
13721556Srgrimes	case NXHERE:
13731556Srgrimes		cmdputs("<<...");
13741556Srgrimes		break;
13751556Srgrimes	default:
13761556Srgrimes		cmdputs("???");
13771556Srgrimes		break;
13781556Srgrimes	}
13791556Srgrimes}
13801556Srgrimes
13811556Srgrimes
13821556Srgrimes
1383213811Sobrienstatic void
1384201053Sjillescmdputs(const char *s)
138590111Simp{
1386201053Sjilles	const char *p;
1387201053Sjilles	char *q;
138825222Ssteve	char c;
13891556Srgrimes	int subtype = 0;
13901556Srgrimes
13911556Srgrimes	if (cmdnleft <= 0)
13921556Srgrimes		return;
13931556Srgrimes	p = s;
13941556Srgrimes	q = cmdnextc;
13951556Srgrimes	while ((c = *p++) != '\0') {
13961556Srgrimes		if (c == CTLESC)
13971556Srgrimes			*q++ = *p++;
13981556Srgrimes		else if (c == CTLVAR) {
13991556Srgrimes			*q++ = '$';
14001556Srgrimes			if (--cmdnleft > 0)
14011556Srgrimes				*q++ = '{';
14021556Srgrimes			subtype = *p++;
1403216246Sjilles			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1404216246Sjilles				*q++ = '#';
14051556Srgrimes		} else if (c == '=' && subtype != 0) {
1406216246Sjilles			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1407216246Sjilles			if (*q)
1408216246Sjilles				q++;
1409216246Sjilles			else
1410216246Sjilles				cmdnleft++;
1411216246Sjilles			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1412216246Sjilles			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1413216246Sjilles			    --cmdnleft > 0)
1414216246Sjilles				*q = q[-1], q++;
14151556Srgrimes			subtype = 0;
14161556Srgrimes		} else if (c == CTLENDVAR) {
14171556Srgrimes			*q++ = '}';
1418216246Sjilles		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1419216246Sjilles			cmdnleft -= 5;
1420216246Sjilles			if (cmdnleft > 0) {
1421216246Sjilles				*q++ = '$';
1422216246Sjilles				*q++ = '(';
1423216246Sjilles				*q++ = '.';
1424216246Sjilles				*q++ = '.';
1425216246Sjilles				*q++ = '.';
1426216246Sjilles				*q++ = ')';
1427216246Sjilles			}
1428216246Sjilles		} else if (c == CTLARI) {
1429216246Sjilles			cmdnleft -= 2;
1430216246Sjilles			if (cmdnleft > 0) {
1431216246Sjilles				*q++ = '$';
1432216246Sjilles				*q++ = '(';
1433216246Sjilles				*q++ = '(';
1434216246Sjilles			}
1435216246Sjilles			p++;
1436216246Sjilles		} else if (c == CTLENDARI) {
1437216246Sjilles			if (--cmdnleft > 0) {
1438216246Sjilles				*q++ = ')';
1439216246Sjilles				*q++ = ')';
1440216246Sjilles			}
1441216246Sjilles		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1442216246Sjilles			cmdnleft++; /* ignore */
14431556Srgrimes		else
14441556Srgrimes			*q++ = c;
14451556Srgrimes		if (--cmdnleft <= 0) {
14461556Srgrimes			*q++ = '.';
14471556Srgrimes			*q++ = '.';
14481556Srgrimes			*q++ = '.';
14491556Srgrimes			break;
14501556Srgrimes		}
14511556Srgrimes	}
14521556Srgrimes	cmdnextc = q;
14531556Srgrimes}
1454