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