xref: /dragonfly/bin/sh/jobs.c (revision 92fc8b5c)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)jobs.c	8.5 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/jobs.c,v 1.92 2011/02/04 22:47:55 jilles Exp $
38  */
39 
40 #include <sys/ioctl.h>
41 #include <sys/param.h>
42 #include <sys/resource.h>
43 #include <sys/time.h>
44 #include <sys/wait.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <paths.h>
48 #include <signal.h>
49 #include <stddef.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 
53 #include "shell.h"
54 #if JOBS
55 #include <termios.h>
56 #undef CEOF			/* syntax.h redefines this */
57 #endif
58 #include "redir.h"
59 #include "show.h"
60 #include "main.h"
61 #include "parser.h"
62 #include "nodes.h"
63 #include "jobs.h"
64 #include "options.h"
65 #include "trap.h"
66 #include "syntax.h"
67 #include "input.h"
68 #include "output.h"
69 #include "memalloc.h"
70 #include "error.h"
71 #include "mystring.h"
72 
73 
74 static struct job *jobtab;	/* array of jobs */
75 static int njobs;		/* size of array */
76 MKINIT pid_t backgndpid = -1;	/* pid of last background process */
77 MKINIT struct job *bgjob = NULL; /* last background process */
78 #if JOBS
79 static struct job *jobmru;	/* most recently used job list */
80 static pid_t initialpgrp;	/* pgrp of shell on invocation */
81 #endif
82 int in_waitcmd = 0;		/* are we in waitcmd()? */
83 int in_dowait = 0;		/* are we in dowait()? */
84 volatile sig_atomic_t breakwaitcmd = 0;	/* should wait be terminated? */
85 static int ttyfd = -1;
86 
87 #if JOBS
88 static void restartjob(struct job *);
89 #endif
90 static void freejob(struct job *);
91 static struct job *getjob(char *);
92 static pid_t dowait(int, struct job *);
93 static pid_t waitproc(int, int *);
94 static void checkzombies(void);
95 static void cmdtxt(union node *);
96 static void cmdputs(const char *);
97 #if JOBS
98 static void setcurjob(struct job *);
99 static void deljob(struct job *);
100 static struct job *getcurjob(struct job *);
101 #endif
102 static void printjobcmd(struct job *);
103 static void showjob(struct job *, int);
104 
105 
106 /*
107  * Turn job control on and off.
108  */
109 
110 MKINIT int jobctl;
111 
112 #if JOBS
113 void
114 setjobctl(int on)
115 {
116 	int i;
117 
118 	if (on == jobctl || rootshell == 0)
119 		return;
120 	if (on) {
121 		if (ttyfd != -1)
122 			close(ttyfd);
123 		if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
124 			i = 0;
125 			while (i <= 2 && !isatty(i))
126 				i++;
127 			if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
128 				goto out;
129 		}
130 		if (ttyfd < 10) {
131 			/*
132 			 * Keep our TTY file descriptor out of the way of
133 			 * the user's redirections.
134 			 */
135 			if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
136 				close(ttyfd);
137 				ttyfd = -1;
138 				goto out;
139 			}
140 			close(ttyfd);
141 			ttyfd = i;
142 		}
143 		if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
144 			close(ttyfd);
145 			ttyfd = -1;
146 			goto out;
147 		}
148 		do { /* while we are in the background */
149 			initialpgrp = tcgetpgrp(ttyfd);
150 			if (initialpgrp < 0) {
151 out:				out2fmt_flush("sh: can't access tty; job control turned off\n");
152 				mflag = 0;
153 				return;
154 			}
155 			if (initialpgrp != getpgrp()) {
156 				kill(0, SIGTTIN);
157 				continue;
158 			}
159 		} while (0);
160 		setsignal(SIGTSTP);
161 		setsignal(SIGTTOU);
162 		setsignal(SIGTTIN);
163 		setpgid(0, rootpid);
164 		tcsetpgrp(ttyfd, rootpid);
165 	} else { /* turning job control off */
166 		setpgid(0, initialpgrp);
167 		tcsetpgrp(ttyfd, initialpgrp);
168 		close(ttyfd);
169 		ttyfd = -1;
170 		setsignal(SIGTSTP);
171 		setsignal(SIGTTOU);
172 		setsignal(SIGTTIN);
173 	}
174 	jobctl = on;
175 }
176 #endif
177 
178 
179 #if JOBS
180 int
181 fgcmd(int argc __unused, char **argv)
182 {
183 	struct job *jp;
184 	pid_t pgrp;
185 	int status;
186 
187 	jp = getjob(argv[1]);
188 	if (jp->jobctl == 0)
189 		error("job not created under job control");
190 	printjobcmd(jp);
191 	flushout(&output);
192 	pgrp = jp->ps[0].pid;
193 	tcsetpgrp(ttyfd, pgrp);
194 	restartjob(jp);
195 	jp->foreground = 1;
196 	INTOFF;
197 	status = waitforjob(jp, NULL);
198 	INTON;
199 	return status;
200 }
201 
202 
203 int
204 bgcmd(int argc, char **argv)
205 {
206 	struct job *jp;
207 
208 	do {
209 		jp = getjob(*++argv);
210 		if (jp->jobctl == 0)
211 			error("job not created under job control");
212 		if (jp->state == JOBDONE)
213 			continue;
214 		restartjob(jp);
215 		jp->foreground = 0;
216 		out1fmt("[%td] ", jp - jobtab + 1);
217 		printjobcmd(jp);
218 	} while (--argc > 1);
219 	return 0;
220 }
221 
222 
223 static void
224 restartjob(struct job *jp)
225 {
226 	struct procstat *ps;
227 	int i;
228 
229 	if (jp->state == JOBDONE)
230 		return;
231 	setcurjob(jp);
232 	INTOFF;
233 	kill(-jp->ps[0].pid, SIGCONT);
234 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
235 		if (WIFSTOPPED(ps->status)) {
236 			ps->status = -1;
237 			jp->state = 0;
238 		}
239 	}
240 	INTON;
241 }
242 #endif
243 
244 
245 int
246 jobscmd(int argc, char *argv[])
247 {
248 	char *id;
249 	int ch, mode;
250 
251 	optind = optreset = 1;
252 	opterr = 0;
253 	mode = SHOWJOBS_DEFAULT;
254 	while ((ch = getopt(argc, argv, "lps")) != -1) {
255 		switch (ch) {
256 		case 'l':
257 			mode = SHOWJOBS_VERBOSE;
258 			break;
259 		case 'p':
260 			mode = SHOWJOBS_PGIDS;
261 			break;
262 		case 's':
263 			mode = SHOWJOBS_PIDS;
264 			break;
265 		case '?':
266 		default:
267 			error("unknown option: -%c", optopt);
268 		}
269 	}
270 	argc -= optind;
271 	argv += optind;
272 
273 	if (argc == 0)
274 		showjobs(0, mode);
275 	else
276 		while ((id = *argv++) != NULL)
277 			showjob(getjob(id), mode);
278 
279 	return (0);
280 }
281 
282 static void
283 printjobcmd(struct job *jp)
284 {
285 	struct procstat *ps;
286 	int i;
287 
288 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
289 		out1str(ps->cmd);
290 		if (i > 0)
291 			out1str(" | ");
292 	}
293 	out1c('\n');
294 }
295 
296 static void
297 showjob(struct job *jp, int mode)
298 {
299 	char s[64];
300 	char statestr[64];
301 	struct procstat *ps;
302 	struct job *j;
303 	int col, curr, i, jobno, prev, procno;
304 	char c;
305 
306 	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
307 	jobno = jp - jobtab + 1;
308 	curr = prev = 0;
309 #if JOBS
310 	if ((j = getcurjob(NULL)) != NULL) {
311 		curr = j - jobtab + 1;
312 		if ((j = getcurjob(j)) != NULL)
313 			prev = j - jobtab + 1;
314 	}
315 #endif
316 	ps = jp->ps + jp->nprocs - 1;
317 	if (jp->state == 0) {
318 		strcpy(statestr, "Running");
319 #if JOBS
320 	} else if (jp->state == JOBSTOPPED) {
321 		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
322 			ps--;
323 		if (WIFSTOPPED(ps->status))
324 			i = WSTOPSIG(ps->status);
325 		else
326 			i = -1;
327 		if (i > 0 && i < sys_nsig && sys_siglist[i])
328 			strcpy(statestr, sys_siglist[i]);
329 		else
330 			strcpy(statestr, "Suspended");
331 #endif
332 	} else if (WIFEXITED(ps->status)) {
333 		if (WEXITSTATUS(ps->status) == 0)
334 			strcpy(statestr, "Done");
335 		else
336 			fmtstr(statestr, 64, "Done(%d)",
337 			    WEXITSTATUS(ps->status));
338 	} else {
339 		i = WTERMSIG(ps->status);
340 		if (i > 0 && i < sys_nsig && sys_siglist[i])
341 			strcpy(statestr, sys_siglist[i]);
342 		else
343 			fmtstr(statestr, 64, "Signal %d", i);
344 		if (WCOREDUMP(ps->status))
345 			strcat(statestr, " (core dumped)");
346 	}
347 
348 	for (ps = jp->ps ; ; ps++) {	/* for each process */
349 		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
350 			out1fmt("%d\n", (int)ps->pid);
351 			goto skip;
352 		}
353 		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
354 			goto skip;
355 		if (jobno == curr && ps == jp->ps)
356 			c = '+';
357 		else if (jobno == prev && ps == jp->ps)
358 			c = '-';
359 		else
360 			c = ' ';
361 		if (ps == jp->ps)
362 			fmtstr(s, 64, "[%d] %c ", jobno, c);
363 		else
364 			fmtstr(s, 64, "    %c ", c);
365 		out1str(s);
366 		col = strlen(s);
367 		if (mode == SHOWJOBS_VERBOSE) {
368 			fmtstr(s, 64, "%d ", (int)ps->pid);
369 			out1str(s);
370 			col += strlen(s);
371 		}
372 		if (ps == jp->ps) {
373 			out1str(statestr);
374 			col += strlen(statestr);
375 		}
376 		do {
377 			out1c(' ');
378 			col++;
379 		} while (col < 30);
380 		if (mode == SHOWJOBS_VERBOSE) {
381 			out1str(ps->cmd);
382 			out1c('\n');
383 		} else
384 			printjobcmd(jp);
385 skip:		if (--procno <= 0)
386 			break;
387 	}
388 }
389 
390 /*
391  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
392  * statuses have changed since the last call to showjobs.
393  *
394  * If the shell is interrupted in the process of creating a job, the
395  * result may be a job structure containing zero processes.  Such structures
396  * will be freed here.
397  */
398 
399 void
400 showjobs(int change, int mode)
401 {
402 	int jobno;
403 	struct job *jp;
404 
405 	TRACE(("showjobs(%d) called\n", change));
406 	checkzombies();
407 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
408 		if (! jp->used)
409 			continue;
410 		if (jp->nprocs == 0) {
411 			freejob(jp);
412 			continue;
413 		}
414 		if (change && ! jp->changed)
415 			continue;
416 		showjob(jp, mode);
417 		jp->changed = 0;
418 		/* Hack: discard jobs for which $! has not been referenced
419 		 * in interactive mode when they terminate.
420 		 */
421 		if (jp->state == JOBDONE && !jp->remembered &&
422 				(iflag || jp != bgjob)) {
423 			freejob(jp);
424 		}
425 	}
426 }
427 
428 
429 /*
430  * Mark a job structure as unused.
431  */
432 
433 static void
434 freejob(struct job *jp)
435 {
436 	struct procstat *ps;
437 	int i;
438 
439 	INTOFF;
440 	if (bgjob == jp)
441 		bgjob = NULL;
442 	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
443 		if (ps->cmd != nullstr)
444 			ckfree(ps->cmd);
445 	}
446 	if (jp->ps != &jp->ps0)
447 		ckfree(jp->ps);
448 	jp->used = 0;
449 #if JOBS
450 	deljob(jp);
451 #endif
452 	INTON;
453 }
454 
455 
456 
457 int
458 waitcmd(int argc, char **argv)
459 {
460 	struct job *job;
461 	int status, retval;
462 	struct job *jp;
463 
464 	if (argc > 1) {
465 		job = getjob(argv[1]);
466 	} else {
467 		job = NULL;
468 	}
469 
470 	/*
471 	 * Loop until a process is terminated or stopped, or a SIGINT is
472 	 * received.
473 	 */
474 
475 	in_waitcmd++;
476 	do {
477 		if (job != NULL) {
478 			if (job->state) {
479 				status = job->ps[job->nprocs - 1].status;
480 				if (WIFEXITED(status))
481 					retval = WEXITSTATUS(status);
482 #if JOBS
483 				else if (WIFSTOPPED(status))
484 					retval = WSTOPSIG(status) + 128;
485 #endif
486 				else
487 					retval = WTERMSIG(status) + 128;
488 				if (! iflag || ! job->changed)
489 					freejob(job);
490 				else {
491 					job->remembered = 0;
492 					if (job == bgjob)
493 						bgjob = NULL;
494 				}
495 				in_waitcmd--;
496 				return retval;
497 			}
498 		} else {
499 			for (jp = jobtab ; jp < jobtab + njobs; jp++)
500 				if (jp->used && jp->state == JOBDONE) {
501 					if (! iflag || ! jp->changed)
502 						freejob(jp);
503 					else {
504 						jp->remembered = 0;
505 						if (jp == bgjob)
506 							bgjob = NULL;
507 					}
508 				}
509 			for (jp = jobtab ; ; jp++) {
510 				if (jp >= jobtab + njobs) {	/* no running procs */
511 					in_waitcmd--;
512 					return 0;
513 				}
514 				if (jp->used && jp->state == 0)
515 					break;
516 			}
517 		}
518 	} while (dowait(1, NULL) != -1);
519 	in_waitcmd--;
520 
521 	return 0;
522 }
523 
524 
525 
526 int
527 jobidcmd(int argc __unused, char **argv)
528 {
529 	struct job *jp;
530 	int i;
531 
532 	jp = getjob(argv[1]);
533 	for (i = 0 ; i < jp->nprocs ; ) {
534 		out1fmt("%d", (int)jp->ps[i].pid);
535 		out1c(++i < jp->nprocs? ' ' : '\n');
536 	}
537 	return 0;
538 }
539 
540 
541 
542 /*
543  * Convert a job name to a job structure.
544  */
545 
546 static struct job *
547 getjob(char *name)
548 {
549 	int jobno;
550 	struct job *found, *jp;
551 	pid_t pid;
552 	int i;
553 
554 	if (name == NULL) {
555 #if JOBS
556 currentjob:	if ((jp = getcurjob(NULL)) == NULL)
557 			error("No current job");
558 		return (jp);
559 #else
560 		error("No current job");
561 #endif
562 	} else if (name[0] == '%') {
563 		if (is_digit(name[1])) {
564 			jobno = number(name + 1);
565 			if (jobno > 0 && jobno <= njobs
566 			 && jobtab[jobno - 1].used != 0)
567 				return &jobtab[jobno - 1];
568 #if JOBS
569 		} else if (name[1] == '%' && name[2] == '\0') {
570 			goto currentjob;
571 		} else if (name[1] == '+' && name[2] == '\0') {
572 			goto currentjob;
573 		} else if (name[1] == '-' && name[2] == '\0') {
574 			if ((jp = getcurjob(NULL)) == NULL ||
575 			    (jp = getcurjob(jp)) == NULL)
576 				error("No previous job");
577 			return (jp);
578 #endif
579 		} else if (name[1] == '?') {
580 			found = NULL;
581 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
582 				if (jp->used && jp->nprocs > 0
583 				 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
584 					if (found)
585 						error("%s: ambiguous", name);
586 					found = jp;
587 				}
588 			}
589 			if (found != NULL)
590 				return (found);
591 		} else {
592 			found = NULL;
593 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
594 				if (jp->used && jp->nprocs > 0
595 				 && prefix(name + 1, jp->ps[0].cmd)) {
596 					if (found)
597 						error("%s: ambiguous", name);
598 					found = jp;
599 				}
600 			}
601 			if (found)
602 				return found;
603 		}
604 	} else if (is_number(name)) {
605 		pid = (pid_t)number(name);
606 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
607 			if (jp->used && jp->nprocs > 0
608 			 && jp->ps[jp->nprocs - 1].pid == pid)
609 				return jp;
610 		}
611 	}
612 	error("No such job: %s", name);
613 	/*NOTREACHED*/
614 	return NULL;
615 }
616 
617 
618 pid_t
619 getjobpgrp(char *name)
620 {
621 	struct job *jp;
622 
623 	jp = getjob(name);
624 	return -jp->ps[0].pid;
625 }
626 
627 /*
628  * Return a new job structure,
629  */
630 
631 struct job *
632 makejob(union node *node __unused, int nprocs)
633 {
634 	int i;
635 	struct job *jp;
636 
637 	for (i = njobs, jp = jobtab ; ; jp++) {
638 		if (--i < 0) {
639 			INTOFF;
640 			if (njobs == 0) {
641 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
642 #if JOBS
643 				jobmru = NULL;
644 #endif
645 			} else {
646 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
647 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
648 #if JOBS
649 				/* Relocate `next' pointers and list head */
650 				if (jobmru != NULL)
651 					jobmru = &jp[jobmru - jobtab];
652 				for (i = 0; i < njobs; i++)
653 					if (jp[i].next != NULL)
654 						jp[i].next = &jp[jp[i].next -
655 						    jobtab];
656 #endif
657 				if (bgjob != NULL)
658 					bgjob = &jp[bgjob - jobtab];
659 				/* Relocate `ps' pointers */
660 				for (i = 0; i < njobs; i++)
661 					if (jp[i].ps == &jobtab[i].ps0)
662 						jp[i].ps = &jp[i].ps0;
663 				ckfree(jobtab);
664 				jobtab = jp;
665 			}
666 			jp = jobtab + njobs;
667 			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
668 			INTON;
669 			break;
670 		}
671 		if (jp->used == 0)
672 			break;
673 	}
674 	INTOFF;
675 	jp->state = 0;
676 	jp->used = 1;
677 	jp->changed = 0;
678 	jp->nprocs = 0;
679 	jp->foreground = 0;
680 	jp->remembered = 0;
681 #if JOBS
682 	jp->jobctl = jobctl;
683 	jp->next = NULL;
684 #endif
685 	if (nprocs > 1) {
686 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
687 	} else {
688 		jp->ps = &jp->ps0;
689 	}
690 	INTON;
691 	TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
692 	    jp - jobtab + 1));
693 	return jp;
694 }
695 
696 #if JOBS
697 static void
698 setcurjob(struct job *cj)
699 {
700 	struct job *jp, *prev;
701 
702 	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
703 		if (jp == cj) {
704 			if (prev != NULL)
705 				prev->next = jp->next;
706 			else
707 				jobmru = jp->next;
708 			jp->next = jobmru;
709 			jobmru = cj;
710 			return;
711 		}
712 	}
713 	cj->next = jobmru;
714 	jobmru = cj;
715 }
716 
717 static void
718 deljob(struct job *j)
719 {
720 	struct job *jp, *prev;
721 
722 	for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
723 		if (jp == j) {
724 			if (prev != NULL)
725 				prev->next = jp->next;
726 			else
727 				jobmru = jp->next;
728 			return;
729 		}
730 	}
731 }
732 
733 /*
734  * Return the most recently used job that isn't `nj', and preferably one
735  * that is stopped.
736  */
737 static struct job *
738 getcurjob(struct job *nj)
739 {
740 	struct job *jp;
741 
742 	/* Try to find a stopped one.. */
743 	for (jp = jobmru; jp != NULL; jp = jp->next)
744 		if (jp->used && jp != nj && jp->state == JOBSTOPPED)
745 			return (jp);
746 	/* Otherwise the most recently used job that isn't `nj' */
747 	for (jp = jobmru; jp != NULL; jp = jp->next)
748 		if (jp->used && jp != nj)
749 			return (jp);
750 
751 	return (NULL);
752 }
753 
754 #endif
755 
756 /*
757  * Fork of a subshell.  If we are doing job control, give the subshell its
758  * own process group.  Jp is a job structure that the job is to be added to.
759  * N is the command that will be evaluated by the child.  Both jp and n may
760  * be NULL.  The mode parameter can be one of the following:
761  *	FORK_FG - Fork off a foreground process.
762  *	FORK_BG - Fork off a background process.
763  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
764  *		     process group even if job control is on.
765  *
766  * When job control is turned off, background processes have their standard
767  * input redirected to /dev/null (except for the second and later processes
768  * in a pipeline).
769  */
770 
771 pid_t
772 forkshell(struct job *jp, union node *n, int mode)
773 {
774 	pid_t pid;
775 	pid_t pgrp;
776 
777 	TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
778 	    mode));
779 	INTOFF;
780 	if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
781 		checkzombies();
782 	flushall();
783 	pid = fork();
784 	if (pid == -1) {
785 		TRACE(("Fork failed, errno=%d\n", errno));
786 		INTON;
787 		error("Cannot fork: %s", strerror(errno));
788 	}
789 	if (pid == 0) {
790 		struct job *p;
791 		int wasroot;
792 		int i;
793 
794 		TRACE(("Child shell %d\n", (int)getpid()));
795 		wasroot = rootshell;
796 		rootshell = 0;
797 		handler = &main_handler;
798 		closescript();
799 		INTON;
800 		clear_traps();
801 #if JOBS
802 		jobctl = 0;		/* do job control only in root shell */
803 		if (wasroot && mode != FORK_NOJOB && mflag) {
804 			if (jp == NULL || jp->nprocs == 0)
805 				pgrp = getpid();
806 			else
807 				pgrp = jp->ps[0].pid;
808 			if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
809 				/*** this causes superfluous TIOCSPGRPS ***/
810 				if (tcsetpgrp(ttyfd, pgrp) < 0)
811 					error("tcsetpgrp failed, errno=%d", errno);
812 			}
813 			setsignal(SIGTSTP);
814 			setsignal(SIGTTOU);
815 		} else if (mode == FORK_BG) {
816 			ignoresig(SIGINT);
817 			ignoresig(SIGQUIT);
818 			if ((jp == NULL || jp->nprocs == 0) &&
819 			    ! fd0_redirected_p ()) {
820 				close(0);
821 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
822 					error("Can't open %s: %s",
823 					    _PATH_DEVNULL, strerror(errno));
824 			}
825 		}
826 #else
827 		if (mode == FORK_BG) {
828 			ignoresig(SIGINT);
829 			ignoresig(SIGQUIT);
830 			if ((jp == NULL || jp->nprocs == 0) &&
831 			    ! fd0_redirected_p ()) {
832 				close(0);
833 				if (open(_PATH_DEVNULL, O_RDONLY) != 0)
834 					error("Can't open %s: %s",
835 					    _PATH_DEVNULL, strerror(errno));
836 			}
837 		}
838 #endif
839 		INTOFF;
840 		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
841 			if (p->used)
842 				freejob(p);
843 		INTON;
844 		if (wasroot && iflag) {
845 			setsignal(SIGINT);
846 			setsignal(SIGQUIT);
847 			setsignal(SIGTERM);
848 		}
849 		return pid;
850 	}
851 	if (rootshell && mode != FORK_NOJOB && mflag) {
852 		if (jp == NULL || jp->nprocs == 0)
853 			pgrp = pid;
854 		else
855 			pgrp = jp->ps[0].pid;
856 		setpgid(pid, pgrp);
857 	}
858 	if (mode == FORK_BG) {
859 		if (bgjob != NULL && bgjob->state == JOBDONE &&
860 		    !bgjob->remembered && !iflag)
861 			freejob(bgjob);
862 		backgndpid = pid;		/* set $! */
863 		bgjob = jp;
864 	}
865 	if (jp) {
866 		struct procstat *ps = &jp->ps[jp->nprocs++];
867 		ps->pid = pid;
868 		ps->status = -1;
869 		ps->cmd = nullstr;
870 		if (iflag && rootshell && n)
871 			ps->cmd = commandtext(n);
872 		jp->foreground = mode == FORK_FG;
873 #if JOBS
874 		setcurjob(jp);
875 #endif
876 	}
877 	INTON;
878 	TRACE(("In parent shell:  child = %d\n", (int)pid));
879 	return pid;
880 }
881 
882 
883 
884 /*
885  * Wait for job to finish.
886  *
887  * Under job control we have the problem that while a child process is
888  * running interrupts generated by the user are sent to the child but not
889  * to the shell.  This means that an infinite loop started by an inter-
890  * active user may be hard to kill.  With job control turned off, an
891  * interactive user may place an interactive program inside a loop.  If
892  * the interactive program catches interrupts, the user doesn't want
893  * these interrupts to also abort the loop.  The approach we take here
894  * is to have the shell ignore interrupt signals while waiting for a
895  * foreground process to terminate, and then send itself an interrupt
896  * signal if the child process was terminated by an interrupt signal.
897  * Unfortunately, some programs want to do a bit of cleanup and then
898  * exit on interrupt; unless these processes terminate themselves by
899  * sending a signal to themselves (instead of calling exit) they will
900  * confuse this approach.
901  */
902 
903 int
904 waitforjob(struct job *jp, int *origstatus)
905 {
906 #if JOBS
907 	pid_t mypgrp = getpgrp();
908 	int propagate_int = jp->jobctl && jp->foreground;
909 #endif
910 	int status;
911 	int st;
912 
913 	INTOFF;
914 	TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
915 	while (jp->state == 0)
916 		if (dowait(1, jp) == -1)
917 			dotrap();
918 #if JOBS
919 	if (jp->jobctl) {
920 		if (tcsetpgrp(ttyfd, mypgrp) < 0)
921 			error("tcsetpgrp failed, errno=%d\n", errno);
922 	}
923 	if (jp->state == JOBSTOPPED)
924 		setcurjob(jp);
925 #endif
926 	status = jp->ps[jp->nprocs - 1].status;
927 	if (origstatus != NULL)
928 		*origstatus = status;
929 	/* convert to 8 bits */
930 	if (WIFEXITED(status))
931 		st = WEXITSTATUS(status);
932 #if JOBS
933 	else if (WIFSTOPPED(status))
934 		st = WSTOPSIG(status) + 128;
935 #endif
936 	else
937 		st = WTERMSIG(status) + 128;
938 	if (! JOBS || jp->state == JOBDONE)
939 		freejob(jp);
940 	if (int_pending()) {
941 		if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
942 			CLEAR_PENDING_INT;
943 	}
944 #if JOBS
945 	else if (rootshell && iflag && propagate_int &&
946 			WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
947 		kill(getpid(), SIGINT);
948 #endif
949 	INTON;
950 	return st;
951 }
952 
953 
954 
955 /*
956  * Wait for a process to terminate.
957  */
958 
959 static pid_t
960 dowait(int block, struct job *job)
961 {
962 	pid_t pid;
963 	int status;
964 	struct procstat *sp;
965 	struct job *jp;
966 	struct job *thisjob;
967 	int done;
968 	int stopped;
969 	int sig;
970 	int coredump;
971 
972 	in_dowait++;
973 	TRACE(("dowait(%d) called\n", block));
974 	do {
975 		pid = waitproc(block, &status);
976 		TRACE(("wait returns %d, status=%d\n", (int)pid, status));
977 	} while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
978 		 (pid > 0 && WIFSTOPPED(status) && !iflag));
979 	in_dowait--;
980 	if (pid == -1 && errno == ECHILD && job != NULL)
981 		job->state = JOBDONE;
982 	if (breakwaitcmd != 0) {
983 		breakwaitcmd = 0;
984 		/*
985 		 * Do not early terminate if the pid is positive, else the
986 		 * job will not be properly recorded.
987 		 */
988 		if (pid <= 0)
989 			return -1;
990 	}
991 	if (pid <= 0)
992 		return pid;
993 	INTOFF;
994 	thisjob = NULL;
995 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
996 		if (jp->used && jp->nprocs > 0) {
997 			done = 1;
998 			stopped = 1;
999 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1000 				if (sp->pid == -1)
1001 					continue;
1002 				if (sp->pid == pid) {
1003 					TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1004 						   (int)pid, sp->status,
1005 						   status));
1006 					sp->status = status;
1007 					thisjob = jp;
1008 				}
1009 				if (sp->status == -1)
1010 					stopped = 0;
1011 				else if (WIFSTOPPED(sp->status))
1012 					done = 0;
1013 			}
1014 			if (stopped) {		/* stopped or done */
1015 				int state = done? JOBDONE : JOBSTOPPED;
1016 				if (jp->state != state) {
1017 					TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1018 					jp->state = state;
1019 					if (jp != job) {
1020 						if (done && !jp->remembered &&
1021 						    !iflag && jp != bgjob)
1022 							freejob(jp);
1023 #if JOBS
1024 						else if (done)
1025 							deljob(jp);
1026 #endif
1027 					}
1028 				}
1029 			}
1030 		}
1031 	}
1032 	INTON;
1033 	if (!thisjob || thisjob->state == 0)
1034 		;
1035 	else if ((!rootshell || !iflag || thisjob == job) &&
1036 	    thisjob->foreground && thisjob->state != JOBSTOPPED) {
1037 		sig = 0;
1038 		coredump = 0;
1039 		for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1040 			if (WIFSIGNALED(sp->status)) {
1041 				sig = WTERMSIG(sp->status);
1042 				coredump = WCOREDUMP(sp->status);
1043 			}
1044 		if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1045 			if (sig < sys_nsig && sys_siglist[sig])
1046 				out2str(sys_siglist[sig]);
1047 			else
1048 				outfmt(out2, "Signal %d", sig);
1049 			if (coredump)
1050 				out2str(" (core dumped)");
1051 			out2c('\n');
1052 			flushout(out2);
1053 		}
1054 	} else {
1055 		TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1056 		thisjob->changed = 1;
1057 	}
1058 	return pid;
1059 }
1060 
1061 
1062 
1063 /*
1064  * Do a wait system call.  If job control is compiled in, we accept
1065  * stopped processes.  If block is zero, we return a value of zero
1066  * rather than blocking.
1067  */
1068 static pid_t
1069 waitproc(int block, int *status)
1070 {
1071 	int flags;
1072 
1073 #if JOBS
1074 	flags = WUNTRACED;
1075 #else
1076 	flags = 0;
1077 #endif
1078 	if (block == 0)
1079 		flags |= WNOHANG;
1080 	return wait3(status, flags, NULL);
1081 }
1082 
1083 /*
1084  * return 1 if there are stopped jobs, otherwise 0
1085  */
1086 int job_warning = 0;
1087 int
1088 stoppedjobs(void)
1089 {
1090 	int jobno;
1091 	struct job *jp;
1092 
1093 	if (job_warning)
1094 		return (0);
1095 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1096 		if (jp->used == 0)
1097 			continue;
1098 		if (jp->state == JOBSTOPPED) {
1099 			out2fmt_flush("You have stopped jobs.\n");
1100 			job_warning = 2;
1101 			return (1);
1102 		}
1103 	}
1104 
1105 	return (0);
1106 }
1107 
1108 
1109 static void
1110 checkzombies(void)
1111 {
1112 	while (njobs > 0 && dowait(0, NULL) > 0)
1113 		;
1114 }
1115 
1116 
1117 int
1118 backgndpidset(void)
1119 {
1120 	return backgndpid != -1;
1121 }
1122 
1123 
1124 pid_t
1125 backgndpidval(void)
1126 {
1127 	if (bgjob != NULL)
1128 		bgjob->remembered = 1;
1129 	return backgndpid;
1130 }
1131 
1132 /*
1133  * Return a string identifying a command (to be printed by the
1134  * jobs command.
1135  */
1136 
1137 static char *cmdnextc;
1138 static int cmdnleft;
1139 #define MAXCMDTEXT	200
1140 
1141 char *
1142 commandtext(union node *n)
1143 {
1144 	char *name;
1145 
1146 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
1147 	cmdnleft = MAXCMDTEXT - 4;
1148 	cmdtxt(n);
1149 	*cmdnextc = '\0';
1150 	return name;
1151 }
1152 
1153 
1154 static void
1155 cmdtxt(union node *n)
1156 {
1157 	union node *np;
1158 	struct nodelist *lp;
1159 	const char *p;
1160 	int i;
1161 	char s[2];
1162 
1163 	if (n == NULL)
1164 		return;
1165 	switch (n->type) {
1166 	case NSEMI:
1167 		cmdtxt(n->nbinary.ch1);
1168 		cmdputs("; ");
1169 		cmdtxt(n->nbinary.ch2);
1170 		break;
1171 	case NAND:
1172 		cmdtxt(n->nbinary.ch1);
1173 		cmdputs(" && ");
1174 		cmdtxt(n->nbinary.ch2);
1175 		break;
1176 	case NOR:
1177 		cmdtxt(n->nbinary.ch1);
1178 		cmdputs(" || ");
1179 		cmdtxt(n->nbinary.ch2);
1180 		break;
1181 	case NPIPE:
1182 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1183 			cmdtxt(lp->n);
1184 			if (lp->next)
1185 				cmdputs(" | ");
1186 		}
1187 		break;
1188 	case NSUBSHELL:
1189 		cmdputs("(");
1190 		cmdtxt(n->nredir.n);
1191 		cmdputs(")");
1192 		break;
1193 	case NREDIR:
1194 	case NBACKGND:
1195 		cmdtxt(n->nredir.n);
1196 		break;
1197 	case NIF:
1198 		cmdputs("if ");
1199 		cmdtxt(n->nif.test);
1200 		cmdputs("; then ");
1201 		cmdtxt(n->nif.ifpart);
1202 		cmdputs("...");
1203 		break;
1204 	case NWHILE:
1205 		cmdputs("while ");
1206 		goto until;
1207 	case NUNTIL:
1208 		cmdputs("until ");
1209 until:
1210 		cmdtxt(n->nbinary.ch1);
1211 		cmdputs("; do ");
1212 		cmdtxt(n->nbinary.ch2);
1213 		cmdputs("; done");
1214 		break;
1215 	case NFOR:
1216 		cmdputs("for ");
1217 		cmdputs(n->nfor.var);
1218 		cmdputs(" in ...");
1219 		break;
1220 	case NCASE:
1221 		cmdputs("case ");
1222 		cmdputs(n->ncase.expr->narg.text);
1223 		cmdputs(" in ...");
1224 		break;
1225 	case NDEFUN:
1226 		cmdputs(n->narg.text);
1227 		cmdputs("() ...");
1228 		break;
1229 	case NCMD:
1230 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
1231 			cmdtxt(np);
1232 			if (np->narg.next)
1233 				cmdputs(" ");
1234 		}
1235 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1236 			cmdputs(" ");
1237 			cmdtxt(np);
1238 		}
1239 		break;
1240 	case NARG:
1241 		cmdputs(n->narg.text);
1242 		break;
1243 	case NTO:
1244 		p = ">";  i = 1;  goto redir;
1245 	case NAPPEND:
1246 		p = ">>";  i = 1;  goto redir;
1247 	case NTOFD:
1248 		p = ">&";  i = 1;  goto redir;
1249 	case NCLOBBER:
1250 		p = ">|"; i = 1; goto redir;
1251 	case NFROM:
1252 		p = "<";  i = 0;  goto redir;
1253 	case NFROMTO:
1254 		p = "<>";  i = 0;  goto redir;
1255 	case NFROMFD:
1256 		p = "<&";  i = 0;  goto redir;
1257 redir:
1258 		if (n->nfile.fd != i) {
1259 			s[0] = n->nfile.fd + '0';
1260 			s[1] = '\0';
1261 			cmdputs(s);
1262 		}
1263 		cmdputs(p);
1264 		if (n->type == NTOFD || n->type == NFROMFD) {
1265 			if (n->ndup.dupfd >= 0)
1266 				s[0] = n->ndup.dupfd + '0';
1267 			else
1268 				s[0] = '-';
1269 			s[1] = '\0';
1270 			cmdputs(s);
1271 		} else {
1272 			cmdtxt(n->nfile.fname);
1273 		}
1274 		break;
1275 	case NHERE:
1276 	case NXHERE:
1277 		cmdputs("<<...");
1278 		break;
1279 	default:
1280 		cmdputs("???");
1281 		break;
1282 	}
1283 }
1284 
1285 
1286 
1287 static void
1288 cmdputs(const char *s)
1289 {
1290 	const char *p;
1291 	char *q;
1292 	char c;
1293 	int subtype = 0;
1294 
1295 	if (cmdnleft <= 0)
1296 		return;
1297 	p = s;
1298 	q = cmdnextc;
1299 	while ((c = *p++) != '\0') {
1300 		if (c == CTLESC)
1301 			*q++ = *p++;
1302 		else if (c == CTLVAR) {
1303 			*q++ = '$';
1304 			if (--cmdnleft > 0)
1305 				*q++ = '{';
1306 			subtype = *p++;
1307 			if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1308 				*q++ = '#';
1309 		} else if (c == '=' && subtype != 0) {
1310 			*q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1311 			if (*q)
1312 				q++;
1313 			else
1314 				cmdnleft++;
1315 			if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1316 			    (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1317 			    --cmdnleft > 0)
1318 				*q = q[-1], q++;
1319 			subtype = 0;
1320 		} else if (c == CTLENDVAR) {
1321 			*q++ = '}';
1322 		} else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1323 			cmdnleft -= 5;
1324 			if (cmdnleft > 0) {
1325 				*q++ = '$';
1326 				*q++ = '(';
1327 				*q++ = '.';
1328 				*q++ = '.';
1329 				*q++ = '.';
1330 				*q++ = ')';
1331 			}
1332 		} else if (c == CTLARI) {
1333 			cmdnleft -= 2;
1334 			if (cmdnleft > 0) {
1335 				*q++ = '$';
1336 				*q++ = '(';
1337 				*q++ = '(';
1338 			}
1339 			p++;
1340 		} else if (c == CTLENDARI) {
1341 			if (--cmdnleft > 0) {
1342 				*q++ = ')';
1343 				*q++ = ')';
1344 			}
1345 		} else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1346 			cmdnleft++; /* ignore */
1347 		else
1348 			*q++ = c;
1349 		if (--cmdnleft <= 0) {
1350 			*q++ = '.';
1351 			*q++ = '.';
1352 			*q++ = '.';
1353 			break;
1354 		}
1355 	}
1356 	cmdnextc = q;
1357 }
1358