jobs.c revision 102007
1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38#if 0
39static char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
40#endif
41#endif /* not lint */
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: head/bin/sh/jobs.c 102007 2002-08-17 13:57:47Z tjr $");
44
45#include <fcntl.h>
46#include <signal.h>
47#include <errno.h>
48#include <paths.h>
49#include <unistd.h>
50#include <stdlib.h>
51#include <sys/param.h>
52#include <sys/wait.h>
53#include <sys/time.h>
54#include <sys/resource.h>
55#include <paths.h>
56#include <sys/ioctl.h>
57
58#include "shell.h"
59#if JOBS
60#include <termios.h>
61#undef CEOF			/* syntax.h redefines this */
62#endif
63#include "redir.h"
64#include "show.h"
65#include "main.h"
66#include "parser.h"
67#include "nodes.h"
68#include "jobs.h"
69#include "options.h"
70#include "trap.h"
71#include "syntax.h"
72#include "input.h"
73#include "output.h"
74#include "memalloc.h"
75#include "error.h"
76#include "mystring.h"
77
78
79struct job *jobtab;		/* array of jobs */
80int njobs;			/* size of array */
81MKINIT pid_t backgndpid = -1;	/* pid of last background process */
82#if JOBS
83struct job *jobmru;		/* most recently used job list */
84pid_t initialpgrp;		/* pgrp of shell on invocation */
85#endif
86int in_waitcmd = 0;		/* are we in waitcmd()? */
87int in_dowait = 0;		/* are we in dowait()? */
88volatile sig_atomic_t breakwaitcmd = 0;	/* should wait be terminated? */
89static int ttyfd = -1;
90
91#if JOBS
92STATIC void restartjob(struct job *);
93#endif
94STATIC void freejob(struct job *);
95STATIC struct job *getjob(char *);
96STATIC pid_t dowait(int, struct job *);
97STATIC pid_t waitproc(int, int *);
98STATIC void cmdtxt(union node *);
99STATIC void cmdputs(char *);
100#if JOBS
101STATIC void setcurjob(struct job *);
102STATIC void deljob(struct job *);
103STATIC struct job *getcurjob(struct job *);
104#endif
105STATIC void showjob(struct job *, pid_t, int, int);
106
107
108/*
109 * Turn job control on and off.
110 */
111
112MKINIT int jobctl;
113
114#if JOBS
115void
116setjobctl(int on)
117{
118	int i;
119
120	if (on == jobctl || rootshell == 0)
121		return;
122	if (on) {
123		if (ttyfd != -1)
124			close(ttyfd);
125		if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
126			i = 0;
127			while (i <= 2 && !isatty(i))
128				i++;
129			if (i > 2 || (ttyfd = dup(i)) < 0)
130				goto out;
131		}
132		if (fcntl(ttyfd, FD_CLOEXEC, 1) < 0) {
133			close(ttyfd);
134			ttyfd = -1;
135			goto out;
136		}
137		do { /* while we are in the background */
138			initialpgrp = tcgetpgrp(ttyfd);
139			if (initialpgrp < 0) {
140out:				out2str("sh: can't access tty; job control turned off\n");
141				mflag = 0;
142				return;
143			}
144			if (initialpgrp == -1)
145				initialpgrp = getpgrp();
146			else if (initialpgrp != getpgrp()) {
147				killpg(0, SIGTTIN);
148				continue;
149			}
150		} while (0);
151		setsignal(SIGTSTP);
152		setsignal(SIGTTOU);
153		setsignal(SIGTTIN);
154		setpgid(0, rootpid);
155		tcsetpgrp(ttyfd, rootpid);
156	} else { /* turning job control off */
157		setpgid(0, initialpgrp);
158		tcsetpgrp(ttyfd, initialpgrp);
159		close(ttyfd);
160		ttyfd = -1;
161		setsignal(SIGTSTP);
162		setsignal(SIGTTOU);
163		setsignal(SIGTTIN);
164	}
165	jobctl = on;
166}
167#endif
168
169
170#ifdef mkinit
171INCLUDE <sys/types.h>
172INCLUDE <stdlib.h>
173
174SHELLPROC {
175	backgndpid = -1;
176#if JOBS
177	jobctl = 0;
178#endif
179}
180
181#endif
182
183
184
185#if JOBS
186int
187fgcmd(int argc __unused, char **argv)
188{
189	struct job *jp;
190	pid_t pgrp;
191	int status;
192
193	jp = getjob(argv[1]);
194	if (jp->jobctl == 0)
195		error("job not created under job control");
196	out1str(jp->ps[0].cmd);
197	out1c('\n');
198	flushout(&output);
199	pgrp = jp->ps[0].pid;
200	tcsetpgrp(ttyfd, pgrp);
201	restartjob(jp);
202	jp->foreground = 1;
203	INTOFF;
204	status = waitforjob(jp, (int *)NULL);
205	INTON;
206	return status;
207}
208
209
210int
211bgcmd(int argc, char **argv)
212{
213	char s[64];
214	struct job *jp;
215
216	do {
217		jp = getjob(*++argv);
218		if (jp->jobctl == 0)
219			error("job not created under job control");
220		if (jp->state == JOBDONE)
221			continue;
222		restartjob(jp);
223		jp->foreground = 0;
224		fmtstr(s, 64, "[%d] ", jp - jobtab + 1);
225		out1str(s);
226		out1str(jp->ps[0].cmd);
227		out1c('\n');
228	} while (--argc > 1);
229	return 0;
230}
231
232
233STATIC void
234restartjob(struct job *jp)
235{
236	struct procstat *ps;
237	int i;
238
239	if (jp->state == JOBDONE)
240		return;
241	setcurjob(jp);
242	INTOFF;
243	killpg(jp->ps[0].pid, SIGCONT);
244	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
245		if (WIFSTOPPED(ps->status)) {
246			ps->status = -1;
247			jp->state = 0;
248		}
249	}
250	INTON;
251}
252#endif
253
254
255int
256jobscmd(int argc, char *argv[])
257{
258	char *id;
259	int ch, sformat, lformat;
260
261	optind = optreset = 1;
262	opterr = 0;
263	sformat = lformat = 0;
264	while ((ch = getopt(argc, argv, "ls")) != -1) {
265		switch (ch) {
266		case 'l':
267			lformat = 1;
268			break;
269		case 's':
270			sformat = 1;
271			break;
272		case '?':
273		default:
274			error("unknown option: -%c", optopt);
275		}
276	}
277	argc -= optind;
278	argv += optind;
279
280	if (argc == 0)
281		showjobs(0, sformat, lformat);
282	else
283		while ((id = *argv++) != NULL)
284			showjob(getjob(id), 0, sformat, lformat);
285
286	return (0);
287}
288
289STATIC void
290showjob(struct job *jp, pid_t pid, int sformat, int lformat)
291{
292	char s[64];
293	struct procstat *ps;
294	struct job *j;
295	int col, curr, i, jobno, prev, procno;
296	char c;
297
298	procno = jp->nprocs;
299	jobno = jp - jobtab + 1;
300	curr = prev = 0;
301#if JOBS
302	if ((j = getcurjob(NULL)) != NULL) {
303		curr = j - jobtab + 1;
304		if ((j = getcurjob(j)) != NULL)
305			prev = j - jobtab + 1;
306	}
307#endif
308	for (ps = jp->ps ; ; ps++) {	/* for each process */
309		if (sformat) {
310			out1fmt("%d\n", (int)ps->pid);
311			goto skip;
312		}
313		if (!lformat && ps != jp->ps && pid == 0)
314			goto skip;
315		if (pid != 0 && pid != ps->pid)
316			goto skip;
317		if (jobno == curr && ps == jp->ps)
318			c = '+';
319		else if (jobno == prev && ps == jp->ps)
320			c = '-';
321		else
322			c = ' ';
323		if (ps == jp->ps)
324			fmtstr(s, 64, "[%d] %c ", jobno, c);
325		else
326			fmtstr(s, 64, "    %c ", c);
327		out1str(s);
328		col = strlen(s);
329		if (lformat) {
330			fmtstr(s, 64, "%d ", (int)ps->pid);
331			out1str(s);
332			col += strlen(s);
333		}
334		s[0] = '\0';
335		if (ps != jp->ps) {
336			*s = '\0';
337		} else if (ps->status == -1) {
338			strcpy(s, "Running");
339		} else if (WIFEXITED(ps->status)) {
340			if (WEXITSTATUS(ps->status) == 0)
341				strcpy(s, "Done");
342			else
343				fmtstr(s, 64, "Done (%d)",
344				    WEXITSTATUS(ps->status));
345		} else {
346#if JOBS
347			if (WIFSTOPPED(ps->status))
348				i = WSTOPSIG(ps->status);
349			else
350#endif
351				i = WTERMSIG(ps->status);
352			if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
353				scopy(sys_siglist[i & 0x7F], s);
354			else
355				fmtstr(s, 64, "Signal %d", i & 0x7F);
356			if (WCOREDUMP(ps->status))
357				strcat(s, " (core dumped)");
358		}
359		out1str(s);
360		col += strlen(s);
361		do {
362			out1c(' ');
363			col++;
364		} while (col < 30);
365		out1str(ps->cmd);
366		out1c('\n');
367skip:		if (--procno <= 0)
368			break;
369	}
370}
371
372/*
373 * Print a list of jobs.  If "change" is nonzero, only print jobs whose
374 * statuses have changed since the last call to showjobs.
375 *
376 * If the shell is interrupted in the process of creating a job, the
377 * result may be a job structure containing zero processes.  Such structures
378 * will be freed here.
379 */
380
381void
382showjobs(int change, int sformat, int lformat)
383{
384	int jobno;
385	struct job *jp;
386
387	TRACE(("showjobs(%d) called\n", change));
388	while (dowait(0, (struct job *)NULL) > 0);
389	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
390		if (! jp->used)
391			continue;
392		if (jp->nprocs == 0) {
393			freejob(jp);
394			continue;
395		}
396		if (change && ! jp->changed)
397			continue;
398		showjob(jp, 0, sformat, lformat);
399		jp->changed = 0;
400		if (jp->state == JOBDONE) {
401			freejob(jp);
402		}
403	}
404}
405
406
407/*
408 * Mark a job structure as unused.
409 */
410
411STATIC void
412freejob(struct job *jp)
413{
414	struct procstat *ps;
415	int i;
416
417	INTOFF;
418	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
419		if (ps->cmd != nullstr)
420			ckfree(ps->cmd);
421	}
422	if (jp->ps != &jp->ps0)
423		ckfree(jp->ps);
424	jp->used = 0;
425#if JOBS
426	deljob(jp);
427#endif
428	INTON;
429}
430
431
432
433int
434waitcmd(int argc, char **argv)
435{
436	struct job *job;
437	int status, retval;
438	struct job *jp;
439
440	if (argc > 1) {
441		job = getjob(argv[1]);
442	} else {
443		job = NULL;
444	}
445
446	/*
447	 * Loop until a process is terminated or stopped, or a SIGINT is
448	 * received.
449	 */
450
451	in_waitcmd++;
452	do {
453		if (job != NULL) {
454			if (job->state) {
455				status = job->ps[job->nprocs - 1].status;
456				if (WIFEXITED(status))
457					retval = WEXITSTATUS(status);
458#if JOBS
459				else if (WIFSTOPPED(status))
460					retval = WSTOPSIG(status) + 128;
461#endif
462				else
463					retval = WTERMSIG(status) + 128;
464				if (! iflag)
465					freejob(job);
466				in_waitcmd--;
467				return retval;
468			}
469		} else {
470			for (jp = jobtab ; ; jp++) {
471				if (jp >= jobtab + njobs) {	/* no running procs */
472					in_waitcmd--;
473					return 0;
474				}
475				if (jp->used && jp->state == 0)
476					break;
477			}
478		}
479	} while (dowait(1, (struct job *)NULL) != -1);
480	in_waitcmd--;
481
482	return 0;
483}
484
485
486
487int
488jobidcmd(int argc __unused, char **argv)
489{
490	struct job *jp;
491	int i;
492
493	jp = getjob(argv[1]);
494	for (i = 0 ; i < jp->nprocs ; ) {
495		out1fmt("%d", (int)jp->ps[i].pid);
496		out1c(++i < jp->nprocs? ' ' : '\n');
497	}
498	return 0;
499}
500
501
502
503/*
504 * Convert a job name to a job structure.
505 */
506
507STATIC struct job *
508getjob(char *name)
509{
510	int jobno;
511	struct job *found, *jp;
512	pid_t pid;
513	int i;
514
515	if (name == NULL) {
516#if JOBS
517currentjob:	if ((jp = getcurjob(NULL)) == NULL)
518			error("No current job");
519		return (jp);
520#else
521		error("No current job");
522#endif
523	} else if (name[0] == '%') {
524		if (is_digit(name[1])) {
525			jobno = number(name + 1);
526			if (jobno > 0 && jobno <= njobs
527			 && jobtab[jobno - 1].used != 0)
528				return &jobtab[jobno - 1];
529#if JOBS
530		} else if (name[1] == '%' && name[2] == '\0') {
531			goto currentjob;
532		} else if (name[1] == '+' && name[2] == '\0') {
533			goto currentjob;
534		} else if (name[1] == '-' && name[2] == '\0') {
535			if ((jp = getcurjob(NULL)) == NULL ||
536			    (jp = getcurjob(jp)) == NULL)
537				error("No previous job");
538			return (jp);
539#endif
540		} else if (name[1] == '?') {
541			found = NULL;
542			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
543				if (jp->used && jp->nprocs > 0
544				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
545					if (found)
546						error("%s: ambiguous", name);
547					found = jp;
548				}
549			}
550			if (found != NULL)
551				return (found);
552		} else {
553			found = NULL;
554			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
555				if (jp->used && jp->nprocs > 0
556				 && prefix(name + 1, jp->ps[0].cmd)) {
557					if (found)
558						error("%s: ambiguous", name);
559					found = jp;
560				}
561			}
562			if (found)
563				return found;
564		}
565	} else if (is_number(name)) {
566		pid = (pid_t)number(name);
567		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
568			if (jp->used && jp->nprocs > 0
569			 && jp->ps[jp->nprocs - 1].pid == pid)
570				return jp;
571		}
572	}
573	error("No such job: %s", name);
574	/*NOTREACHED*/
575	return NULL;
576}
577
578
579
580/*
581 * Return a new job structure,
582 */
583
584struct job *
585makejob(union node *node __unused, int nprocs)
586{
587	int i;
588	struct job *jp;
589
590	for (i = njobs, jp = jobtab ; ; jp++) {
591		if (--i < 0) {
592			INTOFF;
593			if (njobs == 0) {
594				jobtab = ckmalloc(4 * sizeof jobtab[0]);
595#if JOBS
596				jobmru = NULL;
597#endif
598			} else {
599				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
600				memcpy(jp, jobtab, njobs * sizeof jp[0]);
601#if JOBS
602				/* Relocate `next' pointers and list head */
603				if (jobmru != NULL)
604					jobmru = &jp[jobmru - jobtab];
605				for (i = 0; i < njobs; i++)
606					if (jp[i].next != NULL)
607						jp[i].next = &jp[jp[i].next -
608						    jobtab];
609#endif
610				/* Relocate `ps' pointers */
611				for (i = 0; i < njobs; i++)
612					if (jp[i].ps == &jobtab[i].ps0)
613						jp[i].ps = &jp[i].ps0;
614				ckfree(jobtab);
615				jobtab = jp;
616			}
617			jp = jobtab + njobs;
618			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
619			INTON;
620			break;
621		}
622		if (jp->used == 0)
623			break;
624	}
625	INTOFF;
626	jp->state = 0;
627	jp->used = 1;
628	jp->changed = 0;
629	jp->nprocs = 0;
630	jp->foreground = 0;
631#if JOBS
632	jp->jobctl = jobctl;
633	jp->next = NULL;
634#endif
635	if (nprocs > 1) {
636		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
637	} else {
638		jp->ps = &jp->ps0;
639	}
640	INTON;
641	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
642	    jp - jobtab + 1));
643	return jp;
644}
645
646#if JOBS
647STATIC void
648setcurjob(struct job *cj)
649{
650	struct job *jp, *prev;
651
652	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
653		if (jp == cj) {
654			if (prev != NULL)
655				prev->next = jp->next;
656			else
657				jobmru = jp->next;
658			jp->next = jobmru;
659			jobmru = cj;
660			return;
661		}
662	}
663	cj->next = jobmru;
664	jobmru = cj;
665}
666
667STATIC void
668deljob(struct job *j)
669{
670	struct job *jp, *prev;
671
672	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
673		if (jp == j) {
674			if (prev != NULL)
675				prev->next = jp->next;
676			else
677				jobmru = jp->next;
678			return;
679		}
680	}
681}
682
683/*
684 * Return the most recently used job that isn't `nj', and preferably one
685 * that is stopped.
686 */
687STATIC struct job *
688getcurjob(struct job *nj)
689{
690	struct job *jp;
691
692	/* Try to find a stopped one.. */
693	for (jp = jobmru; jp != NULL; jp = jp->next)
694		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
695			return (jp);
696	/* Otherwise the most recently used job that isn't `nj' */
697	for (jp = jobmru; jp != NULL; jp = jp->next)
698		if (jp->used && jp != nj)
699			return (jp);
700
701	return (NULL);
702}
703
704#endif
705
706/*
707 * Fork of a subshell.  If we are doing job control, give the subshell its
708 * own process group.  Jp is a job structure that the job is to be added to.
709 * N is the command that will be evaluated by the child.  Both jp and n may
710 * be NULL.  The mode parameter can be one of the following:
711 *	FORK_FG - Fork off a foreground process.
712 *	FORK_BG - Fork off a background process.
713 *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
714 *		     process group even if job control is on.
715 *
716 * When job control is turned off, background processes have their standard
717 * input redirected to /dev/null (except for the second and later processes
718 * in a pipeline).
719 */
720
721pid_t
722forkshell(struct job *jp, union node *n, int mode)
723{
724	pid_t pid;
725	pid_t pgrp;
726
727	TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
728	    mode));
729	INTOFF;
730	pid = fork();
731	if (pid == -1) {
732		TRACE(("Fork failed, errno=%d\n", errno));
733		INTON;
734		error("Cannot fork: %s", strerror(errno));
735	}
736	if (pid == 0) {
737		struct job *p;
738		int wasroot;
739		int i;
740
741		TRACE(("Child shell %d\n", (int)getpid()));
742		wasroot = rootshell;
743		rootshell = 0;
744		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
745			if (p->used)
746				freejob(p);
747		closescript();
748		INTON;
749		clear_traps();
750#if JOBS
751		jobctl = 0;		/* do job control only in root shell */
752		if (wasroot && mode != FORK_NOJOB && mflag) {
753			if (jp == NULL || jp->nprocs == 0)
754				pgrp = getpid();
755			else
756				pgrp = jp->ps[0].pid;
757			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
758				/*** this causes superfluous TIOCSPGRPS ***/
759				if (tcsetpgrp(ttyfd, pgrp) < 0)
760					error("tcsetpgrp failed, errno=%d", errno);
761			}
762			setsignal(SIGTSTP);
763			setsignal(SIGTTOU);
764		} else if (mode == FORK_BG) {
765			ignoresig(SIGINT);
766			ignoresig(SIGQUIT);
767			if ((jp == NULL || jp->nprocs == 0) &&
768			    ! fd0_redirected_p ()) {
769				close(0);
770				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
771					error("Can't open %s: %s",
772					    _PATH_DEVNULL, strerror(errno));
773			}
774		}
775#else
776		if (mode == FORK_BG) {
777			ignoresig(SIGINT);
778			ignoresig(SIGQUIT);
779			if ((jp == NULL || jp->nprocs == 0) &&
780			    ! fd0_redirected_p ()) {
781				close(0);
782				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
783					error("Can't open %s: %s",
784					    _PATH_DEVNULL, strerror(errno));
785			}
786		}
787#endif
788		if (wasroot && iflag) {
789			setsignal(SIGINT);
790			setsignal(SIGQUIT);
791			setsignal(SIGTERM);
792		}
793		return pid;
794	}
795	if (rootshell && mode != FORK_NOJOB && mflag) {
796		if (jp == NULL || jp->nprocs == 0)
797			pgrp = pid;
798		else
799			pgrp = jp->ps[0].pid;
800		setpgid(pid, pgrp);
801	}
802	if (mode == FORK_BG)
803		backgndpid = pid;		/* set $! */
804	if (jp) {
805		struct procstat *ps = &jp->ps[jp->nprocs++];
806		ps->pid = pid;
807		ps->status = -1;
808		ps->cmd = nullstr;
809		if (iflag && rootshell && n)
810			ps->cmd = commandtext(n);
811		jp->foreground = mode == FORK_FG;
812#if JOBS
813		setcurjob(jp);
814#endif
815	}
816	INTON;
817	TRACE(("In parent shell:  child = %d\n", (int)pid));
818	return pid;
819}
820
821
822
823/*
824 * Wait for job to finish.
825 *
826 * Under job control we have the problem that while a child process is
827 * running interrupts generated by the user are sent to the child but not
828 * to the shell.  This means that an infinite loop started by an inter-
829 * active user may be hard to kill.  With job control turned off, an
830 * interactive user may place an interactive program inside a loop.  If
831 * the interactive program catches interrupts, the user doesn't want
832 * these interrupts to also abort the loop.  The approach we take here
833 * is to have the shell ignore interrupt signals while waiting for a
834 * foreground process to terminate, and then send itself an interrupt
835 * signal if the child process was terminated by an interrupt signal.
836 * Unfortunately, some programs want to do a bit of cleanup and then
837 * exit on interrupt; unless these processes terminate themselves by
838 * sending a signal to themselves (instead of calling exit) they will
839 * confuse this approach.
840 */
841
842int
843waitforjob(struct job *jp, int *origstatus)
844{
845#if JOBS
846	pid_t mypgrp = getpgrp();
847#endif
848	int status;
849	int st;
850
851	INTOFF;
852	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
853	while (jp->state == 0)
854		if (dowait(1, jp) == -1)
855			dotrap();
856#if JOBS
857	if (jp->jobctl) {
858		if (tcsetpgrp(ttyfd, mypgrp) < 0)
859			error("tcsetpgrp failed, errno=%d\n", errno);
860	}
861	if (jp->state == JOBSTOPPED)
862		setcurjob(jp);
863#endif
864	status = jp->ps[jp->nprocs - 1].status;
865	if (origstatus != NULL)
866		*origstatus = status;
867	/* convert to 8 bits */
868	if (WIFEXITED(status))
869		st = WEXITSTATUS(status);
870#if JOBS
871	else if (WIFSTOPPED(status))
872		st = WSTOPSIG(status) + 128;
873#endif
874	else
875		st = WTERMSIG(status) + 128;
876	if (! JOBS || jp->state == JOBDONE)
877		freejob(jp);
878	if (int_pending()) {
879		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
880			kill(getpid(), SIGINT);
881		else
882			CLEAR_PENDING_INT;
883	}
884	INTON;
885	return st;
886}
887
888
889
890/*
891 * Wait for a process to terminate.
892 */
893
894STATIC pid_t
895dowait(int block, struct job *job)
896{
897	pid_t pid;
898	int status;
899	struct procstat *sp;
900	struct job *jp;
901	struct job *thisjob;
902	int done;
903	int stopped;
904	int sig;
905	int i;
906
907	in_dowait++;
908	TRACE(("dowait(%d) called\n", block));
909	do {
910		pid = waitproc(block, &status);
911		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
912	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
913	    (WIFSTOPPED(status) && !iflag));
914	in_dowait--;
915	if (breakwaitcmd != 0) {
916		breakwaitcmd = 0;
917		return -1;
918	}
919	if (pid <= 0)
920		return pid;
921	INTOFF;
922	thisjob = NULL;
923	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
924		if (jp->used) {
925			done = 1;
926			stopped = 1;
927			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
928				if (sp->pid == -1)
929					continue;
930				if (sp->pid == pid) {
931					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
932						   (int)pid, sp->status,
933						   status));
934					sp->status = status;
935					thisjob = jp;
936				}
937				if (sp->status == -1)
938					stopped = 0;
939				else if (WIFSTOPPED(sp->status))
940					done = 0;
941			}
942			if (stopped) {		/* stopped or done */
943				int state = done? JOBDONE : JOBSTOPPED;
944				if (jp->state != state) {
945					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
946					jp->state = state;
947#if JOBS
948					if (done)
949						deljob(jp);
950#endif
951				}
952			}
953		}
954	}
955	INTON;
956	if (! rootshell || ! iflag || (job && thisjob == job)) {
957#if JOBS
958		if (WIFSTOPPED(status))
959			sig = WSTOPSIG(status);
960		else
961#endif
962		{
963			if (WIFEXITED(status))
964				sig = 0;
965			else
966				sig = WTERMSIG(status);
967		}
968		if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
969			if (thisjob->foreground && !WIFSTOPPED(status)) {
970				i = WTERMSIG(status);
971				if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
972					out1str(sys_siglist[i & 0x7F]);
973				else
974					out1fmt("Signal %d", i & 0x7F);
975				if (WCOREDUMP(status))
976					out1str(" (core dumped)");
977				out1c('\n');
978			} else
979				showjob(thisjob, pid, 0, 1);
980		}
981	} else {
982		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
983		if (thisjob)
984			thisjob->changed = 1;
985	}
986	return pid;
987}
988
989
990
991/*
992 * Do a wait system call.  If job control is compiled in, we accept
993 * stopped processes.  If block is zero, we return a value of zero
994 * rather than blocking.
995 */
996STATIC pid_t
997waitproc(int block, int *status)
998{
999	int flags;
1000
1001#if JOBS
1002	flags = WUNTRACED;
1003#else
1004	flags = 0;
1005#endif
1006	if (block == 0)
1007		flags |= WNOHANG;
1008	return wait3(status, flags, (struct rusage *)NULL);
1009}
1010
1011/*
1012 * return 1 if there are stopped jobs, otherwise 0
1013 */
1014int job_warning = 0;
1015int
1016stoppedjobs(void)
1017{
1018	int jobno;
1019	struct job *jp;
1020
1021	if (job_warning)
1022		return (0);
1023	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1024		if (jp->used == 0)
1025			continue;
1026		if (jp->state == JOBSTOPPED) {
1027			out2str("You have stopped jobs.\n");
1028			job_warning = 2;
1029			return (1);
1030		}
1031	}
1032
1033	return (0);
1034}
1035
1036/*
1037 * Return a string identifying a command (to be printed by the
1038 * jobs command.
1039 */
1040
1041STATIC char *cmdnextc;
1042STATIC int cmdnleft;
1043#define MAXCMDTEXT	200
1044
1045char *
1046commandtext(union node *n)
1047{
1048	char *name;
1049
1050	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1051	cmdnleft = MAXCMDTEXT - 4;
1052	cmdtxt(n);
1053	*cmdnextc = '\0';
1054	return name;
1055}
1056
1057
1058STATIC void
1059cmdtxt(union node *n)
1060{
1061	union node *np;
1062	struct nodelist *lp;
1063	char *p;
1064	int i;
1065	char s[2];
1066
1067	if (n == NULL)
1068		return;
1069	switch (n->type) {
1070	case NSEMI:
1071		cmdtxt(n->nbinary.ch1);
1072		cmdputs("; ");
1073		cmdtxt(n->nbinary.ch2);
1074		break;
1075	case NAND:
1076		cmdtxt(n->nbinary.ch1);
1077		cmdputs(" && ");
1078		cmdtxt(n->nbinary.ch2);
1079		break;
1080	case NOR:
1081		cmdtxt(n->nbinary.ch1);
1082		cmdputs(" || ");
1083		cmdtxt(n->nbinary.ch2);
1084		break;
1085	case NPIPE:
1086		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1087			cmdtxt(lp->n);
1088			if (lp->next)
1089				cmdputs(" | ");
1090		}
1091		break;
1092	case NSUBSHELL:
1093		cmdputs("(");
1094		cmdtxt(n->nredir.n);
1095		cmdputs(")");
1096		break;
1097	case NREDIR:
1098	case NBACKGND:
1099		cmdtxt(n->nredir.n);
1100		break;
1101	case NIF:
1102		cmdputs("if ");
1103		cmdtxt(n->nif.test);
1104		cmdputs("; then ");
1105		cmdtxt(n->nif.ifpart);
1106		cmdputs("...");
1107		break;
1108	case NWHILE:
1109		cmdputs("while ");
1110		goto until;
1111	case NUNTIL:
1112		cmdputs("until ");
1113until:
1114		cmdtxt(n->nbinary.ch1);
1115		cmdputs("; do ");
1116		cmdtxt(n->nbinary.ch2);
1117		cmdputs("; done");
1118		break;
1119	case NFOR:
1120		cmdputs("for ");
1121		cmdputs(n->nfor.var);
1122		cmdputs(" in ...");
1123		break;
1124	case NCASE:
1125		cmdputs("case ");
1126		cmdputs(n->ncase.expr->narg.text);
1127		cmdputs(" in ...");
1128		break;
1129	case NDEFUN:
1130		cmdputs(n->narg.text);
1131		cmdputs("() ...");
1132		break;
1133	case NCMD:
1134		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1135			cmdtxt(np);
1136			if (np->narg.next)
1137				cmdputs(" ");
1138		}
1139		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1140			cmdputs(" ");
1141			cmdtxt(np);
1142		}
1143		break;
1144	case NARG:
1145		cmdputs(n->narg.text);
1146		break;
1147	case NTO:
1148		p = ">";  i = 1;  goto redir;
1149	case NAPPEND:
1150		p = ">>";  i = 1;  goto redir;
1151	case NTOFD:
1152		p = ">&";  i = 1;  goto redir;
1153	case NCLOBBER:
1154		p = ">|"; i = 1; goto redir;
1155	case NFROM:
1156		p = "<";  i = 0;  goto redir;
1157	case NFROMTO:
1158		p = "<>";  i = 0;  goto redir;
1159	case NFROMFD:
1160		p = "<&";  i = 0;  goto redir;
1161redir:
1162		if (n->nfile.fd != i) {
1163			s[0] = n->nfile.fd + '0';
1164			s[1] = '\0';
1165			cmdputs(s);
1166		}
1167		cmdputs(p);
1168		if (n->type == NTOFD || n->type == NFROMFD) {
1169			if (n->ndup.dupfd >= 0)
1170				s[0] = n->ndup.dupfd + '0';
1171			else
1172				s[0] = '-';
1173			s[1] = '\0';
1174			cmdputs(s);
1175		} else {
1176			cmdtxt(n->nfile.fname);
1177		}
1178		break;
1179	case NHERE:
1180	case NXHERE:
1181		cmdputs("<<...");
1182		break;
1183	default:
1184		cmdputs("???");
1185		break;
1186	}
1187}
1188
1189
1190
1191STATIC void
1192cmdputs(char *s)
1193{
1194	char *p, *q;
1195	char c;
1196	int subtype = 0;
1197
1198	if (cmdnleft <= 0)
1199		return;
1200	p = s;
1201	q = cmdnextc;
1202	while ((c = *p++) != '\0') {
1203		if (c == CTLESC)
1204			*q++ = *p++;
1205		else if (c == CTLVAR) {
1206			*q++ = '$';
1207			if (--cmdnleft > 0)
1208				*q++ = '{';
1209			subtype = *p++;
1210		} else if (c == '=' && subtype != 0) {
1211			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1212			subtype = 0;
1213		} else if (c == CTLENDVAR) {
1214			*q++ = '}';
1215		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1216			cmdnleft++;		/* ignore it */
1217		else
1218			*q++ = c;
1219		if (--cmdnleft <= 0) {
1220			*q++ = '.';
1221			*q++ = '.';
1222			*q++ = '.';
1223			break;
1224		}
1225	}
1226	cmdnextc = q;
1227}
1228