jobs.c revision 97663
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 97663 2002-05-31 13:07:05Z 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				jobmru = NULL;
533			} else {
534				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
535				memcpy(jp, jobtab, njobs * sizeof jp[0]);
536#if JOBS
537				/* Relocate `next' pointers and list head */
538				jobmru = &jp[jobmru - jobtab];
539				for (i = 0; i < njobs; i++)
540					if (jp[i].next != NULL)
541						jp[i].next = &jp[jp[i].next -
542						    jobtab];
543#endif
544				/* Relocate `ps' pointers */
545				for (i = 0; i < njobs; i++)
546					if (jp[i].ps == &jobtab[i].ps0)
547						jp[i].ps = &jp[i].ps0;
548				ckfree(jobtab);
549				jobtab = jp;
550			}
551			jp = jobtab + njobs;
552			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
553			INTON;
554			break;
555		}
556		if (jp->used == 0)
557			break;
558	}
559	INTOFF;
560	jp->state = 0;
561	jp->used = 1;
562	jp->changed = 0;
563	jp->nprocs = 0;
564#if JOBS
565	jp->jobctl = jobctl;
566	jp->next = NULL;
567#endif
568	if (nprocs > 1) {
569		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
570	} else {
571		jp->ps = &jp->ps0;
572	}
573	INTON;
574	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
575	    jp - jobtab + 1));
576	return jp;
577}
578
579#if JOBS
580STATIC void
581setcurjob(struct job *cj)
582{
583	struct job *jp, *prev;
584
585	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
586		if (jp == cj) {
587			if (prev != NULL)
588				prev->next = jp->next;
589			else
590				jobmru = jp->next;
591			jp->next = jobmru;
592			jobmru = cj;
593			return;
594		}
595	}
596	cj->next = jobmru;
597	jobmru = cj;
598}
599
600STATIC void
601deljob(struct job *j)
602{
603	struct job *jp, *prev;
604
605	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
606		if (jp == j) {
607			if (prev != NULL)
608				prev->next = jp->next;
609			else
610				jobmru = jp->next;
611			return;
612		}
613	}
614}
615
616/*
617 * Return the most recently used job that isn't `nj', and preferably one
618 * that is stopped.
619 */
620STATIC struct job *
621getcurjob(struct job *nj)
622{
623	struct job *jp;
624
625	/* Try to find a stopped one.. */
626	for (jp = jobmru; jp != NULL; jp = jp->next)
627		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
628			return (jp);
629	/* Otherwise the most recently used job that isn't `nj' */
630	for (jp = jobmru; jp != NULL; jp = jp->next)
631		if (jp->used && jp != nj)
632			return (jp);
633
634	return (NULL);
635}
636
637#endif
638
639/*
640 * Fork of a subshell.  If we are doing job control, give the subshell its
641 * own process group.  Jp is a job structure that the job is to be added to.
642 * N is the command that will be evaluated by the child.  Both jp and n may
643 * be NULL.  The mode parameter can be one of the following:
644 *	FORK_FG - Fork off a foreground process.
645 *	FORK_BG - Fork off a background process.
646 *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
647 *		     process group even if job control is on.
648 *
649 * When job control is turned off, background processes have their standard
650 * input redirected to /dev/null (except for the second and later processes
651 * in a pipeline).
652 */
653
654int
655forkshell(struct job *jp, union node *n, int mode)
656{
657	int pid;
658	int pgrp;
659
660	TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
661	    mode));
662	INTOFF;
663	pid = fork();
664	if (pid == -1) {
665		TRACE(("Fork failed, errno=%d\n", errno));
666		INTON;
667		error("Cannot fork: %s", strerror(errno));
668	}
669	if (pid == 0) {
670		struct job *p;
671		int wasroot;
672		int i;
673
674		TRACE(("Child shell %d\n", getpid()));
675		wasroot = rootshell;
676		rootshell = 0;
677		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
678			if (p->used)
679				freejob(p);
680		closescript();
681		INTON;
682		clear_traps();
683#if JOBS
684		jobctl = 0;		/* do job control only in root shell */
685		if (wasroot && mode != FORK_NOJOB && mflag) {
686			if (jp == NULL || jp->nprocs == 0)
687				pgrp = getpid();
688			else
689				pgrp = jp->ps[0].pid;
690			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
691				/*** this causes superfluous TIOCSPGRPS ***/
692#ifdef OLD_TTY_DRIVER
693				if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
694					error("TIOCSPGRP failed, errno=%d", errno);
695#else
696				if (tcsetpgrp(2, pgrp) < 0)
697					error("tcsetpgrp failed, errno=%d", errno);
698#endif
699			}
700			setsignal(SIGTSTP);
701			setsignal(SIGTTOU);
702		} else if (mode == FORK_BG) {
703			ignoresig(SIGINT);
704			ignoresig(SIGQUIT);
705			if ((jp == NULL || jp->nprocs == 0) &&
706			    ! fd0_redirected_p ()) {
707				close(0);
708				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
709					error("Can't open %s: %s",
710					    _PATH_DEVNULL, strerror(errno));
711			}
712		}
713#else
714		if (mode == FORK_BG) {
715			ignoresig(SIGINT);
716			ignoresig(SIGQUIT);
717			if ((jp == NULL || jp->nprocs == 0) &&
718			    ! fd0_redirected_p ()) {
719				close(0);
720				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
721					error("Can't open %s: %s",
722					    _PATH_DEVNULL, strerror(errno));
723			}
724		}
725#endif
726		if (wasroot && iflag) {
727			setsignal(SIGINT);
728			setsignal(SIGQUIT);
729			setsignal(SIGTERM);
730		}
731		return pid;
732	}
733	if (rootshell && mode != FORK_NOJOB && mflag) {
734		if (jp == NULL || jp->nprocs == 0)
735			pgrp = pid;
736		else
737			pgrp = jp->ps[0].pid;
738		setpgid(pid, pgrp);
739	}
740	if (mode == FORK_BG)
741		backgndpid = pid;		/* set $! */
742	if (jp) {
743		struct procstat *ps = &jp->ps[jp->nprocs++];
744		ps->pid = pid;
745		ps->status = -1;
746		ps->cmd = nullstr;
747		if (iflag && rootshell && n)
748			ps->cmd = commandtext(n);
749#if JOBS
750		setcurjob(jp);
751#endif
752	}
753	INTON;
754	TRACE(("In parent shell:  child = %d\n", pid));
755	return pid;
756}
757
758
759
760/*
761 * Wait for job to finish.
762 *
763 * Under job control we have the problem that while a child process is
764 * running interrupts generated by the user are sent to the child but not
765 * to the shell.  This means that an infinite loop started by an inter-
766 * active user may be hard to kill.  With job control turned off, an
767 * interactive user may place an interactive program inside a loop.  If
768 * the interactive program catches interrupts, the user doesn't want
769 * these interrupts to also abort the loop.  The approach we take here
770 * is to have the shell ignore interrupt signals while waiting for a
771 * foreground process to terminate, and then send itself an interrupt
772 * signal if the child process was terminated by an interrupt signal.
773 * Unfortunately, some programs want to do a bit of cleanup and then
774 * exit on interrupt; unless these processes terminate themselves by
775 * sending a signal to themselves (instead of calling exit) they will
776 * confuse this approach.
777 */
778
779int
780waitforjob(struct job *jp, int *origstatus)
781{
782#if JOBS
783	int mypgrp = getpgrp();
784#endif
785	int status;
786	int st;
787
788	INTOFF;
789	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
790	while (jp->state == 0)
791		if (dowait(1, jp) == -1)
792			dotrap();
793#if JOBS
794	if (jp->jobctl) {
795#ifdef OLD_TTY_DRIVER
796		if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
797			error("TIOCSPGRP failed, errno=%d\n", errno);
798#else
799		if (tcsetpgrp(2, mypgrp) < 0)
800			error("tcsetpgrp failed, errno=%d\n", errno);
801#endif
802	}
803	if (jp->state == JOBSTOPPED)
804		setcurjob(jp);
805#endif
806	status = jp->ps[jp->nprocs - 1].status;
807	if (origstatus != NULL)
808		*origstatus = status;
809	/* convert to 8 bits */
810	if (WIFEXITED(status))
811		st = WEXITSTATUS(status);
812#if JOBS
813	else if (WIFSTOPPED(status))
814		st = WSTOPSIG(status) + 128;
815#endif
816	else
817		st = WTERMSIG(status) + 128;
818	if (! JOBS || jp->state == JOBDONE)
819		freejob(jp);
820	if (int_pending()) {
821		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
822			kill(getpid(), SIGINT);
823		else
824			CLEAR_PENDING_INT;
825	}
826	INTON;
827	return st;
828}
829
830
831
832/*
833 * Wait for a process to terminate.
834 */
835
836STATIC int
837dowait(int block, struct job *job)
838{
839	int pid;
840	int status;
841	struct procstat *sp;
842	struct job *jp;
843	struct job *thisjob;
844	int done;
845	int stopped;
846	int core;
847	int sig;
848
849	in_dowait++;
850	TRACE(("dowait(%d) called\n", block));
851	do {
852		pid = waitproc(block, &status);
853		TRACE(("wait returns %d, status=%d\n", pid, status));
854	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
855	    (WIFSTOPPED(status) && !iflag));
856	in_dowait--;
857	if (breakwaitcmd != 0) {
858		breakwaitcmd = 0;
859		return -1;
860	}
861	if (pid <= 0)
862		return pid;
863	INTOFF;
864	thisjob = NULL;
865	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
866		if (jp->used) {
867			done = 1;
868			stopped = 1;
869			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
870				if (sp->pid == -1)
871					continue;
872				if (sp->pid == pid) {
873					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
874						   pid, sp->status, status));
875					sp->status = status;
876					thisjob = jp;
877				}
878				if (sp->status == -1)
879					stopped = 0;
880				else if (WIFSTOPPED(sp->status))
881					done = 0;
882			}
883			if (stopped) {		/* stopped or done */
884				int state = done? JOBDONE : JOBSTOPPED;
885				if (jp->state != state) {
886					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
887					jp->state = state;
888#if JOBS
889					if (done)
890						deljob(jp);
891#endif
892				}
893			}
894		}
895	}
896	INTON;
897	if (! rootshell || ! iflag || (job && thisjob == job)) {
898#if JOBS
899		if (WIFSTOPPED(status))
900			sig = WSTOPSIG(status);
901		else
902#endif
903		{
904			if (WIFEXITED(status))
905				sig = 0;
906			else
907				sig = WTERMSIG(status);
908		}
909		if (sig != 0 && sig != SIGINT && sig != SIGPIPE)
910			showjob(thisjob);
911	} else {
912		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
913		if (thisjob)
914			thisjob->changed = 1;
915	}
916	return pid;
917}
918
919
920
921/*
922 * Do a wait system call.  If job control is compiled in, we accept
923 * stopped processes.  If block is zero, we return a value of zero
924 * rather than blocking.
925 *
926 * System V doesn't have a non-blocking wait system call.  It does
927 * have a SIGCLD signal that is sent to a process when one of it's
928 * children dies.  The obvious way to use SIGCLD would be to install
929 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
930 * was received, and have waitproc bump another counter when it got
931 * the status of a process.  Waitproc would then know that a wait
932 * system call would not block if the two counters were different.
933 * This approach doesn't work because if a process has children that
934 * have not been waited for, System V will send it a SIGCLD when it
935 * installs a signal handler for SIGCLD.  What this means is that when
936 * a child exits, the shell will be sent SIGCLD signals continuously
937 * until is runs out of stack space, unless it does a wait call before
938 * restoring the signal handler.  The code below takes advantage of
939 * this (mis)feature by installing a signal handler for SIGCLD and
940 * then checking to see whether it was called.  If there are any
941 * children to be waited for, it will be.
942 *
943 * If neither SYSV nor BSD is defined, we don't implement nonblocking
944 * waits at all.  In this case, the user will not be informed when
945 * a background process until the next time she runs a real program
946 * (as opposed to running a builtin command or just typing return),
947 * and the jobs command may give out of date information.
948 */
949
950#ifdef SYSV
951STATIC sig_atomic_t gotsigchild;
952
953STATIC int onsigchild() {
954	gotsigchild = 1;
955}
956#endif
957
958
959STATIC int
960waitproc(int block, int *status)
961{
962#ifdef BSD
963	int flags;
964
965#if JOBS
966	flags = WUNTRACED;
967#else
968	flags = 0;
969#endif
970	if (block == 0)
971		flags |= WNOHANG;
972	return wait3(status, flags, (struct rusage *)NULL);
973#else
974#ifdef SYSV
975	int (*save)();
976
977	if (block == 0) {
978		gotsigchild = 0;
979		save = signal(SIGCLD, onsigchild);
980		signal(SIGCLD, save);
981		if (gotsigchild == 0)
982			return 0;
983	}
984	return wait(status);
985#else
986	if (block == 0)
987		return 0;
988	return wait(status);
989#endif
990#endif
991}
992
993/*
994 * return 1 if there are stopped jobs, otherwise 0
995 */
996int job_warning = 0;
997int
998stoppedjobs(void)
999{
1000	int jobno;
1001	struct job *jp;
1002
1003	if (job_warning)
1004		return (0);
1005	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1006		if (jp->used == 0)
1007			continue;
1008		if (jp->state == JOBSTOPPED) {
1009			out2str("You have stopped jobs.\n");
1010			job_warning = 2;
1011			return (1);
1012		}
1013	}
1014
1015	return (0);
1016}
1017
1018/*
1019 * Return a string identifying a command (to be printed by the
1020 * jobs command.
1021 */
1022
1023STATIC char *cmdnextc;
1024STATIC int cmdnleft;
1025#define MAXCMDTEXT	200
1026
1027char *
1028commandtext(union node *n)
1029{
1030	char *name;
1031
1032	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1033	cmdnleft = MAXCMDTEXT - 4;
1034	cmdtxt(n);
1035	*cmdnextc = '\0';
1036	return name;
1037}
1038
1039
1040STATIC void
1041cmdtxt(union node *n)
1042{
1043	union node *np;
1044	struct nodelist *lp;
1045	char *p;
1046	int i;
1047	char s[2];
1048
1049	if (n == NULL)
1050		return;
1051	switch (n->type) {
1052	case NSEMI:
1053		cmdtxt(n->nbinary.ch1);
1054		cmdputs("; ");
1055		cmdtxt(n->nbinary.ch2);
1056		break;
1057	case NAND:
1058		cmdtxt(n->nbinary.ch1);
1059		cmdputs(" && ");
1060		cmdtxt(n->nbinary.ch2);
1061		break;
1062	case NOR:
1063		cmdtxt(n->nbinary.ch1);
1064		cmdputs(" || ");
1065		cmdtxt(n->nbinary.ch2);
1066		break;
1067	case NPIPE:
1068		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1069			cmdtxt(lp->n);
1070			if (lp->next)
1071				cmdputs(" | ");
1072		}
1073		break;
1074	case NSUBSHELL:
1075		cmdputs("(");
1076		cmdtxt(n->nredir.n);
1077		cmdputs(")");
1078		break;
1079	case NREDIR:
1080	case NBACKGND:
1081		cmdtxt(n->nredir.n);
1082		break;
1083	case NIF:
1084		cmdputs("if ");
1085		cmdtxt(n->nif.test);
1086		cmdputs("; then ");
1087		cmdtxt(n->nif.ifpart);
1088		cmdputs("...");
1089		break;
1090	case NWHILE:
1091		cmdputs("while ");
1092		goto until;
1093	case NUNTIL:
1094		cmdputs("until ");
1095until:
1096		cmdtxt(n->nbinary.ch1);
1097		cmdputs("; do ");
1098		cmdtxt(n->nbinary.ch2);
1099		cmdputs("; done");
1100		break;
1101	case NFOR:
1102		cmdputs("for ");
1103		cmdputs(n->nfor.var);
1104		cmdputs(" in ...");
1105		break;
1106	case NCASE:
1107		cmdputs("case ");
1108		cmdputs(n->ncase.expr->narg.text);
1109		cmdputs(" in ...");
1110		break;
1111	case NDEFUN:
1112		cmdputs(n->narg.text);
1113		cmdputs("() ...");
1114		break;
1115	case NCMD:
1116		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1117			cmdtxt(np);
1118			if (np->narg.next)
1119				cmdputs(" ");
1120		}
1121		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1122			cmdputs(" ");
1123			cmdtxt(np);
1124		}
1125		break;
1126	case NARG:
1127		cmdputs(n->narg.text);
1128		break;
1129	case NTO:
1130		p = ">";  i = 1;  goto redir;
1131	case NAPPEND:
1132		p = ">>";  i = 1;  goto redir;
1133	case NTOFD:
1134		p = ">&";  i = 1;  goto redir;
1135	case NCLOBBER:
1136		p = ">|"; i = 1; goto redir;
1137	case NFROM:
1138		p = "<";  i = 0;  goto redir;
1139	case NFROMTO:
1140		p = "<>";  i = 0;  goto redir;
1141	case NFROMFD:
1142		p = "<&";  i = 0;  goto redir;
1143redir:
1144		if (n->nfile.fd != i) {
1145			s[0] = n->nfile.fd + '0';
1146			s[1] = '\0';
1147			cmdputs(s);
1148		}
1149		cmdputs(p);
1150		if (n->type == NTOFD || n->type == NFROMFD) {
1151			s[0] = n->ndup.dupfd + '0';
1152			s[1] = '\0';
1153			cmdputs(s);
1154		} else {
1155			cmdtxt(n->nfile.fname);
1156		}
1157		break;
1158	case NHERE:
1159	case NXHERE:
1160		cmdputs("<<...");
1161		break;
1162	default:
1163		cmdputs("???");
1164		break;
1165	}
1166}
1167
1168
1169
1170STATIC void
1171cmdputs(char *s)
1172{
1173	char *p, *q;
1174	char c;
1175	int subtype = 0;
1176
1177	if (cmdnleft <= 0)
1178		return;
1179	p = s;
1180	q = cmdnextc;
1181	while ((c = *p++) != '\0') {
1182		if (c == CTLESC)
1183			*q++ = *p++;
1184		else if (c == CTLVAR) {
1185			*q++ = '$';
1186			if (--cmdnleft > 0)
1187				*q++ = '{';
1188			subtype = *p++;
1189		} else if (c == '=' && subtype != 0) {
1190			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1191			subtype = 0;
1192		} else if (c == CTLENDVAR) {
1193			*q++ = '}';
1194		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1195			cmdnleft++;		/* ignore it */
1196		else
1197			*q++ = c;
1198		if (--cmdnleft <= 0) {
1199			*q++ = '.';
1200			*q++ = '.';
1201			*q++ = '.';
1202			break;
1203		}
1204	}
1205	cmdnextc = q;
1206}
1207