xref: /original-bsd/bin/sh/jobs.c (revision ca98dac2)
1 /*-
2  * Copyright (c) 1991 The Regents of the University of California.
3  * 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 
37 #ifndef lint
38 static char sccsid[] = "@(#)jobs.c	5.7 (Berkeley) 10/17/92";
39 #endif /* not lint */
40 
41 #include "shell.h"
42 #if JOBS
43 #include "sgtty.h"
44 #undef CEOF			/* syntax.h redefines this */
45 #endif
46 #include "main.h"
47 #include "parser.h"
48 #include "nodes.h"
49 #include "jobs.h"
50 #include "options.h"
51 #include "trap.h"
52 #include "signames.h"
53 #include "syntax.h"
54 #include "input.h"
55 #include "output.h"
56 #include "memalloc.h"
57 #include "error.h"
58 #include "mystring.h"
59 #include <fcntl.h>
60 #include <signal.h>
61 #include <errno.h>
62 #ifdef BSD
63 #include <sys/types.h>
64 #include <sys/wait.h>
65 #include <sys/time.h>
66 #include <sys/resource.h>
67 #endif
68 
69 
70 
71 struct job *jobtab;		/* array of jobs */
72 int njobs;			/* size of array */
73 MKINIT short backgndpid = -1;	/* pid of last background process */
74 #if JOBS
75 int initialpgrp;		/* pgrp of shell on invocation */
76 short curjob;			/* current job */
77 #endif
78 
79 #ifdef __STDC__
80 STATIC void restartjob(struct job *);
81 STATIC struct job *getjob(char *);
82 STATIC void freejob(struct job *);
83 STATIC int procrunning(int);
84 STATIC int dowait(int, struct job *);
85 STATIC int waitproc(int, int *);
86 #else
87 STATIC void restartjob();
88 STATIC struct job *getjob();
89 STATIC void freejob();
90 STATIC int procrunning();
91 STATIC int dowait();
92 STATIC int waitproc();
93 #endif
94 
95 
96 
97 /*
98  * Turn job control on and off.
99  *
100  * Note:  This code assumes that the third arg to ioctl is a character
101  * pointer, which is true on Berkeley systems but not System V.  Since
102  * System V doesn't have job control yet, this isn't a problem now.
103  */
104 
105 MKINIT int jobctl;
106 
107 void
108 setjobctl(on) {
109 #ifdef OLD_TTY_DRIVER
110 	int ldisc;
111 #endif
112 
113 	if (on == jobctl || rootshell == 0)
114 		return;
115 	if (on) {
116 		do { /* while we are in the background */
117 			if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
118 				out2str("sh: can't access tty; job control turned off\n");
119 				mflag = 0;
120 				return;
121 			}
122 			if (initialpgrp == -1)
123 				initialpgrp = getpgrp(0);
124 			else if (initialpgrp != getpgrp(0)) {
125 				killpg(initialpgrp, SIGTTIN);
126 				continue;
127 			}
128 		} while (0);
129 #ifdef OLD_TTY_DRIVER
130 		if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
131 			out2str("sh: need new tty driver to run job control; job control turned off\n");
132 			mflag = 0;
133 			return;
134 		}
135 #endif
136 		setsignal(SIGTSTP);
137 		setsignal(SIGTTOU);
138 		setsignal(SIGTTIN);
139 		setpgrp(0, rootpid);
140 		ioctl(2, TIOCSPGRP, (char *)&rootpid);
141 	} else { /* turning job control off */
142 		setpgrp(0, initialpgrp);
143 		ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
144 		setsignal(SIGTSTP);
145 		setsignal(SIGTTOU);
146 		setsignal(SIGTTIN);
147 	}
148 	jobctl = on;
149 }
150 
151 
152 #ifdef mkinit
153 
154 SHELLPROC {
155 	backgndpid = -1;
156 #if JOBS
157 	jobctl = 0;
158 #endif
159 }
160 
161 #endif
162 
163 
164 
165 #if JOBS
166 fgcmd(argc, argv)  char **argv; {
167 	struct job *jp;
168 	int pgrp;
169 	int status;
170 
171 	jp = getjob(argv[1]);
172 	if (jp->jobctl == 0)
173 		error("job not created under job control");
174 	pgrp = jp->ps[0].pid;
175 	ioctl(2, TIOCSPGRP, (char *)&pgrp);
176 	restartjob(jp);
177 	INTOFF;
178 	status = waitforjob(jp);
179 	INTON;
180 	return status;
181 }
182 
183 
184 bgcmd(argc, argv)  char **argv; {
185 	struct job *jp;
186 
187 	do {
188 		jp = getjob(*++argv);
189 		if (jp->jobctl == 0)
190 			error("job not created under job control");
191 		restartjob(jp);
192 	} while (--argc > 1);
193 	return 0;
194 }
195 
196 
197 STATIC void
198 restartjob(jp)
199 	struct job *jp;
200 	{
201 	struct procstat *ps;
202 	int i;
203 
204 	if (jp->state == JOBDONE)
205 		return;
206 	INTOFF;
207 	killpg(jp->ps[0].pid, SIGCONT);
208 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
209 		if ((ps->status & 0377) == 0177) {
210 			ps->status = -1;
211 			jp->state = 0;
212 		}
213 	}
214 	INTON;
215 }
216 #endif
217 
218 
219 int
220 jobscmd(argc, argv)  char **argv; {
221 	showjobs(0);
222 	return 0;
223 }
224 
225 
226 /*
227  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
228  * statuses have changed since the last call to showjobs.
229  *
230  * If the shell is interrupted in the process of creating a job, the
231  * result may be a job structure containing zero processes.  Such structures
232  * will be freed here.
233  */
234 
235 void
236 showjobs(change) {
237 	int jobno;
238 	int procno;
239 	int i;
240 	struct job *jp;
241 	struct procstat *ps;
242 	int col;
243 	char s[64];
244 
245 	TRACE(("showjobs(%d) called\n", change));
246 	while (dowait(0, (struct job *)NULL) > 0);
247 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
248 		if (! jp->used)
249 			continue;
250 		if (jp->nprocs == 0) {
251 			freejob(jp);
252 			continue;
253 		}
254 		if (change && ! jp->changed)
255 			continue;
256 		procno = jp->nprocs;
257 		for (ps = jp->ps ; ; ps++) {	/* for each process */
258 			if (ps == jp->ps)
259 				fmtstr(s, 64, "[%d] %d ", jobno, ps->pid);
260 			else
261 				fmtstr(s, 64, "    %d ", ps->pid);
262 			out1str(s);
263 			col = strlen(s);
264 			s[0] = '\0';
265 			if (ps->status == -1) {
266 				/* don't print anything */
267 			} else if ((ps->status & 0xFF) == 0) {
268 				fmtstr(s, 64, "Exit %d", ps->status >> 8);
269 			} else {
270 				i = ps->status;
271 #if JOBS
272 				if ((i & 0xFF) == 0177)
273 					i >>= 8;
274 #endif
275 				if ((i & 0x7F) <= MAXSIG && sigmesg[i & 0x7F])
276 					scopy(sigmesg[i & 0x7F], s);
277 				else
278 					fmtstr(s, 64, "Signal %d", i & 0x7F);
279 				if (i & 0x80)
280 					strcat(s, " (core dumped)");
281 			}
282 			out1str(s);
283 			col += strlen(s);
284 			do {
285 				out1c(' ');
286 				col++;
287 			} while (col < 30);
288 			out1str(ps->cmd);
289 			out1c('\n');
290 			if (--procno <= 0)
291 				break;
292 		}
293 		jp->changed = 0;
294 		if (jp->state == JOBDONE) {
295 			freejob(jp);
296 		}
297 	}
298 }
299 
300 
301 /*
302  * Mark a job structure as unused.
303  */
304 
305 STATIC void
306 freejob(jp)
307 	struct job *jp;
308 	{
309 	struct procstat *ps;
310 	int i;
311 
312 	INTOFF;
313 	for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
314 		if (ps->cmd != nullstr)
315 			ckfree(ps->cmd);
316 	}
317 	if (jp->ps != &jp->ps0)
318 		ckfree(jp->ps);
319 	jp->used = 0;
320 #if JOBS
321 	if (curjob == jp - jobtab + 1)
322 		curjob = 0;
323 #endif
324 	INTON;
325 }
326 
327 
328 
329 int
330 waitcmd(argc, argv)  char **argv; {
331 	struct job *job;
332 	int status;
333 	struct job *jp;
334 
335 	if (argc > 1) {
336 		job = getjob(argv[1]);
337 	} else {
338 		job = NULL;
339 	}
340 	for (;;) {	/* loop until process terminated or stopped */
341 		if (job != NULL) {
342 			if (job->state) {
343 				status = job->ps[job->nprocs - 1].status;
344 				if ((status & 0xFF) == 0)
345 					status = status >> 8 & 0xFF;
346 #if JOBS
347 				else if ((status & 0xFF) == 0177)
348 					status = (status >> 8 & 0x7F) + 128;
349 #endif
350 				else
351 					status = (status & 0x7F) + 128;
352 				if (! iflag)
353 					freejob(job);
354 				return status;
355 			}
356 		} else {
357 			for (jp = jobtab ; ; jp++) {
358 				if (jp >= jobtab + njobs) {	/* no running procs */
359 					return 0;
360 				}
361 				if (jp->used && jp->state == 0)
362 					break;
363 			}
364 		}
365 		dowait(1, (struct job *)NULL);
366 	}
367 }
368 
369 
370 
371 jobidcmd(argc, argv)  char **argv; {
372 	struct job *jp;
373 	int i;
374 
375 	jp = getjob(argv[1]);
376 	for (i = 0 ; i < jp->nprocs ; ) {
377 		out1fmt("%d", jp->ps[i].pid);
378 		out1c(++i < jp->nprocs? ' ' : '\n');
379 	}
380 	return 0;
381 }
382 
383 
384 
385 /*
386  * Convert a job name to a job structure.
387  */
388 
389 STATIC struct job *
390 getjob(name)
391 	char *name;
392 	{
393 	int jobno;
394 	register struct job *jp;
395 	int pid;
396 	int i;
397 
398 	if (name == NULL) {
399 #if JOBS
400 currentjob:
401 		if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
402 			error("No current job");
403 		return &jobtab[jobno - 1];
404 #else
405 		error("No current job");
406 #endif
407 	} else if (name[0] == '%') {
408 		if (is_digit(name[1])) {
409 			jobno = number(name + 1);
410 			if (jobno > 0 && jobno <= njobs
411 			 && jobtab[jobno - 1].used != 0)
412 				return &jobtab[jobno - 1];
413 #if JOBS
414 		} else if (name[1] == '%' && name[2] == '\0') {
415 			goto currentjob;
416 #endif
417 		} else {
418 			register struct job *found = NULL;
419 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
420 				if (jp->used && jp->nprocs > 0
421 				 && prefix(name + 1, jp->ps[0].cmd)) {
422 					if (found)
423 						error("%s: ambiguous", name);
424 					found = jp;
425 				}
426 			}
427 			if (found)
428 				return found;
429 		}
430 	} else if (is_number(name)) {
431 		pid = number(name);
432 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
433 			if (jp->used && jp->nprocs > 0
434 			 && jp->ps[jp->nprocs - 1].pid == pid)
435 				return jp;
436 		}
437 	}
438 	error("No such job: %s", name);
439 }
440 
441 
442 
443 /*
444  * Return a new job structure,
445  */
446 
447 struct job *
448 makejob(node, nprocs)
449 	union node *node;
450 	{
451 	int i;
452 	struct job *jp;
453 
454 	for (i = njobs, jp = jobtab ; ; jp++) {
455 		if (--i < 0) {
456 			INTOFF;
457 			if (njobs == 0) {
458 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
459 			} else {
460 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
461 				bcopy(jobtab, jp, njobs * sizeof jp[0]);
462 				ckfree(jobtab);
463 				jobtab = jp;
464 			}
465 			jp = jobtab + njobs;
466 			for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
467 			INTON;
468 			break;
469 		}
470 		if (jp->used == 0)
471 			break;
472 	}
473 	INTOFF;
474 	jp->state = 0;
475 	jp->used = 1;
476 	jp->changed = 0;
477 	jp->nprocs = 0;
478 #if JOBS
479 	jp->jobctl = jobctl;
480 #endif
481 	if (nprocs > 1) {
482 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
483 	} else {
484 		jp->ps = &jp->ps0;
485 	}
486 	INTON;
487 	TRACE(("makejob(0x%x, %d) returns %%%d\n", (int)node, nprocs, jp - jobtab + 1));
488 	return jp;
489 }
490 
491 
492 /*
493  * Fork of a subshell.  If we are doing job control, give the subshell its
494  * own process group.  Jp is a job structure that the job is to be added to.
495  * N is the command that will be evaluated by the child.  Both jp and n may
496  * be NULL.  The mode parameter can be one of the following:
497  *	FORK_FG - Fork off a foreground process.
498  *	FORK_BG - Fork off a background process.
499  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
500  *		     process group even if job control is on.
501  *
502  * When job control is turned off, background processes have their standard
503  * input redirected to /dev/null (except for the second and later processes
504  * in a pipeline).
505  */
506 
507 int
508 forkshell(jp, n, mode)
509 	union node *n;
510 	struct job *jp;
511 	{
512 	int pid;
513 	int pgrp;
514 
515 	TRACE(("forkshell(%%%d, 0x%x, %d) called\n", jp - jobtab, (int)n, mode));
516 	INTOFF;
517 	pid = fork();
518 	if (pid == -1) {
519 		TRACE(("Fork failed, errno=%d\n", errno));
520 		INTON;
521 		error("Cannot fork");
522 	}
523 	if (pid == 0) {
524 		struct job *p;
525 		int wasroot;
526 		int i;
527 
528 		TRACE(("Child shell %d\n", getpid()));
529 		wasroot = rootshell;
530 		rootshell = 0;
531 		for (i = njobs, p = jobtab ; --i >= 0 ; p++)
532 			if (p->used)
533 				freejob(p);
534 		closescript();
535 		INTON;
536 		clear_traps();
537 #if JOBS
538 		jobctl = 0;		/* do job control only in root shell */
539 		if (wasroot && mode != FORK_NOJOB && mflag) {
540 			if (jp == NULL || jp->nprocs == 0)
541 				pgrp = getpid();
542 			else
543 				pgrp = jp->ps[0].pid;
544 			setpgrp(0, pgrp);
545 			if (mode == FORK_FG) {
546 				/*** this causes superfluous TIOCSPGRPS ***/
547 				if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
548 					error("TIOCSPGRP failed, errno=%d\n", errno);
549 			}
550 			setsignal(SIGTSTP);
551 			setsignal(SIGTTOU);
552 		} else if (mode == FORK_BG) {
553 			ignoresig(SIGINT);
554 			ignoresig(SIGQUIT);
555 			if (jp == NULL || jp->nprocs == 0) {
556 				close(0);
557 				if (open("/dev/null", O_RDONLY) != 0)
558 					error("Can't open /dev/null");
559 			}
560 		}
561 #else
562 		if (mode == FORK_BG) {
563 			ignoresig(SIGINT);
564 			ignoresig(SIGQUIT);
565 			if (jp == NULL || jp->nprocs == 0) {
566 				close(0);
567 				if (open("/dev/null", O_RDONLY) != 0)
568 					error("Can't open /dev/null");
569 			}
570 		}
571 #endif
572 		if (wasroot && iflag) {
573 			setsignal(SIGINT);
574 			setsignal(SIGQUIT);
575 			setsignal(SIGTERM);
576 		}
577 		return pid;
578 	}
579 	if (rootshell && mode != FORK_NOJOB && mflag) {
580 		if (jp == NULL || jp->nprocs == 0)
581 			pgrp = pid;
582 		else
583 			pgrp = jp->ps[0].pid;
584 		setpgrp(pid, pgrp);
585 	}
586 	if (mode == FORK_BG)
587 		backgndpid = pid;		/* set $! */
588 	if (jp) {
589 		struct procstat *ps = &jp->ps[jp->nprocs++];
590 		ps->pid = pid;
591 		ps->status = -1;
592 		ps->cmd = nullstr;
593 		if (iflag && rootshell && n)
594 			ps->cmd = commandtext(n);
595 	}
596 	INTON;
597 	TRACE(("In parent shell:  child = %d\n", pid));
598 	return pid;
599 }
600 
601 
602 
603 /*
604  * Wait for job to finish.
605  *
606  * Under job control we have the problem that while a child process is
607  * running interrupts generated by the user are sent to the child but not
608  * to the shell.  This means that an infinite loop started by an inter-
609  * active user may be hard to kill.  With job control turned off, an
610  * interactive user may place an interactive program inside a loop.  If
611  * the interactive program catches interrupts, the user doesn't want
612  * these interrupts to also abort the loop.  The approach we take here
613  * is to have the shell ignore interrupt signals while waiting for a
614  * forground process to terminate, and then send itself an interrupt
615  * signal if the child process was terminated by an interrupt signal.
616  * Unfortunately, some programs want to do a bit of cleanup and then
617  * exit on interrupt; unless these processes terminate themselves by
618  * sending a signal to themselves (instead of calling exit) they will
619  * confuse this approach.
620  */
621 
622 int
623 waitforjob(jp)
624 	register struct job *jp;
625 	{
626 #if JOBS
627 	int mypgrp = getpgrp(0);
628 #endif
629 	int status;
630 	int st;
631 
632 	INTOFF;
633 	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
634 	while (jp->state == 0) {
635 		dowait(1, jp);
636 	}
637 #if JOBS
638 	if (jp->jobctl) {
639 		if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
640 			error("TIOCSPGRP failed, errno=%d\n", errno);
641 	}
642 	if (jp->state == JOBSTOPPED)
643 		curjob = jp - jobtab + 1;
644 #endif
645 	status = jp->ps[jp->nprocs - 1].status;
646 	/* convert to 8 bits */
647 	if ((status & 0xFF) == 0)
648 		st = status >> 8 & 0xFF;
649 #if JOBS
650 	else if ((status & 0xFF) == 0177)
651 		st = (status >> 8 & 0x7F) + 128;
652 #endif
653 	else
654 		st = (status & 0x7F) + 128;
655 	if (! JOBS || jp->state == JOBDONE)
656 		freejob(jp);
657 	CLEAR_PENDING_INT;
658 	if ((status & 0x7F) == SIGINT)
659 		kill(getpid(), SIGINT);
660 	INTON;
661 	return st;
662 }
663 
664 
665 
666 /*
667  * Wait for a process to terminate.
668  */
669 
670 STATIC int
671 dowait(block, job)
672 	struct job *job;
673 	{
674 	int pid;
675 	int status;
676 	struct procstat *sp;
677 	struct job *jp;
678 	struct job *thisjob;
679 	int done;
680 	int stopped;
681 	int core;
682 
683 	TRACE(("dowait(%d) called\n", block));
684 	do {
685 		pid = waitproc(block, &status);
686 		TRACE(("wait returns %d, status=%d\n", pid, status));
687 	} while (pid == -1 && errno == EINTR);
688 	if (pid <= 0)
689 		return pid;
690 	INTOFF;
691 	thisjob = NULL;
692 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
693 		if (jp->used) {
694 			done = 1;
695 			stopped = 1;
696 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
697 				if (sp->pid == -1)
698 					continue;
699 				if (sp->pid == pid) {
700 					TRACE(("Changin status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
701 					sp->status = status;
702 					thisjob = jp;
703 				}
704 				if (sp->status == -1)
705 					stopped = 0;
706 				else if ((sp->status & 0377) == 0177)
707 					done = 0;
708 			}
709 			if (stopped) {		/* stopped or done */
710 				int state = done? JOBDONE : JOBSTOPPED;
711 				if (jp->state != state) {
712 					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
713 					jp->state = state;
714 #if JOBS
715 					if (done && curjob == jp - jobtab + 1)
716 						curjob = 0;		/* no current job */
717 #endif
718 				}
719 			}
720 		}
721 	}
722 	INTON;
723 	if (! rootshell || ! iflag || (job && thisjob == job)) {
724 #if JOBS
725 		if ((status & 0xFF) == 0177)
726 			status >>= 8;
727 #endif
728 		core = status & 0x80;
729 		status &= 0x7F;
730 		if (status != 0 && status != SIGINT && status != SIGPIPE) {
731 			if (thisjob != job)
732 				outfmt(out2, "%d: ", pid);
733 #if JOBS
734 			if (status == SIGTSTP && rootshell && iflag)
735 				outfmt(out2, "%%%d ", job - jobtab + 1);
736 #endif
737 			if (status <= MAXSIG && sigmesg[status])
738 				out2str(sigmesg[status]);
739 			else
740 				outfmt(out2, "Signal %d", status);
741 			if (core)
742 				out2str(" - core dumped");
743 			out2c('\n');
744 			flushout(&errout);
745 		} else {
746 			TRACE(("Not printing status: status=%d\n", status));
747 		}
748 	} else {
749 		TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
750 		if (thisjob)
751 			thisjob->changed = 1;
752 	}
753 	return pid;
754 }
755 
756 
757 
758 /*
759  * Do a wait system call.  If job control is compiled in, we accept
760  * stopped processes.  If block is zero, we return a value of zero
761  * rather than blocking.
762  *
763  * System V doesn't have a non-blocking wait system call.  It does
764  * have a SIGCLD signal that is sent to a process when one of it's
765  * children dies.  The obvious way to use SIGCLD would be to install
766  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
767  * was received, and have waitproc bump another counter when it got
768  * the status of a process.  Waitproc would then know that a wait
769  * system call would not block if the two counters were different.
770  * This approach doesn't work because if a process has children that
771  * have not been waited for, System V will send it a SIGCLD when it
772  * installs a signal handler for SIGCLD.  What this means is that when
773  * a child exits, the shell will be sent SIGCLD signals continuously
774  * until is runs out of stack space, unless it does a wait call before
775  * restoring the signal handler.  The code below takes advantage of
776  * this (mis)feature by installing a signal handler for SIGCLD and
777  * then checking to see whether it was called.  If there are any
778  * children to be waited for, it will be.
779  *
780  * If neither SYSV nor BSD is defined, we don't implement nonblocking
781  * waits at all.  In this case, the user will not be informed when
782  * a background process until the next time she runs a real program
783  * (as opposed to running a builtin command or just typing return),
784  * and the jobs command may give out of date information.
785  */
786 
787 #ifdef SYSV
788 STATIC int gotsigchild;
789 
790 STATIC int onsigchild() {
791 	gotsigchild = 1;
792 }
793 #endif
794 
795 
796 STATIC int
797 waitproc(block, status)
798 	int *status;
799 	{
800 #ifdef BSD
801 	int flags;
802 
803 #if JOBS
804 	flags = WUNTRACED;
805 #else
806 	flags = 0;
807 #endif
808 	if (block == 0)
809 		flags |= WNOHANG;
810 	return wait3(status, flags, (struct rusage *)NULL);
811 #else
812 #ifdef SYSV
813 	int (*save)();
814 
815 	if (block == 0) {
816 		gotsigchild = 0;
817 		save = signal(SIGCLD, onsigchild);
818 		signal(SIGCLD, save);
819 		if (gotsigchild == 0)
820 			return 0;
821 	}
822 	return wait(status);
823 #else
824 	if (block == 0)
825 		return 0;
826 	return wait(status);
827 #endif
828 #endif
829 }
830 
831 /*
832  * return 1 if there are stopped jobs, otherwise 0
833  */
834 int job_warning = 0;
835 int
836 stoppedjobs()
837 {
838 	register int jobno;
839 	register struct job *jp;
840 
841 	if (job_warning)
842 		return (0);
843 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
844 		if (jp->used == 0)
845 			continue;
846 		if (jp->state == JOBSTOPPED) {
847 			out2str("You have stopped jobs.\n");
848 			job_warning = 2;
849 			return (1);
850 		}
851 	}
852 
853 	return (0);
854 }
855 
856 /*
857  * Return a string identifying a command (to be printed by the
858  * jobs command.
859  */
860 
861 STATIC char *cmdnextc;
862 STATIC int cmdnleft;
863 STATIC void cmdtxt(), cmdputs();
864 #define MAXCMDTEXT	200
865 
866 char *
867 commandtext(n)
868 	union node *n;
869 	{
870 	char *name;
871 
872 	cmdnextc = name = ckmalloc(MAXCMDTEXT);
873 	cmdnleft = MAXCMDTEXT - 4;
874 	cmdtxt(n);
875 	*cmdnextc = '\0';
876 	return name;
877 }
878 
879 
880 STATIC void
881 cmdtxt(n)
882 	union node *n;
883 	{
884 	union node *np;
885 	struct nodelist *lp;
886 	char *p;
887 	int i;
888 	char s[2];
889 
890 	if (n == NULL)
891 		return;
892 	switch (n->type) {
893 	case NSEMI:
894 		cmdtxt(n->nbinary.ch1);
895 		cmdputs("; ");
896 		cmdtxt(n->nbinary.ch2);
897 		break;
898 	case NAND:
899 		cmdtxt(n->nbinary.ch1);
900 		cmdputs(" && ");
901 		cmdtxt(n->nbinary.ch2);
902 		break;
903 	case NOR:
904 		cmdtxt(n->nbinary.ch1);
905 		cmdputs(" || ");
906 		cmdtxt(n->nbinary.ch2);
907 		break;
908 	case NPIPE:
909 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
910 			cmdtxt(lp->n);
911 			if (lp->next)
912 				cmdputs(" | ");
913 		}
914 		break;
915 	case NSUBSHELL:
916 		cmdputs("(");
917 		cmdtxt(n->nredir.n);
918 		cmdputs(")");
919 		break;
920 	case NREDIR:
921 	case NBACKGND:
922 		cmdtxt(n->nredir.n);
923 		break;
924 	case NIF:
925 		cmdputs("if ");
926 		cmdtxt(n->nif.test);
927 		cmdputs("; then ");
928 		cmdtxt(n->nif.ifpart);
929 		cmdputs("...");
930 		break;
931 	case NWHILE:
932 		cmdputs("while ");
933 		goto until;
934 	case NUNTIL:
935 		cmdputs("until ");
936 until:
937 		cmdtxt(n->nbinary.ch1);
938 		cmdputs("; do ");
939 		cmdtxt(n->nbinary.ch2);
940 		cmdputs("; done");
941 		break;
942 	case NFOR:
943 		cmdputs("for ");
944 		cmdputs(n->nfor.var);
945 		cmdputs(" in ...");
946 		break;
947 	case NCASE:
948 		cmdputs("case ");
949 		cmdputs(n->ncase.expr->narg.text);
950 		cmdputs(" in ...");
951 		break;
952 	case NDEFUN:
953 		cmdputs(n->narg.text);
954 		cmdputs("() ...");
955 		break;
956 	case NCMD:
957 		for (np = n->ncmd.args ; np ; np = np->narg.next) {
958 			cmdtxt(np);
959 			if (np->narg.next)
960 				cmdputs(" ");
961 		}
962 		for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
963 			cmdputs(" ");
964 			cmdtxt(np);
965 		}
966 		break;
967 	case NARG:
968 		cmdputs(n->narg.text);
969 		break;
970 	case NTO:
971 		p = ">";  i = 1;  goto redir;
972 	case NAPPEND:
973 		p = ">>";  i = 1;  goto redir;
974 	case NTOFD:
975 		p = ">&";  i = 1;  goto redir;
976 	case NFROM:
977 		p = "<";  i = 0;  goto redir;
978 	case NFROMFD:
979 		p = "<&";  i = 0;  goto redir;
980 redir:
981 		if (n->nfile.fd != i) {
982 			s[0] = n->nfile.fd + '0';
983 			s[1] = '\0';
984 			cmdputs(s);
985 		}
986 		cmdputs(p);
987 		if (n->type == NTOFD || n->type == NFROMFD) {
988 			s[0] = n->ndup.dupfd + '0';
989 			s[1] = '\0';
990 			cmdputs(s);
991 		} else {
992 			cmdtxt(n->nfile.fname);
993 		}
994 		break;
995 	case NHERE:
996 	case NXHERE:
997 		cmdputs("<<...");
998 		break;
999 	default:
1000 		cmdputs("???");
1001 		break;
1002 	}
1003 }
1004 
1005 
1006 
1007 STATIC void
1008 cmdputs(s)
1009 	char *s;
1010 	{
1011 	register char *p, *q;
1012 	register char c;
1013 	int subtype = 0;
1014 
1015 	if (cmdnleft <= 0)
1016 		return;
1017 	p = s;
1018 	q = cmdnextc;
1019 	while ((c = *p++) != '\0') {
1020 		if (c == CTLESC)
1021 			*q++ = *p++;
1022 		else if (c == CTLVAR) {
1023 			*q++ = '$';
1024 			if (--cmdnleft > 0)
1025 				*q++ = '{';
1026 			subtype = *p++;
1027 		} else if (c == '=' && subtype != 0) {
1028 			*q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1029 			subtype = 0;
1030 		} else if (c == CTLENDVAR) {
1031 			*q++ = '}';
1032 		} else if (c == CTLBACKQ | c == CTLBACKQ+CTLQUOTE)
1033 			cmdnleft++;		/* ignore it */
1034 		else
1035 			*q++ = c;
1036 		if (--cmdnleft <= 0) {
1037 			*q++ = '.';
1038 			*q++ = '.';
1039 			*q++ = '.';
1040 			break;
1041 		}
1042 	}
1043 	cmdnextc = q;
1044 }
1045