jobs.c revision 3044
1344957Smarcel/*-
2344957Smarcel * Copyright (c) 1991, 1993
3344957Smarcel *	The Regents of the University of California.  All rights reserved.
4344957Smarcel *
5344957Smarcel * This code is derived from software contributed to Berkeley by
6344957Smarcel * Kenneth Almquist.
7344957Smarcel *
8344957Smarcel * Redistribution and use in source and binary forms, with or without
9344957Smarcel * modification, are permitted provided that the following conditions
10344957Smarcel * are met:
11344957Smarcel * 1. Redistributions of source code must retain the above copyright
12344957Smarcel *    notice, this list of conditions and the following disclaimer.
13344957Smarcel * 2. Redistributions in binary form must reproduce the above copyright
14344957Smarcel *    notice, this list of conditions and the following disclaimer in the
15344957Smarcel *    documentation and/or other materials provided with the distribution.
16344957Smarcel * 3. All advertising materials mentioning features or use of this software
17344957Smarcel *    must display the following acknowledgement:
18344957Smarcel *	This product includes software developed by the University of
19344957Smarcel *	California, Berkeley and its contributors.
20344957Smarcel * 4. Neither the name of the University nor the names of its contributors
21344957Smarcel *    may be used to endorse or promote products derived from this software
22344957Smarcel *    without specific prior written permission.
23344957Smarcel *
24344957Smarcel * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25344957Smarcel * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26344957Smarcel * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27344957Smarcel * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28344957Smarcel * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29344957Smarcel * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30344957Smarcel * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31344957Smarcel * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32344957Smarcel * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33344957Smarcel * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34344957Smarcel * SUCH DAMAGE.
35344957Smarcel *
36344957Smarcel *	$Id$
37344957Smarcel */
38344957Smarcel
39344957Smarcel#ifndef lint
40344957Smarcelstatic char sccsid[] = "@(#)jobs.c	8.1 (Berkeley) 5/31/93";
41344957Smarcel#endif /* not lint */
42344957Smarcel
43344957Smarcel#include "shell.h"
44344957Smarcel#if JOBS
45344957Smarcel#include "sgtty.h"
46344957Smarcel#undef CEOF			/* syntax.h redefines this */
47344957Smarcel#endif
48344957Smarcel#include "main.h"
49344957Smarcel#include "parser.h"
50344957Smarcel#include "nodes.h"
51344957Smarcel#include "jobs.h"
52344957Smarcel#include "options.h"
53344957Smarcel#include "trap.h"
54344957Smarcel#include "signames.h"
55344957Smarcel#include "syntax.h"
56344957Smarcel#include "input.h"
57344957Smarcel#include "output.h"
58344957Smarcel#include "memalloc.h"
59344957Smarcel#include "error.h"
60344957Smarcel#include "mystring.h"
61344957Smarcel#include <fcntl.h>
62344957Smarcel#include <signal.h>
63344957Smarcel#include <errno.h>
64344957Smarcel#ifdef BSD
65344957Smarcel#include <sys/types.h>
66344957Smarcel#include <sys/wait.h>
67344957Smarcel#include <sys/time.h>
68344957Smarcel#include <sys/resource.h>
69344957Smarcel#endif
70344957Smarcel
71344957Smarcel
72344957Smarcel
73344957Smarcelstruct job *jobtab;		/* array of jobs */
74344957Smarcelint njobs;			/* size of array */
75344957SmarcelMKINIT short backgndpid = -1;	/* pid of last background process */
76344957Smarcel#if JOBS
77344957Smarcelint initialpgrp;		/* pgrp of shell on invocation */
78344957Smarcelshort curjob;			/* current job */
79344957Smarcel#endif
80344957Smarcel
81344957Smarcel#ifdef __STDC__
82344957SmarcelSTATIC void restartjob(struct job *);
83344957SmarcelSTATIC struct job *getjob(char *);
84344957SmarcelSTATIC void freejob(struct job *);
85344957SmarcelSTATIC int procrunning(int);
86344957SmarcelSTATIC int dowait(int, struct job *);
87344957SmarcelSTATIC int waitproc(int, int *);
88344957Smarcel#else
89344957SmarcelSTATIC void restartjob();
90344957SmarcelSTATIC struct job *getjob();
91344957SmarcelSTATIC void freejob();
92344957SmarcelSTATIC int procrunning();
93344957SmarcelSTATIC int dowait();
94344957SmarcelSTATIC int waitproc();
95344957Smarcel#endif
96344957Smarcel
97344957Smarcel
98344957Smarcel
99344957Smarcel/*
100344957Smarcel * Turn job control on and off.
101344957Smarcel *
102344957Smarcel * Note:  This code assumes that the third arg to ioctl is a character
103344957Smarcel * pointer, which is true on Berkeley systems but not System V.  Since
104344957Smarcel * System V doesn't have job control yet, this isn't a problem now.
105344957Smarcel */
106344957Smarcel
107344957SmarcelMKINIT int jobctl;
108344957Smarcel
109344957Smarcelvoid
110344957Smarcelsetjobctl(on) {
111344957Smarcel#ifdef OLD_TTY_DRIVER
112344957Smarcel	int ldisc;
113344957Smarcel#endif
114344957Smarcel
115344957Smarcel	if (on == jobctl || rootshell == 0)
116344957Smarcel		return;
117344957Smarcel	if (on) {
118344957Smarcel		do { /* while we are in the background */
119344957Smarcel			if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
120344957Smarcel				out2str("sh: can't access tty; job control turned off\n");
121344957Smarcel				mflag = 0;
122344957Smarcel				return;
123344957Smarcel			}
124344957Smarcel			if (initialpgrp == -1)
125344957Smarcel				initialpgrp = getpgrp(0);
126344957Smarcel			else if (initialpgrp != getpgrp(0)) {
127344957Smarcel				killpg(initialpgrp, SIGTTIN);
128344957Smarcel				continue;
129344957Smarcel			}
130344957Smarcel		} while (0);
131344957Smarcel#ifdef OLD_TTY_DRIVER
132344957Smarcel		if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
133344957Smarcel			out2str("sh: need new tty driver to run job control; job control turned off\n");
134344957Smarcel			mflag = 0;
135344957Smarcel			return;
136344957Smarcel		}
137344957Smarcel#endif
138344957Smarcel		setsignal(SIGTSTP);
139344957Smarcel		setsignal(SIGTTOU);
140344957Smarcel		setsignal(SIGTTIN);
141344957Smarcel		setpgrp(0, rootpid);
142344957Smarcel		ioctl(2, TIOCSPGRP, (char *)&rootpid);
143344957Smarcel	} else { /* turning job control off */
144344957Smarcel		setpgrp(0, initialpgrp);
145344957Smarcel		ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
146344957Smarcel		setsignal(SIGTSTP);
147344957Smarcel		setsignal(SIGTTOU);
148344957Smarcel		setsignal(SIGTTIN);
149344957Smarcel	}
150344957Smarcel	jobctl = on;
151344957Smarcel}
152344957Smarcel
153344957Smarcel
154344957Smarcel#ifdef mkinit
155344957Smarcel
156344957SmarcelSHELLPROC {
157344957Smarcel	backgndpid = -1;
158344957Smarcel#if JOBS
159344957Smarcel	jobctl = 0;
160344957Smarcel#endif
161344957Smarcel}
162344957Smarcel
163344957Smarcel#endif
164344957Smarcel
165344957Smarcel
166344957Smarcel
167344957Smarcel#if JOBS
168344957Smarcelfgcmd(argc, argv)  char **argv; {
169344957Smarcel	struct job *jp;
170344957Smarcel	int pgrp;
171344957Smarcel	int status;
172344957Smarcel
173344957Smarcel	jp = getjob(argv[1]);
174344957Smarcel	if (jp->jobctl == 0)
175344957Smarcel		error("job not created under job control");
176344957Smarcel	pgrp = jp->ps[0].pid;
177344957Smarcel	ioctl(2, TIOCSPGRP, (char *)&pgrp);
178344957Smarcel	restartjob(jp);
179344957Smarcel	INTOFF;
180344957Smarcel	status = waitforjob(jp);
181344957Smarcel	INTON;
182344957Smarcel	return status;
183344957Smarcel}
184344957Smarcel
185344957Smarcel
186344957Smarcelbgcmd(argc, argv)  char **argv; {
187344957Smarcel	struct job *jp;
188344957Smarcel
189344957Smarcel	do {
190344957Smarcel		jp = getjob(*++argv);
191344957Smarcel		if (jp->jobctl == 0)
192344957Smarcel			error("job not created under job control");
193344957Smarcel		restartjob(jp);
194344957Smarcel	} while (--argc > 1);
195344957Smarcel	return 0;
196344957Smarcel}
197344957Smarcel
198344957Smarcel
199344957SmarcelSTATIC void
200344957Smarcelrestartjob(jp)
201344957Smarcel	struct job *jp;
202344957Smarcel	{
203344957Smarcel	struct procstat *ps;
204344957Smarcel	int i;
205344957Smarcel
206344957Smarcel	if (jp->state == JOBDONE)
207344957Smarcel		return;
208344957Smarcel	INTOFF;
209344957Smarcel	killpg(jp->ps[0].pid, SIGCONT);
210344957Smarcel	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
211344957Smarcel		if ((ps->status & 0377) == 0177) {
212344957Smarcel			ps->status = -1;
213344957Smarcel			jp->state = 0;
214344957Smarcel		}
215344957Smarcel	}
216344957Smarcel	INTON;
217344957Smarcel}
218344957Smarcel#endif
219344957Smarcel
220344957Smarcel
221344957Smarcelint
222344957Smarceljobscmd(argc, argv)  char **argv; {
223344957Smarcel	showjobs(0);
224344957Smarcel	return 0;
225344957Smarcel}
226344957Smarcel
227344957Smarcel
228344957Smarcel/*
229344957Smarcel * Print a list of jobs.  If "change" is nonzero, only print jobs whose
230344957Smarcel * statuses have changed since the last call to showjobs.
231344957Smarcel *
232344957Smarcel * If the shell is interrupted in the process of creating a job, the
233344957Smarcel * result may be a job structure containing zero processes.  Such structures
234344957Smarcel * will be freed here.
235344957Smarcel */
236344957Smarcel
237344957Smarcelvoid
238344957Smarcelshowjobs(change) {
239344957Smarcel	int jobno;
240344957Smarcel	int procno;
241344957Smarcel	int i;
242344957Smarcel	struct job *jp;
243344957Smarcel	struct procstat *ps;
244344957Smarcel	int col;
245344957Smarcel	char s[64];
246344957Smarcel
247344957Smarcel	TRACE(("showjobs(%d) called\n", change));
248344957Smarcel	while (dowait(0, (struct job *)NULL) > 0);
249344957Smarcel	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
250344957Smarcel		if (! jp->used)
251344957Smarcel			continue;
252344957Smarcel		if (jp->nprocs == 0) {
253344957Smarcel			freejob(jp);
254344957Smarcel			continue;
255344957Smarcel		}
256344957Smarcel		if (change && ! jp->changed)
257344957Smarcel			continue;
258344957Smarcel		procno = jp->nprocs;
259344957Smarcel		for (ps = jp->ps ; ; ps++) {	/* for each process */
260344957Smarcel			if (ps == jp->ps)
261344957Smarcel				fmtstr(s, 64, "[%d] %d ", jobno, ps->pid);
262344957Smarcel			else
263344957Smarcel				fmtstr(s, 64, "    %d ", ps->pid);
264344957Smarcel			out1str(s);
265344957Smarcel			col = strlen(s);
266344957Smarcel			s[0] = '\0';
267344957Smarcel			if (ps->status == -1) {
268344957Smarcel				/* don't print anything */
269344957Smarcel			} else if ((ps->status & 0xFF) == 0) {
270344957Smarcel				fmtstr(s, 64, "Exit %d", ps->status >> 8);
271344957Smarcel			} else {
272344957Smarcel				i = ps->status;
273344957Smarcel#if JOBS
274344957Smarcel				if ((i & 0xFF) == 0177)
275344957Smarcel					i >>= 8;
276344957Smarcel#endif
277344957Smarcel				if ((i & 0x7F) <= MAXSIG && sigmesg[i & 0x7F])
278344957Smarcel					scopy(sigmesg[i & 0x7F], s);
279344957Smarcel				else
280344957Smarcel					fmtstr(s, 64, "Signal %d", i & 0x7F);
281344957Smarcel				if (i & 0x80)
282344957Smarcel					strcat(s, " (core dumped)");
283344957Smarcel			}
284344957Smarcel			out1str(s);
285344957Smarcel			col += strlen(s);
286344957Smarcel			do {
287344957Smarcel				out1c(' ');
288344957Smarcel				col++;
289344957Smarcel			} while (col < 30);
290344957Smarcel			out1str(ps->cmd);
291344957Smarcel			out1c('\n');
292344957Smarcel			if (--procno <= 0)
293344957Smarcel				break;
294344957Smarcel		}
295344957Smarcel		jp->changed = 0;
296344957Smarcel		if (jp->state == JOBDONE) {
297344957Smarcel			freejob(jp);
298344957Smarcel		}
299344957Smarcel	}
300344957Smarcel}
301344957Smarcel
302344957Smarcel
303344957Smarcel/*
304344957Smarcel * Mark a job structure as unused.
305344957Smarcel */
306344957Smarcel
307344957SmarcelSTATIC void
308344957Smarcelfreejob(jp)
309344957Smarcel	struct job *jp;
310344957Smarcel	{
311344957Smarcel	struct procstat *ps;
312344957Smarcel	int i;
313344957Smarcel
314344957Smarcel	INTOFF;
315344957Smarcel	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
316344957Smarcel		if (ps->cmd != nullstr)
317344957Smarcel			ckfree(ps->cmd);
318344957Smarcel	}
319344957Smarcel	if (jp->ps != &jp->ps0)
320344957Smarcel		ckfree(jp->ps);
321344957Smarcel	jp->used = 0;
322344957Smarcel#if JOBS
323344957Smarcel	if (curjob == jp - jobtab + 1)
324344957Smarcel		curjob = 0;
325344957Smarcel#endif
326344957Smarcel	INTON;
327344957Smarcel}
328344957Smarcel
329344957Smarcel
330344957Smarcel
331344957Smarcelint
332344957Smarcelwaitcmd(argc, argv)  char **argv; {
333344957Smarcel	struct job *job;
334344957Smarcel	int status;
335344957Smarcel	struct job *jp;
336344957Smarcel
337344957Smarcel	if (argc > 1) {
338344957Smarcel		job = getjob(argv[1]);
339344957Smarcel	} else {
340344957Smarcel		job = NULL;
341344957Smarcel	}
342344957Smarcel	for (;;) {	/* loop until process terminated or stopped */
343344957Smarcel		if (job != NULL) {
344344957Smarcel			if (job->state) {
345344957Smarcel				status = job->ps[job->nprocs - 1].status;
346344957Smarcel				if ((status & 0xFF) == 0)
347344957Smarcel					status = status >> 8 & 0xFF;
348344957Smarcel#if JOBS
349344957Smarcel				else if ((status & 0xFF) == 0177)
350344957Smarcel					status = (status >> 8 & 0x7F) + 128;
351344957Smarcel#endif
352344957Smarcel				else
353344957Smarcel					status = (status & 0x7F) + 128;
354344957Smarcel				if (! iflag)
355344957Smarcel					freejob(job);
356344957Smarcel				return status;
357344957Smarcel			}
358344957Smarcel		} else {
359344957Smarcel			for (jp = jobtab ; ; jp++) {
360344957Smarcel				if (jp >= jobtab + njobs) {	/* no running procs */
361344957Smarcel					return 0;
362344957Smarcel				}
363344957Smarcel				if (jp->used && jp->state == 0)
364344957Smarcel					break;
365344957Smarcel			}
366344957Smarcel		}
367344957Smarcel		dowait(1, (struct job *)NULL);
368344957Smarcel	}
369344957Smarcel}
370344957Smarcel
371344957Smarcel
372344957Smarcel
373344957Smarceljobidcmd(argc, argv)  char **argv; {
374344957Smarcel	struct job *jp;
375344957Smarcel	int i;
376344957Smarcel
377344957Smarcel	jp = getjob(argv[1]);
378344957Smarcel	for (i = 0 ; i < jp->nprocs ; ) {
379344957Smarcel		out1fmt("%d", jp->ps[i].pid);
380344957Smarcel		out1c(++i < jp->nprocs? ' ' : '\n');
381344957Smarcel	}
382344957Smarcel	return 0;
383344957Smarcel}
384344957Smarcel
385344957Smarcel
386344957Smarcel
387344957Smarcel/*
388344957Smarcel * Convert a job name to a job structure.
389344957Smarcel */
390344957Smarcel
391344957SmarcelSTATIC struct job *
392344957Smarcelgetjob(name)
393344957Smarcel	char *name;
394344957Smarcel	{
395344957Smarcel	int jobno;
396344957Smarcel	register struct job *jp;
397344957Smarcel	int pid;
398344957Smarcel	int i;
399344957Smarcel
400344957Smarcel	if (name == NULL) {
401344957Smarcel#if JOBS
402344957Smarcelcurrentjob:
403344957Smarcel		if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
404344957Smarcel			error("No current job");
405344957Smarcel		return &jobtab[jobno - 1];
406344957Smarcel#else
407344957Smarcel		error("No current job");
408344957Smarcel#endif
409344957Smarcel	} else if (name[0] == '%') {
410344957Smarcel		if (is_digit(name[1])) {
411344957Smarcel			jobno = number(name + 1);
412344957Smarcel			if (jobno > 0 && jobno <= njobs
413344957Smarcel			 && jobtab[jobno - 1].used != 0)
414344957Smarcel				return &jobtab[jobno - 1];
415344957Smarcel#if JOBS
416344957Smarcel		} else if (name[1] == '%' && name[2] == '\0') {
417344957Smarcel			goto currentjob;
418344957Smarcel#endif
419344957Smarcel		} else {
420344957Smarcel			register struct job *found = NULL;
421344957Smarcel			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
422344957Smarcel				if (jp->used && jp->nprocs > 0
423344957Smarcel				 && prefix(name + 1, jp->ps[0].cmd)) {
424344957Smarcel					if (found)
425344957Smarcel						error("%s: ambiguous", name);
426344957Smarcel					found = jp;
427344957Smarcel				}
428344957Smarcel			}
429344957Smarcel			if (found)
430344957Smarcel				return found;
431344957Smarcel		}
432344957Smarcel	} else if (is_number(name)) {
433344957Smarcel		pid = number(name);
434344957Smarcel		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
435344957Smarcel			if (jp->used && jp->nprocs > 0
436344957Smarcel			 && jp->ps[jp->nprocs - 1].pid == pid)
437344957Smarcel				return jp;
438344957Smarcel		}
439344957Smarcel	}
440344957Smarcel	error("No such job: %s", name);
441344957Smarcel}
442344957Smarcel
443344957Smarcel
444344957Smarcel
445344957Smarcel/*
446344957Smarcel * Return a new job structure,
447344957Smarcel */
448344957Smarcel
449344957Smarcelstruct job *
450344957Smarcelmakejob(node, nprocs)
451344957Smarcel	union node *node;
452344957Smarcel	{
453344957Smarcel	int i;
454344957Smarcel	struct job *jp;
455344957Smarcel
456344957Smarcel	for (i = njobs, jp = jobtab ; ; jp++) {
457344957Smarcel		if (--i < 0) {
458344957Smarcel			INTOFF;
459344957Smarcel			if (njobs == 0) {
460344957Smarcel				jobtab = ckmalloc(4 * sizeof jobtab[0]);
461344957Smarcel			} else {
462344957Smarcel				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
463344957Smarcel				bcopy(jobtab, jp, njobs * sizeof jp[0]);
464344957Smarcel				ckfree(jobtab);
465344957Smarcel				jobtab = jp;
466344957Smarcel			}
467344957Smarcel			jp = jobtab + njobs;
468344957Smarcel			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
469344957Smarcel			INTON;
470344957Smarcel			break;
471344957Smarcel		}
472344957Smarcel		if (jp->used == 0)
473344957Smarcel			break;
474344957Smarcel	}
475344957Smarcel	INTOFF;
476344957Smarcel	jp->state = 0;
477344957Smarcel	jp->used = 1;
478344957Smarcel	jp->changed = 0;
479344957Smarcel	jp->nprocs = 0;
480344957Smarcel#if JOBS
481344957Smarcel	jp->jobctl = jobctl;
482344957Smarcel#endif
483344957Smarcel	if (nprocs > 1) {
484344957Smarcel		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
485344957Smarcel	} else {
486344957Smarcel		jp->ps = &jp->ps0;
487344957Smarcel	}
488344957Smarcel	INTON;
489344957Smarcel	TRACE(("makejob(0x%x, %d) returns %%%d\n", (int)node, nprocs, jp - jobtab + 1));
490344957Smarcel	return jp;
491344957Smarcel}
492344957Smarcel
493344957Smarcel
494344957Smarcel/*
495344957Smarcel * Fork of a subshell.  If we are doing job control, give the subshell its
496344957Smarcel * own process group.  Jp is a job structure that the job is to be added to.
497344957Smarcel * N is the command that will be evaluated by the child.  Both jp and n may
498344957Smarcel * be NULL.  The mode parameter can be one of the following:
499344957Smarcel *	FORK_FG - Fork off a foreground process.
500344957Smarcel *	FORK_BG - Fork off a background process.
501344957Smarcel *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
502344957Smarcel *		     process group even if job control is on.
503344957Smarcel *
504344957Smarcel * When job control is turned off, background processes have their standard
505344957Smarcel * input redirected to /dev/null (except for the second and later processes
506344957Smarcel * in a pipeline).
507344957Smarcel */
508344957Smarcel
509344957Smarcelint
510344957Smarcelforkshell(jp, n, mode)
511344957Smarcel	union node *n;
512344957Smarcel	struct job *jp;
513344957Smarcel	{
514344957Smarcel	int pid;
515344957Smarcel	int pgrp;
516344957Smarcel
517344957Smarcel	TRACE(("forkshell(%%%d, 0x%x, %d) called\n", jp - jobtab, (int)n, mode));
518344957Smarcel	INTOFF;
519344957Smarcel	pid = fork();
520344957Smarcel	if (pid == -1) {
521344957Smarcel		TRACE(("Fork failed, errno=%d\n", errno));
522344957Smarcel		INTON;
523344957Smarcel		error("Cannot fork");
524344957Smarcel	}
525344957Smarcel	if (pid == 0) {
526344957Smarcel		struct job *p;
527344957Smarcel		int wasroot;
528344957Smarcel		int i;
529344957Smarcel
530344957Smarcel		TRACE(("Child shell %d\n", getpid()));
531344957Smarcel		wasroot = rootshell;
532344957Smarcel		rootshell = 0;
533344957Smarcel		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
534344957Smarcel			if (p->used)
535344957Smarcel				freejob(p);
536344957Smarcel		closescript();
537344957Smarcel		INTON;
538344957Smarcel		clear_traps();
539344957Smarcel#if JOBS
540344957Smarcel		jobctl = 0;		/* do job control only in root shell */
541344957Smarcel		if (wasroot && mode != FORK_NOJOB && mflag) {
542344957Smarcel			if (jp == NULL || jp->nprocs == 0)
543344957Smarcel				pgrp = getpid();
544344957Smarcel			else
545344957Smarcel				pgrp = jp->ps[0].pid;
546344957Smarcel			setpgrp(0, pgrp);
547344957Smarcel			if (mode == FORK_FG) {
548344957Smarcel				/*** this causes superfluous TIOCSPGRPS ***/
549344957Smarcel				if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
550344957Smarcel					error("TIOCSPGRP failed, errno=%d\n", errno);
551344957Smarcel			}
552344957Smarcel			setsignal(SIGTSTP);
553344957Smarcel			setsignal(SIGTTOU);
554344957Smarcel		} else if (mode == FORK_BG) {
555344957Smarcel			ignoresig(SIGINT);
556344957Smarcel			ignoresig(SIGQUIT);
557344957Smarcel			if ((jp == NULL || jp->nprocs == 0) &&
558344957Smarcel			    ! fd0_redirected_p ()) {
559344957Smarcel				close(0);
560344957Smarcel				if (open("/dev/null", O_RDONLY) != 0)
561344957Smarcel					error("Can't open /dev/null");
562344957Smarcel			}
563344957Smarcel		}
564344957Smarcel#else
565344957Smarcel		if (mode == FORK_BG) {
566344957Smarcel			ignoresig(SIGINT);
567344957Smarcel			ignoresig(SIGQUIT);
568344957Smarcel			if ((jp == NULL || jp->nprocs == 0) &&
569344957Smarcel			    ! fd0_redirected_p ()) {
570344957Smarcel				close(0);
571344957Smarcel				if (open("/dev/null", O_RDONLY) != 0)
572344957Smarcel					error("Can't open /dev/null");
573344957Smarcel			}
574344957Smarcel		}
575344957Smarcel#endif
576344957Smarcel		if (wasroot && iflag) {
577			setsignal(SIGINT);
578			setsignal(SIGQUIT);
579			setsignal(SIGTERM);
580		}
581		return pid;
582	}
583	if (rootshell && mode != FORK_NOJOB && mflag) {
584		if (jp == NULL || jp->nprocs == 0)
585			pgrp = pid;
586		else
587			pgrp = jp->ps[0].pid;
588		setpgrp(pid, pgrp);
589	}
590	if (mode == FORK_BG)
591		backgndpid = pid;		/* set $! */
592	if (jp) {
593		struct procstat *ps = &jp->ps[jp->nprocs++];
594		ps->pid = pid;
595		ps->status = -1;
596		ps->cmd = nullstr;
597		if (iflag && rootshell && n)
598			ps->cmd = commandtext(n);
599	}
600	INTON;
601	TRACE(("In parent shell:  child = %d\n", pid));
602	return pid;
603}
604
605
606
607/*
608 * Wait for job to finish.
609 *
610 * Under job control we have the problem that while a child process is
611 * running interrupts generated by the user are sent to the child but not
612 * to the shell.  This means that an infinite loop started by an inter-
613 * active user may be hard to kill.  With job control turned off, an
614 * interactive user may place an interactive program inside a loop.  If
615 * the interactive program catches interrupts, the user doesn't want
616 * these interrupts to also abort the loop.  The approach we take here
617 * is to have the shell ignore interrupt signals while waiting for a
618 * forground process to terminate, and then send itself an interrupt
619 * signal if the child process was terminated by an interrupt signal.
620 * Unfortunately, some programs want to do a bit of cleanup and then
621 * exit on interrupt; unless these processes terminate themselves by
622 * sending a signal to themselves (instead of calling exit) they will
623 * confuse this approach.
624 */
625
626int
627waitforjob(jp)
628	register struct job *jp;
629	{
630#if JOBS
631	int mypgrp = getpgrp(0);
632#endif
633	int status;
634	int st;
635
636	INTOFF;
637	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
638	while (jp->state == 0) {
639		dowait(1, jp);
640	}
641#if JOBS
642	if (jp->jobctl) {
643		if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
644			error("TIOCSPGRP failed, errno=%d\n", errno);
645	}
646	if (jp->state == JOBSTOPPED)
647		curjob = jp - jobtab + 1;
648#endif
649	status = jp->ps[jp->nprocs - 1].status;
650	/* convert to 8 bits */
651	if ((status & 0xFF) == 0)
652		st = status >> 8 & 0xFF;
653#if JOBS
654	else if ((status & 0xFF) == 0177)
655		st = (status >> 8 & 0x7F) + 128;
656#endif
657	else
658		st = (status & 0x7F) + 128;
659	if (! JOBS || jp->state == JOBDONE)
660		freejob(jp);
661	CLEAR_PENDING_INT;
662	if ((status & 0x7F) == SIGINT)
663		kill(getpid(), SIGINT);
664	INTON;
665	return st;
666}
667
668
669
670/*
671 * Wait for a process to terminate.
672 */
673
674STATIC int
675dowait(block, job)
676	struct job *job;
677	{
678	int pid;
679	int status;
680	struct procstat *sp;
681	struct job *jp;
682	struct job *thisjob;
683	int done;
684	int stopped;
685	int core;
686
687	TRACE(("dowait(%d) called\n", block));
688	do {
689		pid = waitproc(block, &status);
690		TRACE(("wait returns %d, status=%d\n", pid, status));
691	} while (pid == -1 && errno == EINTR);
692	if (pid <= 0)
693		return pid;
694	INTOFF;
695	thisjob = NULL;
696	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
697		if (jp->used) {
698			done = 1;
699			stopped = 1;
700			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
701				if (sp->pid == -1)
702					continue;
703				if (sp->pid == pid) {
704					TRACE(("Changin status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
705					sp->status = status;
706					thisjob = jp;
707				}
708				if (sp->status == -1)
709					stopped = 0;
710				else if ((sp->status & 0377) == 0177)
711					done = 0;
712			}
713			if (stopped) {		/* stopped or done */
714				int state = done? JOBDONE : JOBSTOPPED;
715				if (jp->state != state) {
716					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
717					jp->state = state;
718#if JOBS
719					if (done && curjob == jp - jobtab + 1)
720						curjob = 0;		/* no current job */
721#endif
722				}
723			}
724		}
725	}
726	INTON;
727	if (! rootshell || ! iflag || (job && thisjob == job)) {
728#if JOBS
729		if ((status & 0xFF) == 0177)
730			status >>= 8;
731#endif
732		core = status & 0x80;
733		status &= 0x7F;
734		if (status != 0 && status != SIGINT && status != SIGPIPE) {
735			if (thisjob != job)
736				outfmt(out2, "%d: ", pid);
737#if JOBS
738			if (status == SIGTSTP && rootshell && iflag)
739				outfmt(out2, "%%%d ", job - jobtab + 1);
740#endif
741			if (status <= MAXSIG && sigmesg[status])
742				out2str(sigmesg[status]);
743			else
744				outfmt(out2, "Signal %d", status);
745			if (core)
746				out2str(" - core dumped");
747			out2c('\n');
748			flushout(&errout);
749		} else {
750			TRACE(("Not printing status: status=%d\n", status));
751		}
752	} else {
753		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
754		if (thisjob)
755			thisjob->changed = 1;
756	}
757	return pid;
758}
759
760
761
762/*
763 * Do a wait system call.  If job control is compiled in, we accept
764 * stopped processes.  If block is zero, we return a value of zero
765 * rather than blocking.
766 *
767 * System V doesn't have a non-blocking wait system call.  It does
768 * have a SIGCLD signal that is sent to a process when one of it's
769 * children dies.  The obvious way to use SIGCLD would be to install
770 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
771 * was received, and have waitproc bump another counter when it got
772 * the status of a process.  Waitproc would then know that a wait
773 * system call would not block if the two counters were different.
774 * This approach doesn't work because if a process has children that
775 * have not been waited for, System V will send it a SIGCLD when it
776 * installs a signal handler for SIGCLD.  What this means is that when
777 * a child exits, the shell will be sent SIGCLD signals continuously
778 * until is runs out of stack space, unless it does a wait call before
779 * restoring the signal handler.  The code below takes advantage of
780 * this (mis)feature by installing a signal handler for SIGCLD and
781 * then checking to see whether it was called.  If there are any
782 * children to be waited for, it will be.
783 *
784 * If neither SYSV nor BSD is defined, we don't implement nonblocking
785 * waits at all.  In this case, the user will not be informed when
786 * a background process until the next time she runs a real program
787 * (as opposed to running a builtin command or just typing return),
788 * and the jobs command may give out of date information.
789 */
790
791#ifdef SYSV
792STATIC int gotsigchild;
793
794STATIC int onsigchild() {
795	gotsigchild = 1;
796}
797#endif
798
799
800STATIC int
801waitproc(block, status)
802	int *status;
803	{
804#ifdef BSD
805	int flags;
806
807#if JOBS
808	flags = WUNTRACED;
809#else
810	flags = 0;
811#endif
812	if (block == 0)
813		flags |= WNOHANG;
814	return wait3(status, flags, (struct rusage *)NULL);
815#else
816#ifdef SYSV
817	int (*save)();
818
819	if (block == 0) {
820		gotsigchild = 0;
821		save = signal(SIGCLD, onsigchild);
822		signal(SIGCLD, save);
823		if (gotsigchild == 0)
824			return 0;
825	}
826	return wait(status);
827#else
828	if (block == 0)
829		return 0;
830	return wait(status);
831#endif
832#endif
833}
834
835/*
836 * return 1 if there are stopped jobs, otherwise 0
837 */
838int job_warning = 0;
839int
840stoppedjobs()
841{
842	register int jobno;
843	register struct job *jp;
844
845	if (job_warning)
846		return (0);
847	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
848		if (jp->used == 0)
849			continue;
850		if (jp->state == JOBSTOPPED) {
851			out2str("You have stopped jobs.\n");
852			job_warning = 2;
853			return (1);
854		}
855	}
856
857	return (0);
858}
859
860/*
861 * Return a string identifying a command (to be printed by the
862 * jobs command.
863 */
864
865STATIC char *cmdnextc;
866STATIC int cmdnleft;
867STATIC void cmdtxt(), cmdputs();
868#define MAXCMDTEXT	200
869
870char *
871commandtext(n)
872	union node *n;
873	{
874	char *name;
875
876	cmdnextc = name = ckmalloc(MAXCMDTEXT);
877	cmdnleft = MAXCMDTEXT - 4;
878	cmdtxt(n);
879	*cmdnextc = '\0';
880	return name;
881}
882
883
884STATIC void
885cmdtxt(n)
886	union node *n;
887	{
888	union node *np;
889	struct nodelist *lp;
890	char *p;
891	int i;
892	char s[2];
893
894	if (n == NULL)
895		return;
896	switch (n->type) {
897	case NSEMI:
898		cmdtxt(n->nbinary.ch1);
899		cmdputs("; ");
900		cmdtxt(n->nbinary.ch2);
901		break;
902	case NAND:
903		cmdtxt(n->nbinary.ch1);
904		cmdputs(" && ");
905		cmdtxt(n->nbinary.ch2);
906		break;
907	case NOR:
908		cmdtxt(n->nbinary.ch1);
909		cmdputs(" || ");
910		cmdtxt(n->nbinary.ch2);
911		break;
912	case NPIPE:
913		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
914			cmdtxt(lp->n);
915			if (lp->next)
916				cmdputs(" | ");
917		}
918		break;
919	case NSUBSHELL:
920		cmdputs("(");
921		cmdtxt(n->nredir.n);
922		cmdputs(")");
923		break;
924	case NREDIR:
925	case NBACKGND:
926		cmdtxt(n->nredir.n);
927		break;
928	case NIF:
929		cmdputs("if ");
930		cmdtxt(n->nif.test);
931		cmdputs("; then ");
932		cmdtxt(n->nif.ifpart);
933		cmdputs("...");
934		break;
935	case NWHILE:
936		cmdputs("while ");
937		goto until;
938	case NUNTIL:
939		cmdputs("until ");
940until:
941		cmdtxt(n->nbinary.ch1);
942		cmdputs("; do ");
943		cmdtxt(n->nbinary.ch2);
944		cmdputs("; done");
945		break;
946	case NFOR:
947		cmdputs("for ");
948		cmdputs(n->nfor.var);
949		cmdputs(" in ...");
950		break;
951	case NCASE:
952		cmdputs("case ");
953		cmdputs(n->ncase.expr->narg.text);
954		cmdputs(" in ...");
955		break;
956	case NDEFUN:
957		cmdputs(n->narg.text);
958		cmdputs("() ...");
959		break;
960	case NCMD:
961		for (np = n->ncmd.args ; np ; np = np->narg.next) {
962			cmdtxt(np);
963			if (np->narg.next)
964				cmdputs(" ");
965		}
966		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
967			cmdputs(" ");
968			cmdtxt(np);
969		}
970		break;
971	case NARG:
972		cmdputs(n->narg.text);
973		break;
974	case NTO:
975		p = ">";  i = 1;  goto redir;
976	case NAPPEND:
977		p = ">>";  i = 1;  goto redir;
978	case NTOFD:
979		p = ">&";  i = 1;  goto redir;
980	case NFROM:
981		p = "<";  i = 0;  goto redir;
982	case NFROMFD:
983		p = "<&";  i = 0;  goto redir;
984redir:
985		if (n->nfile.fd != i) {
986			s[0] = n->nfile.fd + '0';
987			s[1] = '\0';
988			cmdputs(s);
989		}
990		cmdputs(p);
991		if (n->type == NTOFD || n->type == NFROMFD) {
992			s[0] = n->ndup.dupfd + '0';
993			s[1] = '\0';
994			cmdputs(s);
995		} else {
996			cmdtxt(n->nfile.fname);
997		}
998		break;
999	case NHERE:
1000	case NXHERE:
1001		cmdputs("<<...");
1002		break;
1003	default:
1004		cmdputs("???");
1005		break;
1006	}
1007}
1008
1009
1010
1011STATIC void
1012cmdputs(s)
1013	char *s;
1014	{
1015	register char *p, *q;
1016	register char c;
1017	int subtype = 0;
1018
1019	if (cmdnleft <= 0)
1020		return;
1021	p = s;
1022	q = cmdnextc;
1023	while ((c = *p++) != '\0') {
1024		if (c == CTLESC)
1025			*q++ = *p++;
1026		else if (c == CTLVAR) {
1027			*q++ = '$';
1028			if (--cmdnleft > 0)
1029				*q++ = '{';
1030			subtype = *p++;
1031		} else if (c == '=' && subtype != 0) {
1032			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1033			subtype = 0;
1034		} else if (c == CTLENDVAR) {
1035			*q++ = '}';
1036		} else if (c == CTLBACKQ | c == CTLBACKQ+CTLQUOTE)
1037			cmdnleft++;		/* ignore it */
1038		else
1039			*q++ = c;
1040		if (--cmdnleft <= 0) {
1041			*q++ = '.';
1042			*q++ = '.';
1043			*q++ = '.';
1044			break;
1045		}
1046	}
1047	cmdnextc = q;
1048}
1049