sh.proc.c revision 131962
1/* $Header: /src/pub/tcsh/sh.proc.c,v 3.81 2003/11/09 03:02:46 christos Exp $ */
2/*
3 * sh.proc.c: Job manipulations
4 */
5/*-
6 * Copyright (c) 1980, 1991 The Regents of the University of California.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33#include "sh.h"
34
35RCSID("$Id: sh.proc.c,v 3.81 2003/11/09 03:02:46 christos Exp $")
36
37#include "ed.h"
38#include "tc.h"
39#include "tc.wait.h"
40
41#ifdef WINNT_NATIVE
42#undef POSIX
43#define POSIX
44#endif /* WINNT_NATIVE */
45#ifdef aiws
46# undef HZ
47# define HZ 16
48#endif /* aiws */
49
50#if defined(_BSD) || (defined(IRIS4D) && __STDC__) || defined(__lucid) || defined(linux)
51# define BSDWAIT
52#endif /* _BSD || (IRIS4D && __STDC__) || __lucid || linux */
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/*
81 * C Shell - functions that manage processes, handling hanging, termination
82 */
83
84#define BIGINDEX	9	/* largest desirable job index */
85
86#ifdef BSDTIMES
87# ifdef convex
88/* use 'cvxrusage' to get parallel statistics */
89static struct cvxrusage zru = {{0L, 0L}, {0L, 0L}, 0L, 0L, 0L, 0L,
90				0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
91				{0L, 0L}, 0LL, 0LL, 0LL, 0LL, 0L, 0L, 0L,
92				0LL, 0LL, {0L, 0L, 0L, 0L, 0L}};
93# else
94#  if defined(SUNOS4) || defined(hp9000) || (defined(__alpha) && defined(__osf__))
95static struct rusage zru = {{0L, 0L}, {0L, 0L}, 0L, 0L, 0L, 0L,
96			    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L};
97
98#  else /* !SUNOS4 && !hp9000 && !(__alpha && __osf__) */
99#   ifdef masscomp
100/*
101 * Initialization of this structure under RTU 4.1A & RTU 5.0 is problematic
102 * because the first two elements are unions of a time_t and a struct timeval.
103 * So we'll just have to trust the loader to do the "right thing", DAS DEC-90.
104 */
105static struct rusage zru;
106#   else	/* masscomp */
107static struct rusage zru = {{0L, 0L}, {0L, 0L}, 0, 0, 0, 0, 0, 0, 0,
108			    0, 0, 0, 0, 0, 0};
109#   endif /* masscomp */
110#  endif	/* SUNOS4 || hp9000 || (__alpha && __osf__) */
111# endif /* convex */
112#else /* !BSDTIMES */
113# ifdef _SEQUENT_
114static struct process_stats zru = {{0L, 0L}, {0L, 0L}, 0, 0, 0, 0, 0, 0, 0,
115				   0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
116# else /* !_SEQUENT_ */
117#  ifdef _SX
118static struct tms zru = {0, 0, 0, 0}, lru = {0, 0, 0, 0};
119#  else	/* !_SX */
120static struct tms zru = {0L, 0L, 0L, 0L}, lru = {0L, 0L, 0L, 0L};
121#  endif	/* !_SX */
122# endif	/* !_SEQUENT_ */
123#endif /* !BSDTIMES */
124
125#ifndef RUSAGE_CHILDREN
126# define	RUSAGE_CHILDREN	-1
127#endif /* RUSAGE_CHILDREN */
128
129static	void		 pflushall	__P((void));
130static	void		 pflush		__P((struct process *));
131static	void		 pfree		__P((struct process *));
132static	void		 pclrcurr	__P((struct process *));
133static	void		 padd		__P((struct command *));
134static	int		 pprint		__P((struct process *, int));
135static	void		 ptprint	__P((struct process *));
136static	void		 pads		__P((Char *));
137static	void		 pkill		__P((Char **, int));
138static	struct process	*pgetcurr	__P((struct process *));
139static	void		 okpcntl	__P((void));
140static	void		 setttypgrp	__P((int));
141
142/*
143 * pchild - called at interrupt level by the SIGCHLD signal
144 *	indicating that at least one child has terminated or stopped
145 *	thus at least one wait system call will definitely return a
146 *	childs status.  Top level routines (like pwait) must be sure
147 *	to mask interrupts when playing with the proclist data structures!
148 */
149sigret_t
150/*ARGSUSED*/
151pchild(snum)
152int snum;
153{
154    register struct process *pp;
155    register struct process *fp;
156    register int pid;
157#if defined(BSDJOBS) || (!defined(BSDTIMES) && (defined(ODT) || defined(aiws) || defined(uts)))
158    extern int insource;
159#endif /* BSDJOBS || (!BSDTIMES && (ODT || aiws || uts)) */
160#ifdef BSDWAIT
161    union wait w;
162#else /* !BSDWAIT */
163    int     w;
164#endif /* !BSDWAIT */
165    int     jobflags;
166#ifdef BSDTIMES
167    struct sysrusage ru;
168#else /* !BSDTIMES */
169# ifdef _SEQUENT_
170    struct process_stats ru;
171    struct process_stats cpst1, cpst2;
172    timeval_t tv;
173# else /* !_SEQUENT_ */
174    struct tms proctimes;
175
176    USE(snum);
177    if (!timesdone) {
178	timesdone++;
179	(void) times(&shtimes);
180    }
181# endif	/* !_SEQUENT_ */
182#endif /* !BSDTIMES */
183
184#ifdef JOBDEBUG
185    xprintf("pchild()\n");
186#endif	/* JOBDEBUG */
187
188/* Christos on where the signal(SIGCHLD, pchild) shoud be:
189 *
190 * I think that it should go *after* the wait, unlike most signal handlers.
191 *
192 * In release two (for which I have manuals), it says that wait will remove
193 * the first child from the queue of dead children.
194 * All the rest of the children that die while in the signal handler of the
195 * SIGC(H)LD, will be placed in the queue. If signal is called to re-establish
196 * the signal handler, and there are items in the queue, the process will
197 * receive another SIGC(H)LD before signal returns. BTW this is from the
198 * manual page on comp-sim... Maybe it is not applicable to the hp's, but
199 * I read on the news in comp.unix.wizards or comp.unix.questions yesterday
200 * that another person was claiming the the signal() call should be after
201 * the wait().
202 */
203
204loop:
205    errno = 0;			/* reset, just in case */
206#ifdef JOBDEBUG
207    xprintf("Waiting...\n");
208    flush();
209#endif /* JOBDEBUG */
210#ifndef WINNT_NATIVE
211# ifdef BSDJOBS
212#  ifdef BSDTIMES
213#   ifdef convex
214    /* use 'cvxwait' to get parallel statistics */
215    pid = cvxwait(&w,
216        (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
217#   else
218    /* both a wait3 and rusage */
219#    if !defined(BSDWAIT) || defined(NeXT) || defined(MACH) || defined(linux) || (defined(IRIS4D) && (__STDC__ || defined(FUNCPROTO)) && SYSVREL <= 3) || defined(__lucid) || defined(__osf__)
220    pid = wait3(&w,
221       (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
222#    else /* BSDWAIT */
223    pid = wait3(&w.w_status,
224       (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
225#    endif /* BSDWAIT */
226#   endif /* convex */
227#  else /* !BSDTIMES */
228#   ifdef _SEQUENT_
229    (void) get_process_stats(&tv, PS_SELF, 0, &cpst1);
230    pid = waitpid(-1, &w,
231	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
232    (void) get_process_stats(&tv, PS_SELF, 0, &cpst2);
233    pr_stat_sub(&cpst2, &cpst1, &ru);
234#   else	/* !_SEQUENT_ */
235#    ifndef POSIX
236    /* we have a wait3, but no rusage stuff */
237    pid = wait3(&w.w_status,
238	 (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), 0);
239#    else /* POSIX */
240    pid = waitpid(-1, &w,
241	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
242#    endif /* POSIX */
243#   endif /* !_SEQUENT_ */
244#  endif	/* !BSDTIMES */
245# else /* !BSDJOBS */
246#  ifdef BSDTIMES
247#   define HAVEwait3
248    /* both a wait3 and rusage */
249#   ifdef hpux
250    pid = wait3(&w.w_status, WNOHANG, 0);
251#   else	/* !hpux */
252    pid = wait3(&w.w_status, WNOHANG, &ru);
253#   endif /* !hpux */
254#  else /* !BSDTIMES */
255#   ifdef ODT  /* For Sco Unix 3.2.0 or ODT 1.0 */
256#    define HAVEwait3
257     pid = waitpid(-1, &w,
258 	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
259#   endif /* ODT */
260#   if defined(aiws) || defined(uts)
261#    define HAVEwait3
262    pid = wait3(&w.w_status,
263	(setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), 0);
264#   endif /* aiws || uts */
265#   ifndef HAVEwait3
266#    ifdef UNRELSIGS
267     /* no wait3, therefore no rusage */
268     /* on Sys V, this may hang.  I hope it's not going to be a problem */
269#     ifdef _MINIX
270      pid = wait(&w);
271#     else /* !_MINIX */
272      pid = ourwait(&w.w_status);
273#     endif /* _MINIX */
274#    else /* !UNRELSIGS */
275     /*
276      * XXX: for greater than 3 we should use waitpid().
277      * but then again, SVR4 falls into the POSIX/BSDJOBS category.
278      */
279     pid = wait(&w.w_status);
280#    endif /* !UNRELSIGS */
281#   endif /* !HAVEwait3 */
282#  endif	/* !BSDTIMES */
283#  ifndef BSDSIGS
284    (void) sigset(SIGCHLD, pchild);
285#  endif /* !BSDSIGS */
286# endif /* !BSDJOBS */
287#else /* WINNT_NATIVE */
288    {
289	extern int insource;
290	pid = waitpid(-1, &w,
291	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
292    }
293#endif /* WINNT_NATIVE */
294
295#ifdef JOBDEBUG
296    xprintf("parent %d pid %d, retval %x termsig %x retcode %x\n",
297	    getpid(), pid, w, WTERMSIG(w), WEXITSTATUS(w));
298    flush();
299#endif /* JOBDEBUG */
300
301    if ((pid == 0) || (pid == -1)) {
302#ifdef JOBDEBUG
303	xprintf("errno == %d\n", errno);
304#endif /* JOBDEBUG */
305	if (errno == EINTR) {
306	    errno = 0;
307	    goto loop;
308	}
309	pnoprocesses = pid == -1;
310#ifndef SIGVOID
311	return (0);
312#else /* !SIGVOID */
313	return;
314#endif /* !SIGVOID */
315    }
316    for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
317	if (pid == pp->p_procid)
318	    goto found;
319#if !defined(BSDJOBS) && !defined(WINNT_NATIVE)
320    /* this should never have happened */
321    stderror(ERR_SYNC, pid);
322    xexit(0);
323#else /* BSDJOBS || WINNT_NATIVE */
324    goto loop;
325#endif /* !BSDJOBS && !WINNT_NATIVE */
326found:
327    pp->p_flags &= ~(PRUNNING | PSTOPPED | PREPORTED);
328    if (WIFSTOPPED(w)) {
329	pp->p_flags |= PSTOPPED;
330	pp->p_reason = WSTOPSIG(w);
331    }
332    else {
333	if (pp->p_flags & (PTIME | PPTIME) || adrof(STRtime))
334#ifndef BSDTIMES
335# ifdef _SEQUENT_
336	    (void) get_process_stats(&pp->p_etime, PS_SELF, NULL, NULL);
337# else	/* !_SEQUENT_ */
338#  ifndef COHERENT
339	    pp->p_etime = times(&proctimes);
340#  else /* COHERENT */
341	    pp->p_etime = HZ * time(NULL);
342	    times(&proctimes);
343#  endif /* COHERENT */
344# endif	/* !_SEQUENT_ */
345#else /* BSDTIMES */
346	    (void) gettimeofday(&pp->p_etime, NULL);
347#endif /* BSDTIMES */
348
349
350#if defined(BSDTIMES) || defined(_SEQUENT_)
351	pp->p_rusage = ru;
352#else /* !BSDTIMES && !_SEQUENT_ */
353	(void) times(&proctimes);
354	pp->p_utime = proctimes.tms_cutime - shtimes.tms_cutime;
355	pp->p_stime = proctimes.tms_cstime - shtimes.tms_cstime;
356	shtimes = proctimes;
357#endif /* !BSDTIMES && !_SEQUENT_ */
358	if (WIFSIGNALED(w)) {
359	    if (WTERMSIG(w) == SIGINT)
360		pp->p_flags |= PINTERRUPTED;
361	    else
362		pp->p_flags |= PSIGNALED;
363	    if (WCOREDUMP(w))
364		pp->p_flags |= PDUMPED;
365	    pp->p_reason = WTERMSIG(w);
366	}
367	else {
368	    pp->p_reason = WEXITSTATUS(w);
369	    if (pp->p_reason != 0)
370		pp->p_flags |= PAEXITED;
371	    else
372		pp->p_flags |= PNEXITED;
373	}
374    }
375    jobflags = 0;
376    fp = pp;
377    do {
378	if ((fp->p_flags & (PPTIME | PRUNNING | PSTOPPED)) == 0 &&
379	    !child && adrof(STRtime) &&
380#ifdef BSDTIMES
381	    fp->p_rusage.ru_utime.tv_sec + fp->p_rusage.ru_stime.tv_sec
382#else /* !BSDTIMES */
383# ifdef _SEQUENT_
384	    fp->p_rusage.ps_utime.tv_sec + fp->p_rusage.ps_stime.tv_sec
385# else /* !_SEQUENT_ */
386#  ifndef POSIX
387	    (fp->p_utime + fp->p_stime) / HZ
388#  else /* POSIX */
389	    (fp->p_utime + fp->p_stime) / clk_tck
390#  endif /* POSIX */
391# endif /* !_SEQUENT_ */
392#endif /* !BSDTIMES */
393	    >= atoi(short2str(varval(STRtime))))
394	    fp->p_flags |= PTIME;
395	jobflags |= fp->p_flags;
396    } while ((fp = fp->p_friends) != pp);
397    pp->p_flags &= ~PFOREGND;
398    if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
399	pp->p_flags &= ~PPTIME;
400	pp->p_flags |= PTIME;
401    }
402    if ((jobflags & (PRUNNING | PREPORTED)) == 0) {
403	fp = pp;
404	do {
405	    if (fp->p_flags & PSTOPPED)
406		fp->p_flags |= PREPORTED;
407	} while ((fp = fp->p_friends) != pp);
408	while (fp->p_procid != fp->p_jobid)
409	    fp = fp->p_friends;
410	if (jobflags & PSTOPPED) {
411	    if (pcurrent && pcurrent != fp)
412		pprevious = pcurrent;
413	    pcurrent = fp;
414	}
415	else
416	    pclrcurr(fp);
417	if (jobflags & PFOREGND) {
418	    if (!(jobflags & (PSIGNALED | PSTOPPED | PPTIME) ||
419#ifdef notdef
420		jobflags & PAEXITED ||
421#endif /* notdef */
422		!eq(dcwd->di_name, fp->p_cwd->di_name))) {
423	    /* PWP: print a newline after ^C */
424		if (jobflags & PINTERRUPTED) {
425#ifdef SHORT_STRINGS
426		    xputchar('\r' | QUOTE), xputchar('\n');
427#else /* !SHORT_STRINGS */
428		    xprintf("\215\n");	/* \215 is a quoted ^M */
429#endif /* !SHORT_STRINGS */
430		}
431#ifdef notdef
432		else if ((jobflags & (PTIME|PSTOPPED)) == PTIME)
433		    ptprint(fp);
434#endif /* notdef */
435	    }
436	}
437	else {
438	    if (jobflags & PNOTIFY || adrof(STRnotify)) {
439#ifdef SHORT_STRINGS
440		xputchar('\r' | QUOTE), xputchar('\n');
441#else /* !SHORT_STRINGS */
442		xprintf("\215\n");	/* \215 is a quoted ^M */
443#endif /* !SHORT_STRINGS */
444		(void) pprint(pp, NUMBER | NAME | REASON);
445		if ((jobflags & PSTOPPED) == 0)
446		    pflush(pp);
447		{
448		    extern Char GettingInput;
449
450		    if (GettingInput) {
451			errno = 0;
452			(void) Rawmode();
453#ifdef notdef
454			/*
455			 * don't really want to do that, because it
456			 * will erase our message in case of multi-line
457			 * input
458			 */
459			ClearLines();
460#endif /* notdef */
461			ClearDisp();
462			Refresh();
463		    }
464		}
465	    }
466	    else {
467		fp->p_flags |= PNEEDNOTE;
468		neednote++;
469	    }
470	}
471    }
472#if defined(BSDJOBS) || defined(HAVEwait3)
473    goto loop;
474#endif /* BSDJOBS || HAVEwait3 */
475}
476
477void
478pnote()
479{
480    register struct process *pp;
481    int     flags;
482#ifdef BSDSIGS
483    sigmask_t omask;
484#endif /* BSDSIGS */
485
486    neednote = 0;
487    for (pp = proclist.p_next; pp != NULL; pp = pp->p_next) {
488	if (pp->p_flags & PNEEDNOTE) {
489#ifdef BSDSIGS
490	    omask = sigblock(sigmask(SIGCHLD));
491#else /* !BSDSIGS */
492	    (void) sighold(SIGCHLD);
493#endif /* !BSDSIGS */
494	    pp->p_flags &= ~PNEEDNOTE;
495	    flags = pprint(pp, NUMBER | NAME | REASON);
496	    if ((flags & (PRUNNING | PSTOPPED)) == 0)
497		pflush(pp);
498#ifdef BSDSIGS
499	    (void) sigsetmask(omask);
500#else /* !BSDSIGS */
501	    (void) sigrelse(SIGCHLD);
502#endif /* !BSDSIGS */
503	}
504    }
505}
506
507
508static void
509pfree(pp)
510    struct process *pp;
511{
512    xfree((ptr_t) pp->p_command);
513    if (pp->p_cwd && --pp->p_cwd->di_count == 0)
514	if (pp->p_cwd->di_next == 0)
515	    dfree(pp->p_cwd);
516    xfree((ptr_t) pp);
517}
518
519
520/*
521 * pwait - wait for current job to terminate, maintaining integrity
522 *	of current and previous job indicators.
523 */
524void
525pwait()
526{
527    register struct process *fp, *pp;
528#ifdef BSDSIGS
529    sigmask_t omask;
530#endif /* BSDSIGS */
531
532    /*
533     * Here's where dead procs get flushed.
534     */
535#ifdef BSDSIGS
536    omask = sigblock(sigmask(SIGCHLD));
537#else /* !BSDSIGS */
538    (void) sighold(SIGCHLD);
539#endif /* !BSDSIGS */
540    for (pp = (fp = &proclist)->p_next; pp != NULL; pp = (fp = pp)->p_next)
541	if (pp->p_procid == 0) {
542	    fp->p_next = pp->p_next;
543	    pfree(pp);
544	    pp = fp;
545	}
546#ifdef BSDSIGS
547    (void) sigsetmask(omask);
548#else /* !BSDSIGS */
549    (void) sigrelse(SIGCHLD);
550# ifdef notdef
551    if (setintr)
552	sigignore(SIGINT);
553# endif /* notdef */
554#endif /* !BSDSIGS */
555    pjwait(pcurrjob);
556}
557
558
559/*
560 * pjwait - wait for a job to finish or become stopped
561 *	It is assumed to be in the foreground state (PFOREGND)
562 */
563void
564pjwait(pp)
565    register struct process *pp;
566{
567    register struct process *fp;
568    int     jobflags, reason;
569#ifdef BSDSIGS
570    sigmask_t omask;
571#endif /* BSDSIGS */
572#ifdef UNRELSIGS
573    signalfun_t inthandler;
574#endif /* UNRELSIGS */
575    while (pp->p_procid != pp->p_jobid)
576	pp = pp->p_friends;
577    fp = pp;
578
579    do {
580	if ((fp->p_flags & (PFOREGND | PRUNNING)) == PRUNNING)
581	    xprintf(CGETS(17, 1, "BUG: waiting for background job!\n"));
582    } while ((fp = fp->p_friends) != pp);
583    /*
584     * Now keep pausing as long as we are not interrupted (SIGINT), and the
585     * target process, or any of its friends, are running
586     */
587    fp = pp;
588#ifdef BSDSIGS
589    omask = sigblock(sigmask(SIGCHLD));
590#endif /* BSDSIGS */
591#ifdef UNRELSIGS
592    if (setintr)
593        inthandler = signal(SIGINT, SIG_IGN);
594#endif /* UNRELSIGS */
595    for (;;) {
596#ifndef BSDSIGS
597	(void) sighold(SIGCHLD);
598#endif /* !BSDSIGS */
599	jobflags = 0;
600	do
601	    jobflags |= fp->p_flags;
602	while ((fp = (fp->p_friends)) != pp);
603	if ((jobflags & PRUNNING) == 0)
604	    break;
605#ifdef JOBDEBUG
606	xprintf("%d starting to sigpause for SIGCHLD on %d\n",
607		getpid(), fp->p_procid);
608#endif /* JOBDEBUG */
609#ifdef BSDSIGS
610	/* (void) sigpause(sigblock((sigmask_t) 0) &~ sigmask(SIGCHLD)); */
611	(void) sigpause(omask & ~sigmask(SIGCHLD));
612#else /* !BSDSIGS */
613	(void) sigpause(SIGCHLD);
614#endif /* !BSDSIGS */
615    }
616#ifdef JOBDEBUG
617	xprintf("%d returned from sigpause loop\n", getpid());
618#endif /* JOBDEBUG */
619#ifdef BSDSIGS
620    (void) sigsetmask(omask);
621#else /* !BSDSIGS */
622    (void) sigrelse(SIGCHLD);
623#endif /* !BSDSIGS */
624#ifdef UNRELSIGS
625    if (setintr)
626        (void) signal(SIGINT, inthandler);
627#endif /* UNRELSIGS */
628#ifdef BSDJOBS
629    if (tpgrp > 0)		/* get tty back */
630	(void) tcsetpgrp(FSHTTY, tpgrp);
631#endif /* BSDJOBS */
632    if ((jobflags & (PSIGNALED | PSTOPPED | PTIME)) ||
633	!eq(dcwd->di_name, fp->p_cwd->di_name)) {
634	if (jobflags & PSTOPPED) {
635	    xputchar('\n');
636	    if (adrof(STRlistjobs)) {
637		Char   *jobcommand[3];
638
639		jobcommand[0] = STRjobs;
640		if (eq(varval(STRlistjobs), STRlong))
641		    jobcommand[1] = STRml;
642		else
643		    jobcommand[1] = NULL;
644		jobcommand[2] = NULL;
645
646		dojobs(jobcommand, NULL);
647		(void) pprint(pp, SHELLDIR);
648	    }
649	    else
650		(void) pprint(pp, AREASON | SHELLDIR);
651	}
652	else
653	    (void) pprint(pp, AREASON | SHELLDIR);
654    }
655    if ((jobflags & (PINTERRUPTED | PSTOPPED)) && setintr &&
656	(!gointr || !eq(gointr, STRminus))) {
657	if ((jobflags & PSTOPPED) == 0)
658	    pflush(pp);
659	pintr1(0);
660	/* NOTREACHED */
661    }
662    reason = 0;
663    fp = pp;
664    do {
665	if (fp->p_reason)
666	    reason = fp->p_flags & (PSIGNALED | PINTERRUPTED) ?
667		fp->p_reason | META : fp->p_reason;
668    } while ((fp = fp->p_friends) != pp);
669    /*
670     * Don't report on backquoted jobs, cause it will mess up
671     * their output.
672     */
673    if ((reason != 0) && (adrof(STRprintexitvalue)) &&
674	(pp->p_flags & PBACKQ) == 0)
675	xprintf(CGETS(17, 2, "Exit %d\n"), reason);
676    set(STRstatus, putn(reason), VAR_READWRITE);
677    if (reason && exiterr)
678	exitstat();
679    pflush(pp);
680}
681
682/*
683 * dowait - wait for all processes to finish
684 */
685
686/*ARGSUSED*/
687void
688dowait(v, c)
689    Char **v;
690    struct command *c;
691{
692    register struct process *pp;
693#ifdef BSDSIGS
694    sigmask_t omask;
695#endif /* BSDSIGS */
696
697    USE(c);
698    USE(v);
699    pjobs++;
700#ifdef BSDSIGS
701    omask = sigblock(sigmask(SIGCHLD));
702loop:
703#else /* !BSDSIGS */
704    if (setintr)
705	(void) sigrelse(SIGINT);
706loop:
707    (void) sighold(SIGCHLD);
708#endif /* !BSDSIGS */
709    for (pp = proclist.p_next; pp; pp = pp->p_next)
710	if (pp->p_procid &&	/* pp->p_procid == pp->p_jobid && */
711	    pp->p_flags & PRUNNING) {
712#ifdef BSDSIGS
713	    (void) sigpause((sigmask_t) 0);
714#else /* !BSDSIGS */
715	    (void) sigpause(SIGCHLD);
716#endif /* !BSDSIGS */
717	    goto loop;
718	}
719#ifdef BSDSIGS
720    (void) sigsetmask(omask);
721#else /* !BSDSIGS */
722    (void) sigrelse(SIGCHLD);
723#endif /* !BSDSIGS */
724    pjobs = 0;
725}
726
727/*
728 * pflushall - flush all jobs from list (e.g. at fork())
729 */
730static void
731pflushall()
732{
733    register struct process *pp;
734
735    for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
736	if (pp->p_procid)
737	    pflush(pp);
738}
739
740/*
741 * pflush - flag all process structures in the same job as the
742 *	the argument process for deletion.  The actual free of the
743 *	space is not done here since pflush is called at interrupt level.
744 */
745static void
746pflush(pp)
747    register struct process *pp;
748{
749    register struct process *np;
750    register int idx;
751
752    if (pp->p_procid == 0) {
753	xprintf(CGETS(17, 3, "BUG: process flushed twice"));
754	return;
755    }
756    while (pp->p_procid != pp->p_jobid)
757	pp = pp->p_friends;
758    pclrcurr(pp);
759    if (pp == pcurrjob)
760	pcurrjob = 0;
761    idx = pp->p_index;
762    np = pp;
763    do {
764	np->p_index = np->p_procid = 0;
765	np->p_flags &= ~PNEEDNOTE;
766    } while ((np = np->p_friends) != pp);
767    if (idx == pmaxindex) {
768	for (np = proclist.p_next, idx = 0; np; np = np->p_next)
769	    if (np->p_index > idx)
770		idx = np->p_index;
771	pmaxindex = idx;
772    }
773}
774
775/*
776 * pclrcurr - make sure the given job is not the current or previous job;
777 *	pp MUST be the job leader
778 */
779static void
780pclrcurr(pp)
781    register struct process *pp;
782{
783    if (pp == pcurrent) {
784	if (pprevious != NULL) {
785	    pcurrent = pprevious;
786	    pprevious = pgetcurr(pp);
787	}
788	else {
789	    pcurrent = pgetcurr(pp);
790	    pprevious = pgetcurr(pp);
791	}
792    }
793    else if (pp == pprevious)
794	pprevious = pgetcurr(pp);
795}
796
797/* +4 here is 1 for '\0', 1 ea for << >& >> */
798static Char command[PMAXLEN + 4];
799static int cmdlen;
800static Char *cmdp;
801
802/* GrP
803 * unparse - Export padd() functionality
804 */
805Char *
806unparse(t)
807    register struct command *t;
808{
809    cmdp = command;
810    cmdlen = 0;
811    padd(t);
812    *cmdp++ = '\0';
813    return Strsave(command);
814}
815
816
817/*
818 * palloc - allocate a process structure and fill it up.
819 *	an important assumption is made that the process is running.
820 */
821void
822palloc(pid, t)
823    int     pid;
824    register struct command *t;
825{
826    register struct process *pp;
827    int     i;
828
829    pp = (struct process *) xcalloc(1, (size_t) sizeof(struct process));
830    pp->p_procid = pid;
831    pp->p_flags = ((t->t_dflg & F_AMPERSAND) ? 0 : PFOREGND) | PRUNNING;
832    if (t->t_dflg & F_TIME)
833	pp->p_flags |= PPTIME;
834    if (t->t_dflg & F_BACKQ)
835	pp->p_flags |= PBACKQ;
836    if (t->t_dflg & F_HUP)
837	pp->p_flags |= PHUP;
838    cmdp = command;
839    cmdlen = 0;
840    padd(t);
841    *cmdp++ = 0;
842    if (t->t_dflg & F_PIPEOUT) {
843	pp->p_flags |= PPOU;
844	if (t->t_dflg & F_STDERR)
845	    pp->p_flags |= PDIAG;
846    }
847    pp->p_command = Strsave(command);
848    if (pcurrjob) {
849	struct process *fp;
850
851	/* careful here with interrupt level */
852	pp->p_cwd = 0;
853	pp->p_index = pcurrjob->p_index;
854	pp->p_friends = pcurrjob;
855	pp->p_jobid = pcurrjob->p_procid;
856	for (fp = pcurrjob; fp->p_friends != pcurrjob; fp = fp->p_friends)
857	    continue;
858	fp->p_friends = pp;
859    }
860    else {
861	pcurrjob = pp;
862	pp->p_jobid = pid;
863	pp->p_friends = pp;
864	pp->p_cwd = dcwd;
865	dcwd->di_count++;
866	if (pmaxindex < BIGINDEX)
867	    pp->p_index = ++pmaxindex;
868	else {
869	    struct process *np;
870
871	    for (i = 1;; i++) {
872		for (np = proclist.p_next; np; np = np->p_next)
873		    if (np->p_index == i)
874			goto tryagain;
875		pp->p_index = i;
876		if (i > pmaxindex)
877		    pmaxindex = i;
878		break;
879	tryagain:;
880	    }
881	}
882	if (pcurrent == NULL)
883	    pcurrent = pp;
884	else if (pprevious == NULL)
885	    pprevious = pp;
886    }
887    pp->p_next = proclist.p_next;
888    proclist.p_next = pp;
889#ifdef BSDTIMES
890    (void) gettimeofday(&pp->p_btime, NULL);
891#else /* !BSDTIMES */
892# ifdef _SEQUENT_
893    (void) get_process_stats(&pp->p_btime, PS_SELF, NULL, NULL);
894# else /* !_SEQUENT_ */
895    {
896	struct tms tmptimes;
897
898#  ifndef COHERENT
899	pp->p_btime = times(&tmptimes);
900#  else /* !COHERENT */
901	pp->p_btime = HZ * time(NULL);
902	times(&tmptimes);
903#  endif /* !COHERENT */
904    }
905# endif /* !_SEQUENT_ */
906#endif /* !BSDTIMES */
907}
908
909static void
910padd(t)
911    register struct command *t;
912{
913    Char  **argp;
914
915    if (t == 0)
916	return;
917    switch (t->t_dtyp) {
918
919    case NODE_PAREN:
920	pads(STRLparensp);
921	padd(t->t_dspr);
922	pads(STRspRparen);
923	break;
924
925    case NODE_COMMAND:
926	for (argp = t->t_dcom; *argp; argp++) {
927	    pads(*argp);
928	    if (argp[1])
929		pads(STRspace);
930	}
931	break;
932
933    case NODE_OR:
934    case NODE_AND:
935    case NODE_PIPE:
936    case NODE_LIST:
937	padd(t->t_dcar);
938	switch (t->t_dtyp) {
939	case NODE_OR:
940	    pads(STRspor2sp);
941	    break;
942	case NODE_AND:
943	    pads(STRspand2sp);
944	    break;
945	case NODE_PIPE:
946	    pads(STRsporsp);
947	    break;
948	case NODE_LIST:
949	    pads(STRsemisp);
950	    break;
951	default:
952	    break;
953	}
954	padd(t->t_dcdr);
955	return;
956
957    default:
958	break;
959    }
960    if ((t->t_dflg & F_PIPEIN) == 0 && t->t_dlef) {
961	pads((t->t_dflg & F_READ) ? STRspLarrow2sp : STRspLarrowsp);
962	pads(t->t_dlef);
963    }
964    if ((t->t_dflg & F_PIPEOUT) == 0 && t->t_drit) {
965	pads((t->t_dflg & F_APPEND) ? STRspRarrow2 : STRspRarrow);
966	if (t->t_dflg & F_STDERR)
967	    pads(STRand);
968	pads(STRspace);
969	pads(t->t_drit);
970    }
971}
972
973static void
974pads(cp)
975    Char   *cp;
976{
977    register int i;
978
979    /*
980     * Avoid the Quoted Space alias hack! Reported by:
981     * sam@john-bigboote.ICS.UCI.EDU (Sam Horrocks)
982     */
983    if (cp[0] == STRQNULL[0])
984	cp++;
985
986    i = (int) Strlen(cp);
987
988    if (cmdlen >= PMAXLEN)
989	return;
990    if (cmdlen + i >= PMAXLEN) {
991	(void) Strcpy(cmdp, STRsp3dots);
992	cmdlen = PMAXLEN;
993	cmdp += 4;
994	return;
995    }
996    (void) Strcpy(cmdp, cp);
997    cmdp += i;
998    cmdlen += i;
999}
1000
1001/*
1002 * psavejob - temporarily save the current job on a one level stack
1003 *	so another job can be created.  Used for { } in exp6
1004 *	and `` in globbing.
1005 */
1006void
1007psavejob()
1008{
1009    pholdjob = pcurrjob;
1010    pcurrjob = NULL;
1011}
1012
1013/*
1014 * prestjob - opposite of psavejob.  This may be missed if we are interrupted
1015 *	somewhere, but pendjob cleans up anyway.
1016 */
1017void
1018prestjob()
1019{
1020    pcurrjob = pholdjob;
1021    pholdjob = NULL;
1022}
1023
1024/*
1025 * pendjob - indicate that a job (set of commands) has been completed
1026 *	or is about to begin.
1027 */
1028void
1029pendjob()
1030{
1031    register struct process *pp, *tp;
1032
1033    if (pcurrjob && (pcurrjob->p_flags & (PFOREGND | PSTOPPED)) == 0) {
1034	pp = pcurrjob;
1035	while (pp->p_procid != pp->p_jobid)
1036	    pp = pp->p_friends;
1037	xprintf("[%d]", pp->p_index);
1038	tp = pp;
1039	do {
1040	    xprintf(" %d", pp->p_procid);
1041	    pp = pp->p_friends;
1042	} while (pp != tp);
1043	xputchar('\n');
1044    }
1045    pholdjob = pcurrjob = 0;
1046}
1047
1048/*
1049 * pprint - print a job
1050 */
1051
1052/*
1053 * Hacks have been added for SVR4 to deal with pipe's being spawned in
1054 * reverse order
1055 *
1056 * David Dawes (dawes@physics.su.oz.au) Oct 1991
1057 */
1058
1059static int
1060pprint(pp, flag)
1061    register struct process *pp;
1062    bool    flag;
1063{
1064    int status, reason;
1065    struct process *tp;
1066    extern char *linp, linbuf[];
1067    int     jobflags, pstatus, pcond;
1068    char   *format;
1069
1070#ifdef BACKPIPE
1071    struct process *pipehead = NULL, *pipetail = NULL, *pmarker = NULL;
1072    int inpipe = 0;
1073#endif /* BACKPIPE */
1074
1075    while (pp->p_procid != pp->p_jobid)
1076	pp = pp->p_friends;
1077    if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
1078	pp->p_flags &= ~PPTIME;
1079	pp->p_flags |= PTIME;
1080    }
1081    tp = pp;
1082    status = reason = -1;
1083    jobflags = 0;
1084    do {
1085#ifdef BACKPIPE
1086	/*
1087	 * The pipeline is reversed, so locate the real head of the pipeline
1088	 * if pp is at the tail of a pipe (and not already in a pipeline)
1089	 */
1090	if ((pp->p_friends->p_flags & PPOU) && !inpipe && (flag & NAME)) {
1091	    inpipe = 1;
1092	    pipetail = pp;
1093	    do
1094		pp = pp->p_friends;
1095	    while (pp->p_friends->p_flags & PPOU);
1096	    pipehead = pp;
1097	    pmarker = pp;
1098	/*
1099	 * pmarker is used to hold the place of the proc being processed, so
1100	 * we can search for the next one downstream later.
1101	 */
1102	}
1103	pcond = (int) (tp != pp || (inpipe && tp == pp));
1104#else /* !BACKPIPE */
1105	pcond = (int) (tp != pp);
1106#endif /* BACKPIPE */
1107
1108	jobflags |= pp->p_flags;
1109	pstatus = (int) (pp->p_flags & PALLSTATES);
1110	if (pcond && linp != linbuf && !(flag & FANCY) &&
1111	    ((pstatus == status && pp->p_reason == reason) ||
1112	     !(flag & REASON)))
1113	    xputchar(' ');
1114	else {
1115	    if (pcond && linp != linbuf)
1116		xputchar('\n');
1117	    if (flag & NUMBER) {
1118#ifdef BACKPIPE
1119		pcond = ((pp == tp && !inpipe) ||
1120			 (inpipe && pipetail == tp && pp == pipehead));
1121#else /* BACKPIPE */
1122		pcond = (pp == tp);
1123#endif /* BACKPIPE */
1124		if (pcond)
1125		    xprintf("[%d]%s %c ", pp->p_index,
1126			    pp->p_index < 10 ? " " : "",
1127			    pp == pcurrent ? '+' :
1128			    (pp == pprevious ? '-' : ' '));
1129		else
1130		    xprintf("       ");
1131	    }
1132	    if (flag & FANCY) {
1133#ifdef TCF
1134		extern char *sitename();
1135
1136#endif /* TCF */
1137		xprintf("%5d ", pp->p_procid);
1138#ifdef TCF
1139		xprintf("%11s ", sitename(pp->p_procid));
1140#endif /* TCF */
1141	    }
1142	    if (flag & (REASON | AREASON)) {
1143		if (flag & NAME)
1144		    format = "%-30s";
1145		else
1146		    format = "%s";
1147		if (pstatus == status) {
1148		    if (pp->p_reason == reason) {
1149			xprintf(format, "");
1150			goto prcomd;
1151		    }
1152		    else
1153			reason = (int) pp->p_reason;
1154		}
1155		else {
1156		    status = pstatus;
1157		    reason = (int) pp->p_reason;
1158		}
1159		switch (status) {
1160
1161		case PRUNNING:
1162		    xprintf(format, CGETS(17, 4, "Running "));
1163		    break;
1164
1165		case PINTERRUPTED:
1166		case PSTOPPED:
1167		case PSIGNALED:
1168		    /*
1169		     * tell what happened to the background job
1170		     * From: Michael Schroeder
1171		     * <mlschroe@immd4.informatik.uni-erlangen.de>
1172		     */
1173		    if ((flag & REASON)
1174			|| ((flag & AREASON)
1175			    && reason != SIGINT
1176			    && (reason != SIGPIPE
1177				|| (pp->p_flags & PPOU) == 0))) {
1178			char *ptr;
1179			char buf[1024];
1180
1181			if ((ptr = mesg[pp->p_reason & ASCII].pname) == NULL)
1182			    xsnprintf(ptr = buf, sizeof(buf), "%s %d",
1183				CGETS(17, 5, "Signal"), pp->p_reason & ASCII);
1184			xprintf(format, ptr);
1185		    }
1186		    else
1187			reason = -1;
1188		    break;
1189
1190		case PNEXITED:
1191		case PAEXITED:
1192		    if (flag & REASON) {
1193			if (pp->p_reason)
1194			    xprintf(CGETS(17, 6, "Exit %-25d"), pp->p_reason);
1195			else
1196			    xprintf(format, CGETS(17, 7, "Done"));
1197		    }
1198		    break;
1199
1200		default:
1201		    xprintf(CGETS(17, 8, "BUG: status=%-9o"),
1202			    status);
1203		}
1204	    }
1205	}
1206prcomd:
1207	if (flag & NAME) {
1208	    xprintf("%S", pp->p_command);
1209	    if (pp->p_flags & PPOU)
1210		xprintf(" |");
1211	    if (pp->p_flags & PDIAG)
1212		xprintf("&");
1213	}
1214	if (flag & (REASON | AREASON) && pp->p_flags & PDUMPED)
1215	    xprintf(CGETS(17, 9, " (core dumped)"));
1216	if (tp == pp->p_friends) {
1217	    if (flag & AMPERSAND)
1218		xprintf(" &");
1219	    if (flag & JOBDIR &&
1220		!eq(tp->p_cwd->di_name, dcwd->di_name)) {
1221		xprintf(CGETS(17, 10, " (wd: "));
1222		dtildepr(tp->p_cwd->di_name);
1223		xprintf(")");
1224	    }
1225	}
1226	if (pp->p_flags & PPTIME && !(status & (PSTOPPED | PRUNNING))) {
1227	    if (linp != linbuf)
1228		xprintf("\n\t");
1229#if defined(BSDTIMES) || defined(_SEQUENT_)
1230	    prusage(&zru, &pp->p_rusage, &pp->p_etime,
1231		    &pp->p_btime);
1232#else /* !BSDTIMES && !SEQUENT */
1233	    lru.tms_utime = pp->p_utime;
1234	    lru.tms_stime = pp->p_stime;
1235	    lru.tms_cutime = 0;
1236	    lru.tms_cstime = 0;
1237	    prusage(&zru, &lru, pp->p_etime,
1238		    pp->p_btime);
1239#endif /* !BSDTIMES && !SEQUENT */
1240
1241	}
1242#ifdef BACKPIPE
1243	pcond = ((tp == pp->p_friends && !inpipe) ||
1244		 (inpipe && pipehead->p_friends == tp && pp == pipetail));
1245#else  /* !BACKPIPE */
1246	pcond = (tp == pp->p_friends);
1247#endif /* BACKPIPE */
1248	if (pcond) {
1249	    if (linp != linbuf)
1250		xputchar('\n');
1251	    if (flag & SHELLDIR && !eq(tp->p_cwd->di_name, dcwd->di_name)) {
1252		xprintf(CGETS(17, 11, "(wd now: "));
1253		dtildepr(dcwd->di_name);
1254		xprintf(")\n");
1255	    }
1256	}
1257#ifdef BACKPIPE
1258	if (inpipe) {
1259	    /*
1260	     * if pmaker == pipetail, we are finished that pipeline, and
1261	     * can now skip to past the head
1262	     */
1263	    if (pmarker == pipetail) {
1264		inpipe = 0;
1265		pp = pipehead;
1266	    }
1267	    else {
1268	    /*
1269	     * set pp to one before the one we want next, so the while below
1270	     * increments to the correct spot.
1271	     */
1272		do
1273		    pp = pp->p_friends;
1274	    	while (pp->p_friends->p_friends != pmarker);
1275	    	pmarker = pp->p_friends;
1276	    }
1277	}
1278	pcond = ((pp = pp->p_friends) != tp || inpipe);
1279#else /* !BACKPIPE */
1280	pcond = ((pp = pp->p_friends) != tp);
1281#endif /* BACKPIPE */
1282    } while (pcond);
1283
1284    if (jobflags & PTIME && (jobflags & (PSTOPPED | PRUNNING)) == 0) {
1285	if (jobflags & NUMBER)
1286	    xprintf("       ");
1287	ptprint(tp);
1288    }
1289    return (jobflags);
1290}
1291
1292/*
1293 * All 4.3 BSD derived implementations are buggy and I've had enough.
1294 * The following implementation produces similar code and works in all
1295 * cases. The 4.3BSD one works only for <, >, !=
1296 */
1297# undef timercmp
1298#  define timercmp(tvp, uvp, cmp) \
1299      (((tvp)->tv_sec == (uvp)->tv_sec) ? \
1300	   ((tvp)->tv_usec cmp (uvp)->tv_usec) : \
1301	   ((tvp)->tv_sec  cmp (uvp)->tv_sec))
1302
1303static void
1304ptprint(tp)
1305    register struct process *tp;
1306{
1307#ifdef BSDTIMES
1308    struct timeval tetime, diff;
1309    static struct timeval ztime;
1310    struct sysrusage ru;
1311    register struct process *pp = tp;
1312
1313    ru = zru;
1314    tetime = ztime;
1315    do {
1316	ruadd(&ru, &pp->p_rusage);
1317	tvsub(&diff, &pp->p_etime, &pp->p_btime);
1318	if (timercmp(&diff, &tetime, >))
1319	    tetime = diff;
1320    } while ((pp = pp->p_friends) != tp);
1321    prusage(&zru, &ru, &tetime, &ztime);
1322#else /* !BSDTIMES */
1323# ifdef _SEQUENT_
1324    timeval_t tetime, diff;
1325    static timeval_t ztime;
1326    struct process_stats ru;
1327    register struct process *pp = tp;
1328
1329    ru = zru;
1330    tetime = ztime;
1331    do {
1332	ruadd(&ru, &pp->p_rusage);
1333	tvsub(&diff, &pp->p_etime, &pp->p_btime);
1334	if (timercmp(&diff, &tetime, >))
1335	    tetime = diff;
1336    } while ((pp = pp->p_friends) != tp);
1337    prusage(&zru, &ru, &tetime, &ztime);
1338# else /* !_SEQUENT_ */
1339#  ifndef POSIX
1340    static time_t ztime = 0;
1341    static time_t zu_time = 0;
1342    static time_t zs_time = 0;
1343    time_t  tetime, diff;
1344    time_t  u_time, s_time;
1345
1346#  else	/* POSIX */
1347    static clock_t ztime = 0;
1348    static clock_t zu_time = 0;
1349    static clock_t zs_time = 0;
1350    clock_t tetime, diff;
1351    clock_t u_time, s_time;
1352
1353#  endif /* POSIX */
1354    struct tms zts, rts;
1355    register struct process *pp = tp;
1356
1357    u_time = zu_time;
1358    s_time = zs_time;
1359    tetime = ztime;
1360    do {
1361	u_time += pp->p_utime;
1362	s_time += pp->p_stime;
1363	diff = pp->p_etime - pp->p_btime;
1364	if (diff > tetime)
1365	    tetime = diff;
1366    } while ((pp = pp->p_friends) != tp);
1367    zts.tms_utime = zu_time;
1368    zts.tms_stime = zs_time;
1369    zts.tms_cutime = 0;
1370    zts.tms_cstime = 0;
1371    rts.tms_utime = u_time;
1372    rts.tms_stime = s_time;
1373    rts.tms_cutime = 0;
1374    rts.tms_cstime = 0;
1375    prusage(&zts, &rts, tetime, ztime);
1376# endif /* !_SEQUENT_ */
1377#endif	/* !BSDTIMES */
1378}
1379
1380/*
1381 * dojobs - print all jobs
1382 */
1383/*ARGSUSED*/
1384void
1385dojobs(v, c)
1386    Char  **v;
1387    struct command *c;
1388{
1389    register struct process *pp;
1390    register int flag = NUMBER | NAME | REASON;
1391    int     i;
1392
1393    USE(c);
1394    if (chkstop)
1395	chkstop = 2;
1396    if (*++v) {
1397	if (v[1] || !eq(*v, STRml))
1398	    stderror(ERR_JOBS);
1399	flag |= FANCY | JOBDIR;
1400    }
1401    for (i = 1; i <= pmaxindex; i++)
1402	for (pp = proclist.p_next; pp; pp = pp->p_next)
1403	    if (pp->p_index == i && pp->p_procid == pp->p_jobid) {
1404		pp->p_flags &= ~PNEEDNOTE;
1405		if (!(pprint(pp, flag) & (PRUNNING | PSTOPPED)))
1406		    pflush(pp);
1407		break;
1408	    }
1409}
1410
1411/*
1412 * dofg - builtin - put the job into the foreground
1413 */
1414/*ARGSUSED*/
1415void
1416dofg(v, c)
1417    Char  **v;
1418    struct command *c;
1419{
1420    register struct process *pp;
1421
1422    USE(c);
1423    okpcntl();
1424    ++v;
1425    do {
1426	pp = pfind(*v);
1427	if (!pstart(pp, 1)) {
1428	    pp->p_procid = 0;
1429	    stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1430	    continue;
1431	}
1432#ifndef BSDSIGS
1433# ifdef notdef
1434	if (setintr)
1435	    sigignore(SIGINT);
1436# endif
1437#endif /* !BSDSIGS */
1438	pjwait(pp);
1439    } while (*v && *++v);
1440}
1441
1442/*
1443 * %... - builtin - put the job into the foreground
1444 */
1445/*ARGSUSED*/
1446void
1447dofg1(v, c)
1448    Char  **v;
1449    struct command *c;
1450{
1451    register struct process *pp;
1452
1453    USE(c);
1454    okpcntl();
1455    pp = pfind(v[0]);
1456    if (!pstart(pp, 1)) {
1457	pp->p_procid = 0;
1458	stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1459	return;
1460    }
1461#ifndef BSDSIGS
1462# ifdef notdef
1463    if (setintr)
1464	sigignore(SIGINT);
1465# endif
1466#endif /* !BSDSIGS */
1467    pjwait(pp);
1468}
1469
1470/*
1471 * dobg - builtin - put the job into the background
1472 */
1473/*ARGSUSED*/
1474void
1475dobg(v, c)
1476    Char  **v;
1477    struct command *c;
1478{
1479    register struct process *pp;
1480
1481    USE(c);
1482    okpcntl();
1483    ++v;
1484    do {
1485	pp = pfind(*v);
1486	if (!pstart(pp, 0)) {
1487	    pp->p_procid = 0;
1488	    stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1489	}
1490    } while (*v && *++v);
1491}
1492
1493/*
1494 * %... & - builtin - put the job into the background
1495 */
1496/*ARGSUSED*/
1497void
1498dobg1(v, c)
1499    Char  **v;
1500    struct command *c;
1501{
1502    register struct process *pp;
1503
1504    USE(c);
1505    pp = pfind(v[0]);
1506    if (!pstart(pp, 0)) {
1507	pp->p_procid = 0;
1508	stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1509    }
1510}
1511
1512/*
1513 * dostop - builtin - stop the job
1514 */
1515/*ARGSUSED*/
1516void
1517dostop(v, c)
1518    Char  **v;
1519    struct command *c;
1520{
1521    USE(c);
1522#ifdef BSDJOBS
1523    pkill(++v, SIGSTOP);
1524#endif /* BSDJOBS */
1525}
1526
1527/*
1528 * dokill - builtin - superset of kill (1)
1529 */
1530/*ARGSUSED*/
1531void
1532dokill(v, c)
1533    Char  **v;
1534    struct command *c;
1535{
1536    register int signum, len = 0;
1537    register char *name;
1538    Char *sigptr;
1539    extern int T_Cols;
1540    extern int nsig;
1541
1542    USE(c);
1543    v++;
1544    if (v[0] && v[0][0] == '-') {
1545	if (v[0][1] == 'l') {
1546	    for (signum = 0; signum <= nsig; signum++) {
1547		if ((name = mesg[signum].iname) != NULL) {
1548		    len += strlen(name) + 1;
1549		    if (len >= T_Cols - 1) {
1550			xputchar('\n');
1551			len = strlen(name) + 1;
1552		    }
1553		    xprintf("%s ", name);
1554		}
1555	    }
1556	    xputchar('\n');
1557	    return;
1558	}
1559 	sigptr = &v[0][1];
1560 	if (v[0][1] == 's') {
1561 	    if (v[1]) {
1562 		v++;
1563 		sigptr = &v[0][0];
1564 	    } else {
1565 		stderror(ERR_NAME | ERR_TOOFEW);
1566 	    }
1567 	}
1568 	if (Isdigit(*sigptr)) {
1569	    char *ep;
1570 	    signum = strtoul(short2str(sigptr), &ep, 0);
1571	    if (*ep || signum < 0 || signum > (MAXSIG-1))
1572		stderror(ERR_NAME | ERR_BADSIG);
1573	}
1574	else {
1575	    for (signum = 0; signum <= nsig; signum++)
1576		if (mesg[signum].iname &&
1577 		    eq(sigptr, str2short(mesg[signum].iname)))
1578		    goto gotsig;
1579 	    setname(short2str(sigptr));
1580	    stderror(ERR_NAME | ERR_UNKSIG);
1581	}
1582gotsig:
1583	v++;
1584    }
1585    else
1586	signum = SIGTERM;
1587    pkill(v, signum);
1588}
1589
1590static void
1591pkill(v, signum)
1592    Char  **v;
1593    int     signum;
1594{
1595    register struct process *pp, *np;
1596    int jobflags = 0, err1 = 0;
1597    pid_t     pid;
1598#ifdef BSDSIGS
1599    sigmask_t omask;
1600#endif /* BSDSIGS */
1601    Char   *cp, **vp;
1602
1603#ifdef BSDSIGS
1604    omask = sigmask(SIGCHLD);
1605    if (setintr)
1606	omask |= sigmask(SIGINT);
1607    omask = sigblock(omask) & ~omask;
1608#else /* !BSDSIGS */
1609    if (setintr)
1610	(void) sighold(SIGINT);
1611    (void) sighold(SIGCHLD);
1612#endif /* !BSDSIGS */
1613
1614    /* Avoid globbing %?x patterns */
1615    for (vp = v; vp && *vp; vp++)
1616	if (**vp == '%')
1617	    (void) quote(*vp);
1618
1619    gflag = 0, tglob(v);
1620    if (gflag) {
1621	v = globall(v);
1622	if (v == 0)
1623	    stderror(ERR_NAME | ERR_NOMATCH);
1624    }
1625    else {
1626	v = gargv = saveblk(v);
1627	trim(v);
1628    }
1629
1630
1631    while (v && (cp = *v)) {
1632	if (*cp == '%') {
1633	    np = pp = pfind(cp);
1634	    do
1635		jobflags |= np->p_flags;
1636	    while ((np = np->p_friends) != pp);
1637#ifdef BSDJOBS
1638	    switch (signum) {
1639
1640	    case SIGSTOP:
1641	    case SIGTSTP:
1642	    case SIGTTIN:
1643	    case SIGTTOU:
1644		if ((jobflags & PRUNNING) == 0) {
1645# ifdef SUSPENDED
1646		    xprintf(CGETS(17, 12, "%S: Already suspended\n"), cp);
1647# else /* !SUSPENDED */
1648		    xprintf(CGETS(17, 13, "%S: Already stopped\n"), cp);
1649# endif /* !SUSPENDED */
1650		    err1++;
1651		    goto cont;
1652		}
1653		break;
1654		/*
1655		 * suspend a process, kill -CONT %, then type jobs; the shell
1656		 * says it is suspended, but it is running; thanks jaap..
1657		 */
1658	    case SIGCONT:
1659		if (!pstart(pp, 0)) {
1660		    pp->p_procid = 0;
1661		    stderror(ERR_NAME|ERR_BADJOB, pp->p_command,
1662			     strerror(errno));
1663		}
1664		goto cont;
1665	    default:
1666		break;
1667	    }
1668#endif /* BSDJOBS */
1669	    if (killpg(pp->p_jobid, signum) < 0) {
1670		xprintf("%S: %s\n", cp, strerror(errno));
1671		err1++;
1672	    }
1673#ifdef BSDJOBS
1674	    if (signum == SIGTERM || signum == SIGHUP)
1675		(void) killpg(pp->p_jobid, SIGCONT);
1676#endif /* BSDJOBS */
1677	}
1678	else if (!(Isdigit(*cp) || *cp == '-'))
1679	    stderror(ERR_NAME | ERR_JOBARGS);
1680	else {
1681	    char *ep;
1682#ifndef WINNT_NATIVE
1683	    pid = strtol(short2str(cp), &ep, 10);
1684#else
1685	    pid = strtoul(short2str(cp), &ep, 0);
1686#endif /* WINNT_NATIVE */
1687	    if (*ep)
1688		stderror(ERR_NAME | ERR_JOBARGS);
1689	    else 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	}
1699cont:
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 */
1718int
1719pstart(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
1793void
1794panystop(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
1805struct process *
1806pfind(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 */
1860static struct process *
1861pgetcurr(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*/
1882void
1883donotify(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
1906int
1907pfork(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
2088static void
2089okpcntl()
2090{
2091    if (tpgrp == -1)
2092	stderror(ERR_JOBCONTROL);
2093    if (tpgrp == 0)
2094	stderror(ERR_JOBCTRLSUB);
2095}
2096
2097
2098static void
2099setttypgrp(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 */
2140void
2141pgetty(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