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