xref: /freebsd/contrib/tcsh/sh.proc.c (revision f5147e312f43a9050468de539aeafa072caa1a60)
1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.proc.c,v 3.134 2016/09/23 19:17:28 christos Exp $ */
2 /*
3  * sh.proc.c: Job manipulations
4  */
5 /*-
6  * Copyright (c) 1980, 1991 The Regents of the University of California.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 #include "sh.h"
34 
35 RCSID("$tcsh: sh.proc.c,v 3.134 2016/09/23 19:17:28 christos Exp $")
36 
37 #include "ed.h"
38 #include "tc.h"
39 #include "tc.wait.h"
40 
41 #ifdef WINNT_NATIVE
42 #undef POSIX
43 #define POSIX
44 #endif /* WINNT_NATIVE */
45 #ifdef aiws
46 # undef HZ
47 # define HZ 16
48 #endif /* aiws */
49 
50 #if defined(_BSD) || (defined(IRIS4D) && __STDC__) || defined(__lucid)
51 # define BSDWAIT
52 #endif /* _BSD || (IRIS4D && __STDC__) || __lucid */
53 #ifndef WTERMSIG
54 # define WTERMSIG(w)	(((union wait *) &(w))->w_termsig)
55 # ifndef BSDWAIT
56 #  define BSDWAIT
57 # endif /* !BSDWAIT */
58 #endif /* !WTERMSIG */
59 #ifndef WEXITSTATUS
60 # define WEXITSTATUS(w)	(((union wait *) &(w))->w_retcode)
61 #endif /* !WEXITSTATUS */
62 #ifndef WSTOPSIG
63 # define WSTOPSIG(w)	(((union wait *) &(w))->w_stopsig)
64 #endif /* !WSTOPSIG */
65 
66 #ifdef __osf__
67 # ifndef WCOREDUMP
68 #  define WCOREDUMP(x) (_W_INT(x) & WCOREFLAG)
69 # endif
70 #endif
71 
72 #ifndef WCOREDUMP
73 # ifdef BSDWAIT
74 #  define WCOREDUMP(w)	(((union wait *) &(w))->w_coredump)
75 # else /* !BSDWAIT */
76 #  define WCOREDUMP(w)	((w) & 0200)
77 # endif /* !BSDWAIT */
78 #endif /* !WCOREDUMP */
79 
80 #ifndef JOBDEBUG
81 # define jobdebug_xprintf(x)	(void)0
82 # define jobdebug_flush()	(void)0
83 #else
84 # define jobdebug_xprintf(s)	xprintf s
85 # define jobdebug_flush()	flush()
86 #endif
87 
88 /*
89  * C Shell - functions that manage processes, handling hanging, termination
90  */
91 
92 #define BIGINDEX	9	/* largest desirable job index */
93 
94 #ifdef BSDTIMES
95 # ifdef convex
96 /* use 'cvxrusage' to get parallel statistics */
97 static struct cvxrusage zru = {{0L, 0L}, {0L, 0L}, 0L, 0L, 0L, 0L,
98 				0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
99 				{0L, 0L}, 0LL, 0LL, 0LL, 0LL, 0L, 0L, 0L,
100 				0LL, 0LL, {0L, 0L, 0L, 0L, 0L}};
101 # else
102 static struct rusage zru;
103 # endif /* convex */
104 #else /* !BSDTIMES */
105 # ifdef _SEQUENT_
106 static struct process_stats zru = {{0L, 0L}, {0L, 0L}, 0, 0, 0, 0, 0, 0, 0,
107 				   0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
108 # else /* !_SEQUENT_ */
109 #  ifdef _SX
110 static struct tms zru = {0, 0, 0, 0}, lru = {0, 0, 0, 0};
111 #  else	/* !_SX */
112 static struct tms zru = {0L, 0L, 0L, 0L}, lru = {0L, 0L, 0L, 0L};
113 #  endif	/* !_SX */
114 # endif	/* !_SEQUENT_ */
115 #endif /* !BSDTIMES */
116 
117 #ifndef BSDTIMES
118 static int timesdone;	/* shtimes buffer full ? */
119 #endif /* BSDTIMES */
120 
121 #ifndef RUSAGE_CHILDREN
122 # define	RUSAGE_CHILDREN	-1
123 #endif /* RUSAGE_CHILDREN */
124 
125 static	void		 pflushall	(void);
126 static	void		 pflush		(struct process *);
127 static	void		 pfree		(struct process *);
128 static	void		 pclrcurr	(struct process *);
129 static	void		 morecommand	(size_t);
130 static	void		 padd		(struct command *);
131 static	int		 pprint		(struct process *, int);
132 static	void		 ptprint	(struct process *);
133 static	void		 pads		(Char *);
134 static	void		 pkill		(Char **, int);
135 static	struct process	*pgetcurr	(struct process *);
136 static	void		 okpcntl	(void);
137 static	void		 setttypgrp	(int);
138 
139 /*
140  * pchild - call queued by the SIGCHLD signal
141  *	indicating that at least one child has terminated or stopped
142  *	thus at least one wait system call will definitely return a
143  *	childs status.  Top level routines (like pwait) must be sure
144  *	to mask interrupts when playing with the proclist data structures!
145  */
146 void
147 pchild(void)
148 {
149     struct process *pp;
150     struct process *fp;
151     pid_t pid;
152 #ifdef BSDWAIT
153     union wait w;
154 #else /* !BSDWAIT */
155     int     w;
156 #endif /* !BSDWAIT */
157     int     jobflags;
158 #ifdef BSDTIMES
159     struct sysrusage ru;
160 #else /* !BSDTIMES */
161 # ifdef _SEQUENT_
162     struct process_stats ru;
163     struct process_stats cpst1, cpst2;
164     timeval_t tv;
165 # else /* !_SEQUENT_ */
166     struct tms proctimes;
167 
168     if (!timesdone) {
169 	timesdone++;
170 	(void) times(&shtimes);
171     }
172 # endif	/* !_SEQUENT_ */
173 #endif /* !BSDTIMES */
174 
175     jobdebug_xprintf(("pchild()\n"));
176 
177 loop:
178     jobdebug_xprintf(("Waiting...\n"));
179     jobdebug_flush();
180     errno = 0;			/* reset, just in case */
181 
182 #ifndef WINNT_NATIVE
183 # ifdef BSDJOBS
184 #  ifdef BSDTIMES
185 #   ifdef convex
186     /* use 'cvxwait' to get parallel statistics */
187     pid = cvxwait(&w,
188         (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
189 #   else
190     /* both a wait3 and rusage */
191 #    if !defined(BSDWAIT) || defined(NeXT) || defined(MACH) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) || (defined(IRIS4D) && SYSVREL <= 3) || defined(__lucid) || defined(__osf__)
192 #ifdef __ANDROID__ /* no wait3, only wait4 */
193     pid = wait4(-1, &w,
194        (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
195 #else
196     pid = wait3(&w,
197        (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
198 #endif /* __ANDROID__ */
199 #    else /* BSDWAIT */
200     pid = wait3(&w.w_status,
201        (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
202 #    endif /* BSDWAIT */
203 #   endif /* convex */
204 #  else /* !BSDTIMES */
205 #   ifdef _SEQUENT_
206     (void) get_process_stats(&tv, PS_SELF, 0, &cpst1);
207     pid = waitpid(-1, &w,
208 	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
209     (void) get_process_stats(&tv, PS_SELF, 0, &cpst2);
210     pr_stat_sub(&cpst2, &cpst1, &ru);
211 #   else	/* !_SEQUENT_ */
212 #    ifndef POSIX
213     /* we have a wait3, but no rusage stuff */
214     pid = wait3(&w.w_status,
215 	 (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), 0);
216 #    else /* POSIX */
217     pid = waitpid(-1, &w,
218 	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
219 #    endif /* POSIX */
220 #   endif /* !_SEQUENT_ */
221 #  endif	/* !BSDTIMES */
222 # else /* !BSDJOBS */
223 #  ifdef BSDTIMES
224 #   define HAVEwait3
225     /* both a wait3 and rusage */
226 #   ifdef hpux
227     pid = wait3(&w.w_status, WNOHANG, 0);
228 #   else	/* !hpux */
229 #     ifndef BSDWAIT
230     pid = wait3(&w, WNOHANG, &ru);
231 #     else
232     pid = wait3(&w.w_status, WNOHANG, &ru);
233 #     endif /* BSDWAIT */
234 #   endif /* !hpux */
235 #  else /* !BSDTIMES */
236 #   ifdef ODT  /* For Sco Unix 3.2.0 or ODT 1.0 */
237 #    define HAVEwait3
238     pid = waitpid(-1, &w,
239  	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
240 #   endif /* ODT */
241 #   if defined(aiws) || defined(uts)
242 #    define HAVEwait3
243     pid = wait3(&w.w_status,
244 	(setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), 0);
245 #   endif /* aiws || uts */
246 #   ifndef HAVEwait3
247 #    ifndef BSDWAIT
248      /* no wait3, therefore no rusage */
249      /* on Sys V, this may hang.  I hope it's not going to be a problem */
250     pid = wait(&w);
251 #    else /* BSDWAIT */
252      /*
253       * XXX: for greater than 3 we should use waitpid().
254       * but then again, SVR4 falls into the POSIX/BSDJOBS category.
255       */
256     pid = wait(&w.w_status);
257 #    endif /* BSDWAIT */
258 #   endif /* !HAVEwait3 */
259 #  endif	/* !BSDTIMES */
260 # endif /* !BSDJOBS */
261 #else /* WINNT_NATIVE */
262     pid = waitpid(-1, &w,
263 	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
264 #endif /* WINNT_NATIVE */
265 
266     jobdebug_xprintf(("parent %d pid %d, retval %x termsig %x retcode %x\n",
267 		      (int)getpid(), (int)pid, w, WTERMSIG(w),
268 		      WEXITSTATUS(w)));
269     jobdebug_flush();
270 
271     if ((pid == 0) || (pid == -1)) {
272 	(void)handle_pending_signals();
273 	jobdebug_xprintf(("errno == %d\n", errno));
274 	if (errno == EINTR)
275 	    goto loop;
276 	goto end;
277     }
278     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
279 	if (pid == pp->p_procid)
280 	    goto found;
281 #if !defined(BSDJOBS) && !defined(WINNT_NATIVE)
282     /* this should never have happened */
283     stderror(ERR_SYNC, pid);
284     xexit(0);
285 #else /* BSDJOBS || WINNT_NATIVE */
286     goto loop;
287 #endif /* !BSDJOBS && !WINNT_NATIVE */
288 found:
289     pp->p_flags &= ~(PRUNNING | PSTOPPED | PREPORTED);
290     if (WIFSTOPPED(w)) {
291 	pp->p_flags |= PSTOPPED;
292 	pp->p_reason = WSTOPSIG(w);
293     }
294     else {
295 	if (pp->p_flags & (PTIME | PPTIME) || adrof(STRtime))
296 #ifndef BSDTIMES
297 # ifdef _SEQUENT_
298 	    (void) get_process_stats(&pp->p_etime, PS_SELF, NULL, NULL);
299 # else	/* !_SEQUENT_ */
300 	    pp->p_etime = times(&proctimes);
301 # endif	/* !_SEQUENT_ */
302 #else /* BSDTIMES */
303 	    (void) gettimeofday(&pp->p_etime, NULL);
304 #endif /* BSDTIMES */
305 
306 
307 #if defined(BSDTIMES) || defined(_SEQUENT_)
308 	pp->p_rusage = ru;
309 #else /* !BSDTIMES && !_SEQUENT_ */
310 	(void) times(&proctimes);
311 	pp->p_utime = proctimes.tms_cutime - shtimes.tms_cutime;
312 	pp->p_stime = proctimes.tms_cstime - shtimes.tms_cstime;
313 	shtimes = proctimes;
314 #endif /* !BSDTIMES && !_SEQUENT_ */
315 	if (WIFSIGNALED(w)) {
316 	    if (WTERMSIG(w) == SIGINT)
317 		pp->p_flags |= PINTERRUPTED;
318 	    else
319 		pp->p_flags |= PSIGNALED;
320 	    if (WCOREDUMP(w))
321 		pp->p_flags |= PDUMPED;
322 	    pp->p_reason = WTERMSIG(w);
323 	}
324 	else {
325 	    pp->p_reason = WEXITSTATUS(w);
326 	    if (pp->p_reason != 0)
327 		pp->p_flags |= PAEXITED;
328 	    else
329 		pp->p_flags |= PNEXITED;
330 	}
331     }
332     jobflags = 0;
333     fp = pp;
334     do {
335 	if ((fp->p_flags & (PPTIME | PRUNNING | PSTOPPED)) == 0 &&
336 	    !child && adrof(STRtime) &&
337 #ifdef BSDTIMES
338 	    fp->p_rusage.ru_utime.tv_sec + fp->p_rusage.ru_stime.tv_sec
339 #else /* !BSDTIMES */
340 # ifdef _SEQUENT_
341 	    fp->p_rusage.ps_utime.tv_sec + fp->p_rusage.ps_stime.tv_sec
342 # else /* !_SEQUENT_ */
343 #  ifndef POSIX
344 	    (fp->p_utime + fp->p_stime) / HZ
345 #  else /* POSIX */
346 	    (fp->p_utime + fp->p_stime) / clk_tck
347 #  endif /* POSIX */
348 # endif /* !_SEQUENT_ */
349 #endif /* !BSDTIMES */
350 	    >= atoi(short2str(varval(STRtime))))
351 	    fp->p_flags |= PTIME;
352 	jobflags |= fp->p_flags;
353     } while ((fp = fp->p_friends) != pp);
354     pp->p_flags &= ~PFOREGND;
355     if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
356 	pp->p_flags &= ~PPTIME;
357 	pp->p_flags |= PTIME;
358     }
359     if ((jobflags & (PRUNNING | PREPORTED)) == 0) {
360 	fp = pp;
361 	do {
362 	    if (fp->p_flags & PSTOPPED)
363 		fp->p_flags |= PREPORTED;
364 	} while ((fp = fp->p_friends) != pp);
365 	while (fp->p_procid != fp->p_jobid)
366 	    fp = fp->p_friends;
367 	if (jobflags & PSTOPPED) {
368 	    if (pcurrent && pcurrent != fp)
369 		pprevious = pcurrent;
370 	    pcurrent = fp;
371 	}
372 	else
373 	    pclrcurr(fp);
374 	if (jobflags & PFOREGND) {
375 	    if (!(jobflags & (PSIGNALED | PSTOPPED | PPTIME) ||
376 #ifdef notdef
377 		jobflags & PAEXITED ||
378 #endif /* notdef */
379 		fp->p_cwd == NULL ||
380 		!eq(dcwd->di_name, fp->p_cwd->di_name))) {
381 	    /* PWP: print a newline after ^C */
382 		if (jobflags & PINTERRUPTED) {
383 		    xputchar('\r' | QUOTE);
384 		    xputchar('\n');
385 		}
386 #ifdef notdef
387 		else if ((jobflags & (PTIME|PSTOPPED)) == PTIME)
388 		    ptprint(fp);
389 #endif /* notdef */
390 	    }
391 	}
392 	else {
393 	    if (jobflags & PNOTIFY || adrof(STRnotify)) {
394 	        xputchar('\r' | QUOTE);
395 		xputchar('\n');
396 		(void) pprint(pp, NUMBER | NAME | REASON);
397 		if ((jobflags & PSTOPPED) == 0)
398 		    pflush(pp);
399 		if (GettingInput) {
400 		    errno = 0;
401 		    (void) Rawmode();
402 #ifdef notdef
403 		    /*
404 		     * don't really want to do that, because it
405 		     * will erase our message in case of multi-line
406 		     * input
407 		     */
408 		    ClearLines();
409 #endif /* notdef */
410 		    ClearDisp();
411 		    Refresh();
412 		}
413 	    }
414 	    else {
415 		fp->p_flags |= PNEEDNOTE;
416 		neednote = 1;
417 	    }
418 	}
419     }
420 #if defined(BSDJOBS) || defined(HAVEwait3) ||defined(WINNT_NATIVE)
421     goto loop;
422 #endif /* BSDJOBS || HAVEwait3 */
423  end:
424     ;
425 }
426 
427 void
428 pnote(void)
429 {
430     struct process *pp;
431     int     flags;
432 
433     neednote = 0;
434     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next) {
435 	if (pp->p_flags & PNEEDNOTE) {
436 	    pchild_disabled++;
437 	    cleanup_push(&pchild_disabled, disabled_cleanup);
438 	    pp->p_flags &= ~PNEEDNOTE;
439 	    flags = pprint(pp, NUMBER | NAME | REASON);
440 	    if ((flags & (PRUNNING | PSTOPPED)) == 0)
441 		pflush(pp);
442 	    cleanup_until(&pchild_disabled);
443 	}
444     }
445 }
446 
447 
448 static void
449 pfree(struct process *pp)
450 {
451     xfree(pp->p_command);
452     if (pp->p_cwd && --pp->p_cwd->di_count == 0)
453 	if (pp->p_cwd->di_next == 0)
454 	    dfree(pp->p_cwd);
455     xfree(pp);
456 }
457 
458 
459 /*
460  * pwait - wait for current job to terminate, maintaining integrity
461  *	of current and previous job indicators.
462  */
463 void
464 pwait(void)
465 {
466     struct process *fp, *pp;
467 
468     /*
469      * Here's where dead procs get flushed.
470      */
471     for (pp = (fp = &proclist)->p_next; pp != NULL; pp = (fp = pp)->p_next)
472 	if (pp->p_procid == 0) {
473 	    fp->p_next = pp->p_next;
474 	    pfree(pp);
475 	    pp = fp;
476 	}
477     pjwait(pcurrjob);
478 }
479 
480 
481 /*
482  * pjwait - wait for a job to finish or become stopped
483  *	It is assumed to be in the foreground state (PFOREGND)
484  */
485 void
486 pjwait(struct process *pp)
487 {
488     struct process *fp;
489     int     jobflags, reason;
490     sigset_t oset, set, pause_mask;
491     Char *reason_str;
492 
493     while (pp->p_procid != pp->p_jobid)
494 	pp = pp->p_friends;
495     fp = pp;
496 
497     do {
498 	if ((fp->p_flags & (PFOREGND | PRUNNING)) == PRUNNING)
499 	  xprintf("%s", CGETS(17, 1, "BUG: waiting for background job!\n"));
500     } while ((fp = fp->p_friends) != pp);
501     /*
502      * Now keep pausing as long as we are not interrupted (SIGINT), and the
503      * target process, or any of its friends, are running
504      */
505     fp = pp;
506     sigemptyset(&set);
507     sigaddset(&set, SIGINT);
508     sigaddset(&set, SIGCHLD);
509     (void)sigprocmask(SIG_BLOCK, &set, &oset);
510     cleanup_push(&oset, sigprocmask_cleanup);
511     pause_mask = oset;
512     sigdelset(&pause_mask, SIGCHLD);
513     sigaddset(&pause_mask, SIGINT);
514     for (;;) {
515 	(void)handle_pending_signals();
516 	jobflags = 0;
517 	do
518 	    jobflags |= fp->p_flags;
519 	while ((fp = (fp->p_friends)) != pp);
520 	if ((jobflags & PRUNNING) == 0)
521 	    break;
522 	jobdebug_xprintf(("%d starting to sigsuspend for SIGCHLD on %d\n",
523 			  getpid(), fp->p_procid));
524 	sigsuspend(&pause_mask);
525     }
526     cleanup_until(&oset);
527     jobdebug_xprintf(("%d returned from sigsuspend loop\n", getpid()));
528 #ifdef BSDJOBS
529     if (tpgrp > 0)		/* get tty back */
530 	(void) tcsetpgrp(FSHTTY, tpgrp);
531 #endif /* BSDJOBS */
532     if ((jobflags & (PSIGNALED | PSTOPPED | PTIME)) ||
533 	fp->p_cwd == NULL || !eq(dcwd->di_name, fp->p_cwd->di_name)) {
534 	if (jobflags & PSTOPPED) {
535 	    xputchar('\n');
536 	    if (adrof(STRlistjobs)) {
537 		Char   *jobcommand[3];
538 
539 		jobcommand[0] = STRjobs;
540 		if (eq(varval(STRlistjobs), STRlong))
541 		    jobcommand[1] = STRml;
542 		else
543 		    jobcommand[1] = NULL;
544 		jobcommand[2] = NULL;
545 
546 		dojobs(jobcommand, NULL);
547 		(void) pprint(pp, SHELLDIR);
548 	    }
549 	    else
550 		(void) pprint(pp, AREASON | SHELLDIR);
551 	}
552 	else
553 	    (void) pprint(pp, AREASON | SHELLDIR);
554     }
555     if ((jobflags & (PINTERRUPTED | PSTOPPED)) && setintr &&
556 	(!gointr || !eq(gointr, STRminus))) {
557 	if ((jobflags & PSTOPPED) == 0)
558 	    pflush(pp);
559 	pintr1(0);
560 	/* NOTREACHED */
561     }
562     reason = 0;
563     fp = pp;
564     do {
565 	/* In case of pipelines only the result of the last
566 	 * command should be taken in account */
567 	if (!anyerror && !(fp->p_flags & PBRACE)
568 		&& ((fp->p_flags & PPOU) || (fp->p_flags & PBACKQ)))
569 	    continue;
570 	if (fp->p_reason)
571 	    reason = fp->p_flags & (PSIGNALED | PINTERRUPTED) ?
572 		fp->p_reason | META : fp->p_reason;
573     } while ((fp = fp->p_friends) != pp);
574     /*
575      * Don't report on backquoted jobs, cause it will mess up
576      * their output.
577      */
578     if ((reason != 0) && (adrof(STRprintexitvalue)) &&
579 	(pp->p_flags & PBACKQ) == 0)
580 	xprintf(CGETS(17, 2, "Exit %d\n"), reason);
581     reason_str = putn((tcsh_number_t)reason);
582     cleanup_push(reason_str, xfree);
583     setv(STRstatus, reason_str, VAR_READWRITE);
584     cleanup_ignore(reason_str);
585     cleanup_until(reason_str);
586     if (reason && exiterr)
587 	exitstat();
588     pflush(pp);
589 }
590 
591 /*
592  * dowait - wait for all processes to finish
593  */
594 
595 /*ARGSUSED*/
596 void
597 dowait(Char **v, struct command *c)
598 {
599     struct process *pp;
600 
601     /* the current block mask to be able to restore */
602     sigset_t old_mask;
603 
604     /* block mask for critical section: OLD_MASK U {SIGCHLD} */
605     sigset_t block_mask;
606 
607     /* ignore those during blocking sigsuspend:
608        OLD_MASK / {SIGCHLD, possibly(SIGINT)} */
609     sigset_t pause_mask;
610 
611     int opintr_disabled, gotsig;
612 
613     USE(c);
614     USE(v);
615     pjobs++;
616 
617     sigprocmask(SIG_BLOCK, NULL, &pause_mask);
618     sigdelset(&pause_mask, SIGCHLD);
619     if (setintr)
620 	sigdelset(&pause_mask, SIGINT);
621 
622     /* critical section, block also SIGCHLD */
623     sigprocmask(SIG_BLOCK, NULL, &block_mask);
624     sigaddset(&block_mask, SIGCHLD);
625     sigprocmask(SIG_BLOCK, &block_mask, &old_mask);
626 
627     /* detect older SIGCHLDs and remove PRUNNING flag from proclist */
628     (void)handle_pending_signals();
629 
630 loop:
631     for (pp = proclist.p_next; pp; pp = pp->p_next)
632 	if (pp->p_procid &&	/* pp->p_procid == pp->p_jobid && */
633 	    pp->p_flags & PRUNNING) {
634 	    /* wait for (or pick up alredy blocked) SIGCHLD */
635 	    sigsuspend(&pause_mask);
636 
637 	    /* make the 'wait' interuptable by CTRL-C */
638 	    opintr_disabled = pintr_disabled;
639 	    pintr_disabled = 0;
640 	    gotsig = handle_pending_signals();
641 	    pintr_disabled = opintr_disabled;
642 	    if (gotsig)
643 		break;
644 	    goto loop;
645 	}
646     pjobs = 0;
647 
648     sigprocmask(SIG_SETMASK, &old_mask, NULL);
649 }
650 
651 /*
652  * pflushall - flush all jobs from list (e.g. at fork())
653  */
654 static void
655 pflushall(void)
656 {
657     struct process *pp;
658 
659     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
660 	if (pp->p_procid)
661 	    pflush(pp);
662 }
663 
664 /*
665  * pflush - flag all process structures in the same job as the
666  *	the argument process for deletion.  The actual free of the
667  *	space is not done here since pflush is called at interrupt level.
668  */
669 static void
670 pflush(struct process *pp)
671 {
672     struct process *np;
673     int idx;
674 
675     if (pp->p_procid == 0) {
676 	xprintf("%s", CGETS(17, 3, "BUG: process flushed twice"));
677 	return;
678     }
679     while (pp->p_procid != pp->p_jobid)
680 	pp = pp->p_friends;
681     pclrcurr(pp);
682     if (pp == pcurrjob)
683 	pcurrjob = 0;
684     idx = pp->p_index;
685     np = pp;
686     do {
687 	np->p_index = np->p_procid = 0;
688 	np->p_flags &= ~PNEEDNOTE;
689     } while ((np = np->p_friends) != pp);
690     if (idx == pmaxindex) {
691 	for (np = proclist.p_next, idx = 0; np; np = np->p_next)
692 	    if (np->p_index > idx)
693 		idx = np->p_index;
694 	pmaxindex = idx;
695     }
696 }
697 
698 /*
699  * pclrcurr - make sure the given job is not the current or previous job;
700  *	pp MUST be the job leader
701  */
702 static void
703 pclrcurr(struct process *pp)
704 {
705     if (pp == pcurrent) {
706 	if (pprevious != NULL) {
707 	    pcurrent = pprevious;
708 	    pprevious = pgetcurr(pp);
709 	}
710 	else {
711 	    pcurrent = pgetcurr(pp);
712 	    pprevious = pgetcurr(pp);
713 	}
714     }
715     else if (pp == pprevious)
716 	pprevious = pgetcurr(pp);
717 }
718 
719 /* +4 here is 1 for '\0', 1 ea for << >& >> */
720 static Char *cmdstr;
721 static size_t cmdmax;
722 static size_t cmdlen;
723 static Char *cmdp;
724 #define CMD_INIT 1024
725 #define CMD_INCR 64
726 
727 static void
728 morecommand(size_t s)
729 {
730     Char *ncmdstr;
731     ptrdiff_t d;
732 
733     cmdmax += s;
734     ncmdstr = xrealloc(cmdstr, cmdmax * sizeof(*cmdstr));
735     d = ncmdstr - cmdstr;
736     cmdstr = ncmdstr;
737     cmdp += d;
738 }
739 
740 /* GrP
741  * unparse - Export padd() functionality
742  */
743 Char *
744 unparse(struct command *t)
745 {
746     if (cmdmax == 0)
747 	morecommand(CMD_INIT);
748     cmdp = cmdstr;
749     cmdlen = 0;
750     padd(t);
751     *cmdp++ = '\0';
752     return Strsave(cmdstr);
753 }
754 
755 
756 /*
757  * palloc - allocate a process structure and fill it up.
758  *	an important assumption is made that the process is running.
759  */
760 void
761 palloc(pid_t pid, struct command *t)
762 {
763     struct process *pp;
764     int     i;
765 
766     pp = xcalloc(1, sizeof(struct process));
767     pp->p_procid = pid;
768     pp->p_parentid = shpgrp;
769     pp->p_flags = ((t->t_dflg & F_AMPERSAND) ? 0 : PFOREGND) | PRUNNING;
770     if (t->t_dflg & F_TIME)
771 	pp->p_flags |= PPTIME;
772     if (t->t_dflg & F_BACKQ)
773 	pp->p_flags |= PBACKQ;
774     if (t->t_dflg & F_HUP)
775 	pp->p_flags |= PHUP;
776     if (t->t_dcom && t->t_dcom[0] && (*t->t_dcom[0] == '{'))
777 	pp->p_flags |= PBRACE;
778     if (cmdmax == 0)
779 	morecommand(CMD_INIT);
780     cmdp = cmdstr;
781     cmdlen = 0;
782     padd(t);
783     *cmdp++ = 0;
784     if (t->t_dflg & F_PIPEOUT) {
785 	pp->p_flags |= PPOU;
786 	if (t->t_dflg & F_STDERR)
787 	    pp->p_flags |= PDIAG;
788     }
789     pp->p_command = Strsave(cmdstr);
790     if (pcurrjob) {
791 	struct process *fp;
792 
793 	/* careful here with interrupt level */
794 	pp->p_cwd = 0;
795 	pp->p_index = pcurrjob->p_index;
796 	pp->p_friends = pcurrjob;
797 	pp->p_jobid = pcurrjob->p_procid;
798 	for (fp = pcurrjob; fp->p_friends != pcurrjob; fp = fp->p_friends)
799 	    continue;
800 	fp->p_friends = pp;
801     }
802     else {
803 	pcurrjob = pp;
804 	pp->p_jobid = pid;
805 	pp->p_friends = pp;
806 	pp->p_cwd = dcwd;
807 	dcwd->di_count++;
808 	if (pmaxindex < BIGINDEX)
809 	    pp->p_index = ++pmaxindex;
810 	else {
811 	    struct process *np;
812 
813 	    for (i = 1;; i++) {
814 		for (np = proclist.p_next; np; np = np->p_next)
815 		    if (np->p_index == i)
816 			goto tryagain;
817 		pp->p_index = i;
818 		if (i > pmaxindex)
819 		    pmaxindex = i;
820 		break;
821 	tryagain:;
822 	    }
823 	}
824 	if (pcurrent == NULL)
825 	    pcurrent = pp;
826 	else if (pprevious == NULL)
827 	    pprevious = pp;
828     }
829     pp->p_next = proclist.p_next;
830     proclist.p_next = pp;
831 #ifdef BSDTIMES
832     (void) gettimeofday(&pp->p_btime, NULL);
833 #else /* !BSDTIMES */
834 # ifdef _SEQUENT_
835     (void) get_process_stats(&pp->p_btime, PS_SELF, NULL, NULL);
836 # else /* !_SEQUENT_ */
837     {
838 	struct tms tmptimes;
839 
840 	pp->p_btime = times(&tmptimes);
841     }
842 # endif /* !_SEQUENT_ */
843 #endif /* !BSDTIMES */
844 }
845 
846 static void
847 padd(struct command *t)
848 {
849     Char  **argp;
850 
851     if (t == 0)
852 	return;
853     switch (t->t_dtyp) {
854 
855     case NODE_PAREN:
856 	pads(STRLparensp);
857 	padd(t->t_dspr);
858 	pads(STRspRparen);
859 	break;
860 
861     case NODE_COMMAND:
862 	for (argp = t->t_dcom; *argp; argp++) {
863 	    pads(*argp);
864 	    if (argp[1])
865 		pads(STRspace);
866 	}
867 	break;
868 
869     case NODE_OR:
870     case NODE_AND:
871     case NODE_PIPE:
872     case NODE_LIST:
873 	padd(t->t_dcar);
874 	switch (t->t_dtyp) {
875 	case NODE_OR:
876 	    pads(STRspor2sp);
877 	    break;
878 	case NODE_AND:
879 	    pads(STRspand2sp);
880 	    break;
881 	case NODE_PIPE:
882 	    pads(STRsporsp);
883 	    break;
884 	case NODE_LIST:
885 	    pads(STRsemisp);
886 	    break;
887 	default:
888 	    break;
889 	}
890 	padd(t->t_dcdr);
891 	return;
892 
893     default:
894 	break;
895     }
896     if ((t->t_dflg & F_PIPEIN) == 0 && t->t_dlef) {
897 	pads((t->t_dflg & F_READ) ? STRspLarrow2sp : STRspLarrowsp);
898 	pads(t->t_dlef);
899     }
900     if ((t->t_dflg & F_PIPEOUT) == 0 && t->t_drit) {
901 	pads((t->t_dflg & F_APPEND) ? STRspRarrow2 : STRspRarrow);
902 	if (t->t_dflg & F_STDERR)
903 	    pads(STRand);
904 	pads(STRspace);
905 	pads(t->t_drit);
906     }
907 }
908 
909 static void
910 pads(Char *cp)
911 {
912     size_t i, len;
913 
914     /*
915      * Avoid the Quoted Space alias hack! Reported by:
916      * sam@john-bigboote.ICS.UCI.EDU (Sam Horrocks)
917      */
918     if (cp[0] == STRQNULL[0])
919 	cp++;
920 
921     i = Strlen(cp);
922 
923     len = cmdlen + i + CMD_INCR;
924     if (len >= cmdmax)
925 	morecommand(len);
926     (void) Strcpy(cmdp, cp);
927     cmdp += i;
928     cmdlen += i;
929 }
930 
931 /*
932  * psavejob - temporarily save the current job on a one level stack
933  *	so another job can be created.  Used for { } in exp6
934  *	and `` in globbing.
935  */
936 void
937 psavejob(void)
938 {
939     pholdjob = pcurrjob;
940     pcurrjob = NULL;
941 }
942 
943 void
944 psavejob_cleanup(void *dummy)
945 {
946     USE(dummy);
947     pcurrjob = pholdjob;
948     pholdjob = NULL;
949 }
950 
951 /*
952  * pendjob - indicate that a job (set of commands) has been completed
953  *	or is about to begin.
954  */
955 void
956 pendjob(void)
957 {
958     struct process *pp, *tp;
959 
960     if (pcurrjob && (pcurrjob->p_flags & (PFOREGND | PSTOPPED)) == 0) {
961 	pp = pcurrjob;
962 	pcurrjob = NULL;
963 	while (pp->p_procid != pp->p_jobid)
964 	    pp = pp->p_friends;
965 	xprintf("[%d]", pp->p_index);
966 	tp = pp;
967 	do {
968 	    xprintf(" %d", pp->p_procid);
969 	    pp = pp->p_friends;
970 	} while (pp != tp);
971 	xputchar('\n');
972     }
973     pholdjob = pcurrjob = 0;
974 }
975 
976 /*
977  * pprint - print a job
978  */
979 
980 /*
981  * Hacks have been added for SVR4 to deal with pipe's being spawned in
982  * reverse order
983  *
984  * David Dawes (dawes@physics.su.oz.au) Oct 1991
985  */
986 
987 static int
988 pprint(struct process *pp, int flag)
989 {
990     int status, reason;
991     struct process *tp;
992     int     jobflags, pstatus, pcond;
993     const char *format;
994     int ohaderr;
995 
996 #ifdef BACKPIPE
997     struct process *pipehead = NULL, *pipetail = NULL, *pmarker = NULL;
998     int inpipe = 0;
999 #endif /* BACKPIPE */
1000 
1001     while (pp->p_procid != pp->p_jobid)
1002 	pp = pp->p_friends;
1003     if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
1004 	pp->p_flags &= ~PPTIME;
1005 	pp->p_flags |= PTIME;
1006     }
1007     tp = pp;
1008     status = reason = -1;
1009     jobflags = 0;
1010     ohaderr = haderr;
1011     /* Print status to stderr, except for jobs built-in */
1012     haderr = !(flag & JOBLIST);
1013     do {
1014 #ifdef BACKPIPE
1015 	/*
1016 	 * The pipeline is reversed, so locate the real head of the pipeline
1017 	 * if pp is at the tail of a pipe (and not already in a pipeline)
1018 	 */
1019 	if ((pp->p_friends->p_flags & PPOU) && !inpipe && (flag & NAME)) {
1020 	    inpipe = 1;
1021 	    pipetail = pp;
1022 	    do
1023 		pp = pp->p_friends;
1024 	    while (pp->p_friends->p_flags & PPOU);
1025 	    pipehead = pp;
1026 	    pmarker = pp;
1027 	/*
1028 	 * pmarker is used to hold the place of the proc being processed, so
1029 	 * we can search for the next one downstream later.
1030 	 */
1031 	}
1032 	pcond = (tp != pp || (inpipe && tp == pp));
1033 #else /* !BACKPIPE */
1034 	pcond = (tp != pp);
1035 #endif /* BACKPIPE */
1036 
1037 	jobflags |= pp->p_flags;
1038 	pstatus = (int) (pp->p_flags & PALLSTATES);
1039 	if (pcond && linp != linbuf && !(flag & FANCY) &&
1040 	    ((pstatus == status && pp->p_reason == reason) ||
1041 	     !(flag & REASON)))
1042 	    xputchar(' ');
1043 	else {
1044 	    if (pcond && linp != linbuf)
1045 		xputchar('\n');
1046 	    if (flag & NUMBER) {
1047 #ifdef BACKPIPE
1048 		pcond = ((pp == tp && !inpipe) ||
1049 			 (inpipe && pipetail == tp && pp == pipehead));
1050 #else /* BACKPIPE */
1051 		pcond = (pp == tp);
1052 #endif /* BACKPIPE */
1053 		if (pcond)
1054 		    xprintf("[%d]%s %c ", pp->p_index,
1055 			    pp->p_index < 10 ? " " : "",
1056 			    pp == pcurrent ? '+' :
1057 			    (pp == pprevious ? '-' : ' '));
1058 		else
1059 		    xprintf("       ");
1060 	    }
1061 	    if (flag & FANCY) {
1062 		xprintf("%5d ", pp->p_procid);
1063 #ifdef TCF
1064 		xprintf("%11s ", sitename(pp->p_procid));
1065 #endif /* TCF */
1066 	    }
1067 	    if (flag & (REASON | AREASON)) {
1068 		if (flag & NAME)
1069 		    format = "%-30s";
1070 		else
1071 		    format = "%s";
1072 		if (pstatus == status) {
1073 		    if (pp->p_reason == reason) {
1074 			xprintf(format, "");
1075 			goto prcomd;
1076 		    }
1077 		    else
1078 			reason = (int) pp->p_reason;
1079 		}
1080 		else {
1081 		    status = pstatus;
1082 		    reason = (int) pp->p_reason;
1083 		}
1084 		switch (status) {
1085 
1086 		case PRUNNING:
1087 		    xprintf(format, CGETS(17, 4, "Running "));
1088 		    break;
1089 
1090 		case PINTERRUPTED:
1091 		case PSTOPPED:
1092 		case PSIGNALED:
1093 		    /*
1094 		     * tell what happened to the background job
1095 		     * From: Michael Schroeder
1096 		     * <mlschroe@immd4.informatik.uni-erlangen.de>
1097 		     */
1098 		    if ((flag & REASON)
1099 			|| ((flag & AREASON)
1100 			    && reason != SIGINT
1101 			    && (reason != SIGPIPE
1102 				|| (pp->p_flags & PPOU) == 0))) {
1103 			char *ptr;
1104 			int free_ptr;
1105 
1106 			free_ptr = 0;
1107 			ptr = (char *)(intptr_t)mesg[pp->p_reason & 0177].pname;
1108 			if (ptr == NULL) {
1109 			    ptr = xasprintf("%s %d", CGETS(17, 5, "Signal"),
1110 					    pp->p_reason & 0177);
1111 			    cleanup_push(ptr, xfree);
1112 			    free_ptr = 1;
1113 			}
1114 			xprintf(format, ptr);
1115 			if (free_ptr != 0)
1116 			    cleanup_until(ptr);
1117 		    }
1118 		    else
1119 			reason = -1;
1120 		    break;
1121 
1122 		case PNEXITED:
1123 		case PAEXITED:
1124 		    if (flag & REASON) {
1125 			if (pp->p_reason)
1126 			    xprintf(CGETS(17, 6, "Exit %-25d"), pp->p_reason);
1127 			else
1128 			    xprintf(format, CGETS(17, 7, "Done"));
1129 		    }
1130 		    break;
1131 
1132 		default:
1133 		    xprintf(CGETS(17, 8, "BUG: status=%-9o"),
1134 			    status);
1135 		}
1136 	    }
1137 	}
1138 prcomd:
1139 	if (flag & NAME) {
1140 	    xprintf("%S", pp->p_command);
1141 	    if (pp->p_flags & PPOU)
1142 		xprintf(" |");
1143 	    if (pp->p_flags & PDIAG)
1144 		xprintf("&");
1145 	}
1146 	if (flag & (REASON | AREASON) && pp->p_flags & PDUMPED)
1147 	    xprintf("%s", CGETS(17, 9, " (core dumped)"));
1148 	if (tp == pp->p_friends) {
1149 	    if (flag & AMPERSAND)
1150 		xprintf(" &");
1151 	    if (flag & JOBDIR &&
1152 		!eq(tp->p_cwd->di_name, dcwd->di_name)) {
1153 		xprintf("%s", CGETS(17, 10, " (wd: "));
1154 		dtildepr(tp->p_cwd->di_name);
1155 		xprintf(")");
1156 	    }
1157 	}
1158 	if (pp->p_flags & PPTIME && !(status & (PSTOPPED | PRUNNING))) {
1159 	    if (linp != linbuf)
1160 		xprintf("\n\t");
1161 #if defined(BSDTIMES) || defined(_SEQUENT_)
1162 	    prusage(&zru, &pp->p_rusage, &pp->p_etime,
1163 		    &pp->p_btime);
1164 #else /* !BSDTIMES && !SEQUENT */
1165 	    lru.tms_utime = pp->p_utime;
1166 	    lru.tms_stime = pp->p_stime;
1167 	    lru.tms_cutime = 0;
1168 	    lru.tms_cstime = 0;
1169 	    prusage(&zru, &lru, pp->p_etime,
1170 		    pp->p_btime);
1171 #endif /* !BSDTIMES && !SEQUENT */
1172 
1173 	}
1174 #ifdef BACKPIPE
1175 	pcond = ((tp == pp->p_friends && !inpipe) ||
1176 		 (inpipe && pipehead->p_friends == tp && pp == pipetail));
1177 #else  /* !BACKPIPE */
1178 	pcond = (tp == pp->p_friends);
1179 #endif /* BACKPIPE */
1180 	if (pcond) {
1181 	    if (linp != linbuf)
1182 		xputchar('\n');
1183 	    if (flag & SHELLDIR && !eq(tp->p_cwd->di_name, dcwd->di_name)) {
1184 		xprintf("%s", CGETS(17, 11, "(wd now: "));
1185 		dtildepr(dcwd->di_name);
1186 		xprintf(")\n");
1187 	    }
1188 	}
1189 #ifdef BACKPIPE
1190 	if (inpipe) {
1191 	    /*
1192 	     * if pmaker == pipetail, we are finished that pipeline, and
1193 	     * can now skip to past the head
1194 	     */
1195 	    if (pmarker == pipetail) {
1196 		inpipe = 0;
1197 		pp = pipehead;
1198 	    }
1199 	    else {
1200 	    /*
1201 	     * set pp to one before the one we want next, so the while below
1202 	     * increments to the correct spot.
1203 	     */
1204 		do
1205 		    pp = pp->p_friends;
1206 	    	while (pp->p_friends->p_friends != pmarker);
1207 	    	pmarker = pp->p_friends;
1208 	    }
1209 	}
1210 	pcond = ((pp = pp->p_friends) != tp || inpipe);
1211 #else /* !BACKPIPE */
1212 	pcond = ((pp = pp->p_friends) != tp);
1213 #endif /* BACKPIPE */
1214     } while (pcond);
1215 
1216     if (jobflags & PTIME && (jobflags & (PSTOPPED | PRUNNING)) == 0) {
1217 	if (jobflags & NUMBER)
1218 	    xprintf("       ");
1219 	ptprint(tp);
1220     }
1221     haderr = ohaderr;
1222     return (jobflags);
1223 }
1224 
1225 /*
1226  * All 4.3 BSD derived implementations are buggy and I've had enough.
1227  * The following implementation produces similar code and works in all
1228  * cases. The 4.3BSD one works only for <, >, !=
1229  */
1230 # undef timercmp
1231 #  define timercmp(tvp, uvp, cmp) \
1232       (((tvp)->tv_sec == (uvp)->tv_sec) ? \
1233 	   ((tvp)->tv_usec cmp (uvp)->tv_usec) : \
1234 	   ((tvp)->tv_sec  cmp (uvp)->tv_sec))
1235 
1236 static void
1237 ptprint(struct process *tp)
1238 {
1239 #ifdef BSDTIMES
1240     struct timeval tetime, diff;
1241     static struct timeval ztime;
1242     struct sysrusage ru;
1243     struct process *pp = tp;
1244 
1245     ru = zru;
1246     tetime = ztime;
1247     do {
1248 	ruadd(&ru, &pp->p_rusage);
1249 	tvsub(&diff, &pp->p_etime, &pp->p_btime);
1250 	if (timercmp(&diff, &tetime, >))
1251 	    tetime = diff;
1252     } while ((pp = pp->p_friends) != tp);
1253     prusage(&zru, &ru, &tetime, &ztime);
1254 #else /* !BSDTIMES */
1255 # ifdef _SEQUENT_
1256     timeval_t tetime, diff;
1257     static timeval_t ztime;
1258     struct process_stats ru;
1259     struct process *pp = tp;
1260 
1261     ru = zru;
1262     tetime = ztime;
1263     do {
1264 	ruadd(&ru, &pp->p_rusage);
1265 	tvsub(&diff, &pp->p_etime, &pp->p_btime);
1266 	if (timercmp(&diff, &tetime, >))
1267 	    tetime = diff;
1268     } while ((pp = pp->p_friends) != tp);
1269     prusage(&zru, &ru, &tetime, &ztime);
1270 # else /* !_SEQUENT_ */
1271 #  ifndef POSIX
1272     static time_t ztime = 0;
1273     static time_t zu_time = 0;
1274     static time_t zs_time = 0;
1275     time_t  tetime, diff;
1276     time_t  u_time, s_time;
1277 
1278 #  else	/* POSIX */
1279     static clock_t ztime = 0;
1280     static clock_t zu_time = 0;
1281     static clock_t zs_time = 0;
1282     clock_t tetime, diff;
1283     clock_t u_time, s_time;
1284 
1285 #  endif /* POSIX */
1286     struct tms zts, rts;
1287     struct process *pp = tp;
1288 
1289     u_time = zu_time;
1290     s_time = zs_time;
1291     tetime = ztime;
1292     do {
1293 	u_time += pp->p_utime;
1294 	s_time += pp->p_stime;
1295 	diff = pp->p_etime - pp->p_btime;
1296 	if (diff > tetime)
1297 	    tetime = diff;
1298     } while ((pp = pp->p_friends) != tp);
1299     zts.tms_utime = zu_time;
1300     zts.tms_stime = zs_time;
1301     zts.tms_cutime = 0;
1302     zts.tms_cstime = 0;
1303     rts.tms_utime = u_time;
1304     rts.tms_stime = s_time;
1305     rts.tms_cutime = 0;
1306     rts.tms_cstime = 0;
1307     prusage(&zts, &rts, tetime, ztime);
1308 # endif /* !_SEQUENT_ */
1309 #endif	/* !BSDTIMES */
1310 }
1311 
1312 /*
1313  * dojobs - print all jobs
1314  */
1315 /*ARGSUSED*/
1316 void
1317 dojobs(Char **v, struct command *c)
1318 {
1319     struct process *pp;
1320     int flag = NUMBER | NAME | REASON | JOBLIST;
1321     int     i;
1322 
1323     USE(c);
1324     if (chkstop)
1325 	chkstop = 2;
1326     if (*++v) {
1327 	if (v[1] || !eq(*v, STRml))
1328 	    stderror(ERR_JOBS);
1329 	flag |= FANCY | JOBDIR;
1330     }
1331     for (i = 1; i <= pmaxindex; i++)
1332 	for (pp = proclist.p_next; pp; pp = pp->p_next)
1333 	    if (pp->p_index == i && pp->p_procid == pp->p_jobid) {
1334 		pp->p_flags &= ~PNEEDNOTE;
1335 		if (!(pprint(pp, flag) & (PRUNNING | PSTOPPED)))
1336 		    pflush(pp);
1337 		break;
1338 	    }
1339 }
1340 
1341 /*
1342  * dofg - builtin - put the job into the foreground
1343  */
1344 /*ARGSUSED*/
1345 void
1346 dofg(Char **v, struct command *c)
1347 {
1348     struct process *pp;
1349 
1350     USE(c);
1351     okpcntl();
1352     ++v;
1353     do {
1354 	pp = pfind(*v);
1355 	if (!pstart(pp, 1)) {
1356 	    pp->p_procid = 0;
1357 	    stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1358 	    continue;
1359 	}
1360 	pjwait(pp);
1361     } while (*v && *++v);
1362 }
1363 
1364 /*
1365  * %... - builtin - put the job into the foreground
1366  */
1367 /*ARGSUSED*/
1368 void
1369 dofg1(Char **v, struct command *c)
1370 {
1371     struct process *pp;
1372 
1373     USE(c);
1374     okpcntl();
1375     pp = pfind(v[0]);
1376     if (!pstart(pp, 1)) {
1377 	pp->p_procid = 0;
1378 	stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1379 	return;
1380     }
1381     pjwait(pp);
1382 }
1383 
1384 /*
1385  * dobg - builtin - put the job into the background
1386  */
1387 /*ARGSUSED*/
1388 void
1389 dobg(Char **v, struct command *c)
1390 {
1391     struct process *pp;
1392 
1393     USE(c);
1394     okpcntl();
1395     ++v;
1396     do {
1397 	pp = pfind(*v);
1398 	if (!pstart(pp, 0)) {
1399 	    pp->p_procid = 0;
1400 	    stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1401 	}
1402     } while (*v && *++v);
1403 }
1404 
1405 /*
1406  * %... & - builtin - put the job into the background
1407  */
1408 /*ARGSUSED*/
1409 void
1410 dobg1(Char **v, struct command *c)
1411 {
1412     struct process *pp;
1413 
1414     USE(c);
1415     pp = pfind(v[0]);
1416     if (!pstart(pp, 0)) {
1417 	pp->p_procid = 0;
1418 	stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1419     }
1420 }
1421 
1422 /*
1423  * dostop - builtin - stop the job
1424  */
1425 /*ARGSUSED*/
1426 void
1427 dostop(Char **v, struct command *c)
1428 {
1429     USE(c);
1430 #ifdef BSDJOBS
1431     pkill(++v, SIGSTOP);
1432 #endif /* BSDJOBS */
1433 }
1434 
1435 /*
1436  * dokill - builtin - superset of kill (1)
1437  */
1438 /*ARGSUSED*/
1439 void
1440 dokill(Char **v, struct command *c)
1441 {
1442     int signum, len = 0;
1443     const char *name;
1444     Char *sigptr;
1445 
1446     USE(c);
1447     v++;
1448     if (v[0] && v[0][0] == '-') {
1449 	if (v[0][1] == 'l') {
1450 	    for (signum = 0; signum <= nsig; signum++) {
1451 		if ((name = mesg[signum].iname) != NULL) {
1452 		    len += strlen(name) + 1;
1453 		    if (len >= TermH - 1) {
1454 			xputchar('\n');
1455 			len = strlen(name) + 1;
1456 		    }
1457 		    xprintf("%s ", name);
1458 		}
1459 	    }
1460 	    xputchar('\n');
1461 	    return;
1462 	}
1463  	sigptr = &v[0][1];
1464  	if (v[0][1] == 's') {
1465  	    if (v[1]) {
1466  		v++;
1467  		sigptr = &v[0][0];
1468  	    } else {
1469  		stderror(ERR_NAME | ERR_TOOFEW);
1470  	    }
1471  	}
1472  	if (Isdigit(*sigptr)) {
1473 	    char *ep;
1474  	    signum = strtoul(short2str(sigptr), &ep, 0);
1475 	    if (*ep || signum < 0 || signum > (MAXSIG-1))
1476 		stderror(ERR_NAME | ERR_BADSIG);
1477 	}
1478 	else {
1479 	    for (signum = 0; signum <= nsig; signum++)
1480 		if (mesg[signum].iname &&
1481  		    eq(sigptr, str2short(mesg[signum].iname)))
1482 		    goto gotsig;
1483  	    setname(short2str(sigptr));
1484 	    stderror(ERR_NAME | ERR_UNKSIG);
1485 	}
1486 gotsig:
1487 	v++;
1488     }
1489     else
1490 	signum = SIGTERM;
1491     pkill(v, signum);
1492 }
1493 
1494 static void
1495 pkill(Char **v, int signum)
1496 {
1497     struct process *pp, *np;
1498     int jobflags = 0, err1 = 0;
1499     pid_t     pid;
1500     Char *cp, **vp, **globbed;
1501 
1502     /* Avoid globbing %?x patterns */
1503     for (vp = v; vp && *vp; vp++)
1504 	if (**vp == '%')
1505 	    (void) quote(*vp);
1506 
1507     v = glob_all_or_error(v);
1508     globbed = v;
1509     cleanup_push(globbed, blk_cleanup);
1510 
1511     pchild_disabled++;
1512     cleanup_push(&pchild_disabled, disabled_cleanup);
1513     if (setintr) {
1514 	pintr_disabled++;
1515 	cleanup_push(&pintr_disabled, disabled_cleanup);
1516     }
1517 
1518     while (v && (cp = *v)) {
1519 	if (*cp == '%') {
1520 	    np = pp = pfind(cp);
1521 	    do
1522 		jobflags |= np->p_flags;
1523 	    while ((np = np->p_friends) != pp);
1524 #ifdef BSDJOBS
1525 	    switch (signum) {
1526 
1527 	    case SIGSTOP:
1528 	    case SIGTSTP:
1529 	    case SIGTTIN:
1530 	    case SIGTTOU:
1531 		if ((jobflags & PRUNNING) == 0) {
1532 # ifdef SUSPENDED
1533 		    xprintf(CGETS(17, 12, "%S: Already suspended\n"), cp);
1534 # else /* !SUSPENDED */
1535 		    xprintf(CGETS(17, 13, "%S: Already stopped\n"), cp);
1536 # endif /* !SUSPENDED */
1537 		    err1++;
1538 		    goto cont;
1539 		}
1540 		break;
1541 		/*
1542 		 * suspend a process, kill -CONT %, then type jobs; the shell
1543 		 * says it is suspended, but it is running; thanks jaap..
1544 		 */
1545 	    case SIGCONT:
1546 		if (!pstart(pp, 0)) {
1547 		    pp->p_procid = 0;
1548 		    stderror(ERR_NAME|ERR_BADJOB, pp->p_command,
1549 			     strerror(errno));
1550 		}
1551 		goto cont;
1552 	    default:
1553 		break;
1554 	    }
1555 #endif /* BSDJOBS */
1556 	    if (killpg(pp->p_jobid, signum) < 0) {
1557 		xprintf("%S: %s\n", cp, strerror(errno));
1558 		err1++;
1559 	    }
1560 #ifdef BSDJOBS
1561 	    if (signum == SIGTERM || signum == SIGHUP)
1562 		(void) killpg(pp->p_jobid, SIGCONT);
1563 #endif /* BSDJOBS */
1564 	}
1565 	else if (!(Isdigit(*cp) || *cp == '-'))
1566 	    stderror(ERR_NAME | ERR_JOBARGS);
1567 	else {
1568 	    char *ep;
1569 #ifndef WINNT_NATIVE
1570 	    pid = strtol(short2str(cp), &ep, 10);
1571 #else
1572 	    pid = strtoul(short2str(cp), &ep, 0);
1573 #endif /* WINNT_NATIVE */
1574 	    if (*ep)
1575 		stderror(ERR_NAME | ERR_JOBARGS);
1576 	    else if (kill(pid, signum) < 0) {
1577 		xprintf("%d: %s\n", pid, strerror(errno));
1578 		err1++;
1579 		goto cont;
1580 	    }
1581 #ifdef BSDJOBS
1582 	    if (signum == SIGTERM || signum == SIGHUP)
1583 		(void) kill(pid, SIGCONT);
1584 #endif /* BSDJOBS */
1585 	}
1586 cont:
1587 	v++;
1588     }
1589     cleanup_until(&pchild_disabled);
1590     if (err1)
1591 	stderror(ERR_SILENT);
1592 }
1593 
1594 /*
1595  * pstart - start the job in foreground/background
1596  */
1597 int
1598 pstart(struct process *pp, int foregnd)
1599 {
1600     int rv = 0;
1601     struct process *np;
1602     /* We don't use jobflags in this function right now (see below) */
1603     /* long    jobflags = 0; */
1604 
1605     pchild_disabled++;
1606     cleanup_push(&pchild_disabled, disabled_cleanup);
1607     np = pp;
1608     do {
1609 	/* We don't use jobflags in this function right now (see below) */
1610 	/* jobflags |= np->p_flags; */
1611 	if (np->p_flags & (PRUNNING | PSTOPPED)) {
1612 	    np->p_flags |= PRUNNING;
1613 	    np->p_flags &= ~PSTOPPED;
1614 	    if (foregnd)
1615 		np->p_flags |= PFOREGND;
1616 	    else
1617 		np->p_flags &= ~PFOREGND;
1618 	}
1619     } while ((np = np->p_friends) != pp);
1620     if (!foregnd)
1621 	pclrcurr(pp);
1622     (void) pprint(pp, foregnd ? NAME | JOBDIR : NUMBER | NAME | AMPERSAND);
1623 
1624     /* GrP run jobcmd hook if foregrounding */
1625     if (foregnd) {
1626 	job_cmd(pp->p_command);
1627     }
1628 
1629 #ifdef BSDJOBS
1630     if (foregnd) {
1631 	rv = tcsetpgrp(FSHTTY, pp->p_jobid);
1632     }
1633     /*
1634      * 1. child process of csh (shell script) receives SIGTTIN/SIGTTOU
1635      * 2. parent process (csh) receives SIGCHLD
1636      * 3. The "csh" signal handling function pchild() is invoked
1637      *    with a SIGCHLD signal.
1638      * 4. pchild() calls wait3(WNOHANG) which returns 0.
1639      *    The child process is NOT ready to be waited for at this time.
1640      *    pchild() returns without picking-up the correct status
1641      *    for the child process which generated the SIGCHLD.
1642      * 5. CONSEQUENCE : csh is UNaware that the process is stopped
1643      * 6. THIS LINE HAS BEEN COMMENTED OUT : if (jobflags&PSTOPPED)
1644      * 	  (beto@aixwiz.austin.ibm.com - aug/03/91)
1645      * 7. I removed the line completely and added extra checks for
1646      *    pstart, so that if a job gets attached to and dies inside
1647      *    a debugger it does not confuse the shell. [christos]
1648      * 8. on the nec sx-4 there seems to be a problem, which requires
1649      *    a syscall(151, getpid(), getpid()) in osinit. Don't ask me
1650      *    what this is doing. [schott@rzg.mpg.de]
1651      */
1652 
1653     if (rv != -1)
1654 	rv = killpg(pp->p_jobid, SIGCONT);
1655 #endif /* BSDJOBS */
1656     cleanup_until(&pchild_disabled);
1657     return rv != -1;
1658 }
1659 
1660 void
1661 panystop(int neednl)
1662 {
1663     struct process *pp;
1664 
1665     chkstop = 2;
1666     for (pp = proclist.p_next; pp; pp = pp->p_next)
1667 	if (pp->p_flags & PSTOPPED)
1668 	    stderror(ERR_STOPPED, neednl ? "\n" : "");
1669 }
1670 
1671 struct process *
1672 pfind(Char *cp)
1673 {
1674     struct process *pp, *np;
1675 
1676     if (cp == 0 || cp[1] == 0 || eq(cp, STRcent2) || eq(cp, STRcentplus)) {
1677 	if (pcurrent == NULL)
1678 	    stderror(ERR_NAME | ERR_JOBCUR);
1679 	return (pcurrent);
1680     }
1681     if (eq(cp, STRcentminus) || eq(cp, STRcenthash)) {
1682 	if (pprevious == NULL)
1683 	    stderror(ERR_NAME | ERR_JOBPREV);
1684 	return (pprevious);
1685     }
1686     if (Isdigit(cp[1])) {
1687 	int     idx = atoi(short2str(cp + 1));
1688 
1689 	for (pp = proclist.p_next; pp; pp = pp->p_next)
1690 	    if (pp->p_index == idx && pp->p_procid == pp->p_jobid)
1691 		return (pp);
1692 	stderror(ERR_NAME | ERR_NOSUCHJOB);
1693     }
1694     np = NULL;
1695     for (pp = proclist.p_next; pp; pp = pp->p_next)
1696 	if (pp->p_procid == pp->p_jobid) {
1697 	    if (cp[1] == '?') {
1698 		Char *dp;
1699 
1700 		for (dp = pp->p_command; *dp; dp++) {
1701 		    if (*dp != cp[2])
1702 			continue;
1703 		    if (prefix(cp + 2, dp))
1704 			goto match;
1705 		}
1706 	    }
1707 	    else if (prefix(cp + 1, pp->p_command)) {
1708 	match:
1709 		if (np)
1710 		    stderror(ERR_NAME | ERR_AMBIG);
1711 		np = pp;
1712 	    }
1713 	}
1714     if (np)
1715 	return (np);
1716     stderror(ERR_NAME | (cp[1] == '?' ? ERR_JOBPAT : ERR_NOSUCHJOB));
1717     /* NOTREACHED */
1718     return (0);
1719 }
1720 
1721 
1722 /*
1723  * pgetcurr - find most recent job that is not pp, preferably stopped
1724  */
1725 static struct process *
1726 pgetcurr(struct process *pp)
1727 {
1728     struct process *np;
1729     struct process *xp = NULL;
1730 
1731     for (np = proclist.p_next; np; np = np->p_next)
1732 	if (np != pcurrent && np != pp && np->p_procid &&
1733 	    np->p_procid == np->p_jobid) {
1734 	    if (np->p_flags & PSTOPPED)
1735 		return (np);
1736 	    if (xp == NULL)
1737 		xp = np;
1738 	}
1739     return (xp);
1740 }
1741 
1742 /*
1743  * donotify - flag the job so as to report termination asynchronously
1744  */
1745 /*ARGSUSED*/
1746 void
1747 donotify(Char **v, struct command *c)
1748 {
1749     struct process *pp;
1750 
1751     USE(c);
1752     pp = pfind(*++v);
1753     pp->p_flags |= PNOTIFY;
1754 }
1755 
1756 #ifdef SIGSYNCH
1757 static void
1758 synch_handler(int sno)
1759 {
1760     USE(sno);
1761 }
1762 #endif /* SIGSYNCH */
1763 
1764 /*
1765  * Do the fork and whatever should be done in the child side that
1766  * should not be done if we are not forking at all (like for simple builtin's)
1767  * Also do everything that needs any signals fiddled with in the parent side
1768  *
1769  * Wanttty tells whether process and/or tty pgrps are to be manipulated:
1770  *	-1:	leave tty alone; inherit pgrp from parent
1771  *	 0:	already have tty; manipulate process pgrps only
1772  *	 1:	want to claim tty; manipulate process and tty pgrps
1773  * It is usually just the value of tpgrp.
1774  */
1775 
1776 pid_t
1777 pfork(struct command *t, int wanttty)
1778 {
1779     pid_t pid;
1780     int    ignint = 0;
1781     pid_t pgrp;
1782 #ifdef SIGSYNCH
1783     struct sigaction osa, nsa;
1784 #endif /* SIGSYNCH */
1785 
1786     /*
1787      * A child will be uninterruptible only under very special conditions.
1788      * Remember that the semantics of '&' is implemented by disconnecting the
1789      * process from the tty so signals do not need to ignored just for '&'.
1790      * Thus signals are set to default action for children unless: we have had
1791      * an "onintr -" (then specifically ignored) we are not playing with
1792      * signals (inherit action)
1793      */
1794     if (setintr)
1795 	ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT))
1796 	    || (gointr && eq(gointr, STRminus));
1797 
1798     /*
1799      * Check for maximum nesting of 16 processes to avoid Forking loops
1800      */
1801     if (child == 16)
1802 	stderror(ERR_NESTING, 16);
1803 #ifdef SIGSYNCH
1804     nsa.sa_handler = synch_handler;
1805     sigfillset(&nsa.sa_mask);
1806     nsa.sa_flags = SA_RESTART;
1807     if (sigaction(SIGSYNCH, &nsa, &osa))
1808 	stderror(ERR_SYSTEM, "pfork: sigaction set", strerror(errno));
1809 #endif /* SIGSYNCH */
1810     /*
1811      * Hold pchild() until we have the process installed in our table.
1812      */
1813     if (wanttty < 0) {
1814 	pchild_disabled++;
1815 	cleanup_push(&pchild_disabled, disabled_cleanup);
1816     }
1817     while ((pid = fork()) == -1)
1818 	if (setintr == 0)
1819 	    (void) sleep(FORKSLEEP);
1820 	else
1821 	    stderror(ERR_NOPROC);
1822     if (pid == 0) {
1823 	(void)cleanup_push_mark(); /* Never to be popped */
1824 	pchild_disabled = 0;
1825 	settimes();
1826 	pgrp = pcurrjob ? pcurrjob->p_jobid : getpid();
1827 	pflushall();
1828 	pcurrjob = NULL;
1829 #if !defined(BSDTIMES) && !defined(_SEQUENT_)
1830 	timesdone = 0;
1831 #endif /* !defined(BSDTIMES) && !defined(_SEQUENT_) */
1832 	child++;
1833 	if (setintr) {
1834 	    setintr = 0;	/* until I think otherwise */
1835 	    /*
1836 	     * Children just get blown away on SIGINT, SIGQUIT unless "onintr
1837 	     * -" seen.
1838 	     */
1839 	    (void) signal(SIGINT, ignint ? SIG_IGN : SIG_DFL);
1840 	    (void) signal(SIGQUIT, ignint ? SIG_IGN : SIG_DFL);
1841 #ifdef BSDJOBS
1842 	    if (wanttty >= 0) {
1843 		/* make stoppable */
1844 		(void) signal(SIGTSTP, SIG_DFL);
1845 		(void) signal(SIGTTIN, SIG_DFL);
1846 		(void) signal(SIGTTOU, SIG_DFL);
1847 	    }
1848 #endif /* BSDJOBS */
1849 	    sigaction(SIGTERM, &parterm, NULL);
1850 	}
1851 	else if (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) {
1852 	    (void) signal(SIGINT, SIG_IGN);
1853 	    (void) signal(SIGQUIT, SIG_IGN);
1854 	}
1855 #ifdef OREO
1856 	signal(SIGIO, SIG_IGN);	/* ignore SIGIO in child too */
1857 #endif /* OREO */
1858 
1859 	pgetty(wanttty, pgrp);
1860 	/*
1861 	 * Nohup and nice apply only to NODE_COMMAND's but it would be nice
1862 	 * (?!?) if you could say "nohup (foo;bar)" Then the parser would have
1863 	 * to know about nice/nohup/time
1864 	 */
1865 	if (t->t_dflg & F_NOHUP)
1866 	    (void) signal(SIGHUP, SIG_IGN);
1867 	if (t->t_dflg & F_NICE) {
1868 	    int nval = SIGN_EXTEND_CHAR(t->t_nice);
1869 #if defined(HAVE_SETPRIORITY) && defined(PRIO_PROCESS)
1870 	    if (setpriority(PRIO_PROCESS, 0, nval) == -1 && errno)
1871 		stderror(ERR_SYSTEM, "setpriority", strerror(errno));
1872 #else /* !HAVE_SETPRIORITY || !PRIO_PROCESS */
1873 	    (void) nice(nval);
1874 #endif /* HAVE_SETPRIORITY  && PRIO_PROCESS */
1875 	}
1876 #ifdef F_VER
1877         if (t->t_dflg & F_VER) {
1878 	    tsetenv(STRSYSTYPE, t->t_systype ? STRbsd43 : STRsys53);
1879 	    dohash(NULL, NULL);
1880 	}
1881 #endif /* F_VER */
1882 #ifdef SIGSYNCH
1883 	/* rfw 8/89 now parent can continue */
1884 	if (kill(getppid(), SIGSYNCH))
1885 	    stderror(ERR_SYSTEM, "pfork child: kill", strerror(errno));
1886 #endif /* SIGSYNCH */
1887 
1888     }
1889     else {
1890 #ifdef POSIXJOBS
1891         if (wanttty >= 0) {
1892 	    /*
1893 	     * `Walking' process group fix from Beto Appleton.
1894 	     * (beto@aixwiz.austin.ibm.com)
1895 	     * If setpgid fails at this point that means that
1896 	     * our process leader has died. We flush the current
1897 	     * job and become the process leader ourselves.
1898 	     * The parent will figure that out later.
1899 	     */
1900 	    pgrp = pcurrjob ? pcurrjob->p_jobid : pid;
1901 	    if (setpgid(pid, pgrp) == -1 && errno == EPERM) {
1902 		pcurrjob = NULL;
1903 		/*
1904 		 * We don't care if this causes an error here;
1905 		 * then we are already in the right process group
1906 		 */
1907 		(void) setpgid(pid, pgrp = pid);
1908 	    }
1909 	}
1910 #endif /* POSIXJOBS */
1911 	palloc(pid, t);
1912 #ifdef SIGSYNCH
1913 	{
1914 	    sigset_t pause_mask;
1915 
1916 	/*
1917 	 * rfw 8/89 Wait for child to own terminal.  Solves half of ugly
1918 	 * synchronization problem.  With this change, we know that the only
1919 	 * reason setpgrp to a previous process in a pipeline can fail is that
1920 	 * the previous process has already exited. Without this hack, he may
1921 	 * either have exited or not yet started to run.  Two uglies become
1922 	 * one.
1923 	 */
1924 	    sigprocmask(SIG_BLOCK, NULL, &pause);
1925 	    sigdelset(&pause_mask, SIGCHLD);
1926 	    sigdelset(&pause_mask, SIGSYNCH);
1927 	    sigsuspend(&pause_mask);
1928 	    (void)handle_pending_signals();
1929 	    if (sigaction(SIGSYNCH, &osa, NULL))
1930 		stderror(ERR_SYSTEM, "pfork parent: sigaction restore",
1931 			 strerror(errno));
1932 	}
1933 #endif /* SIGSYNCH */
1934 
1935 	if (wanttty < 0)
1936 	    cleanup_until(&pchild_disabled);
1937     }
1938     return (pid);
1939 }
1940 
1941 static void
1942 okpcntl(void)
1943 {
1944     if (tpgrp == -1)
1945 	stderror(ERR_JOBCONTROL);
1946     if (tpgrp == 0)
1947 	stderror(ERR_JOBCTRLSUB);
1948 }
1949 
1950 
1951 static void
1952 setttypgrp(int pgrp)
1953 {
1954     /*
1955      * If we are piping out a builtin, eg. 'echo | more' things can go
1956      * out of sequence, i.e. the more can run before the echo. This
1957      * can happen even if we have vfork, since the echo will be forked
1958      * with the regular fork. In this case, we need to set the tty
1959      * pgrp ourselves. If that happens, then the process will be still
1960      * alive. And the tty process group will already be set.
1961      * This should fix the famous sequent problem as a side effect:
1962      *    The controlling terminal is lost if all processes in the
1963      *    terminal process group are zombies. In this case tcgetpgrp()
1964      *    returns 0. If this happens we must set the terminal process
1965      *    group again.
1966      */
1967     if (tcgetpgrp(FSHTTY) != pgrp) {
1968 #ifdef POSIXJOBS
1969 	struct sigaction old;
1970 
1971         /*
1972 	 * tcsetpgrp will set SIGTTOU to all the the processes in
1973 	 * the background according to POSIX... We ignore this here.
1974 	 */
1975 	sigaction(SIGTTOU, NULL, &old);
1976 	signal(SIGTTOU, SIG_IGN);
1977 #endif
1978 	(void) tcsetpgrp(FSHTTY, pgrp);
1979 # ifdef POSIXJOBS
1980 	sigaction(SIGTTOU, &old, NULL);
1981 # endif
1982 
1983     }
1984 }
1985 
1986 
1987 /*
1988  * if we don't have vfork(), things can still go in the wrong order
1989  * resulting in the famous 'Stopped (tty output)'. But some systems
1990  * don't permit the setpgid() call, (these are more recent secure
1991  * systems such as ibm's aix), when they do. Then we'd rather print
1992  * an error message than hang the shell!
1993  * I am open to suggestions how to fix that.
1994  */
1995 void
1996 pgetty(int wanttty, pid_t pgrp)
1997 {
1998 #ifdef BSDJOBS
1999 # ifdef POSIXJOBS
2000     sigset_t oset, set;
2001 # endif /* POSIXJOBS */
2002 
2003     jobdebug_xprintf(("wanttty %d pid %d opgrp%d pgrp %d tpgrp %d\n",
2004 		      wanttty, (int)getpid(), (int)pgrp, (int)mygetpgrp(),
2005 		      (int)tcgetpgrp(FSHTTY)));
2006 # ifdef POSIXJOBS
2007     /*
2008      * christos: I am blocking the tty signals till I've set things
2009      * correctly....
2010      */
2011     if (wanttty > 0) {
2012 	sigemptyset(&set);
2013 	sigaddset(&set, SIGTSTP);
2014 	sigaddset(&set, SIGTTIN);
2015 	(void)sigprocmask(SIG_BLOCK, &set, &oset);
2016 	cleanup_push(&oset, sigprocmask_cleanup);
2017     }
2018 # endif /* POSIXJOBS */
2019 
2020 # ifndef POSIXJOBS
2021     if (wanttty > 0)
2022 	setttypgrp(pgrp);
2023 # endif /* !POSIXJOBS */
2024 
2025     /*
2026      * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
2027      * Don't check for tpgrp >= 0 so even non-interactive shells give
2028      * background jobs process groups Same for the comparison in the other part
2029      * of the #ifdef
2030      */
2031     if (wanttty >= 0) {
2032 	if (setpgid(0, pgrp) == -1) {
2033 # ifdef POSIXJOBS
2034 	    /* Walking process group fix; see above */
2035 	    if (setpgid(0, pgrp = getpid()) == -1) {
2036 # endif /* POSIXJOBS */
2037 		stderror(ERR_SYSTEM, "setpgid child:\n", strerror(errno));
2038 		xexit(0);
2039 # ifdef POSIXJOBS
2040 	    }
2041 	    wanttty = pgrp;  /* Now we really want the tty, since we became the
2042 			      * the process group leader
2043 			      */
2044 # endif /* POSIXJOBS */
2045 	}
2046     }
2047 
2048 # ifdef POSIXJOBS
2049     if (wanttty > 0) {
2050 	setttypgrp(pgrp);
2051 	cleanup_until(&oset);
2052     }
2053 # endif /* POSIXJOBS */
2054 
2055     jobdebug_xprintf(("wanttty %d pid %d pgrp %d tpgrp %d\n",
2056 		      wanttty, getpid(), mygetpgrp(), tcgetpgrp(FSHTTY)));
2057 
2058     if (tpgrp > 0)
2059 	tpgrp = 0;		/* gave tty away */
2060 #endif /* BSDJOBS */
2061 }
2062