jobs.c revision 97822
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 97822 2002-06-04 15:26:00Z 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 *, pid_t, 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), 0, sformat, lformat);
303
304	return (0);
305}
306
307STATIC void
308showjob(struct job *jp, pid_t pid, 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 && pid == 0)
332			goto skip;
333		if (pid != 0 && pid != ps->pid)
334			goto skip;
335		if (jobno == curr && ps == jp->ps)
336			c = '+';
337		else if (jobno == prev && ps == jp->ps)
338			c = '-';
339		else
340			c = ' ';
341		if (ps == jp->ps)
342			fmtstr(s, 64, "[%d] %c ", jobno, c);
343		else
344			fmtstr(s, 64, "    %c ", c);
345		out1str(s);
346		col = strlen(s);
347		if (lformat) {
348			fmtstr(s, 64, "%d ", ps->pid);
349			out1str(s);
350			col += strlen(s);
351		}
352		s[0] = '\0';
353		if (ps != jp->ps) {
354			*s = '\0';
355		} else if (ps->status == -1) {
356			strcpy(s, "Running");
357		} else if (WIFEXITED(ps->status)) {
358			if (WEXITSTATUS(ps->status) == 0)
359				strcpy(s, "Done");
360			else
361				fmtstr(s, 64, "Done (%d)",
362				    WEXITSTATUS(ps->status));
363		} else {
364#if JOBS
365			if (WIFSTOPPED(ps->status))
366				i = WSTOPSIG(ps->status);
367			else
368#endif
369				i = WTERMSIG(ps->status);
370			if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
371				scopy(sys_siglist[i & 0x7F], s);
372			else
373				fmtstr(s, 64, "Signal %d", i & 0x7F);
374			if (WCOREDUMP(ps->status))
375				strcat(s, " (core dumped)");
376		}
377		out1str(s);
378		col += strlen(s);
379		do {
380			out1c(' ');
381			col++;
382		} while (col < 30);
383		out1str(ps->cmd);
384		out1c('\n');
385skip:		if (--procno <= 0)
386			break;
387	}
388}
389
390/*
391 * Print a list of jobs.  If "change" is nonzero, only print jobs whose
392 * statuses have changed since the last call to showjobs.
393 *
394 * If the shell is interrupted in the process of creating a job, the
395 * result may be a job structure containing zero processes.  Such structures
396 * will be freed here.
397 */
398
399void
400showjobs(int change, int sformat, int lformat)
401{
402	int jobno;
403	struct job *jp;
404
405	TRACE(("showjobs(%d) called\n", change));
406	while (dowait(0, (struct job *)NULL) > 0);
407	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
408		if (! jp->used)
409			continue;
410		if (jp->nprocs == 0) {
411			freejob(jp);
412			continue;
413		}
414		if (change && ! jp->changed)
415			continue;
416		showjob(jp, 0, sformat, lformat);
417		jp->changed = 0;
418		if (jp->state == JOBDONE) {
419			freejob(jp);
420		}
421	}
422}
423
424
425/*
426 * Mark a job structure as unused.
427 */
428
429STATIC void
430freejob(struct job *jp)
431{
432	struct procstat *ps;
433	int i;
434
435	INTOFF;
436	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
437		if (ps->cmd != nullstr)
438			ckfree(ps->cmd);
439	}
440	if (jp->ps != &jp->ps0)
441		ckfree(jp->ps);
442	jp->used = 0;
443#if JOBS
444	deljob(jp);
445#endif
446	INTON;
447}
448
449
450
451int
452waitcmd(int argc, char **argv)
453{
454	struct job *job;
455	int status, retval;
456	struct job *jp;
457
458	if (argc > 1) {
459		job = getjob(argv[1]);
460	} else {
461		job = NULL;
462	}
463
464	/*
465	 * Loop until a process is terminated or stopped, or a SIGINT is
466	 * received.
467	 */
468
469	in_waitcmd++;
470	do {
471		if (job != NULL) {
472			if (job->state) {
473				status = job->ps[job->nprocs - 1].status;
474				if (WIFEXITED(status))
475					retval = WEXITSTATUS(status);
476#if JOBS
477				else if (WIFSTOPPED(status))
478					retval = WSTOPSIG(status) + 128;
479#endif
480				else
481					retval = WTERMSIG(status) + 128;
482				if (! iflag)
483					freejob(job);
484				in_waitcmd--;
485				return retval;
486			}
487		} else {
488			for (jp = jobtab ; ; jp++) {
489				if (jp >= jobtab + njobs) {	/* no running procs */
490					in_waitcmd--;
491					return 0;
492				}
493				if (jp->used && jp->state == 0)
494					break;
495			}
496		}
497	} while (dowait(1, (struct job *)NULL) != -1);
498	in_waitcmd--;
499
500	return 0;
501}
502
503
504
505int
506jobidcmd(int argc __unused, char **argv)
507{
508	struct job *jp;
509	int i;
510
511	jp = getjob(argv[1]);
512	for (i = 0 ; i < jp->nprocs ; ) {
513		out1fmt("%d", jp->ps[i].pid);
514		out1c(++i < jp->nprocs? ' ' : '\n');
515	}
516	return 0;
517}
518
519
520
521/*
522 * Convert a job name to a job structure.
523 */
524
525STATIC struct job *
526getjob(char *name)
527{
528	int jobno;
529	struct job *found, *jp;
530	int pid;
531	int i;
532
533	if (name == NULL) {
534#if JOBS
535currentjob:	if ((jp = getcurjob(NULL)) == NULL)
536			error("No current job");
537		return (jp);
538#else
539		error("No current job");
540#endif
541	} else if (name[0] == '%') {
542		if (is_digit(name[1])) {
543			jobno = number(name + 1);
544			if (jobno > 0 && jobno <= njobs
545			 && jobtab[jobno - 1].used != 0)
546				return &jobtab[jobno - 1];
547#if JOBS
548		} else if (name[1] == '%' && name[2] == '\0') {
549			goto currentjob;
550		} else if (name[1] == '+' && name[2] == '\0') {
551			goto currentjob;
552		} else if (name[1] == '-' && name[2] == '\0') {
553			if ((jp = getcurjob(NULL)) == NULL ||
554			    (jp = getcurjob(jp)) == NULL)
555				error("No previous job");
556			return (jp);
557#endif
558		} else if (name[1] == '?') {
559			found = NULL;
560			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
561				if (jp->used && jp->nprocs > 0
562				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
563					if (found)
564						error("%s: ambiguous", name);
565					found = jp;
566				}
567			}
568			if (found != NULL)
569				return (found);
570		} else {
571			found = NULL;
572			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
573				if (jp->used && jp->nprocs > 0
574				 && prefix(name + 1, jp->ps[0].cmd)) {
575					if (found)
576						error("%s: ambiguous", name);
577					found = jp;
578				}
579			}
580			if (found)
581				return found;
582		}
583	} else if (is_number(name)) {
584		pid = number(name);
585		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
586			if (jp->used && jp->nprocs > 0
587			 && jp->ps[jp->nprocs - 1].pid == pid)
588				return jp;
589		}
590	}
591	error("No such job: %s", name);
592	/*NOTREACHED*/
593	return NULL;
594}
595
596
597
598/*
599 * Return a new job structure,
600 */
601
602struct job *
603makejob(union node *node __unused, int nprocs)
604{
605	int i;
606	struct job *jp;
607
608	for (i = njobs, jp = jobtab ; ; jp++) {
609		if (--i < 0) {
610			INTOFF;
611			if (njobs == 0) {
612				jobtab = ckmalloc(4 * sizeof jobtab[0]);
613#if JOBS
614				jobmru = NULL;
615#endif
616			} else {
617				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
618				memcpy(jp, jobtab, njobs * sizeof jp[0]);
619#if JOBS
620				/* Relocate `next' pointers and list head */
621				jobmru = &jp[jobmru - jobtab];
622				for (i = 0; i < njobs; i++)
623					if (jp[i].next != NULL)
624						jp[i].next = &jp[jp[i].next -
625						    jobtab];
626#endif
627				/* Relocate `ps' pointers */
628				for (i = 0; i < njobs; i++)
629					if (jp[i].ps == &jobtab[i].ps0)
630						jp[i].ps = &jp[i].ps0;
631				ckfree(jobtab);
632				jobtab = jp;
633			}
634			jp = jobtab + njobs;
635			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
636			INTON;
637			break;
638		}
639		if (jp->used == 0)
640			break;
641	}
642	INTOFF;
643	jp->state = 0;
644	jp->used = 1;
645	jp->changed = 0;
646	jp->nprocs = 0;
647#if JOBS
648	jp->jobctl = jobctl;
649	jp->next = NULL;
650#endif
651	if (nprocs > 1) {
652		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
653	} else {
654		jp->ps = &jp->ps0;
655	}
656	INTON;
657	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
658	    jp - jobtab + 1));
659	return jp;
660}
661
662#if JOBS
663STATIC void
664setcurjob(struct job *cj)
665{
666	struct job *jp, *prev;
667
668	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
669		if (jp == cj) {
670			if (prev != NULL)
671				prev->next = jp->next;
672			else
673				jobmru = jp->next;
674			jp->next = jobmru;
675			jobmru = cj;
676			return;
677		}
678	}
679	cj->next = jobmru;
680	jobmru = cj;
681}
682
683STATIC void
684deljob(struct job *j)
685{
686	struct job *jp, *prev;
687
688	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
689		if (jp == j) {
690			if (prev != NULL)
691				prev->next = jp->next;
692			else
693				jobmru = jp->next;
694			return;
695		}
696	}
697}
698
699/*
700 * Return the most recently used job that isn't `nj', and preferably one
701 * that is stopped.
702 */
703STATIC struct job *
704getcurjob(struct job *nj)
705{
706	struct job *jp;
707
708	/* Try to find a stopped one.. */
709	for (jp = jobmru; jp != NULL; jp = jp->next)
710		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
711			return (jp);
712	/* Otherwise the most recently used job that isn't `nj' */
713	for (jp = jobmru; jp != NULL; jp = jp->next)
714		if (jp->used && jp != nj)
715			return (jp);
716
717	return (NULL);
718}
719
720#endif
721
722/*
723 * Fork of a subshell.  If we are doing job control, give the subshell its
724 * own process group.  Jp is a job structure that the job is to be added to.
725 * N is the command that will be evaluated by the child.  Both jp and n may
726 * be NULL.  The mode parameter can be one of the following:
727 *	FORK_FG - Fork off a foreground process.
728 *	FORK_BG - Fork off a background process.
729 *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
730 *		     process group even if job control is on.
731 *
732 * When job control is turned off, background processes have their standard
733 * input redirected to /dev/null (except for the second and later processes
734 * in a pipeline).
735 */
736
737int
738forkshell(struct job *jp, union node *n, int mode)
739{
740	int pid;
741	int pgrp;
742
743	TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
744	    mode));
745	INTOFF;
746	pid = fork();
747	if (pid == -1) {
748		TRACE(("Fork failed, errno=%d\n", errno));
749		INTON;
750		error("Cannot fork: %s", strerror(errno));
751	}
752	if (pid == 0) {
753		struct job *p;
754		int wasroot;
755		int i;
756
757		TRACE(("Child shell %d\n", getpid()));
758		wasroot = rootshell;
759		rootshell = 0;
760		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
761			if (p->used)
762				freejob(p);
763		closescript();
764		INTON;
765		clear_traps();
766#if JOBS
767		jobctl = 0;		/* do job control only in root shell */
768		if (wasroot && mode != FORK_NOJOB && mflag) {
769			if (jp == NULL || jp->nprocs == 0)
770				pgrp = getpid();
771			else
772				pgrp = jp->ps[0].pid;
773			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
774				/*** this causes superfluous TIOCSPGRPS ***/
775#ifdef OLD_TTY_DRIVER
776				if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
777					error("TIOCSPGRP failed, errno=%d", errno);
778#else
779				if (tcsetpgrp(2, pgrp) < 0)
780					error("tcsetpgrp failed, errno=%d", errno);
781#endif
782			}
783			setsignal(SIGTSTP);
784			setsignal(SIGTTOU);
785		} else if (mode == FORK_BG) {
786			ignoresig(SIGINT);
787			ignoresig(SIGQUIT);
788			if ((jp == NULL || jp->nprocs == 0) &&
789			    ! fd0_redirected_p ()) {
790				close(0);
791				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
792					error("Can't open %s: %s",
793					    _PATH_DEVNULL, strerror(errno));
794			}
795		}
796#else
797		if (mode == FORK_BG) {
798			ignoresig(SIGINT);
799			ignoresig(SIGQUIT);
800			if ((jp == NULL || jp->nprocs == 0) &&
801			    ! fd0_redirected_p ()) {
802				close(0);
803				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
804					error("Can't open %s: %s",
805					    _PATH_DEVNULL, strerror(errno));
806			}
807		}
808#endif
809		if (wasroot && iflag) {
810			setsignal(SIGINT);
811			setsignal(SIGQUIT);
812			setsignal(SIGTERM);
813		}
814		return pid;
815	}
816	if (rootshell && mode != FORK_NOJOB && mflag) {
817		if (jp == NULL || jp->nprocs == 0)
818			pgrp = pid;
819		else
820			pgrp = jp->ps[0].pid;
821		setpgid(pid, pgrp);
822	}
823	if (mode == FORK_BG)
824		backgndpid = pid;		/* set $! */
825	if (jp) {
826		struct procstat *ps = &jp->ps[jp->nprocs++];
827		ps->pid = pid;
828		ps->status = -1;
829		ps->cmd = nullstr;
830		if (iflag && rootshell && n)
831			ps->cmd = commandtext(n);
832#if JOBS
833		setcurjob(jp);
834#endif
835	}
836	INTON;
837	TRACE(("In parent shell:  child = %d\n", pid));
838	return pid;
839}
840
841
842
843/*
844 * Wait for job to finish.
845 *
846 * Under job control we have the problem that while a child process is
847 * running interrupts generated by the user are sent to the child but not
848 * to the shell.  This means that an infinite loop started by an inter-
849 * active user may be hard to kill.  With job control turned off, an
850 * interactive user may place an interactive program inside a loop.  If
851 * the interactive program catches interrupts, the user doesn't want
852 * these interrupts to also abort the loop.  The approach we take here
853 * is to have the shell ignore interrupt signals while waiting for a
854 * foreground process to terminate, and then send itself an interrupt
855 * signal if the child process was terminated by an interrupt signal.
856 * Unfortunately, some programs want to do a bit of cleanup and then
857 * exit on interrupt; unless these processes terminate themselves by
858 * sending a signal to themselves (instead of calling exit) they will
859 * confuse this approach.
860 */
861
862int
863waitforjob(struct job *jp, int *origstatus)
864{
865#if JOBS
866	int mypgrp = getpgrp();
867#endif
868	int status;
869	int st;
870
871	INTOFF;
872	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
873	while (jp->state == 0)
874		if (dowait(1, jp) == -1)
875			dotrap();
876#if JOBS
877	if (jp->jobctl) {
878#ifdef OLD_TTY_DRIVER
879		if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
880			error("TIOCSPGRP failed, errno=%d\n", errno);
881#else
882		if (tcsetpgrp(2, mypgrp) < 0)
883			error("tcsetpgrp failed, errno=%d\n", errno);
884#endif
885	}
886	if (jp->state == JOBSTOPPED)
887		setcurjob(jp);
888#endif
889	status = jp->ps[jp->nprocs - 1].status;
890	if (origstatus != NULL)
891		*origstatus = status;
892	/* convert to 8 bits */
893	if (WIFEXITED(status))
894		st = WEXITSTATUS(status);
895#if JOBS
896	else if (WIFSTOPPED(status))
897		st = WSTOPSIG(status) + 128;
898#endif
899	else
900		st = WTERMSIG(status) + 128;
901	if (! JOBS || jp->state == JOBDONE)
902		freejob(jp);
903	if (int_pending()) {
904		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
905			kill(getpid(), SIGINT);
906		else
907			CLEAR_PENDING_INT;
908	}
909	INTON;
910	return st;
911}
912
913
914
915/*
916 * Wait for a process to terminate.
917 */
918
919STATIC int
920dowait(int block, struct job *job)
921{
922	int pid;
923	int status;
924	struct procstat *sp;
925	struct job *jp;
926	struct job *thisjob;
927	int done;
928	int stopped;
929	int core;
930	int sig;
931
932	in_dowait++;
933	TRACE(("dowait(%d) called\n", block));
934	do {
935		pid = waitproc(block, &status);
936		TRACE(("wait returns %d, status=%d\n", pid, status));
937	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
938	    (WIFSTOPPED(status) && !iflag));
939	in_dowait--;
940	if (breakwaitcmd != 0) {
941		breakwaitcmd = 0;
942		return -1;
943	}
944	if (pid <= 0)
945		return pid;
946	INTOFF;
947	thisjob = NULL;
948	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
949		if (jp->used) {
950			done = 1;
951			stopped = 1;
952			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
953				if (sp->pid == -1)
954					continue;
955				if (sp->pid == pid) {
956					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
957						   pid, sp->status, status));
958					sp->status = status;
959					thisjob = jp;
960				}
961				if (sp->status == -1)
962					stopped = 0;
963				else if (WIFSTOPPED(sp->status))
964					done = 0;
965			}
966			if (stopped) {		/* stopped or done */
967				int state = done? JOBDONE : JOBSTOPPED;
968				if (jp->state != state) {
969					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
970					jp->state = state;
971#if JOBS
972					if (done)
973						deljob(jp);
974#endif
975				}
976			}
977		}
978	}
979	INTON;
980	if (! rootshell || ! iflag || (job && thisjob == job)) {
981#if JOBS
982		if (WIFSTOPPED(status))
983			sig = WSTOPSIG(status);
984		else
985#endif
986		{
987			if (WIFEXITED(status))
988				sig = 0;
989			else
990				sig = WTERMSIG(status);
991		}
992		if (sig != 0 && sig != SIGINT && sig != SIGPIPE)
993			showjob(thisjob, pid, 0, 1);
994	} else {
995		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
996		if (thisjob)
997			thisjob->changed = 1;
998	}
999	return pid;
1000}
1001
1002
1003
1004/*
1005 * Do a wait system call.  If job control is compiled in, we accept
1006 * stopped processes.  If block is zero, we return a value of zero
1007 * rather than blocking.
1008 *
1009 * System V doesn't have a non-blocking wait system call.  It does
1010 * have a SIGCLD signal that is sent to a process when one of it's
1011 * children dies.  The obvious way to use SIGCLD would be to install
1012 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
1013 * was received, and have waitproc bump another counter when it got
1014 * the status of a process.  Waitproc would then know that a wait
1015 * system call would not block if the two counters were different.
1016 * This approach doesn't work because if a process has children that
1017 * have not been waited for, System V will send it a SIGCLD when it
1018 * installs a signal handler for SIGCLD.  What this means is that when
1019 * a child exits, the shell will be sent SIGCLD signals continuously
1020 * until is runs out of stack space, unless it does a wait call before
1021 * restoring the signal handler.  The code below takes advantage of
1022 * this (mis)feature by installing a signal handler for SIGCLD and
1023 * then checking to see whether it was called.  If there are any
1024 * children to be waited for, it will be.
1025 *
1026 * If neither SYSV nor BSD is defined, we don't implement nonblocking
1027 * waits at all.  In this case, the user will not be informed when
1028 * a background process until the next time she runs a real program
1029 * (as opposed to running a builtin command or just typing return),
1030 * and the jobs command may give out of date information.
1031 */
1032
1033#ifdef SYSV
1034STATIC sig_atomic_t gotsigchild;
1035
1036STATIC int onsigchild() {
1037	gotsigchild = 1;
1038}
1039#endif
1040
1041
1042STATIC int
1043waitproc(int block, int *status)
1044{
1045#ifdef BSD
1046	int flags;
1047
1048#if JOBS
1049	flags = WUNTRACED;
1050#else
1051	flags = 0;
1052#endif
1053	if (block == 0)
1054		flags |= WNOHANG;
1055	return wait3(status, flags, (struct rusage *)NULL);
1056#else
1057#ifdef SYSV
1058	int (*save)();
1059
1060	if (block == 0) {
1061		gotsigchild = 0;
1062		save = signal(SIGCLD, onsigchild);
1063		signal(SIGCLD, save);
1064		if (gotsigchild == 0)
1065			return 0;
1066	}
1067	return wait(status);
1068#else
1069	if (block == 0)
1070		return 0;
1071	return wait(status);
1072#endif
1073#endif
1074}
1075
1076/*
1077 * return 1 if there are stopped jobs, otherwise 0
1078 */
1079int job_warning = 0;
1080int
1081stoppedjobs(void)
1082{
1083	int jobno;
1084	struct job *jp;
1085
1086	if (job_warning)
1087		return (0);
1088	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1089		if (jp->used == 0)
1090			continue;
1091		if (jp->state == JOBSTOPPED) {
1092			out2str("You have stopped jobs.\n");
1093			job_warning = 2;
1094			return (1);
1095		}
1096	}
1097
1098	return (0);
1099}
1100
1101/*
1102 * Return a string identifying a command (to be printed by the
1103 * jobs command.
1104 */
1105
1106STATIC char *cmdnextc;
1107STATIC int cmdnleft;
1108#define MAXCMDTEXT	200
1109
1110char *
1111commandtext(union node *n)
1112{
1113	char *name;
1114
1115	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1116	cmdnleft = MAXCMDTEXT - 4;
1117	cmdtxt(n);
1118	*cmdnextc = '\0';
1119	return name;
1120}
1121
1122
1123STATIC void
1124cmdtxt(union node *n)
1125{
1126	union node *np;
1127	struct nodelist *lp;
1128	char *p;
1129	int i;
1130	char s[2];
1131
1132	if (n == NULL)
1133		return;
1134	switch (n->type) {
1135	case NSEMI:
1136		cmdtxt(n->nbinary.ch1);
1137		cmdputs("; ");
1138		cmdtxt(n->nbinary.ch2);
1139		break;
1140	case NAND:
1141		cmdtxt(n->nbinary.ch1);
1142		cmdputs(" && ");
1143		cmdtxt(n->nbinary.ch2);
1144		break;
1145	case NOR:
1146		cmdtxt(n->nbinary.ch1);
1147		cmdputs(" || ");
1148		cmdtxt(n->nbinary.ch2);
1149		break;
1150	case NPIPE:
1151		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1152			cmdtxt(lp->n);
1153			if (lp->next)
1154				cmdputs(" | ");
1155		}
1156		break;
1157	case NSUBSHELL:
1158		cmdputs("(");
1159		cmdtxt(n->nredir.n);
1160		cmdputs(")");
1161		break;
1162	case NREDIR:
1163	case NBACKGND:
1164		cmdtxt(n->nredir.n);
1165		break;
1166	case NIF:
1167		cmdputs("if ");
1168		cmdtxt(n->nif.test);
1169		cmdputs("; then ");
1170		cmdtxt(n->nif.ifpart);
1171		cmdputs("...");
1172		break;
1173	case NWHILE:
1174		cmdputs("while ");
1175		goto until;
1176	case NUNTIL:
1177		cmdputs("until ");
1178until:
1179		cmdtxt(n->nbinary.ch1);
1180		cmdputs("; do ");
1181		cmdtxt(n->nbinary.ch2);
1182		cmdputs("; done");
1183		break;
1184	case NFOR:
1185		cmdputs("for ");
1186		cmdputs(n->nfor.var);
1187		cmdputs(" in ...");
1188		break;
1189	case NCASE:
1190		cmdputs("case ");
1191		cmdputs(n->ncase.expr->narg.text);
1192		cmdputs(" in ...");
1193		break;
1194	case NDEFUN:
1195		cmdputs(n->narg.text);
1196		cmdputs("() ...");
1197		break;
1198	case NCMD:
1199		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1200			cmdtxt(np);
1201			if (np->narg.next)
1202				cmdputs(" ");
1203		}
1204		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1205			cmdputs(" ");
1206			cmdtxt(np);
1207		}
1208		break;
1209	case NARG:
1210		cmdputs(n->narg.text);
1211		break;
1212	case NTO:
1213		p = ">";  i = 1;  goto redir;
1214	case NAPPEND:
1215		p = ">>";  i = 1;  goto redir;
1216	case NTOFD:
1217		p = ">&";  i = 1;  goto redir;
1218	case NCLOBBER:
1219		p = ">|"; i = 1; goto redir;
1220	case NFROM:
1221		p = "<";  i = 0;  goto redir;
1222	case NFROMTO:
1223		p = "<>";  i = 0;  goto redir;
1224	case NFROMFD:
1225		p = "<&";  i = 0;  goto redir;
1226redir:
1227		if (n->nfile.fd != i) {
1228			s[0] = n->nfile.fd + '0';
1229			s[1] = '\0';
1230			cmdputs(s);
1231		}
1232		cmdputs(p);
1233		if (n->type == NTOFD || n->type == NFROMFD) {
1234			s[0] = n->ndup.dupfd + '0';
1235			s[1] = '\0';
1236			cmdputs(s);
1237		} else {
1238			cmdtxt(n->nfile.fname);
1239		}
1240		break;
1241	case NHERE:
1242	case NXHERE:
1243		cmdputs("<<...");
1244		break;
1245	default:
1246		cmdputs("???");
1247		break;
1248	}
1249}
1250
1251
1252
1253STATIC void
1254cmdputs(char *s)
1255{
1256	char *p, *q;
1257	char c;
1258	int subtype = 0;
1259
1260	if (cmdnleft <= 0)
1261		return;
1262	p = s;
1263	q = cmdnextc;
1264	while ((c = *p++) != '\0') {
1265		if (c == CTLESC)
1266			*q++ = *p++;
1267		else if (c == CTLVAR) {
1268			*q++ = '$';
1269			if (--cmdnleft > 0)
1270				*q++ = '{';
1271			subtype = *p++;
1272		} else if (c == '=' && subtype != 0) {
1273			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1274			subtype = 0;
1275		} else if (c == CTLENDVAR) {
1276			*q++ = '}';
1277		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1278			cmdnleft++;		/* ignore it */
1279		else
1280			*q++ = c;
1281		if (--cmdnleft <= 0) {
1282			*q++ = '.';
1283			*q++ = '.';
1284			*q++ = '.';
1285			break;
1286		}
1287	}
1288	cmdnextc = q;
1289}
1290