xref: /netbsd-src/bin/sh/jobs.c (revision 0a3071956a3a9fdebdbf7f338cf2d439b45fc728)
1 /*	$NetBSD: jobs.c,v 1.122 2024/06/18 07:21:31 kre Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
39 #else
40 __RCSID("$NetBSD: jobs.c,v 1.122 2024/06/18 07:21:31 kre Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <stdlib.h>
50 #include <paths.h>
51 #include <sys/types.h>
52 #include <sys/param.h>
53 #ifdef BSD
54 #include <sys/wait.h>
55 #include <sys/time.h>
56 #include <sys/resource.h>
57 #endif
58 #include <sys/ioctl.h>
59 
60 #include "shell.h"
61 #if JOBS
62 #if OLD_TTY_DRIVER
63 #include "sgtty.h"
64 #else
65 #include <termios.h>
66 #endif
67 #undef CEOF			/* syntax.h redefines this */
68 #endif
69 #include "redir.h"
70 #include "show.h"
71 #include "main.h"
72 #include "parser.h"
73 #include "nodes.h"
74 #include "jobs.h"
75 #include "var.h"
76 #include "options.h"
77 #include "builtins.h"
78 #include "trap.h"
79 #include "syntax.h"
80 #include "input.h"
81 #include "output.h"
82 #include "memalloc.h"
83 #include "error.h"
84 #include "mystring.h"
85 
86 
87 #ifndef	WCONTINUED
88 #define	WCONTINUED 0		/* So we can compile on old systems */
89 #endif
90 #ifndef	WIFCONTINUED
91 #define	WIFCONTINUED(x)	(0)		/* ditto */
92 #endif
93 
94 
95 static struct job *jobtab;		/* array of jobs */
96 static int njobs;			/* size of array */
97 static int jobs_invalid;		/* set in child */
98 MKINIT pid_t backgndpid = -1;	/* pid of last background process */
99 #if JOBS
100 int initialpgrp;		/* pgrp of shell on invocation */
101 static int curjob = -1;		/* current job */
102 #endif
103 static int ttyfd = -1;
104 
105 STATIC void restartjob(struct job *);
106 STATIC void freejob(struct job *);
107 STATIC struct job *getjob(const char *, int);
108 STATIC int dowait(int, struct job *, struct job **);
109 #define WBLOCK	1
110 #define WNOFREE 2
111 #define WSILENT 4
112 STATIC int jobstatus(const struct job *, int);
113 STATIC int waitproc(int, struct job *, int *);
114 STATIC int cmdtxt(union node *, int);
115 STATIC void cmdlist(union node *, int);
116 STATIC void cmdputs(const char *);
117 inline static void cmdputi(int);
118 
119 #define	JNUM(j)	((int)((j) != NULL ? ((j) - jobtab) + 1 : 0))
120 
121 #ifdef SYSV
122 STATIC int onsigchild(void);
123 #endif
124 
125 #ifdef OLD_TTY_DRIVER
126 static pid_t tcgetpgrp(int fd);
127 static int tcsetpgrp(int fd, pid_t pgrp);
128 
129 static pid_t
130 tcgetpgrp(int fd)
131 {
132 	pid_t pgrp;
133 	if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
134 		return -1;
135 	else
136 		return pgrp;
137 }
138 
139 static int
140 tcsetpgrp(int fd, pid_tpgrp)
141 {
142 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
143 }
144 #endif
145 
146 static void
147 ttyfd_change(int from, int to)
148 {
149 	if (ttyfd == from)
150 		ttyfd = to;
151 }
152 
153 /*
154  * Turn job control on and off.
155  *
156  * Note:  This code assumes that the third arg to ioctl is a character
157  * pointer, which is true on Berkeley systems but not System V.  Since
158  * System V doesn't have job control yet, this isn't a problem now.
159  */
160 
161 MKINIT int jobctl;
162 
163 void
164 setjobctl(int on)
165 {
166 #ifdef OLD_TTY_DRIVER
167 	int ldisc;
168 #endif
169 
170 	if (on == jobctl || rootshell == 0)
171 		return;
172 	if (on) {
173 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
174 		int i;
175 
176 		if (ttyfd != -1)
177 			sh_close(ttyfd);
178 		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
179 			for (i = 0; i < 3; i++) {
180 				if (isatty(i) && (ttyfd = dup(i)) != -1)
181 					break;
182 			}
183 			if (i == 3)
184 				goto out;
185 		}
186 		ttyfd = to_upper_fd(ttyfd);	/* Move to a high fd */
187 		register_sh_fd(ttyfd, ttyfd_change);
188 #else
189 		out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
190 		goto out;
191 #endif
192 		if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
193  out:
194 			out2str("sh: can't access tty; job control turned off\n");
195 			mflag = 0;
196 			return;
197 		}
198 		if (initialpgrp == -1)
199 			initialpgrp = getpgrp();
200 		else if (initialpgrp != getpgrp())
201 			killpg(0, SIGTTIN);
202 
203 #ifdef OLD_TTY_DRIVER
204 		if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
205 		    || ldisc != NTTYDISC) {
206 			out2str("sh: need new tty driver to run job control; job control turned off\n");
207 			mflag = 0;
208 			return;
209 		}
210 #endif
211 		setsignal(SIGTSTP, 0);
212 		setsignal(SIGTTOU, 0);
213 		setsignal(SIGTTIN, 0);
214 		if (getpgrp() != rootpid && setpgid(0, rootpid) == -1)
215 			error("Cannot set process group (%s) at %d",
216 			    strerror(errno), __LINE__);
217 		if (tcsetpgrp(ttyfd, rootpid) == -1)
218 			error("Cannot set tty process group (%s) at %d",
219 			    strerror(errno), __LINE__);
220 	} else { /* turning job control off */
221 		if (getpgrp() != initialpgrp && setpgid(0, initialpgrp) == -1)
222 			error("Cannot set process group (%s) at %d",
223 			    strerror(errno), __LINE__);
224 		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
225 			error("Cannot set tty process group (%s) at %d",
226 			    strerror(errno), __LINE__);
227 		sh_close(ttyfd);
228 		ttyfd = -1;
229 		setsignal(SIGTSTP, 0);
230 		setsignal(SIGTTOU, 0);
231 		setsignal(SIGTTIN, 0);
232 	}
233 	jobctl = on;
234 }
235 
236 
237 #ifdef mkinit
238 INCLUDE <stdlib.h>
239 
240 SHELLPROC {
241 	backgndpid = -1;
242 #if JOBS
243 	jobctl = 0;
244 #endif
245 }
246 
247 #endif
248 
249 
250 
251 #if JOBS
252 static int
253 do_fgcmd(const char *arg_ptr)
254 {
255 	struct job *jp;
256 	int i;
257 	int status;
258 
259 	if (jobs_invalid)
260 		error("No current jobs");
261 	jp = getjob(arg_ptr, 0);
262 	if (jp->jobctl == 0)
263 		error("job not created under job control");
264 	out1fmt("%s", jp->ps[0].cmd);
265 	for (i = 1; i < jp->nprocs; i++)
266 		out1fmt(" | %s", jp->ps[i].cmd );
267 	out1c('\n');
268 	flushall();
269 
270 	if (tcsetpgrp(ttyfd, jp->pgrp) == -1) {
271 		error("Cannot set tty process group (%s) at %d",
272 		    strerror(errno), __LINE__);
273 	}
274 	INTOFF;
275 	restartjob(jp);
276 	status = waitforjob(jp);
277 	INTON;
278 	return status;
279 }
280 
281 int
282 fgcmd(int argc, char **argv)
283 {
284 	nextopt("");
285 	return do_fgcmd(*argptr);
286 }
287 
288 int
289 fgcmd_percent(int argc, char **argv)
290 {
291 	nextopt("");
292 	return do_fgcmd(*argv);
293 }
294 
295 static void
296 set_curjob(struct job *jp, int mode)
297 {
298 	struct job *jp1, *jp2;
299 	int i, ji;
300 
301 	ji = jp - jobtab;
302 
303 	/* first remove from list */
304 	if (ji == curjob)
305 		curjob = jp->prev_job;
306 	else {
307 		for (i = 0; i < njobs; i++) {
308 			if (jobtab[i].prev_job != ji)
309 				continue;
310 			jobtab[i].prev_job = jp->prev_job;
311 			break;
312 		}
313 	}
314 
315 	/* Then re-insert in correct position */
316 	switch (mode) {
317 	case 0:	/* job being deleted */
318 		jp->prev_job = -1;
319 		break;
320 	case 1:	/* newly created job or backgrounded job,
321 		   put after all stopped jobs. */
322 		if (curjob != -1 && jobtab[curjob].state == JOBSTOPPED) {
323 			for (jp1 = jobtab + curjob; ; jp1 = jp2) {
324 				if (jp1->prev_job == -1)
325 					break;
326 				jp2 = jobtab + jp1->prev_job;
327 				if (jp2->state != JOBSTOPPED)
328 					break;
329 			}
330 			jp->prev_job = jp1->prev_job;
331 			jp1->prev_job = ji;
332 			break;
333 		}
334 		/* FALLTHROUGH */
335 	case 2:	/* newly stopped job - becomes curjob */
336 		jp->prev_job = curjob;
337 		curjob = ji;
338 		break;
339 	}
340 }
341 
342 int
343 bgcmd(int argc, char **argv)
344 {
345 	struct job *jp;
346 	int i;
347 
348 	nextopt("");
349 	if (jobs_invalid)
350 		error("No current jobs");
351 	do {
352 		jp = getjob(*argptr, 0);
353 		if (jp->jobctl == 0)
354 			error("job not created under job control");
355 		set_curjob(jp, 1);
356 		out1fmt("[%d] %s", JNUM(jp), jp->ps[0].cmd);
357 		for (i = 1; i < jp->nprocs; i++)
358 			out1fmt(" | %s", jp->ps[i].cmd );
359 		out1c('\n');
360 		flushall();
361 		restartjob(jp);
362 	} while (*argptr && *++argptr);
363 	return 0;
364 }
365 
366 
367 STATIC void
368 restartjob(struct job *jp)
369 {
370 	struct procstat *ps;
371 	int i, e;
372 
373 	if (jp->state == JOBDONE)
374 		return;
375 	if (jp->pgrp == 0)
376 		error("Job [%d] does not have a process group", JNUM(jp));
377 
378 	INTOFF;
379 	for (e = i = 0; i < jp->nprocs; i++) {
380 		/*
381 		 * Don't touch a process we already waited for and collected
382 		 * exit status, that pid may have been reused for something
383 		 * else - even another of our jobs
384 		 */
385 		if (jp->ps[i].status != -1 && !WIFSTOPPED(jp->ps[i].status))
386 			continue;
387 
388 		/*
389 		 * Otherwise tell it to continue, if it worked, we're done
390 		 * (we signal the whole process group)
391 		 */
392 		if (killpg(jp->pgrp, SIGCONT) != -1)
393 			break;
394 		e = errno;
395 		break;		/* no point trying again */
396 	}
397 
398 	if (e != 0)
399 		error("Cannot continue job (%s)", strerror(e));
400 	else if (i >= jp->nprocs)
401 		error("Job [%d] has no stopped processes", JNUM(jp));
402 
403 	/*
404 	 * Now change state of all stopped processes in the job to running
405 	 * If there were any, the job is now running as well.
406 	 */
407 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
408 		if (WIFSTOPPED(ps->status)) {
409 			VTRACE(DBG_JOBS, (
410 			   "restartjob: [%d] pid %d status change"
411 			   " from %#x (stopped) to -1 (running)\n",
412 			   JNUM(jp), ps->pid, ps->status));
413 			ps->status = -1;
414 			jp->state = JOBRUNNING;
415 		}
416 	}
417 	INTON;
418 }
419 #endif
420 
421 inline static void
422 cmdputi(int n)
423 {
424 	char str[20];
425 
426 	fmtstr(str, sizeof str, "%d", n);
427 	cmdputs(str);
428 }
429 
430 static void
431 showjob(struct output *out, struct job *jp, int mode)
432 {
433 	int procno;
434 	int st;
435 	struct procstat *ps;
436 	int col;
437 	char s[64];
438 
439 #if JOBS
440 	if (mode & SHOW_PGID) {
441 		/* output only the process group ID (lead process ID) */
442 		outfmt(out, "%ld\n",
443 		    jp->pgrp != 0 ? (long)jp->pgrp : (long)jp->ps->pid);
444 		return;
445 	}
446 #endif
447 
448 	procno = jp->nprocs;
449 	if (!procno)
450 		return;
451 
452 	if (mode & SHOW_PID)
453 		mode |= SHOW_MULTILINE;
454 
455 	if ((procno > 1 && !(mode & SHOW_MULTILINE))
456 	    || (mode & SHOW_SIGNALLED)) {
457 		/* See if we have more than one status to report */
458 		ps = jp->ps;
459 		st = ps->status;
460 		do {
461 			int st1 = ps->status;
462 			if (st1 != st)
463 				/* yes - need multi-line output */
464 				mode |= SHOW_MULTILINE;
465 			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
466 				continue;
467 			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
468 			    && st1 != SIGINT && st1 != SIGPIPE))
469 				mode |= SHOW_ISSIG;
470 
471 		} while (ps++, --procno);
472 		procno = jp->nprocs;
473 	}
474 
475 	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
476 		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
477 			VTRACE(DBG_JOBS, ("showjob: freeing job %d\n",
478 			    JNUM(jp)));
479 			freejob(jp);
480 		}
481 		return;
482 	}
483 
484 	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
485 		if (ps == jp->ps)
486 			fmtstr(s, 16, "[%d] %c ",
487 				JNUM(jp),
488 #if JOBS
489 				jp - jobtab == curjob ?
490 									  '+' :
491 				curjob != -1 &&
492 				    jp - jobtab == jobtab[curjob].prev_job ?
493 									  '-' :
494 #endif
495 				' ');
496 		else
497 			fmtstr(s, 16, "      " );
498 		col = strlen(s);
499 		if (mode & SHOW_PID) {
500 			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
501 			     col += strlen(s + col);
502 		}
503 		if (ps->status == -1) {
504 			scopy("Running", s + col);
505 		} else if (WIFEXITED(ps->status)) {
506 			st = WEXITSTATUS(ps->status);
507 			if (st)
508 				fmtstr(s + col, 16, "Done(%d)", st);
509 			else
510 				fmtstr(s + col, 16, "Done");
511 		} else {
512 #if JOBS
513 			if (WIFSTOPPED(ps->status))
514 				st = WSTOPSIG(ps->status);
515 			else /* WIFSIGNALED(ps->status) */
516 #endif
517 				st = WTERMSIG(ps->status);
518 			scopyn(strsignal(st), s + col, 32);
519 			if (WCOREDUMP(ps->status)) {
520 				col += strlen(s + col);
521 				scopyn(" (core dumped)", s + col,  64 - col);
522 			}
523 		}
524 		col += strlen(s + col);
525 		outstr(s, out);
526 		do {
527 			outc(' ', out);
528 			col++;
529 		} while (col < 30);
530 		outstr(ps->cmd, out);
531 		if (mode & SHOW_MULTILINE) {
532 			if (procno > 0) {
533 				outc(' ', out);
534 				outc('|', out);
535 			}
536 		} else {
537 			while (--procno >= 0)
538 				outfmt(out, " | %s", (++ps)->cmd );
539 		}
540 		outc('\n', out);
541 	}
542 	flushout(out);
543 	jp->flags &= ~JOBCHANGED;
544 	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
545 		freejob(jp);
546 }
547 
548 int
549 jobscmd(int argc, char **argv)
550 {
551 	int mode, m;
552 
553 	mode = 0;
554 	while ((m = nextopt("lpZ")))
555 		switch (m) {
556 		case 'l':
557 			mode = SHOW_PID;
558 			break;
559 		case 'p':
560 			mode = SHOW_PGID;
561 			break;
562 		case 'Z':
563 			mode = SHOW_PROCTITLE;
564 			break;
565 		}
566 
567 	if (mode == SHOW_PROCTITLE) {
568 		if (*argptr && **argptr)
569 			setproctitle("%s", *argptr);
570 		else
571 			setproctitle(NULL);
572 		return 0;
573 	}
574 
575 	if (!iflag && !posix)
576 		mode |= SHOW_NO_FREE;
577 
578 	if (*argptr) {
579 		do
580 			showjob(out1, getjob(*argptr,0), mode);
581 		while (*++argptr);
582 	} else
583 		showjobs(out1, mode);
584 	return 0;
585 }
586 
587 
588 /*
589  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
590  * statuses have changed since the last call to showjobs.
591  *
592  * If the shell is interrupted in the process of creating a job, the
593  * result may be a job structure containing zero processes.  Such structures
594  * will be freed here.
595  */
596 
597 void
598 showjobs(struct output *out, int mode)
599 {
600 	int jobno;
601 	struct job *jp;
602 	int silent = 0, gotpid;
603 
604 	CTRACE(DBG_JOBS, ("showjobs(%x) called\n", mode));
605 
606 	/*  Collect everything pending in the kernel */
607 	if ((gotpid = dowait(WSILENT, NULL, NULL)) > 0)
608 		while (dowait(WSILENT, NULL, NULL) > 0)
609 			continue;
610 #ifdef JOBS
611 	/*
612 	 * Check if we are not in our foreground group, and if not
613 	 * put us in it.
614 	 */
615 	if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
616 		if (tcsetpgrp(ttyfd, getpid()) == -1)
617 			error("Cannot set tty process group (%s) at %d",
618 			    strerror(errno), __LINE__);
619 		VTRACE(DBG_JOBS|DBG_INPUT, ("repaired tty process group\n"));
620 		silent = 1;
621 	}
622 #endif
623 
624 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
625 		if (!jp->used)
626 			continue;
627 		if (jp->nprocs == 0) {
628 			if (!jobs_invalid)
629 				freejob(jp);
630 			continue;
631 		}
632 		if ((mode & SHOW_CHANGED) && !(jp->flags & JOBCHANGED))
633 			continue;
634 		if (silent && (jp->flags & JOBCHANGED)) {
635 			jp->flags &= ~JOBCHANGED;
636 			continue;
637 		}
638 		showjob(out, jp, mode);
639 	}
640 }
641 
642 /*
643  * Mark a job structure as unused.
644  */
645 
646 STATIC void
647 freejob(struct job *jp)
648 {
649 	INTOFF;
650 	if (jp->ps != &jp->ps0) {
651 		ckfree(jp->ps);
652 		jp->ps = &jp->ps0;
653 	}
654 	jp->nprocs = 0;
655 	jp->used = 0;
656 #if JOBS
657 	set_curjob(jp, 0);
658 #endif
659 	INTON;
660 }
661 
662 /*
663  * Extract the status of a completed job (for $?)
664  */
665 STATIC int
666 jobstatus(const struct job *jp, int raw)
667 {
668 	int status = 0;
669 	int retval;
670 
671 	if ((jp->flags & JPIPEFAIL) && jp->nprocs) {
672 		int i;
673 
674 		for (i = 0; i < jp->nprocs; i++)
675 			if (jp->ps[i].status != 0)
676 				status = jp->ps[i].status;
677 	} else
678 		status = jp->ps[jp->nprocs ? jp->nprocs - 1 : 0].status;
679 
680 	if (raw)
681 		return status;
682 
683 	if (WIFEXITED(status))
684 		retval = WEXITSTATUS(status);
685 #if JOBS
686 	else if (WIFSTOPPED(status))
687 		retval = WSTOPSIG(status) + 128;
688 #endif
689 	else {
690 		/* XXX: limits number of signals */
691 		retval = WTERMSIG(status) + 128;
692 	}
693 
694 	return retval;
695 }
696 
697 
698 
699 int
700 waitcmd(int argc, char **argv)
701 {
702 	struct job *job, *last;
703 	int retval;
704 	struct job *jp;
705 	int i;
706 	int any = 0;
707 	int found;
708 	int oldwait = 0;
709 	char *pid = NULL, *fpid;
710 	char **arg;
711 	char idstring[20];
712 
713 	while ((i = nextopt("np:")) != '\0') {
714 		switch (i) {
715 		case 'n':
716 			any = 1;
717 			break;
718 		case 'p':
719 			if (pid)
720 				error("more than one -p unsupported");
721 			pid = optionarg;
722 			break;
723 		}
724 	}
725 
726 	if (!any && *argptr == 0)
727 		oldwait = 1;
728 
729 	if (pid != NULL) {
730 		if (!validname(pid, '\0', NULL))
731 			error("invalid name: -p '%s'", pid);
732 		if (unsetvar(pid, 0))
733 			error("%s readonly", pid);
734 	}
735 
736 	/*
737 	 * If we have forked, and not yet created any new jobs, then
738 	 * we have no children, whatever jobtab claims,
739 	 * so simply return in that case.
740 	 *
741 	 * The return code is 127 if we had any pid args (none are found)
742 	 * or if we had -n (nothing exited), but 0 for plain old "wait".
743 	 */
744 	if (jobs_invalid) {
745 		CTRACE(DBG_WAIT, ("builtin wait%s%s in child, invalid jobtab\n",
746 		    any ? " -n" : "", *argptr ? " pid..." : ""));
747 		return oldwait ? 0 : 127;
748 	}
749 
750 	/*
751 	 * clear stray flags left from previous waitcmd
752 	 * or set them instead if anything will do ("wait -n")
753 	 */
754 	for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
755 		if (any && *argptr == NULL)
756 			jp->flags |= JOBWANTED;
757 		else
758 			jp->flags &= ~JOBWANTED;
759 		jp->ref = NULL;
760 	}
761 
762 	CTRACE(DBG_WAIT,
763 	    ("builtin wait%s%s\n", any ? " -n" : "", *argptr ? " pid..." : ""));
764 
765 	/*
766 	 * First, validate the jobnum args, count how many refer to
767 	 * (different) running jobs, and if we had -n, and found that one has
768 	 * already finished, we return that one.   Otherwise remember
769 	 * which ones we are looking for (JOBWANTED).
770 	 */
771 	found = 0;
772 	last = NULL;
773 	for (arg = argptr; *arg; arg++) {
774 		last = jp = getjob(*arg, 1);
775 		if (!jp)
776 			continue;
777 		if (jp->ref == NULL)
778 			jp->ref = *arg;
779 		if (any && jp->state == JOBDONE) {
780 			/*
781 			 * We just want any of them, and this one is
782 			 * ready for consumption, bon apetit ...
783 			 */
784 			retval = jobstatus(jp, 0);
785 			if (pid)
786 				setvar(pid, *arg, 0);
787 			if (!iflag)
788 				freejob(jp);
789 			CTRACE(DBG_WAIT, ("wait -n found %s already done: %d\n",			    *arg, retval));
790 			return retval;
791 		}
792 		if (!(jp->flags & JOBWANTED)) {
793 			/*
794 			 * It is possible to list the same job several
795 			 * times - the obvious "wait 1 1 1" or
796 			 * "wait %% %2 102" where job 2 is current and pid 102
797 			 * However many times it is requested, it is found once.
798 			 */
799 			found++;
800 			jp->flags |= JOBWANTED;
801 		}
802 		job = jp;
803 	}
804 
805 	VTRACE(DBG_WAIT, ("wait %s%s%sfound %d candidates (last %s)\n",
806 	    any ? "-n " : "", *argptr ? *argptr : "",
807 	    argptr[0] && argptr[1] ? "... " : " ", found,
808 	    job && job->used ? (job->ref ? job->ref : "<no-arg>") : "none"));
809 
810 	/*
811 	 * If we were given a list of jobnums:
812 	 * and none of those exist, then we're done.
813 	 */
814 	if (*argptr && found == 0)
815 		return 127;
816 
817 	/*
818 	 * Otherwise we need to wait for something to complete
819 	 * When it does, we check and see if it is one of the
820 	 * jobs we're waiting on, and if so, we clean it up.
821 	 * If we had -n, then we're done, otherwise we do it all again
822 	 * until all we had listed are done, of if there were no
823 	 * jobnum args, all are done.
824 	 */
825 
826 	retval = any || *argptr ? 127 : 0;
827 	fpid = NULL;
828 	for (;;) {
829 		VTRACE(DBG_WAIT, ("wait waiting (%d remain): ", found));
830 		job = NULL;
831 		for (jp = jobtab, i = njobs; --i >= 0; jp++) {
832 			if (jp->used && jp->flags & JOBWANTED &&
833 			    jp->state == JOBDONE) {
834 				job = jp;
835 				break;
836 			}
837 			if (jp->used && jp->state == JOBRUNNING)
838 				job = jp;
839 		}
840 		if (i < 0 && job == NULL) {
841 			CTRACE(DBG_WAIT, ("nothing running (ret: %d) fpid %s\n",
842 			    retval, fpid ? fpid : "unset"));
843 			if (pid && fpid)
844 				setvar(pid, fpid, 0);
845 			return retval;
846 		}
847 		jp = job;
848 		VTRACE(DBG_WAIT, ("found @%d/%d state: %d\n", njobs-i, njobs,
849 		    jp->state));
850 
851 		/*
852 		 * There is at least 1 job running, so we can
853 		 * safely wait() (blocking) for something to exit.
854 		 */
855 		if (jp->state == JOBRUNNING) {
856 			job = NULL;
857 			if ((i = dowait(WBLOCK|WNOFREE, NULL, &job)) == -1)
858 			       return 128 + lastsig();
859 
860 			/*
861 			 * This happens if an interloper has died
862 			 * (eg: a child of the executable that exec'd us)
863 			 * Simply go back and start all over again
864 			 * (this is rare).
865 			 */
866 			if (job == NULL)
867 				continue;
868 
869 			/*
870 			 * one of the reported job's processes exited,
871 			 * but there are more still running, back for more
872 			 */
873 			if (job->state == JOBRUNNING)
874 				continue;
875 		} else
876 			job = jp;	/* we want this, and it is done */
877 
878 		if (job->flags & JOBWANTED) {
879 			int rv;
880 
881 			job->flags &= ~JOBWANTED;	/* got it */
882 			rv = jobstatus(job, 0);
883 			VTRACE(DBG_WAIT, (
884 			    "wanted %d (%s) done: st=%d", i,
885 			    job->ref ? job->ref : "", rv));
886 			if (any || job == last) {
887 				retval = rv;
888 				fpid = job->ref;
889 
890 				VTRACE(DBG_WAIT, (" save"));
891 				if (pid) {
892 				   /*
893 				    * don't need fpid unless we are going
894 				    * to return it.
895 				    */
896 				   if (fpid == NULL) {
897 					/*
898 					 * this only happens with "wait -n"
899 					 * (that is, no pid args)
900 					 */
901 					snprintf(idstring, sizeof idstring,
902 					    "%d", job->ps[ job->nprocs ?
903 						    job->nprocs-1 : 0 ].pid);
904 					fpid = idstring;
905 				    }
906 				    VTRACE(DBG_WAIT, (" (for %s)", fpid));
907 				}
908 			}
909 
910 			if (job->state == JOBDONE) {
911 				VTRACE(DBG_WAIT, (" free"));
912 				freejob(job);
913 			}
914 
915 			if (any || (found > 0 && --found == 0)) {
916 				if (pid && fpid)
917 					setvar(pid, fpid, 0);
918 				VTRACE(DBG_WAIT, (" return %d\n", retval));
919 				return retval;
920 			}
921 			VTRACE(DBG_WAIT, ("\n"));
922 			continue;
923 		}
924 
925 		/* this is to handle "wait" (no args) */
926 		if (oldwait && job->state == JOBDONE) {
927 			VTRACE(DBG_JOBS|DBG_WAIT, ("Cleanup: %d\n", i));
928 			freejob(job);
929 		}
930 	}
931 }
932 
933 
934 int
935 jobidcmd(int argc, char **argv)
936 {
937 	struct job *jp;
938 	int i;
939 	int pg = 0, onep = 0, job = 0;
940 
941 	while ((i = nextopt("gjp"))) {
942 		switch (i) {
943 		case 'g':	pg = 1;		break;
944 		case 'j':	job = 1;	break;
945 		case 'p':	onep = 1;	break;
946 		}
947 	}
948 	CTRACE(DBG_JOBS, ("jobidcmd%s%s%s%s %s\n", pg ? " -g" : "",
949 	    onep ? " -p" : "", job ? " -j" : "", jobs_invalid ? " [inv]" : "",
950 	    *argptr ? *argptr : "<implicit %%>"));
951 	if (pg + onep + job > 1)
952 		error("-g -j and -p options cannot be combined");
953 
954 	if (argptr[0] && argptr[1])
955 		error("usage: jobid [-g|-p|-r] jobid");
956 
957 	jp = getjob(*argptr, 0);
958 	if (job) {
959 		out1fmt("%%%d\n", JNUM(jp));
960 		return 0;
961 	}
962 	if (pg) {
963 		if (jp->pgrp != 0) {
964 			out1fmt("%ld\n", (long)jp->pgrp);
965 			return 0;
966 		}
967 		return 1;
968 	}
969 	if (onep) {
970 		i = jp->nprocs - 1;
971 		if (i < 0)
972 			return 1;
973 		out1fmt("%ld\n", (long)jp->ps[i].pid);
974 		return 0;
975 	}
976 	for (i = 0 ; i < jp->nprocs ; ) {
977 		out1fmt("%ld", (long)jp->ps[i].pid);
978 		out1c(++i < jp->nprocs ? ' ' : '\n');
979 	}
980 	return 0;
981 }
982 
983 int
984 getjobpgrp(const char *name)
985 {
986 	struct job *jp;
987 
988 	if (jobs_invalid)
989 		error("No such job: %s", name);
990 	jp = getjob(name, 1);
991 	if (jp == 0)
992 		return 0;
993 	return -jp->pgrp;
994 }
995 
996 /*
997  * Convert a job name to a job structure.
998  */
999 
1000 STATIC struct job *
1001 getjob(const char *name, int noerror)
1002 {
1003 	int jobno = -1;
1004 	struct job *jp;
1005 	int pid;
1006 	int i;
1007 	const char *err_msg = "No such job: %s";
1008 
1009 	if (name == NULL) {
1010 #if JOBS
1011 		jobno = curjob;
1012 #endif
1013 		err_msg = "No current job";
1014 	} else if (name[0] == '%') {
1015 		if (is_number(name + 1)) {
1016 			jobno = number(name + 1) - 1;
1017 		} else if (!name[1] || !name[2]) {
1018 			switch (name[1]) {
1019 #if JOBS
1020 			case 0:
1021 			case '+':
1022 			case '%':
1023 				jobno = curjob;
1024 				err_msg = "No current job";
1025 				break;
1026 			case '-':
1027 				jobno = curjob;
1028 				if (jobno != -1)
1029 					jobno = jobtab[jobno].prev_job;
1030 				err_msg = "No previous job";
1031 				break;
1032 #endif
1033 			default:
1034 				goto check_pattern;
1035 			}
1036 		} else {
1037 			struct job *found;
1038     check_pattern:
1039 			found = NULL;
1040 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
1041 				if (!jp->used || jp->nprocs <= 0)
1042 					continue;
1043 				if ((name[1] == '?'
1044 					&& strstr(jp->ps[0].cmd, name + 2))
1045 				    || prefix(name + 1, jp->ps[0].cmd)) {
1046 					if (found) {
1047 						err_msg = "%s: ambiguous";
1048 						found = 0;
1049 						break;
1050 					}
1051 					found = jp;
1052 				}
1053 			}
1054 			if (found)
1055 				return found;
1056 		}
1057 
1058 	} else if (is_number(name)) {
1059 		pid = number(name);
1060 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
1061 			if (jp->used && jp->nprocs > 0
1062 			 && jp->ps[jp->nprocs - 1].pid == pid)
1063 				return jp;
1064 		}
1065 	}
1066 
1067 	if (jobno >= 0 && jobno < njobs) {
1068 		jp = jobtab + jobno;
1069 		if (jp->used)
1070 			return jp;
1071 	}
1072 	if (!noerror)
1073 		error(err_msg, name);
1074 	return 0;
1075 }
1076 
1077 
1078 /*
1079  * Find out if there are any running (that is, unwaited upon)
1080  * background children of the current shell.
1081  *
1082  * Return 1/0 (yes, no).
1083  *
1084  * Needed as we cannot optimise away sub-shell creation if
1085  * we have such a child, or a "wait" in that sub-shell would
1086  * observe the already existing job.
1087  */
1088 int
1089 anyjobs(void)
1090 {
1091 	struct job *jp;
1092 	int i;
1093 
1094 	if (jobs_invalid)
1095 		return 0;
1096 
1097 	for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
1098 		if (jp->used)
1099 			return 1;
1100 	}
1101 
1102 	return 0;
1103 }
1104 
1105 /*
1106  * Output the (new) POSIX required "[%d] %d" string whenever an
1107  * async (ie: background) job is started in an interactive shell.
1108  * Note that a subshell environment is not regarded as interactive.
1109  */
1110 void
1111 jobstarted(struct job *jp)
1112 {
1113 	if (!iflag || !rootshell)
1114 		return;
1115 
1116 	outfmt(out2, "[%d] %ld\n", JNUM(jp),
1117 	    jp->pgrp != 0 ? (long)jp->pgrp : (long)jp->ps->pid);
1118 }
1119 
1120 /*
1121  * Return a new job structure,
1122  */
1123 
1124 struct job *
1125 makejob(union node *node, int nprocs)
1126 {
1127 	int i;
1128 	struct job *jp;
1129 
1130 	if (jobs_invalid) {
1131 		VTRACE(DBG_JOBS, ("makejob(%p, %d) clearing jobtab (%d)\n",
1132 			(void *)node, nprocs, njobs));
1133 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
1134 			if (jp->used)
1135 				freejob(jp);
1136 		}
1137 		jobs_invalid = 0;
1138 	}
1139 
1140 	for (i = njobs, jp = jobtab ; ; jp++) {
1141 		if (--i < 0) {
1142 			INTOFF;
1143 			if (njobs == 0) {
1144 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
1145 			} else {
1146 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
1147 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
1148 				/* Relocate `ps' pointers */
1149 				for (i = 0; i < njobs; i++)
1150 					if (jp[i].ps == &jobtab[i].ps0)
1151 						jp[i].ps = &jp[i].ps0;
1152 				ckfree(jobtab);
1153 				jobtab = jp;
1154 			}
1155 			jp = jobtab + njobs;
1156 			for (i = 4 ; --i >= 0 ; njobs++) {
1157 				jobtab[njobs].used = 0;
1158 				jobtab[njobs].prev_job = -1;
1159 			}
1160 			INTON;
1161 			break;
1162 		}
1163 		if (jp->used == 0)
1164 			break;
1165 	}
1166 	INTOFF;
1167 	jp->state = JOBRUNNING;
1168 	jp->used = 1;
1169 	jp->flags = pipefail ? JPIPEFAIL : 0;
1170 	jp->nprocs = 0;
1171 	jp->pgrp = 0;
1172 #if JOBS
1173 	jp->jobctl = jobctl;
1174 	set_curjob(jp, 1);
1175 #endif
1176 	if (nprocs > 1) {
1177 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
1178 	} else {
1179 		jp->ps = &jp->ps0;
1180 	}
1181 	INTON;
1182 	VTRACE(DBG_JOBS, ("makejob(%p, %d)%s returns %%%d\n", (void *)node,
1183 	    nprocs, (jp->flags & JPIPEFAIL) ? " PF" : "", JNUM(jp)));
1184 	return jp;
1185 }
1186 
1187 
1188 /*
1189  * Fork off a subshell.  If we are doing job control, give the subshell its
1190  * own process group.  Jp is a job structure that the job is to be added to.
1191  * N is the command that will be evaluated by the child.  Both jp and n may
1192  * be NULL.  The mode parameter can be one of the following:
1193  *	FORK_FG - Fork off a foreground process.
1194  *	FORK_BG - Fork off a background process.
1195  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
1196  *		     process group even if job control is on.
1197  *
1198  * When job control is turned off, background processes have their standard
1199  * input redirected to /dev/null (except for the second and later processes
1200  * in a pipeline).
1201  */
1202 
1203 int
1204 forkshell(struct job *jp, union node *n, int mode)
1205 {
1206 	pid_t pid;
1207 	int serrno;
1208 
1209 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
1210 	    JNUM(jp), n, mode));
1211 
1212 	switch ((pid = fork())) {
1213 	case -1:
1214 		serrno = errno;
1215 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
1216 		error("Cannot fork (%s)", strerror(serrno));
1217 		break;
1218 	case 0:
1219 		SHELL_FORKED();
1220 		forkchild(jp, n, mode, 0);
1221 		return 0;
1222 	default:
1223 		return forkparent(jp, n, mode, pid);
1224 	}
1225 }
1226 
1227 int
1228 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
1229 {
1230 	int pgrp = 0;
1231 
1232 	if (rootshell && mode != FORK_NOJOB && mflag) {
1233 		/*
1234 		 * The process group ID must always be that of the
1235 		 * first process created for the job.   If this proc
1236 		 * is the first, that's us, otherwise the pgrp has
1237 		 * already been determined.
1238 		 */
1239 		if (jp == NULL || jp->nprocs == 0)
1240 			pgrp = pid;
1241 		else
1242 			pgrp = jp->pgrp;
1243 		/* This can fail because we are doing it in the child also */
1244 		(void)setpgid(pid, pgrp);
1245 	}
1246 	if (mode == FORK_BG)
1247 		backgndpid = pid;		/* set $! */
1248 	if (jp) {
1249 		struct procstat *ps = &jp->ps[jp->nprocs++];
1250 		ps->pid = pid;
1251 		ps->status = -1;
1252 		ps->cmd[0] = 0;
1253 		jp->pgrp = pgrp;	/* 0 if !mflag */
1254 		if (/* iflag && rootshell && */ n)
1255 			commandtext(ps, n);
1256 	}
1257 	CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
1258 	return pid;
1259 }
1260 
1261 void
1262 forkchild(struct job *jp, union node *n, int mode, int vforked)
1263 {
1264 	int wasroot;
1265 	int pgrp;
1266 	const char *devnull = _PATH_DEVNULL;
1267 	const char *nullerr = "Can't open %s";
1268 
1269 	wasroot = rootshell;
1270 	CTRACE(DBG_JOBS, ("Child shell %d %sforked from %d (mode %d)\n",
1271 	    getpid(), vforked?"v":"", getppid(), mode));
1272 
1273 	if (!vforked) {
1274 		rootshell = 0;
1275 		handler = &main_handler;
1276 	}
1277 
1278 	closescript(vforked);
1279 	clear_traps(vforked);
1280 #if JOBS
1281 	if (!vforked)
1282 		jobctl = 0;		/* do job control only in root shell */
1283 	if (wasroot && mode != FORK_NOJOB && mflag) {
1284 		if (jp == NULL || jp->nprocs == 0)
1285 			pgrp = getpid();
1286 		else
1287 			pgrp = jp->ps[0].pid;
1288 		/* This can fail because we are doing it in the parent also */
1289 		(void)setpgid(0, pgrp);
1290 		if (mode == FORK_FG) {
1291 			if (tcsetpgrp(ttyfd, pgrp) == -1)
1292 				error("Cannot set tty process group (%s) at %d",
1293 				    strerror(errno), __LINE__);
1294 		}
1295 		setsignal(SIGTSTP, vforked);
1296 		setsignal(SIGTTOU, vforked);
1297 	} else if (mode == FORK_BG) {
1298 		ignoresig(SIGINT, vforked);
1299 		ignoresig(SIGQUIT, vforked);
1300 		if ((jp == NULL || jp->nprocs == 0) &&
1301 		    ! fd0_redirected_p ()) {
1302 			close(0);
1303 			if (open(devnull, O_RDONLY) != 0)
1304 				error(nullerr, devnull);
1305 		}
1306 	}
1307 #else
1308 	if (mode == FORK_BG) {
1309 		ignoresig(SIGINT, vforked);
1310 		ignoresig(SIGQUIT, vforked);
1311 		if ((jp == NULL || jp->nprocs == 0) &&
1312 		    ! fd0_redirected_p ()) {
1313 			close(0);
1314 			if (open(devnull, O_RDONLY) != 0)
1315 				error(nullerr, devnull);
1316 		}
1317 	}
1318 #endif
1319 	if (wasroot && iflag) {
1320 		setsignal(SIGINT, vforked);
1321 		setsignal(SIGQUIT, vforked);
1322 		setsignal(SIGTERM, vforked);
1323 	}
1324 
1325 	if (!vforked)
1326 		jobs_invalid = 1;
1327 }
1328 
1329 /*
1330  * Wait for job to finish.
1331  *
1332  * Under job control we have the problem that while a child process is
1333  * running interrupts generated by the user are sent to the child but not
1334  * to the shell.  This means that an infinite loop started by an inter-
1335  * active user may be hard to kill.  With job control turned off, an
1336  * interactive user may place an interactive program inside a loop.  If
1337  * the interactive program catches interrupts, the user doesn't want
1338  * these interrupts to also abort the loop.  The approach we take here
1339  * is to have the shell ignore interrupt signals while waiting for a
1340  * foreground process to terminate, and then send itself an interrupt
1341  * signal if the child process was terminated by an interrupt signal.
1342  * Unfortunately, some programs want to do a bit of cleanup and then
1343  * exit on interrupt; unless these processes terminate themselves by
1344  * sending a signal to themselves (instead of calling exit) they will
1345  * confuse this approach.
1346  */
1347 
1348 int
1349 waitforjob(struct job *jp)
1350 {
1351 #if JOBS
1352 	int mypgrp = getpgrp();
1353 #endif
1354 	int status;
1355 	int st;
1356 
1357 	INTOFF;
1358 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", JNUM(jp)));
1359 	while (jp->state == JOBRUNNING) {
1360 		dowait(WBLOCK, jp, NULL);
1361 	}
1362 #if JOBS
1363 	if (jp->jobctl) {
1364 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
1365 			error("Cannot set tty process group (%s) at %d",
1366 			    strerror(errno), __LINE__);
1367 	}
1368 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
1369 		set_curjob(jp, 2);
1370 #endif
1371 	status = jobstatus(jp, 1);
1372 
1373 	/* convert to 8 bits */
1374 	if (WIFEXITED(status))
1375 		st = WEXITSTATUS(status);
1376 #if JOBS
1377 	else if (WIFSTOPPED(status))
1378 		st = WSTOPSIG(status) + 128;
1379 #endif
1380 	else
1381 		st = WTERMSIG(status) + 128;
1382 
1383 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
1384 		JNUM(jp), jp->nprocs, status, st));
1385 #if JOBS
1386 	if (jp->jobctl) {
1387 		/*
1388 		 * This is truly gross.
1389 		 * If we're doing job control, then we did a TIOCSPGRP which
1390 		 * caused us (the shell) to no longer be in the controlling
1391 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
1392 		 * intuit from the subprocess exit status whether a SIGINT
1393 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
1394 		 */
1395 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1396 			raise(SIGINT);
1397 	}
1398 #endif
1399 	if (! JOBS || jp->state == JOBDONE)
1400 		freejob(jp);
1401 	INTON;
1402 	return st;
1403 }
1404 
1405 
1406 
1407 /*
1408  * Wait for a process (any process) to terminate.
1409  *
1410  * If "job" is given (not NULL), then its jobcontrol status (and mflag)
1411  * are used to determine if we wait for stopping/continuing processes or
1412  * only terminating ones, and the decision whether to report to stdout
1413  * or not varies depending what happened, and whether the affected job
1414  * is the one that was requested or not.
1415  *
1416  * If "changed" is not NULL, then the job which changed because a
1417  * process terminated/stopped will be reported by setting *changed,
1418  * if there is any such job, otherwise we set *changed = NULL.
1419  */
1420 
1421 STATIC int
1422 dowait(int flags, struct job *job, struct job **changed)
1423 {
1424 	int pid;
1425 	int status;
1426 	struct procstat *sp;
1427 	struct job *jp;
1428 	struct job *thisjob;
1429 	int done;
1430 	int stopped;
1431 	int err;
1432 
1433 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called for job %d%s\n",
1434 	    flags, JNUM(job), changed ? " [report change]" : ""));
1435 
1436 	if (changed != NULL)
1437 		*changed = NULL;
1438 
1439 	/*
1440 	 * First deal with the kernel, collect info on any (one) of our
1441 	 * children that has changed state since we last asked.
1442 	 * (loop if we're interrupted by a signal that we aren't processing)
1443 	 */
1444 	do {
1445 		err = 0;
1446 		pid = waitproc(flags & WBLOCK, job, &status);
1447 		if (pid == -1)
1448 			err = errno;
1449 		VTRACE(DBG_JOBS|DBG_PROCS,
1450 		    ("wait returns pid %d (e:%d), status %#x (ps=%d)\n",
1451 		    pid, err, status, pendingsigs));
1452 	} while (pid == -1 && err == EINTR && pendingsigs == 0);
1453 
1454 	/*
1455 	 * if nothing exited/stopped/..., we have nothing else to do
1456 	 */
1457 	if (pid <= 0)
1458 		return pid;
1459 
1460 	/*
1461 	 * Otherwise, try to find the process, somewhere in our job table
1462 	 */
1463 	INTOFF;
1464 	thisjob = NULL;
1465 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1466 		if (jp->used) {
1467 			/*
1468 			 * For each job that is in use (this is one)
1469 			 */
1470 			done = 1;	/* assume it is finished */
1471 			stopped = 1;	/* and has stopped */
1472 
1473 			/*
1474 			 * Now scan all our child processes of the job
1475 			 */
1476 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1477 				if (sp->pid == -1)
1478 					continue;
1479 				/*
1480 				 * If the process that changed is the one
1481 				 * we're looking at, and it was previously
1482 				 * running (-1) or was stopped (anything else
1483 				 * and it must have already finished earlier,
1484 				 * so cannot be the process that just changed)
1485 				 * then we update its status
1486 				 */
1487 				if (sp->pid == pid &&
1488 				  (sp->status==-1 || WIFSTOPPED(sp->status))) {
1489 					VTRACE(DBG_JOBS | DBG_PROCS,
1490 			("Job %d: changing status of proc %d from %#x to ",
1491 					    JNUM(jp), pid, sp->status));
1492 
1493 					/*
1494 					 * If the process continued,
1495 					 * then update its status to running
1496 					 * and mark the job running as well.
1497 					 *
1498 					 * If it was anything but running
1499 					 * before, flag it as a change for
1500 					 * reporting purposes later
1501 					 */
1502 					if (WIFCONTINUED(status)) {
1503 						if (sp->status != -1)
1504 							jp->flags |= JOBCHANGED;
1505 						sp->status = -1;
1506 						jp->state = JOBRUNNING;
1507 						VTRACE(DBG_JOBS|DBG_PROCS,
1508 						    ("running\n"));
1509 					} else {
1510 						/* otherwise update status */
1511 						sp->status = status;
1512 						VTRACE(DBG_JOBS|DBG_PROCS,
1513 						    ("%#x\n", status));
1514 					}
1515 
1516 					/*
1517 					 * We now know the affected job
1518 					 */
1519 					thisjob = jp;
1520 					if (changed != NULL)
1521 						*changed = jp;
1522 				}
1523 				/*
1524 				 * After any update that might have just
1525 				 * happened, if this process is running,
1526 				 * the job is not stopped, or if the process
1527 				 * simply stopped (not terminated) then the
1528 				 * job is certainly not completed (done).
1529 				 */
1530 				if (sp->status == -1)
1531 					stopped = 0;
1532 				else if (WIFSTOPPED(sp->status))
1533 					done = 0;
1534 			}
1535 
1536 			/*
1537 			 * Once we have examined all processes for the
1538 			 * job, if we still show it as stopped, then...
1539 			 */
1540 			if (stopped) {		/* stopped or done */
1541 				/*
1542 				 * it might be stopped, or finished, decide:
1543 				 */
1544 				int state = done ? JOBDONE : JOBSTOPPED;
1545 
1546 				/*
1547 				 * If that wasn't the same as it was before
1548 				 * then update its state, and if it just
1549 				 * completed, make it be the current job (%%)
1550 				 */
1551 				if (jp->state != state) {
1552 					VTRACE(DBG_JOBS,
1553 				("Job %d: changing state from %d to %d\n",
1554 					    JNUM(jp), jp->state, state));
1555 					jp->state = state;
1556 #if JOBS
1557 					if (done)
1558 						set_curjob(jp, 0);
1559 #endif
1560 				}
1561 			}
1562 		}
1563 	}
1564 
1565 	/*
1566 	 * Now we have scanned all jobs.   If we found the job that
1567 	 * the process that changed state belonged to (we occasionally
1568 	 * fork processes without associating them with a job, when one
1569 	 * of those finishes, we simply ignore it, the zombie has been
1570 	 * cleaned up, which is all that matters) then we need to
1571 	 * determine if we should say something about it to stdout
1572 	 */
1573 
1574 	if (thisjob &&
1575 	    (thisjob->state != JOBRUNNING || thisjob->flags & JOBCHANGED)) {
1576 		int mode = 0;
1577 
1578 		if (!rootshell || !iflag)
1579 			mode = SHOW_SIGNALLED;
1580 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
1581 		    job != thisjob)
1582 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
1583 		if (mode && (flags & WSILENT) == 0)
1584 			showjob(out2, thisjob, mode);
1585 		else {
1586 			VTRACE(DBG_JOBS,
1587 			    ("Not printing status for %p [%d], "
1588 			     "mode=%#x rootshell=%d, job=%p [%d]\n",
1589 			    thisjob, JNUM(thisjob), mode, rootshell,
1590 			    job, JNUM(job)));
1591 			thisjob->flags |= JOBCHANGED;
1592 		}
1593 	}
1594 
1595 	INTON;
1596 	/*
1597 	 * Finally tell our caller that something happened (in general all
1598 	 * anyone tests for is <= 0 (or >0) so the actual pid value here
1599 	 * doesn't matter much, but we know pid is >0 so we may as well
1600 	 * give back something meaningful
1601 	 */
1602 	return pid;
1603 }
1604 
1605 
1606 
1607 /*
1608  * Do a wait system call.  If job control is compiled in, we accept
1609  * stopped processes.  If block is zero, we return a value of zero
1610  * rather than blocking.
1611  *
1612  * System V doesn't have a non-blocking wait system call.  It does
1613  * have a SIGCLD signal that is sent to a process when one of its
1614  * children dies.  The obvious way to use SIGCLD would be to install
1615  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
1616  * was received, and have waitproc bump another counter when it got
1617  * the status of a process.  Waitproc would then know that a wait
1618  * system call would not block if the two counters were different.
1619  * This approach doesn't work because if a process has children that
1620  * have not been waited for, System V will send it a SIGCLD when it
1621  * installs a signal handler for SIGCLD.  What this means is that when
1622  * a child exits, the shell will be sent SIGCLD signals continuously
1623  * until is runs out of stack space, unless it does a wait call before
1624  * restoring the signal handler.  The code below takes advantage of
1625  * this (mis)feature by installing a signal handler for SIGCLD and
1626  * then checking to see whether it was called.  If there are any
1627  * children to be waited for, it will be.
1628  *
1629  * If neither SYSV nor BSD is defined, we don't implement nonblocking
1630  * waits at all.  In this case, the user will not be informed when
1631  * a background process ends until the next time she runs a real program
1632  * (as opposed to running a builtin command or just typing return),
1633  * and the jobs command may give out of date information.
1634  */
1635 
1636 #ifdef SYSV
1637 STATIC int gotsigchild;
1638 
1639 STATIC int onsigchild() {
1640 	gotsigchild = 1;
1641 }
1642 #endif
1643 
1644 
1645 STATIC int
1646 waitproc(int block, struct job *jp, int *status)
1647 {
1648 #ifdef BSD
1649 	int flags = 0;
1650 
1651 #if JOBS
1652 	if (mflag || (jp != NULL && jp->jobctl))
1653 		flags |= WUNTRACED | WCONTINUED;
1654 #endif
1655 	if (block == 0)
1656 		flags |= WNOHANG;
1657 	VTRACE(DBG_WAIT, ("waitproc: doing waitpid(flags=%#x)\n", flags));
1658 	return waitpid(-1, status, flags);
1659 #else
1660 #ifdef SYSV
1661 	int (*save)();
1662 
1663 	if (block == 0) {
1664 		gotsigchild = 0;
1665 		save = signal(SIGCLD, onsigchild);
1666 		signal(SIGCLD, save);
1667 		if (gotsigchild == 0)
1668 			return 0;
1669 	}
1670 	return wait(status);
1671 #else
1672 	if (block == 0)
1673 		return 0;
1674 	return wait(status);
1675 #endif
1676 #endif
1677 }
1678 
1679 /*
1680  * return 1 if there are stopped jobs, otherwise 0
1681  */
1682 int job_warning = 0;
1683 int
1684 stoppedjobs(void)
1685 {
1686 	int jobno;
1687 	struct job *jp;
1688 
1689 	if (job_warning || jobs_invalid)
1690 		return (0);
1691 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1692 		if (jp->used == 0)
1693 			continue;
1694 		if (jp->state == JOBSTOPPED) {
1695 			out2str("You have stopped jobs.\n");
1696 			job_warning = 2;
1697 			return (1);
1698 		}
1699 	}
1700 
1701 	return (0);
1702 }
1703 
1704 /*
1705  * Return a string identifying a command (to be printed by the
1706  * jobs command).
1707  */
1708 
1709 STATIC char *cmdnextc;
1710 STATIC int cmdnleft;
1711 
1712 void
1713 commandtext(struct procstat *ps, union node *n)
1714 {
1715 	int len;
1716 
1717 	cmdnextc = ps->cmd;
1718 	if (iflag || mflag || sizeof(ps->cmd) <= 60)
1719 		len = sizeof(ps->cmd);
1720 	else if (sizeof ps->cmd <= 400)
1721 		len = 50;
1722 	else if (sizeof ps->cmd <= 800)
1723 		len = 80;
1724 	else
1725 		len = sizeof(ps->cmd) / 10;
1726 	cmdnleft = len;
1727 	(void)cmdtxt(n, 1);
1728 	if (cmdnleft <= 0) {
1729 		char *p = ps->cmd + len - 4;
1730 		p[0] = '.';
1731 		p[1] = '.';
1732 		p[2] = '.';
1733 		p[3] = 0;
1734 	} else
1735 		*cmdnextc = '\0';
1736 
1737 	VTRACE(DBG_JOBS,
1738 	    ("commandtext: ps->cmd %p, end %p, left %d\n\t\"%s\"\n",
1739 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
1740 }
1741 
1742 
1743 /*
1744  * Generate a string describing tree node n & its descendants (recursive calls)
1745  *
1746  * Return true (non-zero) if the output is complete (ends with an operator)
1747  * so no ';' need be added before the following command.  Return false (zero)
1748  * if a ';' is needed to terminate the output if it is followed by something
1749  * which is not an operator.
1750  */
1751 STATIC int
1752 cmdtxt(union node *n, int top)
1753 {
1754 	union node *np;
1755 	struct nodelist *lp;
1756 	const char *p;
1757 	int i;
1758 
1759 	if (n == NULL || cmdnleft <= 0)
1760 		return 1;
1761 	switch (n->type) {
1762 	case NSEMI:
1763 		if (!cmdtxt(n->nbinary.ch1, 0))
1764 			cmdputs(";");
1765 		cmdputs(" ");
1766 		return cmdtxt(n->nbinary.ch2, 0);
1767 	case NAND:
1768 		(void)cmdtxt(n->nbinary.ch1, 0);
1769 		cmdputs(" && ");
1770 		return cmdtxt(n->nbinary.ch2, 0);
1771 	case NOR:
1772 		(void) cmdtxt(n->nbinary.ch1, 0);
1773 		cmdputs(" || ");
1774 		return cmdtxt(n->nbinary.ch2, 0);
1775 	case NDNOT:
1776 		cmdputs("! ");
1777 		/* FALLTHROUGH */
1778 	case NNOT:
1779 		cmdputs("! ");
1780 		return cmdtxt(n->nnot.com, 0);
1781 		break;
1782 	case NPIPE:
1783 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1784 			(void) cmdtxt(lp->n, 0);
1785 			if (lp->next)
1786 				cmdputs(" | ");
1787 		}
1788 		if (!top && n->npipe.backgnd) {
1789 			cmdputs(" &");
1790 			return 1;
1791 		}
1792 		return 0;
1793 	case NSUBSHELL:
1794 		cmdputs("(");
1795 		(void) cmdtxt(n->nredir.n, 0);
1796 		cmdputs(")");
1797 		return 0;
1798 	case NREDIR:
1799 	case NBACKGND:
1800 		return cmdtxt(n->nredir.n, top);
1801 	case NIF:
1802 		cmdputs("if ");
1803 		if (!cmdtxt(n->nif.test, 0))
1804 			cmdputs(";");
1805 		cmdputs(" then ");
1806 		i = cmdtxt(n->nif.ifpart, 0);
1807 		if (n->nif.elsepart) {
1808 			if (i == 0)
1809 				cmdputs(";");
1810 			cmdputs(" else ");
1811 			i = cmdtxt(n->nif.elsepart, 0);
1812 		}
1813 		if (i == 0)
1814 			cmdputs(";");
1815 		cmdputs(" fi");
1816 		return 0;
1817 	case NWHILE:
1818 		cmdputs("while ");
1819 		goto until;
1820 	case NUNTIL:
1821 		cmdputs("until ");
1822  until:
1823 		if (!cmdtxt(n->nbinary.ch1, 0))
1824 			cmdputs(";");
1825 		cmdputs(" do ");
1826 		if (!cmdtxt(n->nbinary.ch2, 0))
1827 			cmdputs(";");
1828 		cmdputs(" done");
1829 		return 0;
1830 	case NFOR:
1831 		cmdputs("for ");
1832 		cmdputs(n->nfor.var);
1833 		cmdputs(" in ");
1834 		cmdlist(n->nfor.args, 1);
1835 		cmdputs("; do ");
1836 		if (!cmdtxt(n->nfor.body, 0))
1837 			cmdputs(";");
1838 		cmdputs(" done");
1839 		return 0;
1840 	case NCASE:
1841 		cmdputs("case ");
1842 		cmdputs(n->ncase.expr->narg.text);
1843 		cmdputs(" in ");
1844 		for (np = n->ncase.cases; np; np = np->nclist.next) {
1845 			(void) cmdtxt(np->nclist.pattern, 0);
1846 			cmdputs(") ");
1847 			(void) cmdtxt(np->nclist.body, 0);
1848 			switch (n->type) {	/* switch (not if) for later */
1849 			case NCLISTCONT:
1850 				cmdputs(" ;& ");
1851 				break;
1852 			default:
1853 				cmdputs(" ;; ");
1854 				break;
1855 			}
1856 		}
1857 		cmdputs("esac");
1858 		return 0;
1859 	case NDEFUN:
1860 		cmdputs(n->narg.text);
1861 		cmdputs("() { ... }");
1862 		return 0;
1863 	case NCMD:
1864 		cmdlist(n->ncmd.args, 1);
1865 		cmdlist(n->ncmd.redirect, 0);
1866 		if (!top && n->ncmd.backgnd) {
1867 			cmdputs(" &");
1868 			return 1;
1869 		}
1870 		return 0;
1871 	case NARG:
1872 		cmdputs(n->narg.text);
1873 		return 0;
1874 	case NTO:
1875 		p = ">";  i = 1;  goto redir;
1876 	case NCLOBBER:
1877 		p = ">|";  i = 1;  goto redir;
1878 	case NAPPEND:
1879 		p = ">>";  i = 1;  goto redir;
1880 	case NTOFD:
1881 		p = ">&";  i = 1;  goto redir;
1882 	case NFROM:
1883 		p = "<";  i = 0;  goto redir;
1884 	case NFROMFD:
1885 		p = "<&";  i = 0;  goto redir;
1886 	case NFROMTO:
1887 		p = "<>";  i = 0;  goto redir;
1888  redir:
1889 		if (n->nfile.fd != i)
1890 			cmdputi(n->nfile.fd);
1891 		cmdputs(p);
1892 		if (n->type == NTOFD || n->type == NFROMFD) {
1893 			if (n->ndup.dupfd < 0)
1894 				cmdputs("-");
1895 			else
1896 				cmdputi(n->ndup.dupfd);
1897 		} else {
1898 			(void) cmdtxt(n->nfile.fname, 0);
1899 		}
1900 		return 0;
1901 	case NHERE:
1902 	case NXHERE:
1903 		cmdputs("<<...");
1904 		return 0;
1905 	default:
1906 		cmdputs("???");
1907 		return 0;
1908 	}
1909 	return 0;
1910 }
1911 
1912 STATIC void
1913 cmdlist(union node *np, int sep)
1914 {
1915 	for (; np; np = np->narg.next) {
1916 		if (!sep)
1917 			cmdputs(" ");
1918 		(void) cmdtxt(np, 0);
1919 		if (sep && np->narg.next)
1920 			cmdputs(" ");
1921 	}
1922 }
1923 
1924 
1925 STATIC void
1926 cmdputs(const char *s)
1927 {
1928 	const char *p, *str = 0;
1929 	char c, cc[2] = " ";
1930 	char *nextc;
1931 	int nleft;
1932 	int subtype = 0;
1933 	int quoted = 0;
1934 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
1935 					"#", "##", "%", "%%", "}" };
1936 
1937 	p = s;
1938 	nextc = cmdnextc;
1939 	nleft = cmdnleft;
1940 	while (nleft > 0 && (c = *p++) != 0) {
1941 		switch (c) {
1942 		case CTLNONL:
1943 			c = '\0';
1944 			break;
1945 		case CTLESC:
1946 			c = *p++;
1947 			break;
1948 		case CTLVAR:
1949 			subtype = *p++;
1950 			if (subtype & VSLINENO) {	/* undo LINENO hack */
1951 				if ((subtype & VSTYPE) == VSLENGTH)
1952 					str = "${#LINENO";	/*}*/
1953 				else
1954 					str = "${LINENO";	/*}*/
1955 				while (is_digit(*p))
1956 					p++;
1957 			} else if ((subtype & VSTYPE) == VSLENGTH)
1958 				str = "${#"; /*}*/
1959 			else
1960 				str = "${"; /*}*/
1961 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
1962 				quoted ^= 1;
1963 				c = '"';
1964 			} else {
1965 				c = *str++;
1966 			}
1967 			break;
1968 		case CTLENDVAR:		/*{*/
1969 			c = '}';
1970 			if (quoted & 1)
1971 				str = "\"";
1972 			quoted >>= 1;
1973 			subtype = 0;
1974 			break;
1975 		case CTLBACKQ:
1976 			c = '$';
1977 			str = "(...)";
1978 			break;
1979 		case CTLBACKQ+CTLQUOTE:
1980 			c = '"';
1981 			str = "$(...)\"";
1982 			break;
1983 		case CTLARI:
1984 			c = '$';
1985 			if (*p == ' ')
1986 				p++;
1987 			str = "((";	/*))*/
1988 			break;
1989 		case CTLENDARI:		/*((*/
1990 			c = ')';
1991 			str = ")";
1992 			break;
1993 		case CTLQUOTEMARK:
1994 			quoted ^= 1;
1995 			c = '"';
1996 			break;
1997 		case CTLQUOTEEND:
1998 			quoted >>= 1;
1999 			c = '"';
2000 			break;
2001 		case '=':
2002 			if (subtype == 0)
2003 				break;
2004 			str = vstype[subtype & VSTYPE];
2005 			if (subtype & VSNUL)
2006 				c = ':';
2007 			else
2008 				c = *str++;		/*{*/
2009 			if (c != '}')
2010 				quoted <<= 1;
2011 			else if (*p == CTLENDVAR)
2012 				c = *str++;
2013 			subtype = 0;
2014 			break;
2015 		case '\'':
2016 		case '\\':
2017 		case '"':
2018 		case '$':
2019 			/* These can only happen inside quotes */
2020 			cc[0] = c;
2021 			str = cc;
2022 			c = '\\';
2023 			break;
2024 		default:
2025 			break;
2026 		}
2027 		if (c != '\0') do {	/* c == 0 implies nothing in str */
2028 			*nextc++ = c;
2029 		} while (--nleft > 0 && str && (c = *str++));
2030 		str = 0;
2031 	}
2032 	if ((quoted & 1) && nleft) {
2033 		*nextc++ = '"';
2034 		nleft--;
2035 	}
2036 	cmdnleft = nleft;
2037 	cmdnextc = nextc;
2038 }
2039