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