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