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