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