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