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