xref: /netbsd-src/bin/sh/jobs.c (revision 4b896b232495b7a9b8b94a1cf1e21873296d53b8)
1 /*	$NetBSD: jobs.c,v 1.62 2003/12/18 00:56:05 christos 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.62 2003/12/18 00:56:05 christos Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <stdlib.h>
49 #include <paths.h>
50 #include <sys/types.h>
51 #include <sys/param.h>
52 #ifdef BSD
53 #include <sys/wait.h>
54 #include <sys/time.h>
55 #include <sys/resource.h>
56 #endif
57 #include <sys/ioctl.h>
58 
59 #include "shell.h"
60 #if JOBS
61 #if OLD_TTY_DRIVER
62 #include "sgtty.h"
63 #else
64 #include <termios.h>
65 #endif
66 #undef CEOF			/* syntax.h redefines this */
67 #endif
68 #include "redir.h"
69 #include "show.h"
70 #include "main.h"
71 #include "parser.h"
72 #include "nodes.h"
73 #include "jobs.h"
74 #include "options.h"
75 #include "trap.h"
76 #include "syntax.h"
77 #include "input.h"
78 #include "output.h"
79 #include "memalloc.h"
80 #include "error.h"
81 #include "mystring.h"
82 
83 
84 static struct job *jobtab;		/* array of jobs */
85 static int njobs;			/* size of array */
86 static int jobs_invalid;		/* set in child */
87 MKINIT pid_t backgndpid = -1;	/* pid of last background process */
88 #if JOBS
89 int initialpgrp;		/* pgrp of shell on invocation */
90 static int curjob = -1;		/* current job */
91 #endif
92 static int ttyfd = -1;
93 
94 STATIC void restartjob(struct job *);
95 STATIC void freejob(struct job *);
96 STATIC struct job *getjob(const char *, int);
97 STATIC int dowait(int, struct job *);
98 STATIC int onsigchild(void);
99 STATIC int waitproc(int, struct job *, int *);
100 STATIC void cmdtxt(union node *);
101 STATIC void cmdlist(union node *, int);
102 STATIC void cmdputs(const char *);
103 
104 #ifdef OLD_TTY_DRIVER
105 static pid_t tcgetpgrp(int fd);
106 static int tcsetpgrp(int fd, pid_t pgrp);
107 
108 static pid_t
109 tcgetpgrp(int fd)
110 {
111 	pid_t pgrp;
112 	if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
113 		return -1;
114 	else
115 		return pgrp;
116 }
117 
118 static int
119 tcsetpgrp(int fd, pid_tpgrp)
120 {
121 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
122 }
123 #endif
124 
125 /*
126  * Turn job control on and off.
127  *
128  * Note:  This code assumes that the third arg to ioctl is a character
129  * pointer, which is true on Berkeley systems but not System V.  Since
130  * System V doesn't have job control yet, this isn't a problem now.
131  */
132 
133 MKINIT int jobctl;
134 
135 void
136 setjobctl(int on)
137 {
138 #ifdef OLD_TTY_DRIVER
139 	int ldisc;
140 #endif
141 
142 	if (on == jobctl || rootshell == 0)
143 		return;
144 	if (on) {
145 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
146 		int err;
147 		int i;
148 		if (ttyfd != -1)
149 			close(ttyfd);
150 		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
151 			for (i = 0; i < 3; i++) {
152 				if (isatty(i) && (ttyfd = dup(i)) != -1)
153 					break;
154 			}
155 			if (i == 3)
156 				goto out;
157 		}
158 		/* Move to a high fd */
159 		for (i = 10; i > 2; i--) {
160 			if ((err = fcntl(ttyfd, F_DUPFD, (1 << i) - 1)) != -1)
161 				break;
162 		}
163 		if (err != -1) {
164 			close(ttyfd);
165 			ttyfd = err;
166 		}
167 #ifdef FIOCLEX
168 		err = ioctl(ttyfd, FIOCLEX, 0);
169 #elif FD_CLOEXEC
170 		err = fcntl(ttyfd, F_SETFD,
171 		    fcntl(ttyfd, F_GETFD, 0) | FD_CLOEXEC);
172 #endif
173 		if (err == -1) {
174 			close(ttyfd);
175 			ttyfd = -1;
176 			goto out;
177 		}
178 #else
179 		out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
180 		goto out;
181 #endif
182 		do { /* while we are in the background */
183 			if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
184 out:
185 				out2str("sh: can't access tty; job control turned off\n");
186 				mflag = 0;
187 				return;
188 			}
189 			if (initialpgrp == -1)
190 				initialpgrp = getpgrp();
191 			else if (initialpgrp != getpgrp()) {
192 				killpg(0, SIGTTIN);
193 				continue;
194 			}
195 		} while (0);
196 
197 #ifdef OLD_TTY_DRIVER
198 		if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
199 		    || ldisc != NTTYDISC) {
200 			out2str("sh: need new tty driver to run job control; job control turned off\n");
201 			mflag = 0;
202 			return;
203 		}
204 #endif
205 		setsignal(SIGTSTP, 0);
206 		setsignal(SIGTTOU, 0);
207 		setsignal(SIGTTIN, 0);
208 		if (getpgid(0) != rootpid && setpgid(0, rootpid) == -1)
209 			error("Cannot set process group (%s) at %d",
210 			    strerror(errno), __LINE__);
211 		if (tcsetpgrp(ttyfd, rootpid) == -1)
212 			error("Cannot set tty process group (%s) at %d",
213 			    strerror(errno), __LINE__);
214 	} else { /* turning job control off */
215 		if (getpgid(0) != initialpgrp && setpgid(0, initialpgrp) == -1)
216 			error("Cannot set process group (%s) at %d",
217 			    strerror(errno), __LINE__);
218 		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
219 			error("Cannot set tty process group (%s) at %d",
220 			    strerror(errno), __LINE__);
221 		close(ttyfd);
222 		ttyfd = -1;
223 		setsignal(SIGTSTP, 0);
224 		setsignal(SIGTTOU, 0);
225 		setsignal(SIGTTIN, 0);
226 	}
227 	jobctl = on;
228 }
229 
230 
231 #ifdef mkinit
232 INCLUDE <stdlib.h>
233 
234 SHELLPROC {
235 	backgndpid = -1;
236 #if JOBS
237 	jobctl = 0;
238 #endif
239 }
240 
241 #endif
242 
243 
244 
245 #if JOBS
246 int
247 fgcmd(int argc, char **argv)
248 {
249 	struct job *jp;
250 	int i;
251 	int status;
252 
253 	nextopt("");
254 	jp = getjob(*argptr, 0);
255 	if (jp->jobctl == 0)
256 		error("job not created under job control");
257 	out1fmt("%s", jp->ps[0].cmd);
258 	for (i = 1; i < jp->nprocs; i++)
259 		out1fmt(" | %s", jp->ps[i].cmd );
260 	out1c('\n');
261 	flushall();
262 
263 	for (i = 0; i < jp->nprocs; i++)
264 	    if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
265 		    break;
266 
267 	if (i >= jp->nprocs) {
268 		error("Cannot set tty process group (%s) at %d",
269 		    strerror(errno), __LINE__);
270 	}
271 	restartjob(jp);
272 	INTOFF;
273 	status = waitforjob(jp);
274 	INTON;
275 	return status;
276 }
277 
278 static void
279 set_curjob(struct job *jp, int mode)
280 {
281 	struct job *jp1, *jp2;
282 	int i, ji;
283 
284 	ji = jp - jobtab;
285 
286 	/* first remove from list */
287 	if (ji == curjob)
288 		curjob = jp->prev_job;
289 	else {
290 		for (i = 0; i < njobs; i++) {
291 			if (jobtab[i].prev_job != ji)
292 				continue;
293 			jobtab[i].prev_job = jp->prev_job;
294 			break;
295 		}
296 	}
297 
298 	/* Then re-insert in correct position */
299 	switch (mode) {
300 	case 0:	/* job being deleted */
301 		jp->prev_job = -1;
302 		break;
303 	case 1:	/* newly created job or backgrounded job,
304 		   put after all stopped jobs. */
305 		if (curjob != -1 && jobtab[curjob].state == JOBSTOPPED) {
306 			for (jp1 = jobtab + curjob; ; jp1 = jp2) {
307 				if (jp1->prev_job == -1)
308 					break;
309 				jp2 = jobtab + jp1->prev_job;
310 				if (jp2->state != JOBSTOPPED)
311 					break;
312 			}
313 			jp->prev_job = jp1->prev_job;
314 			jp1->prev_job = ji;
315 			break;
316 		}
317 		/* FALLTHROUGH */
318 	case 2:	/* newly stopped job - becomes curjob */
319 		jp->prev_job = curjob;
320 		curjob = ji;
321 		break;
322 	}
323 }
324 
325 int
326 bgcmd(int argc, char **argv)
327 {
328 	struct job *jp;
329 	int i;
330 
331 	nextopt("");
332 	do {
333 		jp = getjob(*argptr, 0);
334 		if (jp->jobctl == 0)
335 			error("job not created under job control");
336 		set_curjob(jp, 1);
337 		out1fmt("[%ld] %s", (long)(jp - jobtab + 1), jp->ps[0].cmd);
338 		for (i = 1; i < jp->nprocs; i++)
339 			out1fmt(" | %s", jp->ps[i].cmd );
340 		out1c('\n');
341 		flushall();
342 		restartjob(jp);
343 	} while (*argptr && *++argptr);
344 	return 0;
345 }
346 
347 
348 STATIC void
349 restartjob(struct job *jp)
350 {
351 	struct procstat *ps;
352 	int i;
353 
354 	if (jp->state == JOBDONE)
355 		return;
356 	INTOFF;
357 	for (i = 0; i < jp->nprocs; i++)
358 		if (killpg(jp->ps[i].pid, SIGCONT) != -1)
359 			break;
360 	if (i >= jp->nprocs)
361 		error("Cannot continue job (%s)", strerror(errno));
362 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
363 		if (WIFSTOPPED(ps->status)) {
364 			ps->status = -1;
365 			jp->state = JOBRUNNING;
366 		}
367 	}
368 	INTON;
369 }
370 #endif
371 
372 static void
373 showjob(struct output *out, struct job *jp, int mode)
374 {
375 	int procno;
376 	int st;
377 	struct procstat *ps;
378 	int col;
379 	char s[64];
380 
381 #if JOBS
382 	if (mode & SHOW_PGID) {
383 		/* just output process (group) id of pipeline */
384 		outfmt(out, "%ld\n", (long)jp->ps->pid);
385 		return;
386 	}
387 #endif
388 
389 	procno = jp->nprocs;
390 	if (!procno)
391 		return;
392 
393 	if (mode & SHOW_PID)
394 		mode |= SHOW_MULTILINE;
395 
396 	if ((procno > 1 && !(mode & SHOW_MULTILINE))
397 	    || (mode & SHOW_SIGNALLED)) {
398 		/* See if we have more than one status to report */
399 		ps = jp->ps;
400 		st = ps->status;
401 		do {
402 			int st1 = ps->status;
403 			if (st1 != st)
404 				/* yes - need multi-line output */
405 				mode |= SHOW_MULTILINE;
406 			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
407 				continue;
408 			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
409 			    && st1 != SIGINT && st1 != SIGPIPE))
410 				mode |= SHOW_ISSIG;
411 
412 		} while (ps++, --procno);
413 		procno = jp->nprocs;
414 	}
415 
416 	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
417 		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
418 			TRACE(("showjob: freeing job %d\n", jp - jobtab + 1));
419 			freejob(jp);
420 		}
421 		return;
422 	}
423 
424 	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
425 		if (ps == jp->ps)
426 			fmtstr(s, 16, "[%ld] %c ",
427 				(long)(jp - jobtab + 1),
428 #if JOBS
429 				jp == jobtab + curjob ? '+' :
430 				curjob != -1 && jp == jobtab +
431 					    jobtab[curjob].prev_job ? '-' :
432 #endif
433 				' ');
434 		else
435 			fmtstr(s, 16, "      " );
436 		col = strlen(s);
437 		if (mode & SHOW_PID) {
438 			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
439 			     col += strlen(s + col);
440 		}
441 		if (ps->status == -1) {
442 			scopy("Running", s + col);
443 		} else if (WIFEXITED(ps->status)) {
444 			st = WEXITSTATUS(ps->status);
445 			if (st)
446 				fmtstr(s + col, 16, "Done(%d)", st);
447 			else
448 				fmtstr(s + col, 16, "Done");
449 		} else {
450 #if JOBS
451 			if (WIFSTOPPED(ps->status))
452 				st = WSTOPSIG(ps->status);
453 			else /* WIFSIGNALED(ps->status) */
454 #endif
455 				st = WTERMSIG(ps->status);
456 			st &= 0x7f;
457 			if (st < NSIG && sys_siglist[st])
458 				scopyn(sys_siglist[st], s + col, 32);
459 			else
460 				fmtstr(s + col, 16, "Signal %d", st);
461 			if (WCOREDUMP(ps->status)) {
462 				col += strlen(s + col);
463 				scopyn(" (core dumped)", s + col,  64 - col);
464 			}
465 		}
466 		col += strlen(s + col);
467 		outstr(s, out);
468 		do {
469 			outc(' ', out);
470 			col++;
471 		} while (col < 30);
472 		outstr(ps->cmd, out);
473 		if (mode & SHOW_MULTILINE) {
474 			if (procno > 0) {
475 				outc(' ', out);
476 				outc('|', out);
477 			}
478 		} else {
479 			while (--procno >= 0)
480 				outfmt(out, " | %s", (++ps)->cmd );
481 		}
482 		outc('\n', out);
483 	}
484 	flushout(out);
485 	jp->changed = 0;
486 	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
487 		freejob(jp);
488 }
489 
490 
491 int
492 jobscmd(int argc, char **argv)
493 {
494 	int mode, m;
495 	int sv = jobs_invalid;
496 
497 	jobs_invalid = 0;
498 	mode = 0;
499 	while ((m = nextopt("lp")))
500 		if (m == 'l')
501 			mode = SHOW_PID;
502 		else
503 			mode = SHOW_PGID;
504 	if (*argptr)
505 		do
506 			showjob(out1, getjob(*argptr,0), mode);
507 		while (*++argptr);
508 	else
509 		showjobs(out1, mode);
510 	jobs_invalid = sv;
511 	return 0;
512 }
513 
514 
515 /*
516  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
517  * statuses have changed since the last call to showjobs.
518  *
519  * If the shell is interrupted in the process of creating a job, the
520  * result may be a job structure containing zero processes.  Such structures
521  * will be freed here.
522  */
523 
524 void
525 showjobs(struct output *out, int mode)
526 {
527 	int jobno;
528 	struct job *jp;
529 	int silent = 0, gotpid;
530 
531 	TRACE(("showjobs(%x) called\n", mode));
532 
533 	/* If not even one one job changed, there is nothing to do */
534 	gotpid = dowait(0, NULL);
535 	while (dowait(0, NULL) > 0)
536 		continue;
537 #ifdef JOBS
538 	/*
539 	 * Check if we are not in our foreground group, and if not
540 	 * put us in it.
541 	 */
542 	if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
543 		if (tcsetpgrp(ttyfd, getpid()) == -1)
544 			error("Cannot set tty process group (%s) at %d",
545 			    strerror(errno), __LINE__);
546 		TRACE(("repaired tty process group\n"));
547 		silent = 1;
548 	}
549 #endif
550 	if (jobs_invalid)
551 		return;
552 
553 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
554 		if (!jp->used)
555 			continue;
556 		if (jp->nprocs == 0) {
557 			freejob(jp);
558 			continue;
559 		}
560 		if ((mode & SHOW_CHANGED) && !jp->changed)
561 			continue;
562 		if (silent && jp->changed) {
563 			jp->changed = 0;
564 			continue;
565 		}
566 		showjob(out, jp, mode);
567 	}
568 }
569 
570 /*
571  * Mark a job structure as unused.
572  */
573 
574 STATIC void
575 freejob(struct job *jp)
576 {
577 	INTOFF;
578 	if (jp->ps != &jp->ps0) {
579 		ckfree(jp->ps);
580 		jp->ps = &jp->ps0;
581 	}
582 	jp->nprocs = 0;
583 	jp->used = 0;
584 #if JOBS
585 	set_curjob(jp, 0);
586 #endif
587 	INTON;
588 }
589 
590 
591 
592 int
593 waitcmd(int argc, char **argv)
594 {
595 	struct job *job;
596 	int status, retval;
597 	struct job *jp;
598 
599 	nextopt("");
600 
601 	if (!*argptr) {
602 		/* wait for all jobs */
603 		jp = jobtab;
604 		if (jobs_invalid)
605 			return 0;
606 		for (;;) {
607 			if (jp >= jobtab + njobs) {
608 				/* no running procs */
609 				return 0;
610 			}
611 			if (!jp->used || jp->state != JOBRUNNING) {
612 				jp++;
613 				continue;
614 			}
615 			if (dowait(1, (struct job *)NULL) == -1)
616 			       return 128 + SIGINT;
617 			jp = jobtab;
618 		}
619 	}
620 
621 	for (; *argptr; argptr++) {
622 		job = getjob(*argptr, 1);
623 		if (!job) {
624 			retval = 127;
625 			continue;
626 		}
627 		/* loop until process terminated or stopped */
628 		while (job->state == JOBRUNNING) {
629 			if (dowait(1, (struct job *)NULL) == -1)
630 			       return 128 + SIGINT;
631 		}
632 		status = job->ps[job->nprocs].status;
633 		if (WIFEXITED(status))
634 			retval = WEXITSTATUS(status);
635 #if JOBS
636 		else if (WIFSTOPPED(status))
637 			retval = WSTOPSIG(status) + 128;
638 #endif
639 		else {
640 			/* XXX: limits number of signals */
641 			retval = WTERMSIG(status) + 128;
642 		}
643 		if (!iflag)
644 			freejob(job);
645 	}
646 	return retval;
647 }
648 
649 
650 
651 int
652 jobidcmd(int argc, char **argv)
653 {
654 	struct job *jp;
655 	int i;
656 
657 	nextopt("");
658 	jp = getjob(*argptr, 0);
659 	for (i = 0 ; i < jp->nprocs ; ) {
660 		out1fmt("%ld", (long)jp->ps[i].pid);
661 		out1c(++i < jp->nprocs ? ' ' : '\n');
662 	}
663 	return 0;
664 }
665 
666 int
667 getjobpgrp(const char *name)
668 {
669 	struct job *jp;
670 
671 	jp = getjob(name, 1);
672 	if (jp == 0)
673 		return 0;
674 	return -jp->ps[0].pid;
675 }
676 
677 /*
678  * Convert a job name to a job structure.
679  */
680 
681 STATIC struct job *
682 getjob(const char *name, int noerror)
683 {
684 	int jobno = -1;
685 	struct job *jp;
686 	int pid;
687 	int i;
688 	const char *err_msg = "No such job: %s";
689 
690 	if (name == NULL) {
691 #if JOBS
692 		jobno = curjob;
693 #endif
694 		err_msg = "No current job";
695 	} else if (name[0] == '%') {
696 		if (is_number(name + 1)) {
697 			jobno = number(name + 1) - 1;
698 		} else if (!name[2]) {
699 			switch (name[1]) {
700 #if JOBS
701 			case 0:
702 			case '+':
703 			case '%':
704 				jobno = curjob;
705 				err_msg = "No current job";
706 				break;
707 			case '-':
708 				jobno = curjob;
709 				if (jobno != -1)
710 					jobno = jobtab[jobno].prev_job;
711 				err_msg = "No previous job";
712 				break;
713 #endif
714 			default:
715 				goto check_pattern;
716 			}
717 		} else {
718 			struct job *found;
719     check_pattern:
720 			found = NULL;
721 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
722 				if (!jp->used || jp->nprocs <= 0)
723 					continue;
724 				if ((name[1] == '?'
725 					&& strstr(jp->ps[0].cmd, name + 2))
726 				    || prefix(name + 1, jp->ps[0].cmd)) {
727 					if (found) {
728 						err_msg = "%s: ambiguous";
729 						found = 0;
730 						break;
731 					}
732 					found = jp;
733 				}
734 			}
735 			if (found)
736 				return found;
737 		}
738 
739 	} else if (is_number(name)) {
740 		pid = number(name);
741 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
742 			if (jp->used && jp->nprocs > 0
743 			 && jp->ps[jp->nprocs - 1].pid == pid)
744 				return jp;
745 		}
746 	}
747 
748 	if (!jobs_invalid && jobno >= 0 && jobno < njobs) {
749 		jp = jobtab + jobno;
750 		if (jp->used)
751 			return jp;
752 	}
753 	if (!noerror)
754 		error(err_msg, name);
755 	return 0;
756 }
757 
758 
759 
760 /*
761  * Return a new job structure,
762  */
763 
764 struct job *
765 makejob(union node *node, int nprocs)
766 {
767 	int i;
768 	struct job *jp;
769 
770 	if (jobs_invalid) {
771 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
772 			if (jp->used)
773 				freejob(jp);
774 		}
775 		jobs_invalid = 0;
776 	}
777 
778 	for (i = njobs, jp = jobtab ; ; jp++) {
779 		if (--i < 0) {
780 			INTOFF;
781 			if (njobs == 0) {
782 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
783 			} else {
784 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
785 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
786 				/* Relocate `ps' pointers */
787 				for (i = 0; i < njobs; i++)
788 					if (jp[i].ps == &jobtab[i].ps0)
789 						jp[i].ps = &jp[i].ps0;
790 				ckfree(jobtab);
791 				jobtab = jp;
792 			}
793 			jp = jobtab + njobs;
794 			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
795 			INTON;
796 			break;
797 		}
798 		if (jp->used == 0)
799 			break;
800 	}
801 	INTOFF;
802 	jp->state = JOBRUNNING;
803 	jp->used = 1;
804 	jp->changed = 0;
805 	jp->nprocs = 0;
806 #if JOBS
807 	jp->jobctl = jobctl;
808 	set_curjob(jp, 1);
809 #endif
810 	if (nprocs > 1) {
811 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
812 	} else {
813 		jp->ps = &jp->ps0;
814 	}
815 	INTON;
816 	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
817 	    jp - jobtab + 1));
818 	return jp;
819 }
820 
821 
822 /*
823  * Fork off a subshell.  If we are doing job control, give the subshell its
824  * own process group.  Jp is a job structure that the job is to be added to.
825  * N is the command that will be evaluated by the child.  Both jp and n may
826  * be NULL.  The mode parameter can be one of the following:
827  *	FORK_FG - Fork off a foreground process.
828  *	FORK_BG - Fork off a background process.
829  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
830  *		     process group even if job control is on.
831  *
832  * When job control is turned off, background processes have their standard
833  * input redirected to /dev/null (except for the second and later processes
834  * in a pipeline).
835  */
836 
837 int
838 forkshell(struct job *jp, union node *n, int mode)
839 {
840 	int pid;
841 
842 	TRACE(("forkshell(%%%d, %p, %d) called\n", jp - jobtab, n, mode));
843 	switch ((pid = fork())) {
844 	case -1:
845 		TRACE(("Fork failed, errno=%d\n", errno));
846 		INTON;
847 		error("Cannot fork");
848 		break;
849 	case 0:
850 		forkchild(jp, n, mode, 0);
851 		return 0;
852 	default:
853 		return forkparent(jp, n, mode, pid);
854 	}
855 }
856 
857 int
858 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
859 {
860 	int pgrp;
861 
862 	if (rootshell && mode != FORK_NOJOB && mflag) {
863 		if (jp == NULL || jp->nprocs == 0)
864 			pgrp = pid;
865 		else
866 			pgrp = jp->ps[0].pid;
867 		/* This can fail because we are doing it in the child also */
868 		(void)setpgid(pid, pgrp);
869 	}
870 	if (mode == FORK_BG)
871 		backgndpid = pid;		/* set $! */
872 	if (jp) {
873 		struct procstat *ps = &jp->ps[jp->nprocs++];
874 		ps->pid = pid;
875 		ps->status = -1;
876 		ps->cmd[0] = 0;
877 		if (/* iflag && rootshell && */ n)
878 			commandtext(ps, n);
879 	}
880 	TRACE(("In parent shell:  child = %d\n", pid));
881 	return pid;
882 }
883 
884 void
885 forkchild(struct job *jp, union node *n, int mode, int vforked)
886 {
887 	int wasroot;
888 	int pgrp;
889 	const char *devnull = _PATH_DEVNULL;
890 	const char *nullerr = "Can't open %s";
891 
892 	wasroot = rootshell;
893 	TRACE(("Child shell %d\n", getpid()));
894 	if (!vforked)
895 		rootshell = 0;
896 
897 	closescript(vforked);
898 	clear_traps(vforked);
899 #if JOBS
900 	if (!vforked)
901 		jobctl = 0;		/* do job control only in root shell */
902 	if (wasroot && mode != FORK_NOJOB && mflag) {
903 		if (jp == NULL || jp->nprocs == 0)
904 			pgrp = getpid();
905 		else
906 			pgrp = jp->ps[0].pid;
907 		/* This can fail because we are doing it in the parent also */
908 		(void)setpgid(0, pgrp);
909 		if (mode == FORK_FG) {
910 			if (tcsetpgrp(ttyfd, pgrp) == -1)
911 				error("Cannot set tty process group (%s) at %d",
912 				    strerror(errno), __LINE__);
913 		}
914 		setsignal(SIGTSTP, vforked);
915 		setsignal(SIGTTOU, vforked);
916 	} else if (mode == FORK_BG) {
917 		ignoresig(SIGINT, vforked);
918 		ignoresig(SIGQUIT, vforked);
919 		if ((jp == NULL || jp->nprocs == 0) &&
920 		    ! fd0_redirected_p ()) {
921 			close(0);
922 			if (open(devnull, O_RDONLY) != 0)
923 				error(nullerr, devnull);
924 		}
925 	}
926 #else
927 	if (mode == FORK_BG) {
928 		ignoresig(SIGINT, vforked);
929 		ignoresig(SIGQUIT, vforked);
930 		if ((jp == NULL || jp->nprocs == 0) &&
931 		    ! fd0_redirected_p ()) {
932 			close(0);
933 			if (open(devnull, O_RDONLY) != 0)
934 				error(nullerr, devnull);
935 		}
936 	}
937 #endif
938 	if (wasroot && iflag) {
939 		setsignal(SIGINT, vforked);
940 		setsignal(SIGQUIT, vforked);
941 		setsignal(SIGTERM, vforked);
942 	}
943 
944 	if (!vforked)
945 		jobs_invalid = 1;
946 }
947 
948 /*
949  * Wait for job to finish.
950  *
951  * Under job control we have the problem that while a child process is
952  * running interrupts generated by the user are sent to the child but not
953  * to the shell.  This means that an infinite loop started by an inter-
954  * active user may be hard to kill.  With job control turned off, an
955  * interactive user may place an interactive program inside a loop.  If
956  * the interactive program catches interrupts, the user doesn't want
957  * these interrupts to also abort the loop.  The approach we take here
958  * is to have the shell ignore interrupt signals while waiting for a
959  * forground process to terminate, and then send itself an interrupt
960  * signal if the child process was terminated by an interrupt signal.
961  * Unfortunately, some programs want to do a bit of cleanup and then
962  * exit on interrupt; unless these processes terminate themselves by
963  * sending a signal to themselves (instead of calling exit) they will
964  * confuse this approach.
965  */
966 
967 int
968 waitforjob(struct job *jp)
969 {
970 #if JOBS
971 	int mypgrp = getpgrp();
972 #endif
973 	int status;
974 	int st;
975 
976 	INTOFF;
977 	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
978 	while (jp->state == JOBRUNNING) {
979 		dowait(1, jp);
980 	}
981 #if JOBS
982 	if (jp->jobctl) {
983 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
984 			error("Cannot set tty process group (%s) at %d",
985 			    strerror(errno), __LINE__);
986 	}
987 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
988 		set_curjob(jp, 2);
989 #endif
990 	status = jp->ps[jp->nprocs - 1].status;
991 	/* convert to 8 bits */
992 	if (WIFEXITED(status))
993 		st = WEXITSTATUS(status);
994 #if JOBS
995 	else if (WIFSTOPPED(status))
996 		st = WSTOPSIG(status) + 128;
997 #endif
998 	else
999 		st = WTERMSIG(status) + 128;
1000 	TRACE(("waitforjob: job %d, nproc %d, status %x, st %x\n",
1001 		jp - jobtab + 1, jp->nprocs, status, st ));
1002 #if JOBS
1003 	if (jp->jobctl) {
1004 		/*
1005 		 * This is truly gross.
1006 		 * If we're doing job control, then we did a TIOCSPGRP which
1007 		 * caused us (the shell) to no longer be in the controlling
1008 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
1009 		 * intuit from the subprocess exit status whether a SIGINT
1010 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
1011 		 */
1012 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1013 			raise(SIGINT);
1014 	}
1015 #endif
1016 	if (! JOBS || jp->state == JOBDONE)
1017 		freejob(jp);
1018 	INTON;
1019 	return st;
1020 }
1021 
1022 
1023 
1024 /*
1025  * Wait for a process to terminate.
1026  */
1027 
1028 STATIC int
1029 dowait(int block, struct job *job)
1030 {
1031 	int pid;
1032 	int status;
1033 	struct procstat *sp;
1034 	struct job *jp;
1035 	struct job *thisjob;
1036 	int done;
1037 	int stopped;
1038 	extern volatile char gotsig[];
1039 
1040 	TRACE(("dowait(%d) called\n", block));
1041 	do {
1042 		pid = waitproc(block, job, &status);
1043 		TRACE(("wait returns pid %d, status %d\n", pid, status));
1044 	} while (pid == -1 && errno == EINTR && gotsig[SIGINT - 1] == 0);
1045 	if (pid <= 0)
1046 		return pid;
1047 	INTOFF;
1048 	thisjob = NULL;
1049 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1050 		if (jp->used) {
1051 			done = 1;
1052 			stopped = 1;
1053 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1054 				if (sp->pid == -1)
1055 					continue;
1056 				if (sp->pid == pid) {
1057 					TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jp - jobtab + 1, pid, sp->status, status));
1058 					sp->status = status;
1059 					thisjob = jp;
1060 				}
1061 				if (sp->status == -1)
1062 					stopped = 0;
1063 				else if (WIFSTOPPED(sp->status))
1064 					done = 0;
1065 			}
1066 			if (stopped) {		/* stopped or done */
1067 				int state = done ? JOBDONE : JOBSTOPPED;
1068 				if (jp->state != state) {
1069 					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1070 					jp->state = state;
1071 #if JOBS
1072 					if (done)
1073 						set_curjob(jp, 0);
1074 #endif
1075 				}
1076 			}
1077 		}
1078 	}
1079 
1080 	if (thisjob && thisjob->state != JOBRUNNING) {
1081 		int mode = 0;
1082 		if (!rootshell || !iflag)
1083 			mode = SHOW_SIGNALLED;
1084 		if (job == thisjob)
1085 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
1086 		if (mode)
1087 			showjob(out2, thisjob, mode);
1088 		else {
1089 			TRACE(("Not printing status, rootshell=%d, job=%p\n",
1090 				rootshell, job));
1091 			thisjob->changed = 1;
1092 		}
1093 	}
1094 
1095 	INTON;
1096 	return pid;
1097 }
1098 
1099 
1100 
1101 /*
1102  * Do a wait system call.  If job control is compiled in, we accept
1103  * stopped processes.  If block is zero, we return a value of zero
1104  * rather than blocking.
1105  *
1106  * System V doesn't have a non-blocking wait system call.  It does
1107  * have a SIGCLD signal that is sent to a process when one of it's
1108  * children dies.  The obvious way to use SIGCLD would be to install
1109  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
1110  * was received, and have waitproc bump another counter when it got
1111  * the status of a process.  Waitproc would then know that a wait
1112  * system call would not block if the two counters were different.
1113  * This approach doesn't work because if a process has children that
1114  * have not been waited for, System V will send it a SIGCLD when it
1115  * installs a signal handler for SIGCLD.  What this means is that when
1116  * a child exits, the shell will be sent SIGCLD signals continuously
1117  * until is runs out of stack space, unless it does a wait call before
1118  * restoring the signal handler.  The code below takes advantage of
1119  * this (mis)feature by installing a signal handler for SIGCLD and
1120  * then checking to see whether it was called.  If there are any
1121  * children to be waited for, it will be.
1122  *
1123  * If neither SYSV nor BSD is defined, we don't implement nonblocking
1124  * waits at all.  In this case, the user will not be informed when
1125  * a background process until the next time she runs a real program
1126  * (as opposed to running a builtin command or just typing return),
1127  * and the jobs command may give out of date information.
1128  */
1129 
1130 #ifdef SYSV
1131 STATIC int gotsigchild;
1132 
1133 STATIC int onsigchild() {
1134 	gotsigchild = 1;
1135 }
1136 #endif
1137 
1138 
1139 STATIC int
1140 waitproc(int block, struct job *jp, int *status)
1141 {
1142 #ifdef BSD
1143 	int flags = 0;
1144 
1145 #if JOBS
1146 	if (jp != NULL && jp->jobctl)
1147 		flags |= WUNTRACED;
1148 #endif
1149 	if (block == 0)
1150 		flags |= WNOHANG;
1151 	return wait3(status, flags, (struct rusage *)NULL);
1152 #else
1153 #ifdef SYSV
1154 	int (*save)();
1155 
1156 	if (block == 0) {
1157 		gotsigchild = 0;
1158 		save = signal(SIGCLD, onsigchild);
1159 		signal(SIGCLD, save);
1160 		if (gotsigchild == 0)
1161 			return 0;
1162 	}
1163 	return wait(status);
1164 #else
1165 	if (block == 0)
1166 		return 0;
1167 	return wait(status);
1168 #endif
1169 #endif
1170 }
1171 
1172 /*
1173  * return 1 if there are stopped jobs, otherwise 0
1174  */
1175 int job_warning = 0;
1176 int
1177 stoppedjobs(void)
1178 {
1179 	int jobno;
1180 	struct job *jp;
1181 
1182 	if (job_warning || jobs_invalid)
1183 		return (0);
1184 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1185 		if (jp->used == 0)
1186 			continue;
1187 		if (jp->state == JOBSTOPPED) {
1188 			out2str("You have stopped jobs.\n");
1189 			job_warning = 2;
1190 			return (1);
1191 		}
1192 	}
1193 
1194 	return (0);
1195 }
1196 
1197 /*
1198  * Return a string identifying a command (to be printed by the
1199  * jobs command).
1200  */
1201 
1202 STATIC char *cmdnextc;
1203 STATIC int cmdnleft;
1204 
1205 void
1206 commandtext(struct procstat *ps, union node *n)
1207 {
1208 	int len;
1209 
1210 	cmdnextc = ps->cmd;
1211 	if (iflag || mflag || sizeof ps->cmd < 100)
1212 		len = sizeof(ps->cmd);
1213 	else
1214 		len = sizeof(ps->cmd) / 10;
1215 	cmdnleft = len;
1216 	cmdtxt(n);
1217 	if (cmdnleft <= 0) {
1218 		char *p = ps->cmd + len - 4;
1219 		p[0] = '.';
1220 		p[1] = '.';
1221 		p[2] = '.';
1222 		p[3] = 0;
1223 	} else
1224 		*cmdnextc = '\0';
1225 	TRACE(("commandtext: ps->cmd %x, end %x, left %d\n\t\"%s\"\n",
1226 		ps->cmd, cmdnextc, cmdnleft, ps->cmd));
1227 }
1228 
1229 
1230 STATIC void
1231 cmdtxt(union node *n)
1232 {
1233 	union node *np;
1234 	struct nodelist *lp;
1235 	const char *p;
1236 	int i;
1237 	char s[2];
1238 
1239 	if (n == NULL || cmdnleft <= 0)
1240 		return;
1241 	switch (n->type) {
1242 	case NSEMI:
1243 		cmdtxt(n->nbinary.ch1);
1244 		cmdputs("; ");
1245 		cmdtxt(n->nbinary.ch2);
1246 		break;
1247 	case NAND:
1248 		cmdtxt(n->nbinary.ch1);
1249 		cmdputs(" && ");
1250 		cmdtxt(n->nbinary.ch2);
1251 		break;
1252 	case NOR:
1253 		cmdtxt(n->nbinary.ch1);
1254 		cmdputs(" || ");
1255 		cmdtxt(n->nbinary.ch2);
1256 		break;
1257 	case NPIPE:
1258 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1259 			cmdtxt(lp->n);
1260 			if (lp->next)
1261 				cmdputs(" | ");
1262 		}
1263 		break;
1264 	case NSUBSHELL:
1265 		cmdputs("(");
1266 		cmdtxt(n->nredir.n);
1267 		cmdputs(")");
1268 		break;
1269 	case NREDIR:
1270 	case NBACKGND:
1271 		cmdtxt(n->nredir.n);
1272 		break;
1273 	case NIF:
1274 		cmdputs("if ");
1275 		cmdtxt(n->nif.test);
1276 		cmdputs("; then ");
1277 		cmdtxt(n->nif.ifpart);
1278 		if (n->nif.elsepart) {
1279 			cmdputs("; else ");
1280 			cmdtxt(n->nif.elsepart);
1281 		}
1282 		cmdputs("; fi");
1283 		break;
1284 	case NWHILE:
1285 		cmdputs("while ");
1286 		goto until;
1287 	case NUNTIL:
1288 		cmdputs("until ");
1289 until:
1290 		cmdtxt(n->nbinary.ch1);
1291 		cmdputs("; do ");
1292 		cmdtxt(n->nbinary.ch2);
1293 		cmdputs("; done");
1294 		break;
1295 	case NFOR:
1296 		cmdputs("for ");
1297 		cmdputs(n->nfor.var);
1298 		cmdputs(" in ");
1299 		cmdlist(n->nfor.args, 1);
1300 		cmdputs("; do ");
1301 		cmdtxt(n->nfor.body);
1302 		cmdputs("; done");
1303 		break;
1304 	case NCASE:
1305 		cmdputs("case ");
1306 		cmdputs(n->ncase.expr->narg.text);
1307 		cmdputs(" in ");
1308 		for (np = n->ncase.cases; np; np = np->nclist.next) {
1309 			cmdtxt(np->nclist.pattern);
1310 			cmdputs(") ");
1311 			cmdtxt(np->nclist.body);
1312 			cmdputs(";; ");
1313 		}
1314 		cmdputs("esac");
1315 		break;
1316 	case NDEFUN:
1317 		cmdputs(n->narg.text);
1318 		cmdputs("() { ... }");
1319 		break;
1320 	case NCMD:
1321 		cmdlist(n->ncmd.args, 1);
1322 		cmdlist(n->ncmd.redirect, 0);
1323 		break;
1324 	case NARG:
1325 		cmdputs(n->narg.text);
1326 		break;
1327 	case NTO:
1328 		p = ">";  i = 1;  goto redir;
1329 	case NCLOBBER:
1330 		p = ">|";  i = 1;  goto redir;
1331 	case NAPPEND:
1332 		p = ">>";  i = 1;  goto redir;
1333 	case NTOFD:
1334 		p = ">&";  i = 1;  goto redir;
1335 	case NFROM:
1336 		p = "<";  i = 0;  goto redir;
1337 	case NFROMFD:
1338 		p = "<&";  i = 0;  goto redir;
1339 	case NFROMTO:
1340 		p = "<>";  i = 0;  goto redir;
1341 redir:
1342 		if (n->nfile.fd != i) {
1343 			s[0] = n->nfile.fd + '0';
1344 			s[1] = '\0';
1345 			cmdputs(s);
1346 		}
1347 		cmdputs(p);
1348 		if (n->type == NTOFD || n->type == NFROMFD) {
1349 			s[0] = n->ndup.dupfd + '0';
1350 			s[1] = '\0';
1351 			cmdputs(s);
1352 		} else {
1353 			cmdtxt(n->nfile.fname);
1354 		}
1355 		break;
1356 	case NHERE:
1357 	case NXHERE:
1358 		cmdputs("<<...");
1359 		break;
1360 	default:
1361 		cmdputs("???");
1362 		break;
1363 	}
1364 }
1365 
1366 STATIC void
1367 cmdlist(union node *np, int sep)
1368 {
1369 	for (; np; np = np->narg.next) {
1370 		if (!sep)
1371 			cmdputs(" ");
1372 		cmdtxt(np);
1373 		if (sep && np->narg.next)
1374 			cmdputs(" ");
1375 	}
1376 }
1377 
1378 
1379 STATIC void
1380 cmdputs(const char *s)
1381 {
1382 	const char *p, *str = 0;
1383 	char c, cc[2] = " ";
1384 	char *nextc;
1385 	int nleft;
1386 	int subtype = 0;
1387 	int quoted = 0;
1388 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
1389 					"#", "##", "%", "%%" };
1390 
1391 	p = s;
1392 	nextc = cmdnextc;
1393 	nleft = cmdnleft;
1394 	while (nleft > 0 && (c = *p++) != 0) {
1395 		switch (c) {
1396 		case CTLESC:
1397 			c = *p++;
1398 			break;
1399 		case CTLVAR:
1400 			subtype = *p++;
1401 			if ((subtype & VSTYPE) == VSLENGTH)
1402 				str = "${#";
1403 			else
1404 				str = "${";
1405 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
1406 				quoted ^= 1;
1407 				c = '"';
1408 			} else
1409 				c = *str++;
1410 			break;
1411 		case CTLENDVAR:
1412 			if (quoted & 1) {
1413 				c = '"';
1414 				str = "}";
1415 			} else
1416 				c = '}';
1417 			quoted >>= 1;
1418 			subtype = 0;
1419 			break;
1420 		case CTLBACKQ:
1421 			c = '$';
1422 			str = "(...)";
1423 			break;
1424 		case CTLBACKQ+CTLQUOTE:
1425 			c = '"';
1426 			str = "$(...)\"";
1427 			break;
1428 		case CTLARI:
1429 			c = '$';
1430 			str = "((";
1431 			break;
1432 		case CTLENDARI:
1433 			c = ')';
1434 			str = ")";
1435 			break;
1436 		case CTLQUOTEMARK:
1437 			quoted ^= 1;
1438 			c = '"';
1439 			break;
1440 		case '=':
1441 			if (subtype == 0)
1442 				break;
1443 			str = vstype[subtype & VSTYPE];
1444 			if (subtype & VSNUL)
1445 				c = ':';
1446 			else
1447 				c = *str++;
1448 			if (c != '}')
1449 				quoted <<= 1;
1450 			break;
1451 		case '\'':
1452 		case '\\':
1453 		case '"':
1454 		case '$':
1455 			/* These can only happen inside quotes */
1456 			cc[0] = c;
1457 			str = cc;
1458 			c = '\\';
1459 			break;
1460 		default:
1461 			break;
1462 		}
1463 		do {
1464 			*nextc++ = c;
1465 		} while (--nleft > 0 && str && (c = *str++));
1466 		str = 0;
1467 	}
1468 	if ((quoted & 1) && nleft) {
1469 		*nextc++ = '"';
1470 		nleft--;
1471 	}
1472 	cmdnleft = nleft;
1473 	cmdnextc = nextc;
1474 }
1475