xref: /netbsd/bin/sh/jobs.c (revision 14acc88f)
1 /*	$NetBSD: jobs.c,v 1.118 2023/04/07 10:34:13 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.118 2023/04/07 10:34:13 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 void cmdtxt(union node *);
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
tcgetpgrp(int fd)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
tcsetpgrp(int fd,pid_tpgrp)140 tcsetpgrp(int fd, pid_tpgrp)
141 {
142 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
143 }
144 #endif
145 
146 static void
ttyfd_change(int from,int to)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
setjobctl(int on)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
do_fgcmd(const char * arg_ptr)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
fgcmd(int argc,char ** argv)282 fgcmd(int argc, char **argv)
283 {
284 	nextopt("");
285 	return do_fgcmd(*argptr);
286 }
287 
288 int
fgcmd_percent(int argc,char ** argv)289 fgcmd_percent(int argc, char **argv)
290 {
291 	nextopt("");
292 	return do_fgcmd(*argv);
293 }
294 
295 static void
set_curjob(struct job * jp,int mode)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
bgcmd(int argc,char ** argv)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
restartjob(struct job * jp)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
cmdputi(int n)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
showjob(struct output * out,struct job * jp,int mode)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", (long)jp->pgrp);
443 		return;
444 	}
445 #endif
446 
447 	procno = jp->nprocs;
448 	if (!procno)
449 		return;
450 
451 	if (mode & SHOW_PID)
452 		mode |= SHOW_MULTILINE;
453 
454 	if ((procno > 1 && !(mode & SHOW_MULTILINE))
455 	    || (mode & SHOW_SIGNALLED)) {
456 		/* See if we have more than one status to report */
457 		ps = jp->ps;
458 		st = ps->status;
459 		do {
460 			int st1 = ps->status;
461 			if (st1 != st)
462 				/* yes - need multi-line output */
463 				mode |= SHOW_MULTILINE;
464 			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
465 				continue;
466 			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
467 			    && st1 != SIGINT && st1 != SIGPIPE))
468 				mode |= SHOW_ISSIG;
469 
470 		} while (ps++, --procno);
471 		procno = jp->nprocs;
472 	}
473 
474 	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
475 		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
476 			VTRACE(DBG_JOBS, ("showjob: freeing job %d\n",
477 			    JNUM(jp)));
478 			freejob(jp);
479 		}
480 		return;
481 	}
482 
483 	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
484 		if (ps == jp->ps)
485 			fmtstr(s, 16, "[%d] %c ",
486 				JNUM(jp),
487 #if JOBS
488 				jp - jobtab == curjob ?
489 									  '+' :
490 				curjob != -1 &&
491 				    jp - jobtab == jobtab[curjob].prev_job ?
492 									  '-' :
493 #endif
494 				' ');
495 		else
496 			fmtstr(s, 16, "      " );
497 		col = strlen(s);
498 		if (mode & SHOW_PID) {
499 			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
500 			     col += strlen(s + col);
501 		}
502 		if (ps->status == -1) {
503 			scopy("Running", s + col);
504 		} else if (WIFEXITED(ps->status)) {
505 			st = WEXITSTATUS(ps->status);
506 			if (st)
507 				fmtstr(s + col, 16, "Done(%d)", st);
508 			else
509 				fmtstr(s + col, 16, "Done");
510 		} else {
511 #if JOBS
512 			if (WIFSTOPPED(ps->status))
513 				st = WSTOPSIG(ps->status);
514 			else /* WIFSIGNALED(ps->status) */
515 #endif
516 				st = WTERMSIG(ps->status);
517 			scopyn(strsignal(st), s + col, 32);
518 			if (WCOREDUMP(ps->status)) {
519 				col += strlen(s + col);
520 				scopyn(" (core dumped)", s + col,  64 - col);
521 			}
522 		}
523 		col += strlen(s + col);
524 		outstr(s, out);
525 		do {
526 			outc(' ', out);
527 			col++;
528 		} while (col < 30);
529 		outstr(ps->cmd, out);
530 		if (mode & SHOW_MULTILINE) {
531 			if (procno > 0) {
532 				outc(' ', out);
533 				outc('|', out);
534 			}
535 		} else {
536 			while (--procno >= 0)
537 				outfmt(out, " | %s", (++ps)->cmd );
538 		}
539 		outc('\n', out);
540 	}
541 	flushout(out);
542 	jp->flags &= ~JOBCHANGED;
543 	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
544 		freejob(jp);
545 }
546 
547 int
jobscmd(int argc,char ** argv)548 jobscmd(int argc, char **argv)
549 {
550 	int mode, m;
551 
552 	mode = 0;
553 	while ((m = nextopt("lpZ")))
554 		switch (m) {
555 		case 'l':
556 			mode = SHOW_PID;
557 			break;
558 		case 'p':
559 			mode = SHOW_PGID;
560 			break;
561 		case 'Z':
562 			mode = SHOW_PROCTITLE;
563 			break;
564 		}
565 
566 	if (mode == SHOW_PROCTITLE) {
567 		if (*argptr && **argptr)
568 			setproctitle("%s", *argptr);
569 		else
570 			setproctitle(NULL);
571 		return 0;
572 	}
573 
574 	if (!iflag && !posix)
575 		mode |= SHOW_NO_FREE;
576 
577 	if (*argptr) {
578 		do
579 			showjob(out1, getjob(*argptr,0), mode);
580 		while (*++argptr);
581 	} else
582 		showjobs(out1, mode);
583 	return 0;
584 }
585 
586 
587 /*
588  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
589  * statuses have changed since the last call to showjobs.
590  *
591  * If the shell is interrupted in the process of creating a job, the
592  * result may be a job structure containing zero processes.  Such structures
593  * will be freed here.
594  */
595 
596 void
showjobs(struct output * out,int mode)597 showjobs(struct output *out, int mode)
598 {
599 	int jobno;
600 	struct job *jp;
601 	int silent = 0, gotpid;
602 
603 	CTRACE(DBG_JOBS, ("showjobs(%x) called\n", mode));
604 
605 	/*  Collect everything pending in the kernel */
606 	if ((gotpid = dowait(WSILENT, NULL, NULL)) > 0)
607 		while (dowait(WSILENT, NULL, NULL) > 0)
608 			continue;
609 #ifdef JOBS
610 	/*
611 	 * Check if we are not in our foreground group, and if not
612 	 * put us in it.
613 	 */
614 	if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
615 		if (tcsetpgrp(ttyfd, getpid()) == -1)
616 			error("Cannot set tty process group (%s) at %d",
617 			    strerror(errno), __LINE__);
618 		VTRACE(DBG_JOBS|DBG_INPUT, ("repaired tty process group\n"));
619 		silent = 1;
620 	}
621 #endif
622 
623 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
624 		if (!jp->used)
625 			continue;
626 		if (jp->nprocs == 0) {
627 			if (!jobs_invalid)
628 				freejob(jp);
629 			continue;
630 		}
631 		if ((mode & SHOW_CHANGED) && !(jp->flags & JOBCHANGED))
632 			continue;
633 		if (silent && (jp->flags & JOBCHANGED)) {
634 			jp->flags &= ~JOBCHANGED;
635 			continue;
636 		}
637 		showjob(out, jp, mode);
638 	}
639 }
640 
641 /*
642  * Mark a job structure as unused.
643  */
644 
645 STATIC void
freejob(struct job * jp)646 freejob(struct job *jp)
647 {
648 	INTOFF;
649 	if (jp->ps != &jp->ps0) {
650 		ckfree(jp->ps);
651 		jp->ps = &jp->ps0;
652 	}
653 	jp->nprocs = 0;
654 	jp->used = 0;
655 #if JOBS
656 	set_curjob(jp, 0);
657 #endif
658 	INTON;
659 }
660 
661 /*
662  * Extract the status of a completed job (for $?)
663  */
664 STATIC int
jobstatus(const struct job * jp,int raw)665 jobstatus(const struct job *jp, int raw)
666 {
667 	int status = 0;
668 	int retval;
669 
670 	if ((jp->flags & JPIPEFAIL) && jp->nprocs) {
671 		int i;
672 
673 		for (i = 0; i < jp->nprocs; i++)
674 			if (jp->ps[i].status != 0)
675 				status = jp->ps[i].status;
676 	} else
677 		status = jp->ps[jp->nprocs ? jp->nprocs - 1 : 0].status;
678 
679 	if (raw)
680 		return status;
681 
682 	if (WIFEXITED(status))
683 		retval = WEXITSTATUS(status);
684 #if JOBS
685 	else if (WIFSTOPPED(status))
686 		retval = WSTOPSIG(status) + 128;
687 #endif
688 	else {
689 		/* XXX: limits number of signals */
690 		retval = WTERMSIG(status) + 128;
691 	}
692 
693 	return retval;
694 }
695 
696 
697 
698 int
waitcmd(int argc,char ** argv)699 waitcmd(int argc, char **argv)
700 {
701 	struct job *job, *last;
702 	int retval;
703 	struct job *jp;
704 	int i;
705 	int any = 0;
706 	int found;
707 	char *pid = NULL, *fpid;
708 	char **arg;
709 	char idstring[20];
710 
711 	while ((i = nextopt("np:")) != '\0') {
712 		switch (i) {
713 		case 'n':
714 			any = 1;
715 			break;
716 		case 'p':
717 			if (pid)
718 				error("more than one -p unsupported");
719 			pid = optionarg;
720 			break;
721 		}
722 	}
723 
724 	if (pid != NULL) {
725 		if (!validname(pid, '\0', NULL))
726 			error("invalid name: -p '%s'", pid);
727 		if (unsetvar(pid, 0))
728 			error("%s readonly", pid);
729 	}
730 
731 	/*
732 	 * If we have forked, and not yet created any new jobs, then
733 	 * we have no children, whatever jobtab claims,
734 	 * so simply return in that case.
735 	 *
736 	 * The return code is 127 if we had any pid args (none are found)
737 	 * or if we had -n (nothing exited), but 0 for plain old "wait".
738 	 */
739 	if (jobs_invalid) {
740 		CTRACE(DBG_WAIT, ("builtin wait%s%s in child, invalid jobtab\n",
741 		    any ? " -n" : "", *argptr ? " pid..." : ""));
742 		return (any || *argptr) ? 127 : 0;
743 	}
744 
745 	/*
746 	 * clear stray flags left from previous waitcmd
747 	 * or set them instead if anything will do ("wait -n")
748 	 */
749 	for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
750 		if (any && *argptr == NULL)
751 			jp->flags |= JOBWANTED;
752 		else
753 			jp->flags &= ~JOBWANTED;
754 		jp->ref = NULL;
755 	}
756 
757 	CTRACE(DBG_WAIT,
758 	    ("builtin wait%s%s\n", any ? " -n" : "", *argptr ? " pid..." : ""));
759 
760 	/*
761 	 * First, validate the jobnum args, count how many refer to
762 	 * (different) running jobs, and if we had -n, and found that one has
763 	 * already finished, we return that one.   Otherwise remember
764 	 * which ones we are looking for (JOBWANTED).
765 	 */
766 	found = 0;
767 	last = NULL;
768 	for (arg = argptr; *arg; arg++) {
769 		last = jp = getjob(*arg, 1);
770 		if (!jp)
771 			continue;
772 		if (jp->ref == NULL)
773 			jp->ref = *arg;
774 		if (any && jp->state == JOBDONE) {
775 			/*
776 			 * We just want any of them, and this one is
777 			 * ready for consumption, bon apetit ...
778 			 */
779 			retval = jobstatus(jp, 0);
780 			if (pid)
781 				setvar(pid, *arg, 0);
782 			if (!iflag)
783 				freejob(jp);
784 			CTRACE(DBG_WAIT, ("wait -n found %s already done: %d\n",			    *arg, retval));
785 			return retval;
786 		}
787 		if (!(jp->flags & JOBWANTED)) {
788 			/*
789 			 * It is possible to list the same job several
790 			 * times - the obvious "wait 1 1 1" or
791 			 * "wait %% %2 102" where job 2 is current and pid 102
792 			 * However many times it is requested, it is found once.
793 			 */
794 			found++;
795 			jp->flags |= JOBWANTED;
796 		}
797 		job = jp;
798 	}
799 
800 	VTRACE(DBG_WAIT, ("wait %s%s%sfound %d candidates (last %s)\n",
801 	    any ? "-n " : "", *argptr ? *argptr : "",
802 	    argptr[0] && argptr[1] ? "... " : " ", found,
803 	    job && job->used ? (job->ref ? job->ref : "<no-arg>") : "none"));
804 
805 	/*
806 	 * If we were given a list of jobnums:
807 	 * and none of those exist, then we're done.
808 	 */
809 	if (*argptr && found == 0)
810 		return 127;
811 
812 	/*
813 	 * Otherwise we need to wait for something to complete
814 	 * When it does, we check and see if it is one of the
815 	 * jobs we're waiting on, and if so, we clean it up.
816 	 * If we had -n, then we're done, otherwise we do it all again
817 	 * until all we had listed are done, of if there were no
818 	 * jobnum args, all are done.
819 	 */
820 
821 	retval = any || *argptr ? 127 : 0;
822 	fpid = NULL;
823 	for (;;) {
824 		VTRACE(DBG_WAIT, ("wait waiting (%d remain): ", found));
825 		job = NULL;
826 		for (jp = jobtab, i = njobs; --i >= 0; jp++) {
827 			if (jp->used && jp->flags & JOBWANTED &&
828 			    jp->state == JOBDONE) {
829 				job = jp;
830 				break;
831 			}
832 			if (jp->used && jp->state == JOBRUNNING)
833 				job = jp;
834 		}
835 		if (i < 0 && job == NULL) {
836 			CTRACE(DBG_WAIT, ("nothing running (ret: %d) fpid %s\n",
837 			    retval, fpid ? fpid : "unset"));
838 			if (pid && fpid)
839 				setvar(pid, fpid, 0);
840 			return retval;
841 		}
842 		jp = job;
843 		VTRACE(DBG_WAIT, ("found @%d/%d state: %d\n", njobs-i, njobs,
844 		    jp->state));
845 
846 		/*
847 		 * There is at least 1 job running, so we can
848 		 * safely wait() (blocking) for something to exit.
849 		 */
850 		if (jp->state == JOBRUNNING) {
851 			job = NULL;
852 			if ((i = dowait(WBLOCK|WNOFREE, NULL, &job)) == -1)
853 			       return 128 + lastsig();
854 
855 			/*
856 			 * This happens if an interloper has died
857 			 * (eg: a child of the executable that exec'd us)
858 			 * Simply go back and start all over again
859 			 * (this is rare).
860 			 */
861 			if (job == NULL)
862 				continue;
863 
864 			/*
865 			 * one of the reported job's processes exited,
866 			 * but there are more still running, back for more
867 			 */
868 			if (job->state == JOBRUNNING)
869 				continue;
870 		} else
871 			job = jp;	/* we want this, and it is done */
872 
873 		if (job->flags & JOBWANTED) {
874 			int rv;
875 
876 			job->flags &= ~JOBWANTED;	/* got it */
877 			rv = jobstatus(job, 0);
878 			VTRACE(DBG_WAIT, (
879 			    "wanted %d (%s) done: st=%d", i,
880 			    job->ref ? job->ref : "", rv));
881 			if (any || job == last) {
882 				retval = rv;
883 				fpid = job->ref;
884 
885 				VTRACE(DBG_WAIT, (" save"));
886 				if (pid) {
887 				   /*
888 				    * don't need fpid unless we are going
889 				    * to return it.
890 				    */
891 				   if (fpid == NULL) {
892 					/*
893 					 * this only happens with "wait -n"
894 					 * (that is, no pid args)
895 					 */
896 					snprintf(idstring, sizeof idstring,
897 					    "%d", job->ps[ job->nprocs ?
898 						    job->nprocs-1 : 0 ].pid);
899 					fpid = idstring;
900 				    }
901 				    VTRACE(DBG_WAIT, (" (for %s)", fpid));
902 				}
903 			}
904 
905 			if (job->state == JOBDONE) {
906 				VTRACE(DBG_WAIT, (" free"));
907 				freejob(job);
908 			}
909 
910 			if (any || (found > 0 && --found == 0)) {
911 				if (pid && fpid)
912 					setvar(pid, fpid, 0);
913 				VTRACE(DBG_WAIT, (" return %d\n", retval));
914 				return retval;
915 			}
916 			VTRACE(DBG_WAIT, ("\n"));
917 			continue;
918 		}
919 
920 		/* this is to handle "wait" (no args) */
921 		if (found == 0 && job->state == JOBDONE) {
922 			VTRACE(DBG_JOBS|DBG_WAIT, ("Cleanup: %d\n", i));
923 			freejob(job);
924 		}
925 	}
926 }
927 
928 
929 int
jobidcmd(int argc,char ** argv)930 jobidcmd(int argc, char **argv)
931 {
932 	struct job *jp;
933 	int i;
934 	int pg = 0, onep = 0, job = 0;
935 
936 	while ((i = nextopt("gjp"))) {
937 		switch (i) {
938 		case 'g':	pg = 1;		break;
939 		case 'j':	job = 1;	break;
940 		case 'p':	onep = 1;	break;
941 		}
942 	}
943 	CTRACE(DBG_JOBS, ("jobidcmd%s%s%s%s %s\n", pg ? " -g" : "",
944 	    onep ? " -p" : "", job ? " -j" : "", jobs_invalid ? " [inv]" : "",
945 	    *argptr ? *argptr : "<implicit %%>"));
946 	if (pg + onep + job > 1)
947 		error("-g -j and -p options cannot be combined");
948 
949 	if (argptr[0] && argptr[1])
950 		error("usage: jobid [-g|-p|-r] jobid");
951 
952 	jp = getjob(*argptr, 0);
953 	if (job) {
954 		out1fmt("%%%d\n", JNUM(jp));
955 		return 0;
956 	}
957 	if (pg) {
958 		if (jp->pgrp != 0) {
959 			out1fmt("%ld\n", (long)jp->pgrp);
960 			return 0;
961 		}
962 		return 1;
963 	}
964 	if (onep) {
965 		i = jp->nprocs - 1;
966 		if (i < 0)
967 			return 1;
968 		out1fmt("%ld\n", (long)jp->ps[i].pid);
969 		return 0;
970 	}
971 	for (i = 0 ; i < jp->nprocs ; ) {
972 		out1fmt("%ld", (long)jp->ps[i].pid);
973 		out1c(++i < jp->nprocs ? ' ' : '\n');
974 	}
975 	return 0;
976 }
977 
978 int
getjobpgrp(const char * name)979 getjobpgrp(const char *name)
980 {
981 	struct job *jp;
982 
983 	if (jobs_invalid)
984 		error("No such job: %s", name);
985 	jp = getjob(name, 1);
986 	if (jp == 0)
987 		return 0;
988 	return -jp->pgrp;
989 }
990 
991 /*
992  * Convert a job name to a job structure.
993  */
994 
995 STATIC struct job *
getjob(const char * name,int noerror)996 getjob(const char *name, int noerror)
997 {
998 	int jobno = -1;
999 	struct job *jp;
1000 	int pid;
1001 	int i;
1002 	const char *err_msg = "No such job: %s";
1003 
1004 	if (name == NULL) {
1005 #if JOBS
1006 		jobno = curjob;
1007 #endif
1008 		err_msg = "No current job";
1009 	} else if (name[0] == '%') {
1010 		if (is_number(name + 1)) {
1011 			jobno = number(name + 1) - 1;
1012 		} else if (!name[1] || !name[2]) {
1013 			switch (name[1]) {
1014 #if JOBS
1015 			case 0:
1016 			case '+':
1017 			case '%':
1018 				jobno = curjob;
1019 				err_msg = "No current job";
1020 				break;
1021 			case '-':
1022 				jobno = curjob;
1023 				if (jobno != -1)
1024 					jobno = jobtab[jobno].prev_job;
1025 				err_msg = "No previous job";
1026 				break;
1027 #endif
1028 			default:
1029 				goto check_pattern;
1030 			}
1031 		} else {
1032 			struct job *found;
1033     check_pattern:
1034 			found = NULL;
1035 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
1036 				if (!jp->used || jp->nprocs <= 0)
1037 					continue;
1038 				if ((name[1] == '?'
1039 					&& strstr(jp->ps[0].cmd, name + 2))
1040 				    || prefix(name + 1, jp->ps[0].cmd)) {
1041 					if (found) {
1042 						err_msg = "%s: ambiguous";
1043 						found = 0;
1044 						break;
1045 					}
1046 					found = jp;
1047 				}
1048 			}
1049 			if (found)
1050 				return found;
1051 		}
1052 
1053 	} else if (is_number(name)) {
1054 		pid = number(name);
1055 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
1056 			if (jp->used && jp->nprocs > 0
1057 			 && jp->ps[jp->nprocs - 1].pid == pid)
1058 				return jp;
1059 		}
1060 	}
1061 
1062 	if (jobno >= 0 && jobno < njobs) {
1063 		jp = jobtab + jobno;
1064 		if (jp->used)
1065 			return jp;
1066 	}
1067 	if (!noerror)
1068 		error(err_msg, name);
1069 	return 0;
1070 }
1071 
1072 
1073 /*
1074  * Find out if there are any running (that is, unwaited upon)
1075  * background children of the current shell.
1076  *
1077  * Return 1/0 (yes, no).
1078  *
1079  * Needed as we cannot optimise away sub-shell creation if
1080  * we have such a child, or a "wait" in that sub-shell would
1081  * observe the already existing job.
1082  */
1083 int
anyjobs(void)1084 anyjobs(void)
1085 {
1086 	struct job *jp;
1087 	int i;
1088 
1089 	if (jobs_invalid)
1090 		return 0;
1091 
1092 	for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
1093 		if (jp->used)
1094 			return 1;
1095 	}
1096 
1097 	return 0;
1098 }
1099 
1100 /*
1101  * Return a new job structure,
1102  */
1103 
1104 struct job *
makejob(union node * node,int nprocs)1105 makejob(union node *node, int nprocs)
1106 {
1107 	int i;
1108 	struct job *jp;
1109 
1110 	if (jobs_invalid) {
1111 		VTRACE(DBG_JOBS, ("makejob(%p, %d) clearing jobtab (%d)\n",
1112 			(void *)node, nprocs, njobs));
1113 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
1114 			if (jp->used)
1115 				freejob(jp);
1116 		}
1117 		jobs_invalid = 0;
1118 	}
1119 
1120 	for (i = njobs, jp = jobtab ; ; jp++) {
1121 		if (--i < 0) {
1122 			INTOFF;
1123 			if (njobs == 0) {
1124 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
1125 			} else {
1126 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
1127 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
1128 				/* Relocate `ps' pointers */
1129 				for (i = 0; i < njobs; i++)
1130 					if (jp[i].ps == &jobtab[i].ps0)
1131 						jp[i].ps = &jp[i].ps0;
1132 				ckfree(jobtab);
1133 				jobtab = jp;
1134 			}
1135 			jp = jobtab + njobs;
1136 			for (i = 4 ; --i >= 0 ; njobs++) {
1137 				jobtab[njobs].used = 0;
1138 				jobtab[njobs].prev_job = -1;
1139 			}
1140 			INTON;
1141 			break;
1142 		}
1143 		if (jp->used == 0)
1144 			break;
1145 	}
1146 	INTOFF;
1147 	jp->state = JOBRUNNING;
1148 	jp->used = 1;
1149 	jp->flags = pipefail ? JPIPEFAIL : 0;
1150 	jp->nprocs = 0;
1151 	jp->pgrp = 0;
1152 #if JOBS
1153 	jp->jobctl = jobctl;
1154 	set_curjob(jp, 1);
1155 #endif
1156 	if (nprocs > 1) {
1157 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
1158 	} else {
1159 		jp->ps = &jp->ps0;
1160 	}
1161 	INTON;
1162 	VTRACE(DBG_JOBS, ("makejob(%p, %d)%s returns %%%d\n", (void *)node,
1163 	    nprocs, (jp->flags & JPIPEFAIL) ? " PF" : "", JNUM(jp)));
1164 	return jp;
1165 }
1166 
1167 
1168 /*
1169  * Fork off a subshell.  If we are doing job control, give the subshell its
1170  * own process group.  Jp is a job structure that the job is to be added to.
1171  * N is the command that will be evaluated by the child.  Both jp and n may
1172  * be NULL.  The mode parameter can be one of the following:
1173  *	FORK_FG - Fork off a foreground process.
1174  *	FORK_BG - Fork off a background process.
1175  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
1176  *		     process group even if job control is on.
1177  *
1178  * When job control is turned off, background processes have their standard
1179  * input redirected to /dev/null (except for the second and later processes
1180  * in a pipeline).
1181  */
1182 
1183 int
forkshell(struct job * jp,union node * n,int mode)1184 forkshell(struct job *jp, union node *n, int mode)
1185 {
1186 	pid_t pid;
1187 	int serrno;
1188 
1189 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
1190 	    JNUM(jp), n, mode));
1191 
1192 	switch ((pid = fork())) {
1193 	case -1:
1194 		serrno = errno;
1195 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
1196 		error("Cannot fork (%s)", strerror(serrno));
1197 		break;
1198 	case 0:
1199 		SHELL_FORKED();
1200 		forkchild(jp, n, mode, 0);
1201 		return 0;
1202 	default:
1203 		return forkparent(jp, n, mode, pid);
1204 	}
1205 }
1206 
1207 int
forkparent(struct job * jp,union node * n,int mode,pid_t pid)1208 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
1209 {
1210 	int pgrp = 0;
1211 
1212 	if (rootshell && mode != FORK_NOJOB && mflag) {
1213 		/*
1214 		 * The process group ID must always be that of the
1215 		 * first process created for the job.   If this proc
1216 		 * is the first, that's us, otherwise the pgrp has
1217 		 * already been determined.
1218 		 */
1219 		if (jp == NULL || jp->nprocs == 0)
1220 			pgrp = pid;
1221 		else
1222 			pgrp = jp->pgrp;
1223 		/* This can fail because we are doing it in the child also */
1224 		(void)setpgid(pid, pgrp);
1225 	}
1226 	if (mode == FORK_BG)
1227 		backgndpid = pid;		/* set $! */
1228 	if (jp) {
1229 		struct procstat *ps = &jp->ps[jp->nprocs++];
1230 		ps->pid = pid;
1231 		ps->status = -1;
1232 		ps->cmd[0] = 0;
1233 		jp->pgrp = pgrp;	/* 0 if !mflag */
1234 		if (/* iflag && rootshell && */ n)
1235 			commandtext(ps, n);
1236 	}
1237 	CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
1238 	return pid;
1239 }
1240 
1241 void
forkchild(struct job * jp,union node * n,int mode,int vforked)1242 forkchild(struct job *jp, union node *n, int mode, int vforked)
1243 {
1244 	int wasroot;
1245 	int pgrp;
1246 	const char *devnull = _PATH_DEVNULL;
1247 	const char *nullerr = "Can't open %s";
1248 
1249 	wasroot = rootshell;
1250 	CTRACE(DBG_JOBS, ("Child shell %d %sforked from %d (mode %d)\n",
1251 	    getpid(), vforked?"v":"", getppid(), mode));
1252 
1253 	if (!vforked) {
1254 		rootshell = 0;
1255 		handler = &main_handler;
1256 	}
1257 
1258 	closescript(vforked);
1259 	clear_traps(vforked);
1260 #if JOBS
1261 	if (!vforked)
1262 		jobctl = 0;		/* do job control only in root shell */
1263 	if (wasroot && mode != FORK_NOJOB && mflag) {
1264 		if (jp == NULL || jp->nprocs == 0)
1265 			pgrp = getpid();
1266 		else
1267 			pgrp = jp->ps[0].pid;
1268 		/* This can fail because we are doing it in the parent also */
1269 		(void)setpgid(0, pgrp);
1270 		if (mode == FORK_FG) {
1271 			if (tcsetpgrp(ttyfd, pgrp) == -1)
1272 				error("Cannot set tty process group (%s) at %d",
1273 				    strerror(errno), __LINE__);
1274 		}
1275 		setsignal(SIGTSTP, vforked);
1276 		setsignal(SIGTTOU, vforked);
1277 	} else if (mode == FORK_BG) {
1278 		ignoresig(SIGINT, vforked);
1279 		ignoresig(SIGQUIT, vforked);
1280 		if ((jp == NULL || jp->nprocs == 0) &&
1281 		    ! fd0_redirected_p ()) {
1282 			close(0);
1283 			if (open(devnull, O_RDONLY) != 0)
1284 				error(nullerr, devnull);
1285 		}
1286 	}
1287 #else
1288 	if (mode == FORK_BG) {
1289 		ignoresig(SIGINT, vforked);
1290 		ignoresig(SIGQUIT, vforked);
1291 		if ((jp == NULL || jp->nprocs == 0) &&
1292 		    ! fd0_redirected_p ()) {
1293 			close(0);
1294 			if (open(devnull, O_RDONLY) != 0)
1295 				error(nullerr, devnull);
1296 		}
1297 	}
1298 #endif
1299 	if (wasroot && iflag) {
1300 		setsignal(SIGINT, vforked);
1301 		setsignal(SIGQUIT, vforked);
1302 		setsignal(SIGTERM, vforked);
1303 	}
1304 
1305 	if (!vforked)
1306 		jobs_invalid = 1;
1307 }
1308 
1309 /*
1310  * Wait for job to finish.
1311  *
1312  * Under job control we have the problem that while a child process is
1313  * running interrupts generated by the user are sent to the child but not
1314  * to the shell.  This means that an infinite loop started by an inter-
1315  * active user may be hard to kill.  With job control turned off, an
1316  * interactive user may place an interactive program inside a loop.  If
1317  * the interactive program catches interrupts, the user doesn't want
1318  * these interrupts to also abort the loop.  The approach we take here
1319  * is to have the shell ignore interrupt signals while waiting for a
1320  * foreground process to terminate, and then send itself an interrupt
1321  * signal if the child process was terminated by an interrupt signal.
1322  * Unfortunately, some programs want to do a bit of cleanup and then
1323  * exit on interrupt; unless these processes terminate themselves by
1324  * sending a signal to themselves (instead of calling exit) they will
1325  * confuse this approach.
1326  */
1327 
1328 int
waitforjob(struct job * jp)1329 waitforjob(struct job *jp)
1330 {
1331 #if JOBS
1332 	int mypgrp = getpgrp();
1333 #endif
1334 	int status;
1335 	int st;
1336 
1337 	INTOFF;
1338 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", JNUM(jp)));
1339 	while (jp->state == JOBRUNNING) {
1340 		dowait(WBLOCK, jp, NULL);
1341 	}
1342 #if JOBS
1343 	if (jp->jobctl) {
1344 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
1345 			error("Cannot set tty process group (%s) at %d",
1346 			    strerror(errno), __LINE__);
1347 	}
1348 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
1349 		set_curjob(jp, 2);
1350 #endif
1351 	status = jobstatus(jp, 1);
1352 
1353 	/* convert to 8 bits */
1354 	if (WIFEXITED(status))
1355 		st = WEXITSTATUS(status);
1356 #if JOBS
1357 	else if (WIFSTOPPED(status))
1358 		st = WSTOPSIG(status) + 128;
1359 #endif
1360 	else
1361 		st = WTERMSIG(status) + 128;
1362 
1363 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
1364 		JNUM(jp), jp->nprocs, status, st));
1365 #if JOBS
1366 	if (jp->jobctl) {
1367 		/*
1368 		 * This is truly gross.
1369 		 * If we're doing job control, then we did a TIOCSPGRP which
1370 		 * caused us (the shell) to no longer be in the controlling
1371 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
1372 		 * intuit from the subprocess exit status whether a SIGINT
1373 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
1374 		 */
1375 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1376 			raise(SIGINT);
1377 	}
1378 #endif
1379 	if (! JOBS || jp->state == JOBDONE)
1380 		freejob(jp);
1381 	INTON;
1382 	return st;
1383 }
1384 
1385 
1386 
1387 /*
1388  * Wait for a process (any process) to terminate.
1389  *
1390  * If "job" is given (not NULL), then its jobcontrol status (and mflag)
1391  * are used to determine if we wait for stopping/continuing processes or
1392  * only terminating ones, and the decision whether to report to stdout
1393  * or not varies depending what happened, and whether the affected job
1394  * is the one that was requested or not.
1395  *
1396  * If "changed" is not NULL, then the job which changed because a
1397  * process terminated/stopped will be reported by setting *changed,
1398  * if there is any such job, otherwise we set *changed = NULL.
1399  */
1400 
1401 STATIC int
dowait(int flags,struct job * job,struct job ** changed)1402 dowait(int flags, struct job *job, struct job **changed)
1403 {
1404 	int pid;
1405 	int status;
1406 	struct procstat *sp;
1407 	struct job *jp;
1408 	struct job *thisjob;
1409 	int done;
1410 	int stopped;
1411 	int err;
1412 
1413 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called for job %d%s\n",
1414 	    flags, JNUM(job), changed ? " [report change]" : ""));
1415 
1416 	if (changed != NULL)
1417 		*changed = NULL;
1418 
1419 	/*
1420 	 * First deal with the kernel, collect info on any (one) of our
1421 	 * children that has changed state since we last asked.
1422 	 * (loop if we're interrupted by a signal that we aren't processing)
1423 	 */
1424 	do {
1425 		err = 0;
1426 		pid = waitproc(flags & WBLOCK, job, &status);
1427 		if (pid == -1)
1428 			err = errno;
1429 		VTRACE(DBG_JOBS|DBG_PROCS,
1430 		    ("wait returns pid %d (e:%d), status %#x (ps=%d)\n",
1431 		    pid, err, status, pendingsigs));
1432 	} while (pid == -1 && err == EINTR && pendingsigs == 0);
1433 
1434 	/*
1435 	 * if nothing exited/stopped/..., we have nothing else to do
1436 	 */
1437 	if (pid <= 0)
1438 		return pid;
1439 
1440 	/*
1441 	 * Otherwise, try to find the process, somewhere in our job table
1442 	 */
1443 	INTOFF;
1444 	thisjob = NULL;
1445 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1446 		if (jp->used) {
1447 			/*
1448 			 * For each job that is in use (this is one)
1449 			 */
1450 			done = 1;	/* assume it is finished */
1451 			stopped = 1;	/* and has stopped */
1452 
1453 			/*
1454 			 * Now scan all our child processes of the job
1455 			 */
1456 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1457 				if (sp->pid == -1)
1458 					continue;
1459 				/*
1460 				 * If the process that changed is the one
1461 				 * we're looking at, and it was previously
1462 				 * running (-1) or was stopped (anything else
1463 				 * and it must have already finished earlier,
1464 				 * so cannot be the process that just changed)
1465 				 * then we update its status
1466 				 */
1467 				if (sp->pid == pid &&
1468 				  (sp->status==-1 || WIFSTOPPED(sp->status))) {
1469 					VTRACE(DBG_JOBS | DBG_PROCS,
1470 			("Job %d: changing status of proc %d from %#x to ",
1471 					    JNUM(jp), pid, sp->status));
1472 
1473 					/*
1474 					 * If the process continued,
1475 					 * then update its status to running
1476 					 * and mark the job running as well.
1477 					 *
1478 					 * If it was anything but running
1479 					 * before, flag it as a change for
1480 					 * reporting purposes later
1481 					 */
1482 					if (WIFCONTINUED(status)) {
1483 						if (sp->status != -1)
1484 							jp->flags |= JOBCHANGED;
1485 						sp->status = -1;
1486 						jp->state = JOBRUNNING;
1487 						VTRACE(DBG_JOBS|DBG_PROCS,
1488 						    ("running\n"));
1489 					} else {
1490 						/* otherwise update status */
1491 						sp->status = status;
1492 						VTRACE(DBG_JOBS|DBG_PROCS,
1493 						    ("%#x\n", status));
1494 					}
1495 
1496 					/*
1497 					 * We now know the affected job
1498 					 */
1499 					thisjob = jp;
1500 					if (changed != NULL)
1501 						*changed = jp;
1502 				}
1503 				/*
1504 				 * After any update that might have just
1505 				 * happened, if this process is running,
1506 				 * the job is not stopped, or if the process
1507 				 * simply stopped (not terminated) then the
1508 				 * job is certainly not completed (done).
1509 				 */
1510 				if (sp->status == -1)
1511 					stopped = 0;
1512 				else if (WIFSTOPPED(sp->status))
1513 					done = 0;
1514 			}
1515 
1516 			/*
1517 			 * Once we have examined all processes for the
1518 			 * job, if we still show it as stopped, then...
1519 			 */
1520 			if (stopped) {		/* stopped or done */
1521 				/*
1522 				 * it might be stopped, or finished, decide:
1523 				 */
1524 				int state = done ? JOBDONE : JOBSTOPPED;
1525 
1526 				/*
1527 				 * If that wasn't the same as it was before
1528 				 * then update its state, and if it just
1529 				 * completed, make it be the current job (%%)
1530 				 */
1531 				if (jp->state != state) {
1532 					VTRACE(DBG_JOBS,
1533 				("Job %d: changing state from %d to %d\n",
1534 					    JNUM(jp), jp->state, state));
1535 					jp->state = state;
1536 #if JOBS
1537 					if (done)
1538 						set_curjob(jp, 0);
1539 #endif
1540 				}
1541 			}
1542 		}
1543 	}
1544 
1545 	/*
1546 	 * Now we have scanned all jobs.   If we found the job that
1547 	 * the process that changed state belonged to (we occasionally
1548 	 * fork processes without associating them with a job, when one
1549 	 * of those finishes, we simply ignore it, the zombie has been
1550 	 * cleaned up, which is all that matters) then we need to
1551 	 * determine if we should say something about it to stdout
1552 	 */
1553 
1554 	if (thisjob &&
1555 	    (thisjob->state != JOBRUNNING || thisjob->flags & JOBCHANGED)) {
1556 		int mode = 0;
1557 
1558 		if (!rootshell || !iflag)
1559 			mode = SHOW_SIGNALLED;
1560 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
1561 		    job != thisjob)
1562 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
1563 		if (mode && (flags & WSILENT) == 0)
1564 			showjob(out2, thisjob, mode);
1565 		else {
1566 			VTRACE(DBG_JOBS,
1567 			    ("Not printing status for %p [%d], "
1568 			     "mode=%#x rootshell=%d, job=%p [%d]\n",
1569 			    thisjob, JNUM(thisjob), mode, rootshell,
1570 			    job, JNUM(job)));
1571 			thisjob->flags |= JOBCHANGED;
1572 		}
1573 	}
1574 
1575 	INTON;
1576 	/*
1577 	 * Finally tell our caller that something happened (in general all
1578 	 * anyone tests for is <= 0 (or >0) so the actual pid value here
1579 	 * doesn't matter much, but we know pid is >0 so we may as well
1580 	 * give back something meaningful
1581 	 */
1582 	return pid;
1583 }
1584 
1585 
1586 
1587 /*
1588  * Do a wait system call.  If job control is compiled in, we accept
1589  * stopped processes.  If block is zero, we return a value of zero
1590  * rather than blocking.
1591  *
1592  * System V doesn't have a non-blocking wait system call.  It does
1593  * have a SIGCLD signal that is sent to a process when one of its
1594  * children dies.  The obvious way to use SIGCLD would be to install
1595  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
1596  * was received, and have waitproc bump another counter when it got
1597  * the status of a process.  Waitproc would then know that a wait
1598  * system call would not block if the two counters were different.
1599  * This approach doesn't work because if a process has children that
1600  * have not been waited for, System V will send it a SIGCLD when it
1601  * installs a signal handler for SIGCLD.  What this means is that when
1602  * a child exits, the shell will be sent SIGCLD signals continuously
1603  * until is runs out of stack space, unless it does a wait call before
1604  * restoring the signal handler.  The code below takes advantage of
1605  * this (mis)feature by installing a signal handler for SIGCLD and
1606  * then checking to see whether it was called.  If there are any
1607  * children to be waited for, it will be.
1608  *
1609  * If neither SYSV nor BSD is defined, we don't implement nonblocking
1610  * waits at all.  In this case, the user will not be informed when
1611  * a background process ends until the next time she runs a real program
1612  * (as opposed to running a builtin command or just typing return),
1613  * and the jobs command may give out of date information.
1614  */
1615 
1616 #ifdef SYSV
1617 STATIC int gotsigchild;
1618 
onsigchild()1619 STATIC int onsigchild() {
1620 	gotsigchild = 1;
1621 }
1622 #endif
1623 
1624 
1625 STATIC int
waitproc(int block,struct job * jp,int * status)1626 waitproc(int block, struct job *jp, int *status)
1627 {
1628 #ifdef BSD
1629 	int flags = 0;
1630 
1631 #if JOBS
1632 	if (mflag || (jp != NULL && jp->jobctl))
1633 		flags |= WUNTRACED | WCONTINUED;
1634 #endif
1635 	if (block == 0)
1636 		flags |= WNOHANG;
1637 	VTRACE(DBG_WAIT, ("waitproc: doing waitpid(flags=%#x)\n", flags));
1638 	return waitpid(-1, status, flags);
1639 #else
1640 #ifdef SYSV
1641 	int (*save)();
1642 
1643 	if (block == 0) {
1644 		gotsigchild = 0;
1645 		save = signal(SIGCLD, onsigchild);
1646 		signal(SIGCLD, save);
1647 		if (gotsigchild == 0)
1648 			return 0;
1649 	}
1650 	return wait(status);
1651 #else
1652 	if (block == 0)
1653 		return 0;
1654 	return wait(status);
1655 #endif
1656 #endif
1657 }
1658 
1659 /*
1660  * return 1 if there are stopped jobs, otherwise 0
1661  */
1662 int job_warning = 0;
1663 int
stoppedjobs(void)1664 stoppedjobs(void)
1665 {
1666 	int jobno;
1667 	struct job *jp;
1668 
1669 	if (job_warning || jobs_invalid)
1670 		return (0);
1671 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1672 		if (jp->used == 0)
1673 			continue;
1674 		if (jp->state == JOBSTOPPED) {
1675 			out2str("You have stopped jobs.\n");
1676 			job_warning = 2;
1677 			return (1);
1678 		}
1679 	}
1680 
1681 	return (0);
1682 }
1683 
1684 /*
1685  * Return a string identifying a command (to be printed by the
1686  * jobs command).
1687  */
1688 
1689 STATIC char *cmdnextc;
1690 STATIC int cmdnleft;
1691 
1692 void
commandtext(struct procstat * ps,union node * n)1693 commandtext(struct procstat *ps, union node *n)
1694 {
1695 	int len;
1696 
1697 	cmdnextc = ps->cmd;
1698 	if (iflag || mflag || sizeof(ps->cmd) <= 60)
1699 		len = sizeof(ps->cmd);
1700 	else if (sizeof ps->cmd <= 400)
1701 		len = 50;
1702 	else if (sizeof ps->cmd <= 800)
1703 		len = 80;
1704 	else
1705 		len = sizeof(ps->cmd) / 10;
1706 	cmdnleft = len;
1707 	cmdtxt(n);
1708 	if (cmdnleft <= 0) {
1709 		char *p = ps->cmd + len - 4;
1710 		p[0] = '.';
1711 		p[1] = '.';
1712 		p[2] = '.';
1713 		p[3] = 0;
1714 	} else
1715 		*cmdnextc = '\0';
1716 
1717 	VTRACE(DBG_JOBS,
1718 	    ("commandtext: ps->cmd %p, end %p, left %d\n\t\"%s\"\n",
1719 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
1720 }
1721 
1722 
1723 STATIC void
cmdtxt(union node * n)1724 cmdtxt(union node *n)
1725 {
1726 	union node *np;
1727 	struct nodelist *lp;
1728 	const char *p;
1729 	int i;
1730 
1731 	if (n == NULL || cmdnleft <= 0)
1732 		return;
1733 	switch (n->type) {
1734 	case NSEMI:
1735 		cmdtxt(n->nbinary.ch1);
1736 		cmdputs("; ");
1737 		cmdtxt(n->nbinary.ch2);
1738 		break;
1739 	case NAND:
1740 		cmdtxt(n->nbinary.ch1);
1741 		cmdputs(" && ");
1742 		cmdtxt(n->nbinary.ch2);
1743 		break;
1744 	case NOR:
1745 		cmdtxt(n->nbinary.ch1);
1746 		cmdputs(" || ");
1747 		cmdtxt(n->nbinary.ch2);
1748 		break;
1749 	case NDNOT:
1750 		cmdputs("! ");
1751 		/* FALLTHROUGH */
1752 	case NNOT:
1753 		cmdputs("! ");
1754 		cmdtxt(n->nnot.com);
1755 		break;
1756 	case NPIPE:
1757 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1758 			cmdtxt(lp->n);
1759 			if (lp->next)
1760 				cmdputs(" | ");
1761 		}
1762 		if (n->npipe.backgnd)
1763 			cmdputs(" &");
1764 		break;
1765 	case NSUBSHELL:
1766 		cmdputs("(");
1767 		cmdtxt(n->nredir.n);
1768 		cmdputs(")");
1769 		break;
1770 	case NREDIR:
1771 	case NBACKGND:
1772 		cmdtxt(n->nredir.n);
1773 		break;
1774 	case NIF:
1775 		cmdputs("if ");
1776 		cmdtxt(n->nif.test);
1777 		cmdputs("; then ");
1778 		cmdtxt(n->nif.ifpart);
1779 		if (n->nif.elsepart) {
1780 			cmdputs("; else ");
1781 			cmdtxt(n->nif.elsepart);
1782 		}
1783 		cmdputs("; fi");
1784 		break;
1785 	case NWHILE:
1786 		cmdputs("while ");
1787 		goto until;
1788 	case NUNTIL:
1789 		cmdputs("until ");
1790  until:
1791 		cmdtxt(n->nbinary.ch1);
1792 		cmdputs("; do ");
1793 		cmdtxt(n->nbinary.ch2);
1794 		cmdputs("; done");
1795 		break;
1796 	case NFOR:
1797 		cmdputs("for ");
1798 		cmdputs(n->nfor.var);
1799 		cmdputs(" in ");
1800 		cmdlist(n->nfor.args, 1);
1801 		cmdputs("; do ");
1802 		cmdtxt(n->nfor.body);
1803 		cmdputs("; done");
1804 		break;
1805 	case NCASE:
1806 		cmdputs("case ");
1807 		cmdputs(n->ncase.expr->narg.text);
1808 		cmdputs(" in ");
1809 		for (np = n->ncase.cases; np; np = np->nclist.next) {
1810 			cmdtxt(np->nclist.pattern);
1811 			cmdputs(") ");
1812 			cmdtxt(np->nclist.body);
1813 			switch (n->type) {	/* switch (not if) for later */
1814 			case NCLISTCONT:
1815 				cmdputs(";& ");
1816 				break;
1817 			default:
1818 				cmdputs(";; ");
1819 				break;
1820 			}
1821 		}
1822 		cmdputs("esac");
1823 		break;
1824 	case NDEFUN:
1825 		cmdputs(n->narg.text);
1826 		cmdputs("() { ... }");
1827 		break;
1828 	case NCMD:
1829 		cmdlist(n->ncmd.args, 1);
1830 		cmdlist(n->ncmd.redirect, 0);
1831 		if (n->ncmd.backgnd)
1832 			cmdputs(" &");
1833 		break;
1834 	case NARG:
1835 		cmdputs(n->narg.text);
1836 		break;
1837 	case NTO:
1838 		p = ">";  i = 1;  goto redir;
1839 	case NCLOBBER:
1840 		p = ">|";  i = 1;  goto redir;
1841 	case NAPPEND:
1842 		p = ">>";  i = 1;  goto redir;
1843 	case NTOFD:
1844 		p = ">&";  i = 1;  goto redir;
1845 	case NFROM:
1846 		p = "<";  i = 0;  goto redir;
1847 	case NFROMFD:
1848 		p = "<&";  i = 0;  goto redir;
1849 	case NFROMTO:
1850 		p = "<>";  i = 0;  goto redir;
1851  redir:
1852 		if (n->nfile.fd != i)
1853 			cmdputi(n->nfile.fd);
1854 		cmdputs(p);
1855 		if (n->type == NTOFD || n->type == NFROMFD) {
1856 			if (n->ndup.dupfd < 0)
1857 				cmdputs("-");
1858 			else
1859 				cmdputi(n->ndup.dupfd);
1860 		} else {
1861 			cmdtxt(n->nfile.fname);
1862 		}
1863 		break;
1864 	case NHERE:
1865 	case NXHERE:
1866 		cmdputs("<<...");
1867 		break;
1868 	default:
1869 		cmdputs("???");
1870 		break;
1871 	}
1872 }
1873 
1874 STATIC void
cmdlist(union node * np,int sep)1875 cmdlist(union node *np, int sep)
1876 {
1877 	for (; np; np = np->narg.next) {
1878 		if (!sep)
1879 			cmdputs(" ");
1880 		cmdtxt(np);
1881 		if (sep && np->narg.next)
1882 			cmdputs(" ");
1883 	}
1884 }
1885 
1886 
1887 STATIC void
cmdputs(const char * s)1888 cmdputs(const char *s)
1889 {
1890 	const char *p, *str = 0;
1891 	char c, cc[2] = " ";
1892 	char *nextc;
1893 	int nleft;
1894 	int subtype = 0;
1895 	int quoted = 0;
1896 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
1897 					"#", "##", "%", "%%", "}" };
1898 
1899 	p = s;
1900 	nextc = cmdnextc;
1901 	nleft = cmdnleft;
1902 	while (nleft > 0 && (c = *p++) != 0) {
1903 		switch (c) {
1904 		case CTLNONL:
1905 			c = '\0';
1906 			break;
1907 		case CTLESC:
1908 			c = *p++;
1909 			break;
1910 		case CTLVAR:
1911 			subtype = *p++;
1912 			if (subtype & VSLINENO) {	/* undo LINENO hack */
1913 				if ((subtype & VSTYPE) == VSLENGTH)
1914 					str = "${#LINENO";	/*}*/
1915 				else
1916 					str = "${LINENO";	/*}*/
1917 				while (is_digit(*p))
1918 					p++;
1919 			} else if ((subtype & VSTYPE) == VSLENGTH)
1920 				str = "${#"; /*}*/
1921 			else
1922 				str = "${"; /*}*/
1923 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
1924 				quoted ^= 1;
1925 				c = '"';
1926 			} else {
1927 				c = *str++;
1928 			}
1929 			break;
1930 		case CTLENDVAR:		/*{*/
1931 			c = '}';
1932 			if (quoted & 1)
1933 				str = "\"";
1934 			quoted >>= 1;
1935 			subtype = 0;
1936 			break;
1937 		case CTLBACKQ:
1938 			c = '$';
1939 			str = "(...)";
1940 			break;
1941 		case CTLBACKQ+CTLQUOTE:
1942 			c = '"';
1943 			str = "$(...)\"";
1944 			break;
1945 		case CTLARI:
1946 			c = '$';
1947 			if (*p == ' ')
1948 				p++;
1949 			str = "((";	/*))*/
1950 			break;
1951 		case CTLENDARI:		/*((*/
1952 			c = ')';
1953 			str = ")";
1954 			break;
1955 		case CTLQUOTEMARK:
1956 			quoted ^= 1;
1957 			c = '"';
1958 			break;
1959 		case CTLQUOTEEND:
1960 			quoted >>= 1;
1961 			c = '"';
1962 			break;
1963 		case '=':
1964 			if (subtype == 0)
1965 				break;
1966 			str = vstype[subtype & VSTYPE];
1967 			if (subtype & VSNUL)
1968 				c = ':';
1969 			else
1970 				c = *str++;		/*{*/
1971 			if (c != '}')
1972 				quoted <<= 1;
1973 			else if (*p == CTLENDVAR)
1974 				c = *str++;
1975 			subtype = 0;
1976 			break;
1977 		case '\'':
1978 		case '\\':
1979 		case '"':
1980 		case '$':
1981 			/* These can only happen inside quotes */
1982 			cc[0] = c;
1983 			str = cc;
1984 			c = '\\';
1985 			break;
1986 		default:
1987 			break;
1988 		}
1989 		if (c != '\0') do {	/* c == 0 implies nothing in str */
1990 			*nextc++ = c;
1991 		} while (--nleft > 0 && str && (c = *str++));
1992 		str = 0;
1993 	}
1994 	if ((quoted & 1) && nleft) {
1995 		*nextc++ = '"';
1996 		nleft--;
1997 	}
1998 	cmdnleft = nleft;
1999 	cmdnextc = nextc;
2000 }
2001