jobs.c revision 46684
1262639Sdelphij/*-
2262639Sdelphij * Copyright (c) 1991, 1993
3262639Sdelphij *	The Regents of the University of California.  All rights reserved.
4262639Sdelphij *
5262639Sdelphij * This code is derived from software contributed to Berkeley by
6262639Sdelphij * Kenneth Almquist.
7262639Sdelphij *
8262639Sdelphij * Redistribution and use in source and binary forms, with or without
9262639Sdelphij * modification, are permitted provided that the following conditions
10262639Sdelphij * are met:
11262639Sdelphij * 1. Redistributions of source code must retain the above copyright
12262639Sdelphij *    notice, this list of conditions and the following disclaimer.
13262639Sdelphij * 2. Redistributions in binary form must reproduce the above copyright
14262639Sdelphij *    notice, this list of conditions and the following disclaimer in the
15262639Sdelphij *    documentation and/or other materials provided with the distribution.
16262639Sdelphij * 3. All advertising materials mentioning features or use of this software
17262639Sdelphij *    must display the following acknowledgement:
18262639Sdelphij *	This product includes software developed by the University of
19262639Sdelphij *	California, Berkeley and its contributors.
20262639Sdelphij * 4. Neither the name of the University nor the names of its contributors
21262639Sdelphij *    may be used to endorse or promote products derived from this software
22262639Sdelphij *    without specific prior written permission.
23262639Sdelphij *
24262639Sdelphij * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25262639Sdelphij * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26262639Sdelphij * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27262639Sdelphij * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28262639Sdelphij * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29262639Sdelphij * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30262639Sdelphij * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31262639Sdelphij * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32262639Sdelphij * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33262639Sdelphij * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34262639Sdelphij * SUCH DAMAGE.
35262639Sdelphij */
36262639Sdelphij
37262639Sdelphij#ifndef lint
38262639Sdelphij#if 0
39262639Sdelphijstatic char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
40262639Sdelphij#endif
41262639Sdelphijstatic const char rcsid[] =
42262639Sdelphij	"$Id: jobs.c,v 1.24 1999/04/21 11:52:39 cracauer Exp $";
43262639Sdelphij#endif /* not lint */
44262639Sdelphij
45262639Sdelphij#include <fcntl.h>
46262639Sdelphij#include <signal.h>
47262639Sdelphij#include <errno.h>
48262639Sdelphij#include <unistd.h>
49262639Sdelphij#include <stdlib.h>
50262639Sdelphij#include <sys/param.h>
51262639Sdelphij#ifdef BSD
52262639Sdelphij#include <sys/wait.h>
53262639Sdelphij#include <sys/time.h>
54262639Sdelphij#include <sys/resource.h>
55262639Sdelphij#endif
56262639Sdelphij#include <sys/ioctl.h>
57262639Sdelphij
58262639Sdelphij#include "shell.h"
59262639Sdelphij#if JOBS
60262639Sdelphij#if OLD_TTY_DRIVER
61262639Sdelphij#include "sgtty.h"
62262639Sdelphij#else
63262639Sdelphij#include <termios.h>
64262639Sdelphij#endif
65262639Sdelphij#undef CEOF			/* syntax.h redefines this */
66262639Sdelphij#endif
67262639Sdelphij#include "redir.h"
68262639Sdelphij#include "show.h"
69262639Sdelphij#include "main.h"
70262639Sdelphij#include "parser.h"
71262639Sdelphij#include "nodes.h"
72262639Sdelphij#include "jobs.h"
73262639Sdelphij#include "options.h"
74262639Sdelphij#include "trap.h"
75262639Sdelphij#include "syntax.h"
76262639Sdelphij#include "input.h"
77262639Sdelphij#include "output.h"
78262639Sdelphij#include "memalloc.h"
79262639Sdelphij#include "error.h"
80262639Sdelphij#include "mystring.h"
81262639Sdelphij
82262639Sdelphij
83262639Sdelphijstruct job *jobtab;		/* array of jobs */
84262639Sdelphijint njobs;			/* size of array */
85262639SdelphijMKINIT pid_t backgndpid = -1;	/* pid of last background process */
86262639Sdelphij#if JOBS
87262639Sdelphijint initialpgrp;		/* pgrp of shell on invocation */
88262639Sdelphijint curjob;			/* current job */
89262639Sdelphij#endif
90262639Sdelphijint in_waitcmd = 0;		/* are we in waitcmd()? */
91262639Sdelphijint in_dowait = 0;		/* are we in dowait()? */
92262639Sdelphijvolatile sig_atomic_t breakwaitcmd = 0;	/* should wait be terminated? */
93262639Sdelphij
94262639Sdelphij#if JOBS
95262639SdelphijSTATIC void restartjob __P((struct job *));
96262639Sdelphij#endif
97262639SdelphijSTATIC void freejob __P((struct job *));
98262639SdelphijSTATIC struct job *getjob __P((char *));
99262639SdelphijSTATIC int dowait __P((int, struct job *));
100262639Sdelphij#if SYSV
101262639SdelphijSTATIC int onsigchild __P((void));
102262639Sdelphij#endif
103262639SdelphijSTATIC int waitproc __P((int, int *));
104262639SdelphijSTATIC void cmdtxt __P((union node *));
105262639SdelphijSTATIC void cmdputs __P((char *));
106262639Sdelphij
107262639Sdelphij
108262639Sdelphij/*
109262639Sdelphij * Turn job control on and off.
110262639Sdelphij *
111262639Sdelphij * Note:  This code assumes that the third arg to ioctl is a character
112262639Sdelphij * pointer, which is true on Berkeley systems but not System V.  Since
113262639Sdelphij * System V doesn't have job control yet, this isn't a problem now.
114262639Sdelphij */
115262639Sdelphij
116262639SdelphijMKINIT int jobctl;
117262639Sdelphij
118262639Sdelphij#if JOBS
119262639Sdelphijvoid
120262639Sdelphijsetjobctl(on)
121262639Sdelphij	int on;
122262639Sdelphij{
123262639Sdelphij#ifdef OLD_TTY_DRIVER
124262639Sdelphij	int ldisc;
125262639Sdelphij#endif
126262639Sdelphij
127262639Sdelphij	if (on == jobctl || rootshell == 0)
128262639Sdelphij		return;
129262639Sdelphij	if (on) {
130262639Sdelphij		do { /* while we are in the background */
131262639Sdelphij#ifdef OLD_TTY_DRIVER
132262639Sdelphij			if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
133262639Sdelphij#else
134262639Sdelphij			initialpgrp = tcgetpgrp(2);
135262639Sdelphij			if (initialpgrp < 0) {
136262639Sdelphij#endif
137262639Sdelphij				out2str("sh: can't access tty; job control turned off\n");
138262639Sdelphij				mflag = 0;
139262639Sdelphij				return;
140262639Sdelphij			}
141262639Sdelphij			if (initialpgrp == -1)
142262639Sdelphij				initialpgrp = getpgrp();
143262639Sdelphij			else if (initialpgrp != getpgrp()) {
144262639Sdelphij				killpg(initialpgrp, SIGTTIN);
145262639Sdelphij				continue;
146262639Sdelphij			}
147262639Sdelphij		} while (0);
148262639Sdelphij#ifdef OLD_TTY_DRIVER
149262639Sdelphij		if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
150262639Sdelphij			out2str("sh: need new tty driver to run job control; job control turned off\n");
151262639Sdelphij			mflag = 0;
152262639Sdelphij			return;
153262639Sdelphij		}
154262639Sdelphij#endif
155262639Sdelphij		setsignal(SIGTSTP);
156262639Sdelphij		setsignal(SIGTTOU);
157262639Sdelphij		setsignal(SIGTTIN);
158262639Sdelphij		setpgid(0, rootpid);
159262639Sdelphij#ifdef OLD_TTY_DRIVER
160262639Sdelphij		ioctl(2, TIOCSPGRP, (char *)&rootpid);
161262639Sdelphij#else
162262639Sdelphij		tcsetpgrp(2, rootpid);
163262639Sdelphij#endif
164262639Sdelphij	} else { /* turning job control off */
165262639Sdelphij		setpgid(0, initialpgrp);
166262639Sdelphij#ifdef OLD_TTY_DRIVER
167262639Sdelphij		ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
168262639Sdelphij#else
169262639Sdelphij		tcsetpgrp(2, initialpgrp);
170262639Sdelphij#endif
171262639Sdelphij		setsignal(SIGTSTP);
172262639Sdelphij		setsignal(SIGTTOU);
173262639Sdelphij		setsignal(SIGTTIN);
174262639Sdelphij	}
175262639Sdelphij	jobctl = on;
176262639Sdelphij}
177262639Sdelphij#endif
178262639Sdelphij
179262639Sdelphij
180262639Sdelphij#ifdef mkinit
181262639SdelphijINCLUDE <sys/types.h>
182262639SdelphijINCLUDE <stdlib.h>
183262639Sdelphij
184262639SdelphijSHELLPROC {
185262639Sdelphij	backgndpid = -1;
186262639Sdelphij#if JOBS
187262639Sdelphij	jobctl = 0;
188262639Sdelphij#endif
189262639Sdelphij}
190262639Sdelphij
191262639Sdelphij#endif
192262639Sdelphij
193262639Sdelphij
194262639Sdelphij
195262639Sdelphij#if JOBS
196262639Sdelphijint
197262639Sdelphijfgcmd(argc, argv)
198262639Sdelphij	int argc __unused;
199262639Sdelphij	char **argv;
200262639Sdelphij{
201262639Sdelphij	struct job *jp;
202262639Sdelphij	int pgrp;
203262639Sdelphij	int status;
204262639Sdelphij
205262639Sdelphij	jp = getjob(argv[1]);
206262639Sdelphij	if (jp->jobctl == 0)
207262639Sdelphij		error("job not created under job control");
208262639Sdelphij	pgrp = jp->ps[0].pid;
209262639Sdelphij#ifdef OLD_TTY_DRIVER
210262639Sdelphij	ioctl(2, TIOCSPGRP, (char *)&pgrp);
211262639Sdelphij#else
212262639Sdelphij	tcsetpgrp(2, pgrp);
213#endif
214	restartjob(jp);
215	INTOFF;
216	status = waitforjob(jp, (int *)NULL);
217	INTON;
218	return status;
219}
220
221
222int
223bgcmd(argc, argv)
224	int argc;
225	char **argv;
226{
227	struct job *jp;
228
229	do {
230		jp = getjob(*++argv);
231		if (jp->jobctl == 0)
232			error("job not created under job control");
233		restartjob(jp);
234	} while (--argc > 1);
235	return 0;
236}
237
238
239STATIC void
240restartjob(jp)
241	struct job *jp;
242{
243	struct procstat *ps;
244	int i;
245
246	if (jp->state == JOBDONE)
247		return;
248	INTOFF;
249	killpg(jp->ps[0].pid, SIGCONT);
250	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
251		if (WIFSTOPPED(ps->status)) {
252			ps->status = -1;
253			jp->state = 0;
254		}
255	}
256	INTON;
257}
258#endif
259
260
261int
262jobscmd(argc, argv)
263	int argc __unused;
264	char **argv __unused;
265{
266	showjobs(0);
267	return 0;
268}
269
270
271/*
272 * Print a list of jobs.  If "change" is nonzero, only print jobs whose
273 * statuses have changed since the last call to showjobs.
274 *
275 * If the shell is interrupted in the process of creating a job, the
276 * result may be a job structure containing zero processes.  Such structures
277 * will be freed here.
278 */
279
280void
281showjobs(change)
282	int change;
283{
284	int jobno;
285	int procno;
286	int i;
287	struct job *jp;
288	struct procstat *ps;
289	int col;
290	char s[64];
291
292	TRACE(("showjobs(%d) called\n", change));
293	while (dowait(0, (struct job *)NULL) > 0);
294	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
295		if (! jp->used)
296			continue;
297		if (jp->nprocs == 0) {
298			freejob(jp);
299			continue;
300		}
301		if (change && ! jp->changed)
302			continue;
303		procno = jp->nprocs;
304		for (ps = jp->ps ; ; ps++) {	/* for each process */
305			if (ps == jp->ps)
306				fmtstr(s, 64, "[%d] %d ", jobno, ps->pid);
307			else
308				fmtstr(s, 64, "    %d ", ps->pid);
309			out1str(s);
310			col = strlen(s);
311			s[0] = '\0';
312			if (ps->status == -1) {
313				/* don't print anything */
314			} else if (WIFEXITED(ps->status)) {
315				fmtstr(s, 64, "Exit %d", WEXITSTATUS(ps->status));
316			} else {
317#if JOBS
318				if (WIFSTOPPED(ps->status))
319					i = WSTOPSIG(ps->status);
320				else
321#endif
322					i = WTERMSIG(ps->status);
323				if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
324					scopy(sys_siglist[i & 0x7F], s);
325				else
326					fmtstr(s, 64, "Signal %d", i & 0x7F);
327				if (WCOREDUMP(ps->status))
328					strcat(s, " (core dumped)");
329			}
330			out1str(s);
331			col += strlen(s);
332			do {
333				out1c(' ');
334				col++;
335			} while (col < 30);
336			out1str(ps->cmd);
337			out1c('\n');
338			if (--procno <= 0)
339				break;
340		}
341		jp->changed = 0;
342		if (jp->state == JOBDONE) {
343			freejob(jp);
344		}
345	}
346}
347
348
349/*
350 * Mark a job structure as unused.
351 */
352
353STATIC void
354freejob(jp)
355	struct job *jp;
356	{
357	struct procstat *ps;
358	int i;
359
360	INTOFF;
361	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
362		if (ps->cmd != nullstr)
363			ckfree(ps->cmd);
364	}
365	if (jp->ps != &jp->ps0)
366		ckfree(jp->ps);
367	jp->used = 0;
368#if JOBS
369	if (curjob == jp - jobtab + 1)
370		curjob = 0;
371#endif
372	INTON;
373}
374
375
376
377int
378waitcmd(argc, argv)
379	int argc;
380	char **argv;
381{
382	struct job *job;
383	int status, retval;
384	struct job *jp;
385
386	if (argc > 1) {
387		job = getjob(argv[1]);
388	} else {
389		job = NULL;
390	}
391
392	/*
393	 * Loop until a process is terminated or stopped, or a SIGINT is
394	 * received.
395	 */
396
397	in_waitcmd++;
398	do {
399		if (job != NULL) {
400			if (job->state) {
401				status = job->ps[job->nprocs - 1].status;
402				if (WIFEXITED(status))
403					retval = WEXITSTATUS(status);
404#if JOBS
405				else if (WIFSTOPPED(status))
406					retval = WSTOPSIG(status) + 128;
407#endif
408				else
409					retval = WTERMSIG(status) + 128;
410				if (! iflag)
411					freejob(job);
412				in_waitcmd--;
413				return retval;
414			}
415		} else {
416			for (jp = jobtab ; ; jp++) {
417				if (jp >= jobtab + njobs) {	/* no running procs */
418					in_waitcmd--;
419					return 0;
420				}
421				if (jp->used && jp->state == 0)
422					break;
423			}
424		}
425	} while (dowait(1, (struct job *)NULL) != -1);
426	in_waitcmd--;
427
428	return 0;
429}
430
431
432
433int
434jobidcmd(argc, argv)
435	int argc __unused;
436	char **argv;
437{
438	struct job *jp;
439	int i;
440
441	jp = getjob(argv[1]);
442	for (i = 0 ; i < jp->nprocs ; ) {
443		out1fmt("%d", jp->ps[i].pid);
444		out1c(++i < jp->nprocs? ' ' : '\n');
445	}
446	return 0;
447}
448
449
450
451/*
452 * Convert a job name to a job structure.
453 */
454
455STATIC struct job *
456getjob(name)
457	char *name;
458	{
459	int jobno;
460	struct job *jp;
461	int pid;
462	int i;
463
464	if (name == NULL) {
465#if JOBS
466currentjob:
467		if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
468			error("No current job");
469		return &jobtab[jobno - 1];
470#else
471		error("No current job");
472#endif
473	} else if (name[0] == '%') {
474		if (is_digit(name[1])) {
475			jobno = number(name + 1);
476			if (jobno > 0 && jobno <= njobs
477			 && jobtab[jobno - 1].used != 0)
478				return &jobtab[jobno - 1];
479#if JOBS
480		} else if (name[1] == '%' && name[2] == '\0') {
481			goto currentjob;
482#endif
483		} else {
484			struct job *found = NULL;
485			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
486				if (jp->used && jp->nprocs > 0
487				 && prefix(name + 1, jp->ps[0].cmd)) {
488					if (found)
489						error("%s: ambiguous", name);
490					found = jp;
491				}
492			}
493			if (found)
494				return found;
495		}
496	} else if (is_number(name)) {
497		pid = number(name);
498		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
499			if (jp->used && jp->nprocs > 0
500			 && jp->ps[jp->nprocs - 1].pid == pid)
501				return jp;
502		}
503	}
504	error("No such job: %s", name);
505	/*NOTREACHED*/
506	return NULL;
507}
508
509
510
511/*
512 * Return a new job structure,
513 */
514
515struct job *
516makejob(node, nprocs)
517	union node *node __unused;
518	int nprocs;
519{
520	int i;
521	struct job *jp;
522
523	for (i = njobs, jp = jobtab ; ; jp++) {
524		if (--i < 0) {
525			INTOFF;
526			if (njobs == 0) {
527				jobtab = ckmalloc(4 * sizeof jobtab[0]);
528			} else {
529				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
530				memcpy(jp, jobtab, njobs * sizeof jp[0]);
531				/* Relocate `ps' pointers */
532				for (i = 0; i < njobs; i++)
533					if (jp[i].ps == &jobtab[i].ps0)
534						jp[i].ps = &jp[i].ps0;
535				ckfree(jobtab);
536				jobtab = jp;
537			}
538			jp = jobtab + njobs;
539			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
540			INTON;
541			break;
542		}
543		if (jp->used == 0)
544			break;
545	}
546	INTOFF;
547	jp->state = 0;
548	jp->used = 1;
549	jp->changed = 0;
550	jp->nprocs = 0;
551#if JOBS
552	jp->jobctl = jobctl;
553#endif
554	if (nprocs > 1) {
555		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
556	} else {
557		jp->ps = &jp->ps0;
558	}
559	INTON;
560	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
561	    jp - jobtab + 1));
562	return jp;
563}
564
565
566/*
567 * Fork of a subshell.  If we are doing job control, give the subshell its
568 * own process group.  Jp is a job structure that the job is to be added to.
569 * N is the command that will be evaluated by the child.  Both jp and n may
570 * be NULL.  The mode parameter can be one of the following:
571 *	FORK_FG - Fork off a foreground process.
572 *	FORK_BG - Fork off a background process.
573 *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
574 *		     process group even if job control is on.
575 *
576 * When job control is turned off, background processes have their standard
577 * input redirected to /dev/null (except for the second and later processes
578 * in a pipeline).
579 */
580
581int
582forkshell(jp, n, mode)
583	union node *n;
584	struct job *jp;
585	int mode;
586{
587	int pid;
588	int pgrp;
589
590	TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
591	    mode));
592	INTOFF;
593	pid = fork();
594	if (pid == -1) {
595		TRACE(("Fork failed, errno=%d\n", errno));
596		INTON;
597		error("Cannot fork");
598	}
599	if (pid == 0) {
600		struct job *p;
601		int wasroot;
602		int i;
603
604		TRACE(("Child shell %d\n", getpid()));
605		wasroot = rootshell;
606		rootshell = 0;
607		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
608			if (p->used)
609				freejob(p);
610		closescript();
611		INTON;
612		clear_traps();
613#if JOBS
614		jobctl = 0;		/* do job control only in root shell */
615		if (wasroot && mode != FORK_NOJOB && mflag) {
616			if (jp == NULL || jp->nprocs == 0)
617				pgrp = getpid();
618			else
619				pgrp = jp->ps[0].pid;
620			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
621				/*** this causes superfluous TIOCSPGRPS ***/
622#ifdef OLD_TTY_DRIVER
623				if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
624					error("TIOCSPGRP failed, errno=%d", errno);
625#else
626				if (tcsetpgrp(2, pgrp) < 0)
627					error("tcsetpgrp failed, errno=%d", errno);
628#endif
629			}
630			setsignal(SIGTSTP);
631			setsignal(SIGTTOU);
632		} else if (mode == FORK_BG) {
633			ignoresig(SIGINT);
634			ignoresig(SIGQUIT);
635			if ((jp == NULL || jp->nprocs == 0) &&
636			    ! fd0_redirected_p ()) {
637				close(0);
638				if (open("/dev/null", O_RDONLY) != 0)
639					error("Can't open /dev/null");
640			}
641		}
642#else
643		if (mode == FORK_BG) {
644			ignoresig(SIGINT);
645			ignoresig(SIGQUIT);
646			if ((jp == NULL || jp->nprocs == 0) &&
647			    ! fd0_redirected_p ()) {
648				close(0);
649				if (open("/dev/null", O_RDONLY) != 0)
650					error("Can't open /dev/null");
651			}
652		}
653#endif
654		if (wasroot && iflag) {
655			setsignal(SIGINT);
656			setsignal(SIGQUIT);
657			setsignal(SIGTERM);
658		}
659		return pid;
660	}
661	if (rootshell && mode != FORK_NOJOB && mflag) {
662		if (jp == NULL || jp->nprocs == 0)
663			pgrp = pid;
664		else
665			pgrp = jp->ps[0].pid;
666		setpgid(pid, pgrp);
667	}
668	if (mode == FORK_BG)
669		backgndpid = pid;		/* set $! */
670	if (jp) {
671		struct procstat *ps = &jp->ps[jp->nprocs++];
672		ps->pid = pid;
673		ps->status = -1;
674		ps->cmd = nullstr;
675		if (iflag && rootshell && n)
676			ps->cmd = commandtext(n);
677	}
678	INTON;
679	TRACE(("In parent shell:  child = %d\n", pid));
680	return pid;
681}
682
683
684
685/*
686 * Wait for job to finish.
687 *
688 * Under job control we have the problem that while a child process is
689 * running interrupts generated by the user are sent to the child but not
690 * to the shell.  This means that an infinite loop started by an inter-
691 * active user may be hard to kill.  With job control turned off, an
692 * interactive user may place an interactive program inside a loop.  If
693 * the interactive program catches interrupts, the user doesn't want
694 * these interrupts to also abort the loop.  The approach we take here
695 * is to have the shell ignore interrupt signals while waiting for a
696 * foreground process to terminate, and then send itself an interrupt
697 * signal if the child process was terminated by an interrupt signal.
698 * Unfortunately, some programs want to do a bit of cleanup and then
699 * exit on interrupt; unless these processes terminate themselves by
700 * sending a signal to themselves (instead of calling exit) they will
701 * confuse this approach.
702 */
703
704int
705waitforjob(jp, origstatus)
706	struct job *jp;
707	int *origstatus;
708{
709#if JOBS
710	int mypgrp = getpgrp();
711#endif
712	int status;
713	int st;
714
715	INTOFF;
716	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
717	while (jp->state == 0)
718		if (dowait(1, jp) == -1)
719			dotrap();
720#if JOBS
721	if (jp->jobctl) {
722#ifdef OLD_TTY_DRIVER
723		if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
724			error("TIOCSPGRP failed, errno=%d\n", errno);
725#else
726		if (tcsetpgrp(2, mypgrp) < 0)
727			error("tcsetpgrp failed, errno=%d\n", errno);
728#endif
729	}
730	if (jp->state == JOBSTOPPED)
731		curjob = jp - jobtab + 1;
732#endif
733	status = jp->ps[jp->nprocs - 1].status;
734	if (origstatus != NULL)
735		*origstatus = status;
736	/* convert to 8 bits */
737	if (WIFEXITED(status))
738		st = WEXITSTATUS(status);
739#if JOBS
740	else if (WIFSTOPPED(status))
741		st = WSTOPSIG(status) + 128;
742#endif
743	else
744		st = WTERMSIG(status) + 128;
745	if (! JOBS || jp->state == JOBDONE)
746		freejob(jp);
747	if (int_pending()) {
748		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
749			kill(getpid(), SIGINT);
750		else
751			CLEAR_PENDING_INT;
752	}
753	INTON;
754	return st;
755}
756
757
758
759/*
760 * Wait for a process to terminate.
761 */
762
763STATIC int
764dowait(block, job)
765	int block;
766	struct job *job;
767{
768	int pid;
769	int status;
770	struct procstat *sp;
771	struct job *jp;
772	struct job *thisjob;
773	int done;
774	int stopped;
775	int core;
776	int sig;
777
778	in_dowait++;
779	TRACE(("dowait(%d) called\n", block));
780	do {
781		pid = waitproc(block, &status);
782		TRACE(("wait returns %d, status=%d\n", pid, status));
783	} while (pid == -1 && errno == EINTR && breakwaitcmd == 0);
784	in_dowait--;
785	if (breakwaitcmd != 0) {
786		breakwaitcmd = 0;
787		return -1;
788	}
789	if (pid <= 0)
790		return pid;
791	INTOFF;
792	thisjob = NULL;
793	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
794		if (jp->used) {
795			done = 1;
796			stopped = 1;
797			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
798				if (sp->pid == -1)
799					continue;
800				if (sp->pid == pid) {
801					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
802						   pid, sp->status, status));
803					sp->status = status;
804					thisjob = jp;
805				}
806				if (sp->status == -1)
807					stopped = 0;
808				else if (WIFSTOPPED(sp->status))
809					done = 0;
810			}
811			if (stopped) {		/* stopped or done */
812				int state = done? JOBDONE : JOBSTOPPED;
813				if (jp->state != state) {
814					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
815					jp->state = state;
816#if JOBS
817					if (done && curjob == jp - jobtab + 1)
818						curjob = 0;		/* no current job */
819#endif
820				}
821			}
822		}
823	}
824	INTON;
825	if (! rootshell || ! iflag || (job && thisjob == job)) {
826		core = WCOREDUMP(status);
827#if JOBS
828		if (WIFSTOPPED(status))
829			sig = WSTOPSIG(status);
830		else
831#endif
832			if (WIFEXITED(status))
833				sig = 0;
834			else
835				sig = WTERMSIG(status);
836
837		if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
838			if (thisjob != job)
839				outfmt(out2, "%d: ", pid);
840#if JOBS
841			if (sig == SIGTSTP && rootshell && iflag)
842				outfmt(out2, "%%%d ", job - jobtab + 1);
843#endif
844			if (sig < NSIG && sys_siglist[sig])
845				out2str(sys_siglist[sig]);
846			else
847				outfmt(out2, "Signal %d", sig);
848			if (core)
849				out2str(" - core dumped");
850			out2c('\n');
851			flushout(&errout);
852		} else {
853			TRACE(("Not printing status: status=%d, sig=%d\n",
854				   status, sig));
855		}
856	} else {
857		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
858		if (thisjob)
859			thisjob->changed = 1;
860	}
861	return pid;
862}
863
864
865
866/*
867 * Do a wait system call.  If job control is compiled in, we accept
868 * stopped processes.  If block is zero, we return a value of zero
869 * rather than blocking.
870 *
871 * System V doesn't have a non-blocking wait system call.  It does
872 * have a SIGCLD signal that is sent to a process when one of it's
873 * children dies.  The obvious way to use SIGCLD would be to install
874 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
875 * was received, and have waitproc bump another counter when it got
876 * the status of a process.  Waitproc would then know that a wait
877 * system call would not block if the two counters were different.
878 * This approach doesn't work because if a process has children that
879 * have not been waited for, System V will send it a SIGCLD when it
880 * installs a signal handler for SIGCLD.  What this means is that when
881 * a child exits, the shell will be sent SIGCLD signals continuously
882 * until is runs out of stack space, unless it does a wait call before
883 * restoring the signal handler.  The code below takes advantage of
884 * this (mis)feature by installing a signal handler for SIGCLD and
885 * then checking to see whether it was called.  If there are any
886 * children to be waited for, it will be.
887 *
888 * If neither SYSV nor BSD is defined, we don't implement nonblocking
889 * waits at all.  In this case, the user will not be informed when
890 * a background process until the next time she runs a real program
891 * (as opposed to running a builtin command or just typing return),
892 * and the jobs command may give out of date information.
893 */
894
895#ifdef SYSV
896STATIC sig_atomic_t gotsigchild;
897
898STATIC int onsigchild() {
899	gotsigchild = 1;
900}
901#endif
902
903
904STATIC int
905waitproc(block, status)
906	int block;
907	int *status;
908{
909#ifdef BSD
910	int flags;
911
912#if JOBS
913	flags = WUNTRACED;
914#else
915	flags = 0;
916#endif
917	if (block == 0)
918		flags |= WNOHANG;
919	return wait3(status, flags, (struct rusage *)NULL);
920#else
921#ifdef SYSV
922	int (*save)();
923
924	if (block == 0) {
925		gotsigchild = 0;
926		save = signal(SIGCLD, onsigchild);
927		signal(SIGCLD, save);
928		if (gotsigchild == 0)
929			return 0;
930	}
931	return wait(status);
932#else
933	if (block == 0)
934		return 0;
935	return wait(status);
936#endif
937#endif
938}
939
940/*
941 * return 1 if there are stopped jobs, otherwise 0
942 */
943int job_warning = 0;
944int
945stoppedjobs()
946{
947	int jobno;
948	struct job *jp;
949
950	if (job_warning)
951		return (0);
952	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
953		if (jp->used == 0)
954			continue;
955		if (jp->state == JOBSTOPPED) {
956			out2str("You have stopped jobs.\n");
957			job_warning = 2;
958			return (1);
959		}
960	}
961
962	return (0);
963}
964
965/*
966 * Return a string identifying a command (to be printed by the
967 * jobs command.
968 */
969
970STATIC char *cmdnextc;
971STATIC int cmdnleft;
972STATIC void cmdtxt(), cmdputs();
973#define MAXCMDTEXT	200
974
975char *
976commandtext(n)
977	union node *n;
978	{
979	char *name;
980
981	cmdnextc = name = ckmalloc(MAXCMDTEXT);
982	cmdnleft = MAXCMDTEXT - 4;
983	cmdtxt(n);
984	*cmdnextc = '\0';
985	return name;
986}
987
988
989STATIC void
990cmdtxt(n)
991	union node *n;
992	{
993	union node *np;
994	struct nodelist *lp;
995	char *p;
996	int i;
997	char s[2];
998
999	if (n == NULL)
1000		return;
1001	switch (n->type) {
1002	case NSEMI:
1003		cmdtxt(n->nbinary.ch1);
1004		cmdputs("; ");
1005		cmdtxt(n->nbinary.ch2);
1006		break;
1007	case NAND:
1008		cmdtxt(n->nbinary.ch1);
1009		cmdputs(" && ");
1010		cmdtxt(n->nbinary.ch2);
1011		break;
1012	case NOR:
1013		cmdtxt(n->nbinary.ch1);
1014		cmdputs(" || ");
1015		cmdtxt(n->nbinary.ch2);
1016		break;
1017	case NPIPE:
1018		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1019			cmdtxt(lp->n);
1020			if (lp->next)
1021				cmdputs(" | ");
1022		}
1023		break;
1024	case NSUBSHELL:
1025		cmdputs("(");
1026		cmdtxt(n->nredir.n);
1027		cmdputs(")");
1028		break;
1029	case NREDIR:
1030	case NBACKGND:
1031		cmdtxt(n->nredir.n);
1032		break;
1033	case NIF:
1034		cmdputs("if ");
1035		cmdtxt(n->nif.test);
1036		cmdputs("; then ");
1037		cmdtxt(n->nif.ifpart);
1038		cmdputs("...");
1039		break;
1040	case NWHILE:
1041		cmdputs("while ");
1042		goto until;
1043	case NUNTIL:
1044		cmdputs("until ");
1045until:
1046		cmdtxt(n->nbinary.ch1);
1047		cmdputs("; do ");
1048		cmdtxt(n->nbinary.ch2);
1049		cmdputs("; done");
1050		break;
1051	case NFOR:
1052		cmdputs("for ");
1053		cmdputs(n->nfor.var);
1054		cmdputs(" in ...");
1055		break;
1056	case NCASE:
1057		cmdputs("case ");
1058		cmdputs(n->ncase.expr->narg.text);
1059		cmdputs(" in ...");
1060		break;
1061	case NDEFUN:
1062		cmdputs(n->narg.text);
1063		cmdputs("() ...");
1064		break;
1065	case NCMD:
1066		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1067			cmdtxt(np);
1068			if (np->narg.next)
1069				cmdputs(" ");
1070		}
1071		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1072			cmdputs(" ");
1073			cmdtxt(np);
1074		}
1075		break;
1076	case NARG:
1077		cmdputs(n->narg.text);
1078		break;
1079	case NTO:
1080		p = ">";  i = 1;  goto redir;
1081	case NAPPEND:
1082		p = ">>";  i = 1;  goto redir;
1083	case NTOFD:
1084		p = ">&";  i = 1;  goto redir;
1085	case NFROM:
1086		p = "<";  i = 0;  goto redir;
1087	case NFROMFD:
1088		p = "<&";  i = 0;  goto redir;
1089redir:
1090		if (n->nfile.fd != i) {
1091			s[0] = n->nfile.fd + '0';
1092			s[1] = '\0';
1093			cmdputs(s);
1094		}
1095		cmdputs(p);
1096		if (n->type == NTOFD || n->type == NFROMFD) {
1097			s[0] = n->ndup.dupfd + '0';
1098			s[1] = '\0';
1099			cmdputs(s);
1100		} else {
1101			cmdtxt(n->nfile.fname);
1102		}
1103		break;
1104	case NHERE:
1105	case NXHERE:
1106		cmdputs("<<...");
1107		break;
1108	default:
1109		cmdputs("???");
1110		break;
1111	}
1112}
1113
1114
1115
1116STATIC void
1117cmdputs(s)
1118	char *s;
1119	{
1120	char *p, *q;
1121	char c;
1122	int subtype = 0;
1123
1124	if (cmdnleft <= 0)
1125		return;
1126	p = s;
1127	q = cmdnextc;
1128	while ((c = *p++) != '\0') {
1129		if (c == CTLESC)
1130			*q++ = *p++;
1131		else if (c == CTLVAR) {
1132			*q++ = '$';
1133			if (--cmdnleft > 0)
1134				*q++ = '{';
1135			subtype = *p++;
1136		} else if (c == '=' && subtype != 0) {
1137			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1138			subtype = 0;
1139		} else if (c == CTLENDVAR) {
1140			*q++ = '}';
1141		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1142			cmdnleft++;		/* ignore it */
1143		else
1144			*q++ = c;
1145		if (--cmdnleft <= 0) {
1146			*q++ = '.';
1147			*q++ = '.';
1148			*q++ = '.';
1149			break;
1150		}
1151	}
1152	cmdnextc = q;
1153}
1154