xref: /netbsd-src/bin/sh/jobs.c (revision d1c86d363ded009f6c33bcf689f64a39b49f56b7)
1 /*	$NetBSD: jobs.c,v 1.123 2024/10/09 13:43:32 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.123 2024/10/09 13:43:32 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 #if JOBS
984 #ifndef SMALL
985 
986 static int
987 stop_me(int sig, int force, int pgrp, pid_t pid)
988 {
989 	if (force || (!loginsh && mflag && rootshell)) {
990 		struct sigaction sig_dfl, sig_was;
991 
992 		sig_dfl.sa_handler = SIG_DFL;
993 		sig_dfl.sa_flags = 0;
994 		sigemptyset(&sig_dfl.sa_mask);
995 
996 		(void)sigaction(sig, &sig_dfl, &sig_was);
997 
998 		if (kill(pgrp ? 0 : pid, sig) == -1) {
999 			sh_warn("suspend myself");
1000 			(void)sigaction(sig, &sig_was, NULL);
1001 			error(NULL);
1002 		}
1003 
1004 		(void)sigaction(sig, &sig_was, NULL);
1005 
1006 		return 0;
1007 	}
1008 
1009 	if (!rootshell)
1010 		sh_warnx("subshell environment");
1011 	else if (!mflag)
1012 		sh_warnx("job control disabled");
1013 	else if (loginsh)
1014 		sh_warnx("login shell");
1015 	else
1016 		sh_warnx("not possible??");
1017 
1018 	return 1;
1019 }
1020 
1021 int
1022 suspendcmd(int argc, char **argv)
1023 {
1024 	int sig = SIGTSTP;
1025 	int force = 0;
1026 	int pgrp = 0;
1027 	int status = 0;
1028 	char *target;
1029 	int c;
1030 
1031 	while ((c = nextopt("fgs:")) != 0) {
1032 		switch (c) {
1033 		case 'f':
1034 			force = 1;
1035 			break;
1036 		case 'g':
1037 			pgrp = 1;
1038 			break;
1039 		case 's':
1040 			sig = signame_to_signum(optionarg);
1041 
1042 			if (sig != SIGSTOP && sig != SIGTSTP &&
1043 			    sig != SIGTTIN && sig != SIGTTOU)
1044 				error("bad signal '%s'", optionarg);
1045 			break;
1046 		}
1047 	}
1048 
1049 	if (!*argptr)		/* suspend myself */
1050 		return stop_me(sig, force, pgrp, getpid());
1051 
1052 	while ((target = *argptr++) != NULL)
1053 	{
1054 		int pid;
1055 
1056 		if (is_number(target)) {
1057 			if ((pid = number(target)) == 0) {
1058 				sh_warnx("Cannot (yet) suspend kernel (%s)",
1059 				    target);
1060 				status = 1;
1061 				continue;
1062 			}
1063 		} else if ((pid = getjobpgrp(target)) == 0) {
1064 			sh_warnx("Unknown job: %s", target);
1065 			status = 1;
1066 			continue;
1067 		}
1068 
1069 		if (pid == rootpid || pid == getpid()) {
1070 			status |= stop_me(sig, force, pgrp, pid);
1071 			continue;
1072 		}
1073 
1074 		if (pid == 1 || pid == -1) {
1075 			sh_warnx("Don't be funny");
1076 			status = 1;
1077 			continue;
1078 		}
1079 
1080 		if (pid > 0 && pgrp)
1081 			pid = -pid;
1082 
1083 		if (kill(pid, sig) == -1) {
1084 			sh_warn("failed to suspend %s", target);
1085 			status = 1;
1086 		}
1087 	}
1088 
1089 	return status;
1090 }
1091 #endif	/* SMALL */
1092 #endif	/* JOBS */
1093 
1094 int
1095 getjobpgrp(const char *name)
1096 {
1097 	struct job *jp;
1098 
1099 	if (jobs_invalid)
1100 		return 0;
1101 	jp = getjob(name, 1);
1102 	if (jp == 0)
1103 		return 0;
1104 	return -jp->pgrp;
1105 }
1106 
1107 /*
1108  * Convert a job name to a job structure.
1109  */
1110 
1111 STATIC struct job *
1112 getjob(const char *name, int noerror)
1113 {
1114 	int jobno = -1;
1115 	struct job *jp;
1116 	int pid;
1117 	int i;
1118 	const char *err_msg = "No such job: %s";
1119 
1120 	if (name == NULL) {
1121 #if JOBS
1122 		jobno = curjob;
1123 #endif
1124 		err_msg = "No current job";
1125 	} else if (name[0] == '%') {
1126 		if (is_number(name + 1)) {
1127 			jobno = number(name + 1) - 1;
1128 		} else if (!name[1] || !name[2]) {
1129 			switch (name[1]) {
1130 #if JOBS
1131 			case 0:
1132 			case '+':
1133 			case '%':
1134 				jobno = curjob;
1135 				err_msg = "No current job";
1136 				break;
1137 			case '-':
1138 				jobno = curjob;
1139 				if (jobno != -1)
1140 					jobno = jobtab[jobno].prev_job;
1141 				err_msg = "No previous job";
1142 				break;
1143 #endif
1144 			default:
1145 				goto check_pattern;
1146 			}
1147 		} else {
1148 			struct job *found;
1149     check_pattern:
1150 			found = NULL;
1151 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
1152 				if (!jp->used || jp->nprocs <= 0)
1153 					continue;
1154 				if ((name[1] == '?'
1155 					&& strstr(jp->ps[0].cmd, name + 2))
1156 				    || prefix(name + 1, jp->ps[0].cmd)) {
1157 					if (found) {
1158 						err_msg = "%s: ambiguous";
1159 						found = 0;
1160 						break;
1161 					}
1162 					found = jp;
1163 				}
1164 			}
1165 			if (found)
1166 				return found;
1167 		}
1168 
1169 	} else if (is_number(name)) {
1170 		pid = number(name);
1171 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
1172 			if (jp->used && jp->nprocs > 0
1173 			 && jp->ps[jp->nprocs - 1].pid == pid)
1174 				return jp;
1175 		}
1176 	}
1177 
1178 	if (jobno >= 0 && jobno < njobs) {
1179 		jp = jobtab + jobno;
1180 		if (jp->used)
1181 			return jp;
1182 	}
1183 	if (!noerror)
1184 		error(err_msg, name);
1185 	return 0;
1186 }
1187 
1188 
1189 /*
1190  * Find out if there are any running (that is, unwaited upon)
1191  * background children of the current shell.
1192  *
1193  * Return 1/0 (yes, no).
1194  *
1195  * Needed as we cannot optimise away sub-shell creation if
1196  * we have such a child, or a "wait" in that sub-shell would
1197  * observe the already existing job.
1198  */
1199 int
1200 anyjobs(void)
1201 {
1202 	struct job *jp;
1203 	int i;
1204 
1205 	if (jobs_invalid)
1206 		return 0;
1207 
1208 	for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
1209 		if (jp->used)
1210 			return 1;
1211 	}
1212 
1213 	return 0;
1214 }
1215 
1216 /*
1217  * Output the (new) POSIX required "[%d] %d" string whenever an
1218  * async (ie: background) job is started in an interactive shell.
1219  * Note that a subshell environment is not regarded as interactive.
1220  */
1221 void
1222 jobstarted(struct job *jp)
1223 {
1224 	if (!iflag || !rootshell)
1225 		return;
1226 
1227 	outfmt(out2, "[%d] %ld\n", JNUM(jp),
1228 	    jp->pgrp != 0 ? (long)jp->pgrp : (long)jp->ps->pid);
1229 }
1230 
1231 /*
1232  * Return a new job structure,
1233  */
1234 
1235 struct job *
1236 makejob(union node *node, int nprocs)
1237 {
1238 	int i;
1239 	struct job *jp;
1240 
1241 	if (jobs_invalid) {
1242 		VTRACE(DBG_JOBS, ("makejob(%p, %d) clearing jobtab (%d)\n",
1243 			(void *)node, nprocs, njobs));
1244 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
1245 			if (jp->used)
1246 				freejob(jp);
1247 		}
1248 		jobs_invalid = 0;
1249 	}
1250 
1251 	for (i = njobs, jp = jobtab ; ; jp++) {
1252 		if (--i < 0) {
1253 			INTOFF;
1254 			if (njobs == 0) {
1255 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
1256 			} else {
1257 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
1258 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
1259 				/* Relocate `ps' pointers */
1260 				for (i = 0; i < njobs; i++)
1261 					if (jp[i].ps == &jobtab[i].ps0)
1262 						jp[i].ps = &jp[i].ps0;
1263 				ckfree(jobtab);
1264 				jobtab = jp;
1265 			}
1266 			jp = jobtab + njobs;
1267 			for (i = 4 ; --i >= 0 ; njobs++) {
1268 				jobtab[njobs].used = 0;
1269 				jobtab[njobs].prev_job = -1;
1270 			}
1271 			INTON;
1272 			break;
1273 		}
1274 		if (jp->used == 0)
1275 			break;
1276 	}
1277 	INTOFF;
1278 	jp->state = JOBRUNNING;
1279 	jp->used = 1;
1280 	jp->flags = pipefail ? JPIPEFAIL : 0;
1281 	jp->nprocs = 0;
1282 	jp->pgrp = 0;
1283 #if JOBS
1284 	jp->jobctl = jobctl;
1285 	set_curjob(jp, 1);
1286 #endif
1287 	if (nprocs > 1) {
1288 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
1289 	} else {
1290 		jp->ps = &jp->ps0;
1291 	}
1292 	INTON;
1293 	VTRACE(DBG_JOBS, ("makejob(%p, %d)%s returns %%%d\n", (void *)node,
1294 	    nprocs, (jp->flags & JPIPEFAIL) ? " PF" : "", JNUM(jp)));
1295 	return jp;
1296 }
1297 
1298 
1299 /*
1300  * Fork off a subshell.  If we are doing job control, give the subshell its
1301  * own process group.  Jp is a job structure that the job is to be added to.
1302  * N is the command that will be evaluated by the child.  Both jp and n may
1303  * be NULL.  The mode parameter can be one of the following:
1304  *	FORK_FG - Fork off a foreground process.
1305  *	FORK_BG - Fork off a background process.
1306  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
1307  *		     process group even if job control is on.
1308  *
1309  * When job control is turned off, background processes have their standard
1310  * input redirected to /dev/null (except for the second and later processes
1311  * in a pipeline).
1312  */
1313 
1314 int
1315 forkshell(struct job *jp, union node *n, int mode)
1316 {
1317 	pid_t pid;
1318 	int serrno;
1319 
1320 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
1321 	    JNUM(jp), n, mode));
1322 
1323 	switch ((pid = fork())) {
1324 	case -1:
1325 		serrno = errno;
1326 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
1327 		error("Cannot fork (%s)", strerror(serrno));
1328 		break;
1329 	case 0:
1330 		SHELL_FORKED();
1331 		forkchild(jp, n, mode, 0);
1332 		return 0;
1333 	default:
1334 		return forkparent(jp, n, mode, pid);
1335 	}
1336 }
1337 
1338 int
1339 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
1340 {
1341 	int pgrp = 0;
1342 
1343 	if (rootshell && mode != FORK_NOJOB && mflag) {
1344 		/*
1345 		 * The process group ID must always be that of the
1346 		 * first process created for the job.   If this proc
1347 		 * is the first, that's us, otherwise the pgrp has
1348 		 * already been determined.
1349 		 */
1350 		if (jp == NULL || jp->nprocs == 0)
1351 			pgrp = pid;
1352 		else
1353 			pgrp = jp->pgrp;
1354 		/* This can fail because we are doing it in the child also */
1355 		(void)setpgid(pid, pgrp);
1356 	}
1357 	if (mode == FORK_BG)
1358 		backgndpid = pid;		/* set $! */
1359 	if (jp) {
1360 		struct procstat *ps = &jp->ps[jp->nprocs++];
1361 		ps->pid = pid;
1362 		ps->status = -1;
1363 		ps->cmd[0] = 0;
1364 		jp->pgrp = pgrp;	/* 0 if !mflag */
1365 		if (/* iflag && rootshell && */ n)
1366 			commandtext(ps, n);
1367 	}
1368 	CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
1369 	return pid;
1370 }
1371 
1372 void
1373 forkchild(struct job *jp, union node *n, int mode, int vforked)
1374 {
1375 	int wasroot;
1376 	int pgrp;
1377 	const char *devnull = _PATH_DEVNULL;
1378 	const char *nullerr = "Can't open %s";
1379 
1380 	wasroot = rootshell;
1381 	CTRACE(DBG_JOBS, ("Child shell %d %sforked from %d (mode %d)\n",
1382 	    getpid(), vforked?"v":"", getppid(), mode));
1383 
1384 	if (!vforked) {
1385 		rootshell = 0;
1386 		handler = &main_handler;
1387 	}
1388 
1389 	closescript(vforked);
1390 	clear_traps(vforked);
1391 #if JOBS
1392 	if (!vforked)
1393 		jobctl = 0;		/* do job control only in root shell */
1394 	if (wasroot && mode != FORK_NOJOB && mflag) {
1395 		if (jp == NULL || jp->nprocs == 0)
1396 			pgrp = getpid();
1397 		else
1398 			pgrp = jp->ps[0].pid;
1399 		/* This can fail because we are doing it in the parent also */
1400 		(void)setpgid(0, pgrp);
1401 		if (mode == FORK_FG) {
1402 			if (tcsetpgrp(ttyfd, pgrp) == -1)
1403 				error("Cannot set tty process group (%s) at %d",
1404 				    strerror(errno), __LINE__);
1405 		}
1406 		setsignal(SIGTSTP, vforked);
1407 		setsignal(SIGTTOU, vforked);
1408 	} else if (mode == FORK_BG) {
1409 		ignoresig(SIGINT, vforked);
1410 		ignoresig(SIGQUIT, vforked);
1411 		if ((jp == NULL || jp->nprocs == 0) &&
1412 		    ! fd0_redirected_p ()) {
1413 			close(0);
1414 			if (open(devnull, O_RDONLY) != 0)
1415 				error(nullerr, devnull);
1416 		}
1417 	}
1418 #else
1419 	if (mode == FORK_BG) {
1420 		ignoresig(SIGINT, vforked);
1421 		ignoresig(SIGQUIT, vforked);
1422 		if ((jp == NULL || jp->nprocs == 0) &&
1423 		    ! fd0_redirected_p ()) {
1424 			close(0);
1425 			if (open(devnull, O_RDONLY) != 0)
1426 				error(nullerr, devnull);
1427 		}
1428 	}
1429 #endif
1430 	if (wasroot && iflag) {
1431 		setsignal(SIGINT, vforked);
1432 		setsignal(SIGQUIT, vforked);
1433 		setsignal(SIGTERM, vforked);
1434 	}
1435 
1436 	if (!vforked)
1437 		jobs_invalid = 1;
1438 }
1439 
1440 /*
1441  * Wait for job to finish.
1442  *
1443  * Under job control we have the problem that while a child process is
1444  * running interrupts generated by the user are sent to the child but not
1445  * to the shell.  This means that an infinite loop started by an inter-
1446  * active user may be hard to kill.  With job control turned off, an
1447  * interactive user may place an interactive program inside a loop.  If
1448  * the interactive program catches interrupts, the user doesn't want
1449  * these interrupts to also abort the loop.  The approach we take here
1450  * is to have the shell ignore interrupt signals while waiting for a
1451  * foreground process to terminate, and then send itself an interrupt
1452  * signal if the child process was terminated by an interrupt signal.
1453  * Unfortunately, some programs want to do a bit of cleanup and then
1454  * exit on interrupt; unless these processes terminate themselves by
1455  * sending a signal to themselves (instead of calling exit) they will
1456  * confuse this approach.
1457  */
1458 
1459 int
1460 waitforjob(struct job *jp)
1461 {
1462 #if JOBS
1463 	int mypgrp = getpgrp();
1464 #endif
1465 	int status;
1466 	int st;
1467 
1468 	INTOFF;
1469 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", JNUM(jp)));
1470 	while (jp->state == JOBRUNNING) {
1471 		dowait(WBLOCK, jp, NULL);
1472 	}
1473 #if JOBS
1474 	if (jp->jobctl) {
1475 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
1476 			error("Cannot set tty process group (%s) at %d",
1477 			    strerror(errno), __LINE__);
1478 	}
1479 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
1480 		set_curjob(jp, 2);
1481 #endif
1482 	status = jobstatus(jp, 1);
1483 
1484 	/* convert to 8 bits */
1485 	if (WIFEXITED(status))
1486 		st = WEXITSTATUS(status);
1487 #if JOBS
1488 	else if (WIFSTOPPED(status))
1489 		st = WSTOPSIG(status) + 128;
1490 #endif
1491 	else
1492 		st = WTERMSIG(status) + 128;
1493 
1494 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
1495 		JNUM(jp), jp->nprocs, status, st));
1496 #if JOBS
1497 	if (jp->jobctl) {
1498 		/*
1499 		 * This is truly gross.
1500 		 * If we're doing job control, then we did a TIOCSPGRP which
1501 		 * caused us (the shell) to no longer be in the controlling
1502 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
1503 		 * intuit from the subprocess exit status whether a SIGINT
1504 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
1505 		 */
1506 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1507 			raise(SIGINT);
1508 	}
1509 #endif
1510 	if (! JOBS || jp->state == JOBDONE)
1511 		freejob(jp);
1512 	INTON;
1513 	return st;
1514 }
1515 
1516 
1517 
1518 /*
1519  * Wait for a process (any process) to terminate.
1520  *
1521  * If "job" is given (not NULL), then its jobcontrol status (and mflag)
1522  * are used to determine if we wait for stopping/continuing processes or
1523  * only terminating ones, and the decision whether to report to stdout
1524  * or not varies depending what happened, and whether the affected job
1525  * is the one that was requested or not.
1526  *
1527  * If "changed" is not NULL, then the job which changed because a
1528  * process terminated/stopped will be reported by setting *changed,
1529  * if there is any such job, otherwise we set *changed = NULL.
1530  */
1531 
1532 STATIC int
1533 dowait(int flags, struct job *job, struct job **changed)
1534 {
1535 	int pid;
1536 	int status;
1537 	struct procstat *sp;
1538 	struct job *jp;
1539 	struct job *thisjob;
1540 	int done;
1541 	int stopped;
1542 	int err;
1543 
1544 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called for job %d%s\n",
1545 	    flags, JNUM(job), changed ? " [report change]" : ""));
1546 
1547 	if (changed != NULL)
1548 		*changed = NULL;
1549 
1550 	/*
1551 	 * First deal with the kernel, collect info on any (one) of our
1552 	 * children that has changed state since we last asked.
1553 	 * (loop if we're interrupted by a signal that we aren't processing)
1554 	 */
1555 	do {
1556 		err = 0;
1557 		pid = waitproc(flags & WBLOCK, job, &status);
1558 		if (pid == -1)
1559 			err = errno;
1560 		VTRACE(DBG_JOBS|DBG_PROCS,
1561 		    ("wait returns pid %d (e:%d), status %#x (ps=%d)\n",
1562 		    pid, err, status, pendingsigs));
1563 	} while (pid == -1 && err == EINTR && pendingsigs == 0);
1564 
1565 	/*
1566 	 * if nothing exited/stopped/..., we have nothing else to do
1567 	 */
1568 	if (pid <= 0)
1569 		return pid;
1570 
1571 	/*
1572 	 * Otherwise, try to find the process, somewhere in our job table
1573 	 */
1574 	INTOFF;
1575 	thisjob = NULL;
1576 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1577 		if (jp->used) {
1578 			/*
1579 			 * For each job that is in use (this is one)
1580 			 */
1581 			done = 1;	/* assume it is finished */
1582 			stopped = 1;	/* and has stopped */
1583 
1584 			/*
1585 			 * Now scan all our child processes of the job
1586 			 */
1587 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1588 				if (sp->pid == -1)
1589 					continue;
1590 				/*
1591 				 * If the process that changed is the one
1592 				 * we're looking at, and it was previously
1593 				 * running (-1) or was stopped (anything else
1594 				 * and it must have already finished earlier,
1595 				 * so cannot be the process that just changed)
1596 				 * then we update its status
1597 				 */
1598 				if (sp->pid == pid &&
1599 				  (sp->status==-1 || WIFSTOPPED(sp->status))) {
1600 					VTRACE(DBG_JOBS | DBG_PROCS,
1601 			("Job %d: changing status of proc %d from %#x to ",
1602 					    JNUM(jp), pid, sp->status));
1603 
1604 					/*
1605 					 * If the process continued,
1606 					 * then update its status to running
1607 					 * and mark the job running as well.
1608 					 *
1609 					 * If it was anything but running
1610 					 * before, flag it as a change for
1611 					 * reporting purposes later
1612 					 */
1613 					if (WIFCONTINUED(status)) {
1614 						if (sp->status != -1)
1615 							jp->flags |= JOBCHANGED;
1616 						sp->status = -1;
1617 						jp->state = JOBRUNNING;
1618 						VTRACE(DBG_JOBS|DBG_PROCS,
1619 						    ("running\n"));
1620 					} else {
1621 						/* otherwise update status */
1622 						sp->status = status;
1623 						VTRACE(DBG_JOBS|DBG_PROCS,
1624 						    ("%#x\n", status));
1625 					}
1626 
1627 					/*
1628 					 * We now know the affected job
1629 					 */
1630 					thisjob = jp;
1631 					if (changed != NULL)
1632 						*changed = jp;
1633 				}
1634 				/*
1635 				 * After any update that might have just
1636 				 * happened, if this process is running,
1637 				 * the job is not stopped, or if the process
1638 				 * simply stopped (not terminated) then the
1639 				 * job is certainly not completed (done).
1640 				 */
1641 				if (sp->status == -1)
1642 					stopped = 0;
1643 				else if (WIFSTOPPED(sp->status))
1644 					done = 0;
1645 			}
1646 
1647 			/*
1648 			 * Once we have examined all processes for the
1649 			 * job, if we still show it as stopped, then...
1650 			 */
1651 			if (stopped) {		/* stopped or done */
1652 				/*
1653 				 * it might be stopped, or finished, decide:
1654 				 */
1655 				int state = done ? JOBDONE : JOBSTOPPED;
1656 
1657 				/*
1658 				 * If that wasn't the same as it was before
1659 				 * then update its state, and if it just
1660 				 * completed, make it be the current job (%%)
1661 				 */
1662 				if (jp->state != state) {
1663 					VTRACE(DBG_JOBS,
1664 				("Job %d: changing state from %d to %d\n",
1665 					    JNUM(jp), jp->state, state));
1666 					jp->state = state;
1667 #if JOBS
1668 					if (done)
1669 						set_curjob(jp, 0);
1670 #endif
1671 				}
1672 			}
1673 		}
1674 	}
1675 
1676 	/*
1677 	 * Now we have scanned all jobs.   If we found the job that
1678 	 * the process that changed state belonged to (we occasionally
1679 	 * fork processes without associating them with a job, when one
1680 	 * of those finishes, we simply ignore it, the zombie has been
1681 	 * cleaned up, which is all that matters) then we need to
1682 	 * determine if we should say something about it to stdout
1683 	 */
1684 
1685 	if (thisjob &&
1686 	    (thisjob->state != JOBRUNNING || thisjob->flags & JOBCHANGED)) {
1687 		int mode = 0;
1688 
1689 		if (!rootshell || !iflag)
1690 			mode = SHOW_SIGNALLED;
1691 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
1692 		    job != thisjob)
1693 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
1694 		if (mode && (flags & WSILENT) == 0)
1695 			showjob(out2, thisjob, mode);
1696 		else {
1697 			VTRACE(DBG_JOBS,
1698 			    ("Not printing status for %p [%d], "
1699 			     "mode=%#x rootshell=%d, job=%p [%d]\n",
1700 			    thisjob, JNUM(thisjob), mode, rootshell,
1701 			    job, JNUM(job)));
1702 			thisjob->flags |= JOBCHANGED;
1703 		}
1704 	}
1705 
1706 	INTON;
1707 	/*
1708 	 * Finally tell our caller that something happened (in general all
1709 	 * anyone tests for is <= 0 (or >0) so the actual pid value here
1710 	 * doesn't matter much, but we know pid is >0 so we may as well
1711 	 * give back something meaningful
1712 	 */
1713 	return pid;
1714 }
1715 
1716 
1717 
1718 /*
1719  * Do a wait system call.  If job control is compiled in, we accept
1720  * stopped processes.  If block is zero, we return a value of zero
1721  * rather than blocking.
1722  *
1723  * System V doesn't have a non-blocking wait system call.  It does
1724  * have a SIGCLD signal that is sent to a process when one of its
1725  * children dies.  The obvious way to use SIGCLD would be to install
1726  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
1727  * was received, and have waitproc bump another counter when it got
1728  * the status of a process.  Waitproc would then know that a wait
1729  * system call would not block if the two counters were different.
1730  * This approach doesn't work because if a process has children that
1731  * have not been waited for, System V will send it a SIGCLD when it
1732  * installs a signal handler for SIGCLD.  What this means is that when
1733  * a child exits, the shell will be sent SIGCLD signals continuously
1734  * until is runs out of stack space, unless it does a wait call before
1735  * restoring the signal handler.  The code below takes advantage of
1736  * this (mis)feature by installing a signal handler for SIGCLD and
1737  * then checking to see whether it was called.  If there are any
1738  * children to be waited for, it will be.
1739  *
1740  * If neither SYSV nor BSD is defined, we don't implement nonblocking
1741  * waits at all.  In this case, the user will not be informed when
1742  * a background process ends until the next time she runs a real program
1743  * (as opposed to running a builtin command or just typing return),
1744  * and the jobs command may give out of date information.
1745  */
1746 
1747 #ifdef SYSV
1748 STATIC int gotsigchild;
1749 
1750 STATIC int onsigchild() {
1751 	gotsigchild = 1;
1752 }
1753 #endif
1754 
1755 
1756 STATIC int
1757 waitproc(int block, struct job *jp, int *status)
1758 {
1759 #ifdef BSD
1760 	int flags = 0;
1761 
1762 #if JOBS
1763 	if (mflag || (jp != NULL && jp->jobctl))
1764 		flags |= WUNTRACED | WCONTINUED;
1765 #endif
1766 	if (block == 0)
1767 		flags |= WNOHANG;
1768 	VTRACE(DBG_WAIT, ("waitproc: doing waitpid(flags=%#x)\n", flags));
1769 	return waitpid(-1, status, flags);
1770 #else
1771 #ifdef SYSV
1772 	int (*save)();
1773 
1774 	if (block == 0) {
1775 		gotsigchild = 0;
1776 		save = signal(SIGCLD, onsigchild);
1777 		signal(SIGCLD, save);
1778 		if (gotsigchild == 0)
1779 			return 0;
1780 	}
1781 	return wait(status);
1782 #else
1783 	if (block == 0)
1784 		return 0;
1785 	return wait(status);
1786 #endif
1787 #endif
1788 }
1789 
1790 /*
1791  * return 1 if there are stopped jobs, otherwise 0
1792  */
1793 int job_warning = 0;
1794 int
1795 stoppedjobs(void)
1796 {
1797 	int jobno;
1798 	struct job *jp;
1799 
1800 	if (job_warning || jobs_invalid)
1801 		return (0);
1802 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1803 		if (jp->used == 0)
1804 			continue;
1805 		if (jp->state == JOBSTOPPED) {
1806 			out2str("You have stopped jobs.\n");
1807 			job_warning = 2;
1808 			return (1);
1809 		}
1810 	}
1811 
1812 	return (0);
1813 }
1814 
1815 /*
1816  * Return a string identifying a command (to be printed by the
1817  * jobs command).
1818  */
1819 
1820 STATIC char *cmdnextc;
1821 STATIC int cmdnleft;
1822 
1823 void
1824 commandtext(struct procstat *ps, union node *n)
1825 {
1826 	int len;
1827 
1828 	cmdnextc = ps->cmd;
1829 	if (iflag || mflag || sizeof(ps->cmd) <= 60)
1830 		len = sizeof(ps->cmd);
1831 	else if (sizeof ps->cmd <= 400)
1832 		len = 50;
1833 	else if (sizeof ps->cmd <= 800)
1834 		len = 80;
1835 	else
1836 		len = sizeof(ps->cmd) / 10;
1837 	cmdnleft = len;
1838 	(void)cmdtxt(n, 1);
1839 	if (cmdnleft <= 0) {
1840 		char *p = ps->cmd + len - 4;
1841 		p[0] = '.';
1842 		p[1] = '.';
1843 		p[2] = '.';
1844 		p[3] = 0;
1845 	} else
1846 		*cmdnextc = '\0';
1847 
1848 	VTRACE(DBG_JOBS,
1849 	    ("commandtext: ps->cmd %p, end %p, left %d\n\t\"%s\"\n",
1850 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
1851 }
1852 
1853 
1854 /*
1855  * Generate a string describing tree node n & its descendants (recursive calls)
1856  *
1857  * Return true (non-zero) if the output is complete (ends with an operator)
1858  * so no ';' need be added before the following command.  Return false (zero)
1859  * if a ';' is needed to terminate the output if it is followed by something
1860  * which is not an operator.
1861  */
1862 STATIC int
1863 cmdtxt(union node *n, int top)
1864 {
1865 	union node *np;
1866 	struct nodelist *lp;
1867 	const char *p;
1868 	int i;
1869 
1870 	if (n == NULL || cmdnleft <= 0)
1871 		return 1;
1872 	switch (n->type) {
1873 	case NSEMI:
1874 		if (!cmdtxt(n->nbinary.ch1, 0))
1875 			cmdputs(";");
1876 		cmdputs(" ");
1877 		return cmdtxt(n->nbinary.ch2, 0);
1878 	case NAND:
1879 		(void)cmdtxt(n->nbinary.ch1, 0);
1880 		cmdputs(" && ");
1881 		return cmdtxt(n->nbinary.ch2, 0);
1882 	case NOR:
1883 		(void) cmdtxt(n->nbinary.ch1, 0);
1884 		cmdputs(" || ");
1885 		return cmdtxt(n->nbinary.ch2, 0);
1886 	case NDNOT:
1887 		cmdputs("! ");
1888 		/* FALLTHROUGH */
1889 	case NNOT:
1890 		cmdputs("! ");
1891 		return cmdtxt(n->nnot.com, 0);
1892 		break;
1893 	case NPIPE:
1894 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1895 			(void) cmdtxt(lp->n, 0);
1896 			if (lp->next)
1897 				cmdputs(" | ");
1898 		}
1899 		if (!top && n->npipe.backgnd) {
1900 			cmdputs(" &");
1901 			return 1;
1902 		}
1903 		return 0;
1904 	case NSUBSHELL:
1905 		cmdputs("(");
1906 		(void) cmdtxt(n->nredir.n, 0);
1907 		cmdputs(")");
1908 		return 0;
1909 	case NREDIR:
1910 	case NBACKGND:
1911 		return cmdtxt(n->nredir.n, top);
1912 	case NIF:
1913 		cmdputs("if ");
1914 		if (!cmdtxt(n->nif.test, 0))
1915 			cmdputs(";");
1916 		cmdputs(" then ");
1917 		i = cmdtxt(n->nif.ifpart, 0);
1918 		if (n->nif.elsepart) {
1919 			if (i == 0)
1920 				cmdputs(";");
1921 			cmdputs(" else ");
1922 			i = cmdtxt(n->nif.elsepart, 0);
1923 		}
1924 		if (i == 0)
1925 			cmdputs(";");
1926 		cmdputs(" fi");
1927 		return 0;
1928 	case NWHILE:
1929 		cmdputs("while ");
1930 		goto until;
1931 	case NUNTIL:
1932 		cmdputs("until ");
1933  until:
1934 		if (!cmdtxt(n->nbinary.ch1, 0))
1935 			cmdputs(";");
1936 		cmdputs(" do ");
1937 		if (!cmdtxt(n->nbinary.ch2, 0))
1938 			cmdputs(";");
1939 		cmdputs(" done");
1940 		return 0;
1941 	case NFOR:
1942 		cmdputs("for ");
1943 		cmdputs(n->nfor.var);
1944 		cmdputs(" in ");
1945 		cmdlist(n->nfor.args, 1);
1946 		cmdputs("; do ");
1947 		if (!cmdtxt(n->nfor.body, 0))
1948 			cmdputs(";");
1949 		cmdputs(" done");
1950 		return 0;
1951 	case NCASE:
1952 		cmdputs("case ");
1953 		cmdputs(n->ncase.expr->narg.text);
1954 		cmdputs(" in ");
1955 		for (np = n->ncase.cases; np; np = np->nclist.next) {
1956 			(void) cmdtxt(np->nclist.pattern, 0);
1957 			cmdputs(") ");
1958 			(void) cmdtxt(np->nclist.body, 0);
1959 			switch (n->type) {	/* switch (not if) for later */
1960 			case NCLISTCONT:
1961 				cmdputs(" ;& ");
1962 				break;
1963 			default:
1964 				cmdputs(" ;; ");
1965 				break;
1966 			}
1967 		}
1968 		cmdputs("esac");
1969 		return 0;
1970 	case NDEFUN:
1971 		cmdputs(n->narg.text);
1972 		cmdputs("() { ... }");
1973 		return 0;
1974 	case NCMD:
1975 		cmdlist(n->ncmd.args, 1);
1976 		cmdlist(n->ncmd.redirect, 0);
1977 		if (!top && n->ncmd.backgnd) {
1978 			cmdputs(" &");
1979 			return 1;
1980 		}
1981 		return 0;
1982 	case NARG:
1983 		cmdputs(n->narg.text);
1984 		return 0;
1985 	case NTO:
1986 		p = ">";  i = 1;  goto redir;
1987 	case NCLOBBER:
1988 		p = ">|";  i = 1;  goto redir;
1989 	case NAPPEND:
1990 		p = ">>";  i = 1;  goto redir;
1991 	case NTOFD:
1992 		p = ">&";  i = 1;  goto redir;
1993 	case NFROM:
1994 		p = "<";  i = 0;  goto redir;
1995 	case NFROMFD:
1996 		p = "<&";  i = 0;  goto redir;
1997 	case NFROMTO:
1998 		p = "<>";  i = 0;  goto redir;
1999  redir:
2000 		if (n->nfile.fd != i)
2001 			cmdputi(n->nfile.fd);
2002 		cmdputs(p);
2003 		if (n->type == NTOFD || n->type == NFROMFD) {
2004 			if (n->ndup.dupfd < 0)
2005 				cmdputs("-");
2006 			else
2007 				cmdputi(n->ndup.dupfd);
2008 		} else {
2009 			(void) cmdtxt(n->nfile.fname, 0);
2010 		}
2011 		return 0;
2012 	case NHERE:
2013 	case NXHERE:
2014 		cmdputs("<<...");
2015 		return 0;
2016 	default:
2017 		cmdputs("???");
2018 		return 0;
2019 	}
2020 	return 0;
2021 }
2022 
2023 STATIC void
2024 cmdlist(union node *np, int sep)
2025 {
2026 	for (; np; np = np->narg.next) {
2027 		if (!sep)
2028 			cmdputs(" ");
2029 		(void) cmdtxt(np, 0);
2030 		if (sep && np->narg.next)
2031 			cmdputs(" ");
2032 	}
2033 }
2034 
2035 
2036 STATIC void
2037 cmdputs(const char *s)
2038 {
2039 	const char *p, *str = 0;
2040 	char c, cc[2] = " ";
2041 	char *nextc;
2042 	int nleft;
2043 	int subtype = 0;
2044 	int quoted = 0;
2045 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
2046 					"#", "##", "%", "%%", "}" };
2047 
2048 	p = s;
2049 	nextc = cmdnextc;
2050 	nleft = cmdnleft;
2051 	while (nleft > 0 && (c = *p++) != 0) {
2052 		switch (c) {
2053 		case CTLNONL:
2054 			c = '\0';
2055 			break;
2056 		case CTLESC:
2057 			c = *p++;
2058 			break;
2059 		case CTLVAR:
2060 			subtype = *p++;
2061 			if (subtype & VSLINENO) {	/* undo LINENO hack */
2062 				if ((subtype & VSTYPE) == VSLENGTH)
2063 					str = "${#LINENO";	/*}*/
2064 				else
2065 					str = "${LINENO";	/*}*/
2066 				while (is_digit(*p))
2067 					p++;
2068 			} else if ((subtype & VSTYPE) == VSLENGTH)
2069 				str = "${#"; /*}*/
2070 			else
2071 				str = "${"; /*}*/
2072 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
2073 				quoted ^= 1;
2074 				c = '"';
2075 			} else {
2076 				c = *str++;
2077 			}
2078 			break;
2079 		case CTLENDVAR:		/*{*/
2080 			c = '}';
2081 			if (quoted & 1)
2082 				str = "\"";
2083 			quoted >>= 1;
2084 			subtype = 0;
2085 			break;
2086 		case CTLBACKQ:
2087 			c = '$';
2088 			str = "(...)";
2089 			break;
2090 		case CTLBACKQ+CTLQUOTE:
2091 			c = '"';
2092 			str = "$(...)\"";
2093 			break;
2094 		case CTLARI:
2095 			c = '$';
2096 			if (*p == ' ')
2097 				p++;
2098 			str = "((";	/*))*/
2099 			break;
2100 		case CTLENDARI:		/*((*/
2101 			c = ')';
2102 			str = ")";
2103 			break;
2104 		case CTLQUOTEMARK:
2105 			quoted ^= 1;
2106 			c = '"';
2107 			break;
2108 		case CTLQUOTEEND:
2109 			quoted >>= 1;
2110 			c = '"';
2111 			break;
2112 		case '=':
2113 			if (subtype == 0)
2114 				break;
2115 			str = vstype[subtype & VSTYPE];
2116 			if (subtype & VSNUL)
2117 				c = ':';
2118 			else
2119 				c = *str++;		/*{*/
2120 			if (c != '}')
2121 				quoted <<= 1;
2122 			else if (*p == CTLENDVAR)
2123 				c = *str++;
2124 			subtype = 0;
2125 			break;
2126 		case '\'':
2127 		case '\\':
2128 		case '"':
2129 		case '$':
2130 			/* These can only happen inside quotes */
2131 			cc[0] = c;
2132 			str = cc;
2133 			c = '\\';
2134 			break;
2135 		default:
2136 			break;
2137 		}
2138 		if (c != '\0') do {	/* c == 0 implies nothing in str */
2139 			*nextc++ = c;
2140 		} while (--nleft > 0 && str && (c = *str++));
2141 		str = 0;
2142 	}
2143 	if ((quoted & 1) && nleft) {
2144 		*nextc++ = '"';
2145 		nleft--;
2146 	}
2147 	cmdnleft = nleft;
2148 	cmdnextc = nextc;
2149 }
2150