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