sh.proc.c revision 59243
1/* $Header: /src/pub/tcsh/sh.proc.c,v 3.70 1998/10/25 15:10:22 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
39RCSID("$Id: sh.proc.c,v 3.70 1998/10/25 15:10:22 christos Exp $")
40
41#include "ed.h"
42#include "tc.h"
43#include "tc.wait.h"
44
45#ifdef WINNT
46#undef POSIX
47#define POSIX
48#endif /* WINNT */
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 */
93static 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__))
99static 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 */
109static struct rusage zru;
110#   else	/* masscomp */
111static 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_
118static 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
122static struct tms zru = {0, 0, 0, 0}, lru = {0, 0, 0, 0};
123#  else	/* !_SX */
124static 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
133static	void		 pflushall	__P((void));
134static	void		 pflush		__P((struct process *));
135static	void		 pfree		__P((struct process *));
136static	void		 pclrcurr	__P((struct process *));
137static	void		 padd		__P((struct command *));
138static	int		 pprint		__P((struct process *, int));
139static	void		 ptprint	__P((struct process *));
140static	void		 pads		__P((Char *));
141static	void		 pkill		__P((Char **, int));
142static	struct process	*pgetcurr	__P((struct process *));
143static	void		 okpcntl	__P((void));
144static	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 */
153sigret_t
154/*ARGSUSED*/
155pchild(snum)
156int 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
208loop:
209    errno = 0;			/* reset, just in case */
210#ifdef JOBDEBUG
211    xprintf("Waiting...\n");
212    flush();
213#endif /* JOBDEBUG */
214#ifndef WINNT
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 */
292    {
293	extern int insource;
294	pid = waitpid(-1, &w,
295	    (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG));
296    }
297#endif /* WINNT */
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)
324    /* this should never have happened */
325    stderror(ERR_SYNC, pid);
326    xexit(0);
327#else /* BSDJOBS || WINNT */
328    goto loop;
329#endif /* !BSDJOBS && !WINNT */
330found:
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
481void
482pnote()
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
512static void
513pfree(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 */
528void
529pwait()
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 */
567void
568pjwait(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*/
691void
692dowait(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));
706loop:
707#else /* !BSDSIGS */
708    if (setintr)
709	(void) sigrelse(SIGINT);
710loop:
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 */
734static void
735pflushall()
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 */
749static void
750pflush(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 */
783static void
784pclrcurr(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 << >& >> */
802static Char command[PMAXLEN + 4];
803static int cmdlen;
804static Char *cmdp;
805
806/*
807 * palloc - allocate a process structure and fill it up.
808 *	an important assumption is made that the process is running.
809 */
810void
811palloc(pid, t)
812    int     pid;
813    register struct command *t;
814{
815    register struct process *pp;
816    int     i;
817
818    pp = (struct process *) xcalloc(1, (size_t) sizeof(struct process));
819    pp->p_procid = pid;
820    pp->p_flags = ((t->t_dflg & F_AMPERSAND) ? 0 : PFOREGND) | PRUNNING;
821    if (t->t_dflg & F_TIME)
822	pp->p_flags |= PPTIME;
823    if (t->t_dflg & F_BACKQ)
824	pp->p_flags |= PBACKQ;
825    if (t->t_dflg & F_HUP)
826	pp->p_flags |= PHUP;
827    cmdp = command;
828    cmdlen = 0;
829    padd(t);
830    *cmdp++ = 0;
831    if (t->t_dflg & F_PIPEOUT) {
832	pp->p_flags |= PPOU;
833	if (t->t_dflg & F_STDERR)
834	    pp->p_flags |= PDIAG;
835    }
836    pp->p_command = Strsave(command);
837    if (pcurrjob) {
838	struct process *fp;
839
840	/* careful here with interrupt level */
841	pp->p_cwd = 0;
842	pp->p_index = pcurrjob->p_index;
843	pp->p_friends = pcurrjob;
844	pp->p_jobid = pcurrjob->p_procid;
845	for (fp = pcurrjob; fp->p_friends != pcurrjob; fp = fp->p_friends)
846	    continue;
847	fp->p_friends = pp;
848    }
849    else {
850	pcurrjob = pp;
851	pp->p_jobid = pid;
852	pp->p_friends = pp;
853	pp->p_cwd = dcwd;
854	dcwd->di_count++;
855	if (pmaxindex < BIGINDEX)
856	    pp->p_index = ++pmaxindex;
857	else {
858	    struct process *np;
859
860	    for (i = 1;; i++) {
861		for (np = proclist.p_next; np; np = np->p_next)
862		    if (np->p_index == i)
863			goto tryagain;
864		pp->p_index = i;
865		if (i > pmaxindex)
866		    pmaxindex = i;
867		break;
868	tryagain:;
869	    }
870	}
871	if (pcurrent == NULL)
872	    pcurrent = pp;
873	else if (pprevious == NULL)
874	    pprevious = pp;
875    }
876    pp->p_next = proclist.p_next;
877    proclist.p_next = pp;
878#ifdef BSDTIMES
879    (void) gettimeofday(&pp->p_btime, NULL);
880#else /* !BSDTIMES */
881# ifdef _SEQUENT_
882    (void) get_process_stats(&pp->p_btime, PS_SELF, NULL, NULL);
883# else /* !_SEQUENT_ */
884    {
885	struct tms tmptimes;
886
887#  ifndef COHERENT
888	pp->p_btime = times(&tmptimes);
889#  else /* !COHERENT */
890	pp->p_btime = HZ * time(NULL);
891	times(&tmptimes);
892#  endif /* !COHERENT */
893    }
894# endif /* !_SEQUENT_ */
895#endif /* !BSDTIMES */
896}
897
898static void
899padd(t)
900    register struct command *t;
901{
902    Char  **argp;
903
904    if (t == 0)
905	return;
906    switch (t->t_dtyp) {
907
908    case NODE_PAREN:
909	pads(STRLparensp);
910	padd(t->t_dspr);
911	pads(STRspRparen);
912	break;
913
914    case NODE_COMMAND:
915	for (argp = t->t_dcom; *argp; argp++) {
916	    pads(*argp);
917	    if (argp[1])
918		pads(STRspace);
919	}
920	break;
921
922    case NODE_OR:
923    case NODE_AND:
924    case NODE_PIPE:
925    case NODE_LIST:
926	padd(t->t_dcar);
927	switch (t->t_dtyp) {
928	case NODE_OR:
929	    pads(STRspor2sp);
930	    break;
931	case NODE_AND:
932	    pads(STRspand2sp);
933	    break;
934	case NODE_PIPE:
935	    pads(STRsporsp);
936	    break;
937	case NODE_LIST:
938	    pads(STRsemisp);
939	    break;
940	default:
941	    break;
942	}
943	padd(t->t_dcdr);
944	return;
945
946    default:
947	break;
948    }
949    if ((t->t_dflg & F_PIPEIN) == 0 && t->t_dlef) {
950	pads((t->t_dflg & F_READ) ? STRspLarrow2sp : STRspLarrowsp);
951	pads(t->t_dlef);
952    }
953    if ((t->t_dflg & F_PIPEOUT) == 0 && t->t_drit) {
954	pads((t->t_dflg & F_APPEND) ? STRspRarrow2 : STRspRarrow);
955	if (t->t_dflg & F_STDERR)
956	    pads(STRand);
957	pads(STRspace);
958	pads(t->t_drit);
959    }
960}
961
962static void
963pads(cp)
964    Char   *cp;
965{
966    register int i;
967
968    /*
969     * Avoid the Quoted Space alias hack! Reported by:
970     * sam@john-bigboote.ICS.UCI.EDU (Sam Horrocks)
971     */
972    if (cp[0] == STRQNULL[0])
973	cp++;
974
975    i = (int) Strlen(cp);
976
977    if (cmdlen >= PMAXLEN)
978	return;
979    if (cmdlen + i >= PMAXLEN) {
980	(void) Strcpy(cmdp, STRsp3dots);
981	cmdlen = PMAXLEN;
982	cmdp += 4;
983	return;
984    }
985    (void) Strcpy(cmdp, cp);
986    cmdp += i;
987    cmdlen += i;
988}
989
990/*
991 * psavejob - temporarily save the current job on a one level stack
992 *	so another job can be created.  Used for { } in exp6
993 *	and `` in globbing.
994 */
995void
996psavejob()
997{
998    pholdjob = pcurrjob;
999    pcurrjob = NULL;
1000}
1001
1002/*
1003 * prestjob - opposite of psavejob.  This may be missed if we are interrupted
1004 *	somewhere, but pendjob cleans up anyway.
1005 */
1006void
1007prestjob()
1008{
1009    pcurrjob = pholdjob;
1010    pholdjob = NULL;
1011}
1012
1013/*
1014 * pendjob - indicate that a job (set of commands) has been completed
1015 *	or is about to begin.
1016 */
1017void
1018pendjob()
1019{
1020    register struct process *pp, *tp;
1021
1022    if (pcurrjob && (pcurrjob->p_flags & (PFOREGND | PSTOPPED)) == 0) {
1023	pp = pcurrjob;
1024	while (pp->p_procid != pp->p_jobid)
1025	    pp = pp->p_friends;
1026	xprintf("[%d]", pp->p_index);
1027	tp = pp;
1028	do {
1029	    xprintf(" %d", pp->p_procid);
1030	    pp = pp->p_friends;
1031	} while (pp != tp);
1032	xputchar('\n');
1033    }
1034    pholdjob = pcurrjob = 0;
1035}
1036
1037/*
1038 * pprint - print a job
1039 */
1040
1041/*
1042 * Hacks have been added for SVR4 to deal with pipe's being spawned in
1043 * reverse order
1044 *
1045 * David Dawes (dawes@physics.su.oz.au) Oct 1991
1046 */
1047
1048static int
1049pprint(pp, flag)
1050    register struct process *pp;
1051    bool    flag;
1052{
1053    int status, reason;
1054    struct process *tp;
1055    extern char *linp, linbuf[];
1056    int     jobflags, pstatus, pcond;
1057    char   *format;
1058
1059#ifdef BACKPIPE
1060    struct process *pipehead = NULL, *pipetail = NULL, *pmarker = NULL;
1061    int inpipe = 0;
1062#endif /* BACKPIPE */
1063
1064    while (pp->p_procid != pp->p_jobid)
1065	pp = pp->p_friends;
1066    if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
1067	pp->p_flags &= ~PPTIME;
1068	pp->p_flags |= PTIME;
1069    }
1070    tp = pp;
1071    status = reason = -1;
1072    jobflags = 0;
1073    do {
1074#ifdef BACKPIPE
1075	/*
1076	 * The pipeline is reversed, so locate the real head of the pipeline
1077	 * if pp is at the tail of a pipe (and not already in a pipeline)
1078	 */
1079	if ((pp->p_friends->p_flags & PPOU) && !inpipe && (flag & NAME)) {
1080	    inpipe = 1;
1081	    pipetail = pp;
1082	    do
1083		pp = pp->p_friends;
1084	    while (pp->p_friends->p_flags & PPOU);
1085	    pipehead = pp;
1086	    pmarker = pp;
1087	/*
1088	 * pmarker is used to hold the place of the proc being processed, so
1089	 * we can search for the next one downstream later.
1090	 */
1091	}
1092	pcond = (int) (tp != pp || (inpipe && tp == pp));
1093#else /* !BACKPIPE */
1094	pcond = (int) (tp != pp);
1095#endif /* BACKPIPE */
1096
1097	jobflags |= pp->p_flags;
1098	pstatus = (int) (pp->p_flags & PALLSTATES);
1099	if (pcond && linp != linbuf && !(flag & FANCY) &&
1100	    ((pstatus == status && pp->p_reason == reason) ||
1101	     !(flag & REASON)))
1102	    xputchar(' ');
1103	else {
1104	    if (pcond && linp != linbuf)
1105		xputchar('\n');
1106	    if (flag & NUMBER) {
1107#ifdef BACKPIPE
1108		pcond = ((pp == tp && !inpipe) ||
1109			 (inpipe && pipetail == tp && pp == pipehead));
1110#else /* BACKPIPE */
1111		pcond = (pp == tp);
1112#endif /* BACKPIPE */
1113		if (pcond)
1114		    xprintf("[%d]%s %c ", pp->p_index,
1115			    pp->p_index < 10 ? " " : "",
1116			    pp == pcurrent ? '+' :
1117			    (pp == pprevious ? '-' : ' '));
1118		else
1119		    xprintf("       ");
1120	    }
1121	    if (flag & FANCY) {
1122#ifdef TCF
1123		extern char *sitename();
1124
1125#endif /* TCF */
1126		xprintf("%5d ", pp->p_procid);
1127#ifdef TCF
1128		xprintf("%11s ", sitename(pp->p_procid));
1129#endif /* TCF */
1130	    }
1131	    if (flag & (REASON | AREASON)) {
1132		if (flag & NAME)
1133		    format = "%-30s";
1134		else
1135		    format = "%s";
1136		if (pstatus == status) {
1137		    if (pp->p_reason == reason) {
1138			xprintf(format, "");
1139			goto prcomd;
1140		    }
1141		    else
1142			reason = (int) pp->p_reason;
1143		}
1144		else {
1145		    status = pstatus;
1146		    reason = (int) pp->p_reason;
1147		}
1148		switch (status) {
1149
1150		case PRUNNING:
1151		    xprintf(format, CGETS(17, 4, "Running "));
1152		    break;
1153
1154		case PINTERRUPTED:
1155		case PSTOPPED:
1156		case PSIGNALED:
1157		    /*
1158		     * tell what happened to the background job
1159		     * From: Michael Schroeder
1160		     * <mlschroe@immd4.informatik.uni-erlangen.de>
1161		     */
1162		    if ((flag & REASON)
1163			|| ((flag & AREASON)
1164			    && reason != SIGINT
1165			    && (reason != SIGPIPE
1166				|| (pp->p_flags & PPOU) == 0))) {
1167			char *ptr;
1168			char buf[1024];
1169
1170			if ((ptr = mesg[pp->p_reason & ASCII].pname) == NULL)
1171			    xsnprintf(ptr = buf, sizeof(buf), "%s %d",
1172				CGETS(17, 5, "Signal"), pp->p_reason & ASCII);
1173			xprintf(format, ptr);
1174		    }
1175		    else
1176			reason = -1;
1177		    break;
1178
1179		case PNEXITED:
1180		case PAEXITED:
1181		    if (flag & REASON) {
1182			if (pp->p_reason)
1183			    xprintf(CGETS(17, 6, "Exit %-25d"), pp->p_reason);
1184			else
1185			    xprintf(format, CGETS(17, 7, "Done"));
1186		    }
1187		    break;
1188
1189		default:
1190		    xprintf(CGETS(17, 8, "BUG: status=%-9o"),
1191			    status);
1192		}
1193	    }
1194	}
1195prcomd:
1196	if (flag & NAME) {
1197	    xprintf("%S", pp->p_command);
1198	    if (pp->p_flags & PPOU)
1199		xprintf(" |");
1200	    if (pp->p_flags & PDIAG)
1201		xprintf("&");
1202	}
1203	if (flag & (REASON | AREASON) && pp->p_flags & PDUMPED)
1204	    xprintf(CGETS(17, 9, " (core dumped)"));
1205	if (tp == pp->p_friends) {
1206	    if (flag & AMPERSAND)
1207		xprintf(" &");
1208	    if (flag & JOBDIR &&
1209		!eq(tp->p_cwd->di_name, dcwd->di_name)) {
1210		xprintf(CGETS(17, 10, " (wd: "));
1211		dtildepr(tp->p_cwd->di_name);
1212		xprintf(")");
1213	    }
1214	}
1215	if (pp->p_flags & PPTIME && !(status & (PSTOPPED | PRUNNING))) {
1216	    if (linp != linbuf)
1217		xprintf("\n\t");
1218#if defined(BSDTIMES) || defined(_SEQUENT_)
1219	    prusage(&zru, &pp->p_rusage, &pp->p_etime,
1220		    &pp->p_btime);
1221#else /* !BSDTIMES && !SEQUENT */
1222	    lru.tms_utime = pp->p_utime;
1223	    lru.tms_stime = pp->p_stime;
1224	    lru.tms_cutime = 0;
1225	    lru.tms_cstime = 0;
1226	    prusage(&zru, &lru, pp->p_etime,
1227		    pp->p_btime);
1228#endif /* !BSDTIMES && !SEQUENT */
1229
1230	}
1231#ifdef BACKPIPE
1232	pcond = ((tp == pp->p_friends && !inpipe) ||
1233		 (inpipe && pipehead->p_friends == tp && pp == pipetail));
1234#else  /* !BACKPIPE */
1235	pcond = (tp == pp->p_friends);
1236#endif /* BACKPIPE */
1237	if (pcond) {
1238	    if (linp != linbuf)
1239		xputchar('\n');
1240	    if (flag & SHELLDIR && !eq(tp->p_cwd->di_name, dcwd->di_name)) {
1241		xprintf(CGETS(17, 11, "(wd now: "));
1242		dtildepr(dcwd->di_name);
1243		xprintf(")\n");
1244	    }
1245	}
1246#ifdef BACKPIPE
1247	if (inpipe) {
1248	    /*
1249	     * if pmaker == pipetail, we are finished that pipeline, and
1250	     * can now skip to past the head
1251	     */
1252	    if (pmarker == pipetail) {
1253		inpipe = 0;
1254		pp = pipehead;
1255	    }
1256	    else {
1257	    /*
1258	     * set pp to one before the one we want next, so the while below
1259	     * increments to the correct spot.
1260	     */
1261		do
1262		    pp = pp->p_friends;
1263	    	while (pp->p_friends->p_friends != pmarker);
1264	    	pmarker = pp->p_friends;
1265	    }
1266	}
1267	pcond = ((pp = pp->p_friends) != tp || inpipe);
1268#else /* !BACKPIPE */
1269	pcond = ((pp = pp->p_friends) != tp);
1270#endif /* BACKPIPE */
1271    } while (pcond);
1272
1273    if (jobflags & PTIME && (jobflags & (PSTOPPED | PRUNNING)) == 0) {
1274	if (jobflags & NUMBER)
1275	    xprintf("       ");
1276	ptprint(tp);
1277    }
1278    return (jobflags);
1279}
1280
1281/*
1282 * All 4.3 BSD derived implementations are buggy and I've had enough.
1283 * The following implementation produces similar code and works in all
1284 * cases. The 4.3BSD one works only for <, >, !=
1285 */
1286# undef timercmp
1287#  define timercmp(tvp, uvp, cmp) \
1288      (((tvp)->tv_sec == (uvp)->tv_sec) ? \
1289	   ((tvp)->tv_usec cmp (uvp)->tv_usec) : \
1290	   ((tvp)->tv_sec  cmp (uvp)->tv_sec))
1291
1292static void
1293ptprint(tp)
1294    register struct process *tp;
1295{
1296#ifdef BSDTIMES
1297    struct timeval tetime, diff;
1298    static struct timeval ztime;
1299    struct sysrusage ru;
1300    register struct process *pp = tp;
1301
1302    ru = zru;
1303    tetime = ztime;
1304    do {
1305	ruadd(&ru, &pp->p_rusage);
1306	tvsub(&diff, &pp->p_etime, &pp->p_btime);
1307	if (timercmp(&diff, &tetime, >))
1308	    tetime = diff;
1309    } while ((pp = pp->p_friends) != tp);
1310    prusage(&zru, &ru, &tetime, &ztime);
1311#else /* !BSDTIMES */
1312# ifdef _SEQUENT_
1313    timeval_t tetime, diff;
1314    static timeval_t ztime;
1315    struct process_stats ru;
1316    register struct process *pp = tp;
1317
1318    ru = zru;
1319    tetime = ztime;
1320    do {
1321	ruadd(&ru, &pp->p_rusage);
1322	tvsub(&diff, &pp->p_etime, &pp->p_btime);
1323	if (timercmp(&diff, &tetime, >))
1324	    tetime = diff;
1325    } while ((pp = pp->p_friends) != tp);
1326    prusage(&zru, &ru, &tetime, &ztime);
1327# else /* !_SEQUENT_ */
1328#  ifndef POSIX
1329    static time_t ztime = 0;
1330    static time_t zu_time = 0;
1331    static time_t zs_time = 0;
1332    time_t  tetime, diff;
1333    time_t  u_time, s_time;
1334
1335#  else	/* POSIX */
1336    static clock_t ztime = 0;
1337    static clock_t zu_time = 0;
1338    static clock_t zs_time = 0;
1339    clock_t tetime, diff;
1340    clock_t u_time, s_time;
1341
1342#  endif /* POSIX */
1343    struct tms zts, rts;
1344    register struct process *pp = tp;
1345
1346    u_time = zu_time;
1347    s_time = zs_time;
1348    tetime = ztime;
1349    do {
1350	u_time += pp->p_utime;
1351	s_time += pp->p_stime;
1352	diff = pp->p_etime - pp->p_btime;
1353	if (diff > tetime)
1354	    tetime = diff;
1355    } while ((pp = pp->p_friends) != tp);
1356    zts.tms_utime = zu_time;
1357    zts.tms_stime = zs_time;
1358    zts.tms_cutime = 0;
1359    zts.tms_cstime = 0;
1360    rts.tms_utime = u_time;
1361    rts.tms_stime = s_time;
1362    rts.tms_cutime = 0;
1363    rts.tms_cstime = 0;
1364    prusage(&zts, &rts, tetime, ztime);
1365# endif /* !_SEQUENT_ */
1366#endif	/* !BSDTIMES */
1367}
1368
1369/*
1370 * dojobs - print all jobs
1371 */
1372/*ARGSUSED*/
1373void
1374dojobs(v, c)
1375    Char  **v;
1376    struct command *c;
1377{
1378    register struct process *pp;
1379    register int flag = NUMBER | NAME | REASON;
1380    int     i;
1381
1382    USE(c);
1383    if (chkstop)
1384	chkstop = 2;
1385    if (*++v) {
1386	if (v[1] || !eq(*v, STRml))
1387	    stderror(ERR_JOBS);
1388	flag |= FANCY | JOBDIR;
1389    }
1390    for (i = 1; i <= pmaxindex; i++)
1391	for (pp = proclist.p_next; pp; pp = pp->p_next)
1392	    if (pp->p_index == i && pp->p_procid == pp->p_jobid) {
1393		pp->p_flags &= ~PNEEDNOTE;
1394		if (!(pprint(pp, flag) & (PRUNNING | PSTOPPED)))
1395		    pflush(pp);
1396		break;
1397	    }
1398}
1399
1400/*
1401 * dofg - builtin - put the job into the foreground
1402 */
1403/*ARGSUSED*/
1404void
1405dofg(v, c)
1406    Char  **v;
1407    struct command *c;
1408{
1409    register struct process *pp;
1410
1411    USE(c);
1412    okpcntl();
1413    ++v;
1414    do {
1415	pp = pfind(*v);
1416	if (!pstart(pp, 1)) {
1417	    pp->p_procid = 0;
1418	    stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1419	    continue;
1420	}
1421#ifndef BSDSIGS
1422# ifdef notdef
1423	if (setintr)
1424	    sigignore(SIGINT);
1425# endif
1426#endif /* !BSDSIGS */
1427	pjwait(pp);
1428    } while (*v && *++v);
1429}
1430
1431/*
1432 * %... - builtin - put the job into the foreground
1433 */
1434/*ARGSUSED*/
1435void
1436dofg1(v, c)
1437    Char  **v;
1438    struct command *c;
1439{
1440    register struct process *pp;
1441
1442    USE(c);
1443    okpcntl();
1444    pp = pfind(v[0]);
1445    if (!pstart(pp, 1)) {
1446	pp->p_procid = 0;
1447	stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1448	return;
1449    }
1450#ifndef BSDSIGS
1451# ifdef notdef
1452    if (setintr)
1453	sigignore(SIGINT);
1454# endif
1455#endif /* !BSDSIGS */
1456    pjwait(pp);
1457}
1458
1459/*
1460 * dobg - builtin - put the job into the background
1461 */
1462/*ARGSUSED*/
1463void
1464dobg(v, c)
1465    Char  **v;
1466    struct command *c;
1467{
1468    register struct process *pp;
1469
1470    USE(c);
1471    okpcntl();
1472    ++v;
1473    do {
1474	pp = pfind(*v);
1475	if (!pstart(pp, 0)) {
1476	    pp->p_procid = 0;
1477	    stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1478	}
1479    } while (*v && *++v);
1480}
1481
1482/*
1483 * %... & - builtin - put the job into the background
1484 */
1485/*ARGSUSED*/
1486void
1487dobg1(v, c)
1488    Char  **v;
1489    struct command *c;
1490{
1491    register struct process *pp;
1492
1493    USE(c);
1494    pp = pfind(v[0]);
1495    if (!pstart(pp, 0)) {
1496	pp->p_procid = 0;
1497	stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno));
1498    }
1499}
1500
1501/*
1502 * dostop - builtin - stop the job
1503 */
1504/*ARGSUSED*/
1505void
1506dostop(v, c)
1507    Char  **v;
1508    struct command *c;
1509{
1510    USE(c);
1511#ifdef BSDJOBS
1512    pkill(++v, SIGSTOP);
1513#endif /* BSDJOBS */
1514}
1515
1516/*
1517 * dokill - builtin - superset of kill (1)
1518 */
1519/*ARGSUSED*/
1520void
1521dokill(v, c)
1522    Char  **v;
1523    struct command *c;
1524{
1525    register int signum, len = 0;
1526    register char *name;
1527    extern int T_Cols;
1528    extern int nsig;
1529
1530    USE(c);
1531    v++;
1532    if (v[0] && v[0][0] == '-') {
1533	if (v[0][1] == 'l') {
1534	    for (signum = 0; signum <= nsig; signum++) {
1535		if ((name = mesg[signum].iname) != NULL) {
1536		    len += strlen(name) + 1;
1537		    if (len >= T_Cols - 1) {
1538			xputchar('\n');
1539			len = strlen(name) + 1;
1540		    }
1541		    xprintf("%s ", name);
1542		}
1543	    }
1544	    xputchar('\n');
1545	    return;
1546	}
1547	if (Isdigit(v[0][1])) {
1548	    signum = atoi(short2str(v[0] + 1));
1549	    if (signum < 0 || signum > (MAXSIG-1))
1550		stderror(ERR_NAME | ERR_BADSIG);
1551	}
1552	else {
1553	    for (signum = 0; signum <= nsig; signum++)
1554		if (mesg[signum].iname &&
1555		    eq(&v[0][1], str2short(mesg[signum].iname)))
1556		    goto gotsig;
1557	    setname(short2str(&v[0][1]));
1558	    stderror(ERR_NAME | ERR_UNKSIG);
1559	}
1560gotsig:
1561	v++;
1562    }
1563    else
1564	signum = SIGTERM;
1565    pkill(v, signum);
1566}
1567
1568static void
1569pkill(v, signum)
1570    Char  **v;
1571    int     signum;
1572{
1573    register struct process *pp, *np;
1574    int jobflags = 0, err1 = 0;
1575    pid_t     pid;
1576#ifdef BSDSIGS
1577    sigmask_t omask;
1578#endif /* BSDSIGS */
1579    Char   *cp, **vp;
1580
1581#ifdef BSDSIGS
1582    omask = sigmask(SIGCHLD);
1583    if (setintr)
1584	omask |= sigmask(SIGINT);
1585    omask = sigblock(omask) & ~omask;
1586#else /* !BSDSIGS */
1587    if (setintr)
1588	(void) sighold(SIGINT);
1589    (void) sighold(SIGCHLD);
1590#endif /* !BSDSIGS */
1591
1592    /* Avoid globbing %?x patterns */
1593    for (vp = v; vp && *vp; vp++)
1594	if (**vp == '%')
1595	    (void) quote(*vp);
1596
1597    gflag = 0, tglob(v);
1598    if (gflag) {
1599	v = globall(v);
1600	if (v == 0)
1601	    stderror(ERR_NAME | ERR_NOMATCH);
1602    }
1603    else {
1604	v = gargv = saveblk(v);
1605	trim(v);
1606    }
1607
1608
1609    while (v && (cp = *v)) {
1610	if (*cp == '%') {
1611	    np = pp = pfind(cp);
1612	    do
1613		jobflags |= np->p_flags;
1614	    while ((np = np->p_friends) != pp);
1615#ifdef BSDJOBS
1616	    switch (signum) {
1617
1618	    case SIGSTOP:
1619	    case SIGTSTP:
1620	    case SIGTTIN:
1621	    case SIGTTOU:
1622		if ((jobflags & PRUNNING) == 0) {
1623# ifdef SUSPENDED
1624		    xprintf(CGETS(17, 12, "%S: Already suspended\n"), cp);
1625# else /* !SUSPENDED */
1626		    xprintf(CGETS(17, 13, "%S: Already stopped\n"), cp);
1627# endif /* !SUSPENDED */
1628		    err1++;
1629		    goto cont;
1630		}
1631		break;
1632		/*
1633		 * suspend a process, kill -CONT %, then type jobs; the shell
1634		 * says it is suspended, but it is running; thanks jaap..
1635		 */
1636	    case SIGCONT:
1637		if (!pstart(pp, 0)) {
1638		    pp->p_procid = 0;
1639		    stderror(ERR_NAME|ERR_BADJOB, pp->p_command,
1640			     strerror(errno));
1641		}
1642		goto cont;
1643	    default:
1644		break;
1645	    }
1646#endif /* BSDJOBS */
1647	    if (killpg(pp->p_jobid, signum) < 0) {
1648		xprintf("%S: %s\n", cp, strerror(errno));
1649		err1++;
1650	    }
1651#ifdef BSDJOBS
1652	    if (signum == SIGTERM || signum == SIGHUP)
1653		(void) killpg(pp->p_jobid, SIGCONT);
1654#endif /* BSDJOBS */
1655	}
1656	else if (!(Isdigit(*cp) || *cp == '-'))
1657	    stderror(ERR_NAME | ERR_JOBARGS);
1658	else {
1659#ifndef WINNT
1660	    pid = atoi(short2str(cp));
1661#else
1662		pid = strtoul(short2str(cp),NULL,0);
1663#endif /* WINNT */
1664	    if (kill(pid, signum) < 0) {
1665		xprintf("%d: %s\n", pid, strerror(errno));
1666		err1++;
1667		goto cont;
1668	    }
1669#ifdef BSDJOBS
1670	    if (signum == SIGTERM || signum == SIGHUP)
1671		(void) kill(pid, SIGCONT);
1672#endif /* BSDJOBS */
1673	}
1674cont:
1675	v++;
1676    }
1677    if (gargv)
1678	blkfree(gargv), gargv = 0;
1679#ifdef BSDSIGS
1680    (void) sigsetmask(omask);
1681#else /* !BSDSIGS */
1682    (void) sigrelse(SIGCHLD);
1683    if (setintr)
1684	(void) sigrelse(SIGINT);
1685#endif /* !BSDSIGS */
1686    if (err1)
1687	stderror(ERR_SILENT);
1688}
1689
1690/*
1691 * pstart - start the job in foreground/background
1692 */
1693int
1694pstart(pp, foregnd)
1695    register struct process *pp;
1696    int     foregnd;
1697{
1698    int rv = 0;
1699    register struct process *np;
1700#ifdef BSDSIGS
1701    sigmask_t omask;
1702#endif /* BSDSIGS */
1703    /* We don't use jobflags in this function right now (see below) */
1704    /* long    jobflags = 0; */
1705
1706#ifdef BSDSIGS
1707    omask = sigblock(sigmask(SIGCHLD));
1708#else /* !BSDSIGS */
1709    (void) sighold(SIGCHLD);
1710#endif
1711    np = pp;
1712    do {
1713	/* We don't use jobflags in this function right now (see below) */
1714	/* jobflags |= np->p_flags; */
1715	if (np->p_flags & (PRUNNING | PSTOPPED)) {
1716	    np->p_flags |= PRUNNING;
1717	    np->p_flags &= ~PSTOPPED;
1718	    if (foregnd)
1719		np->p_flags |= PFOREGND;
1720	    else
1721		np->p_flags &= ~PFOREGND;
1722	}
1723    } while ((np = np->p_friends) != pp);
1724    if (!foregnd)
1725	pclrcurr(pp);
1726    (void) pprint(pp, foregnd ? NAME | JOBDIR : NUMBER | NAME | AMPERSAND);
1727#ifdef BSDJOBS
1728    if (foregnd) {
1729	rv = tcsetpgrp(FSHTTY, pp->p_jobid);
1730    }
1731    /*
1732     * 1. child process of csh (shell script) receives SIGTTIN/SIGTTOU
1733     * 2. parent process (csh) receives SIGCHLD
1734     * 3. The "csh" signal handling function pchild() is invoked
1735     *    with a SIGCHLD signal.
1736     * 4. pchild() calls wait3(WNOHANG) which returns 0.
1737     *    The child process is NOT ready to be waited for at this time.
1738     *    pchild() returns without picking-up the correct status
1739     *    for the child process which generated the SIGCHILD.
1740     * 5. CONSEQUENCE : csh is UNaware that the process is stopped
1741     * 6. THIS LINE HAS BEEN COMMENTED OUT : if (jobflags&PSTOPPED)
1742     * 	  (beto@aixwiz.austin.ibm.com - aug/03/91)
1743     * 7. I removed the line completely and added extra checks for
1744     *    pstart, so that if a job gets attached to and dies inside
1745     *    a debugger it does not confuse the shell. [christos]
1746     * 8. on the nec sx-4 there seems to be a problem, which requires
1747     *    a syscall(151, getpid(), getpid()) in osinit. Don't ask me
1748     *    what this is doing. [schott@rzg.mpg.de]
1749     */
1750
1751    if (rv != -1)
1752	rv = killpg(pp->p_jobid, SIGCONT);
1753#endif /* BSDJOBS */
1754#ifdef BSDSIGS
1755    (void) sigsetmask(omask);
1756#else /* !BSDSIGS */
1757    (void) sigrelse(SIGCHLD);
1758#endif /* !BSDSIGS */
1759    return rv != -1;
1760}
1761
1762void
1763panystop(neednl)
1764    bool    neednl;
1765{
1766    register struct process *pp;
1767
1768    chkstop = 2;
1769    for (pp = proclist.p_next; pp; pp = pp->p_next)
1770	if (pp->p_flags & PSTOPPED)
1771	    stderror(ERR_STOPPED, neednl ? "\n" : "");
1772}
1773
1774struct process *
1775pfind(cp)
1776    Char   *cp;
1777{
1778    register struct process *pp, *np;
1779
1780    if (cp == 0 || cp[1] == 0 || eq(cp, STRcent2) || eq(cp, STRcentplus)) {
1781	if (pcurrent == NULL)
1782	    stderror(ERR_NAME | ERR_JOBCUR);
1783	return (pcurrent);
1784    }
1785    if (eq(cp, STRcentminus) || eq(cp, STRcenthash)) {
1786	if (pprevious == NULL)
1787	    stderror(ERR_NAME | ERR_JOBPREV);
1788	return (pprevious);
1789    }
1790    if (Isdigit(cp[1])) {
1791	int     idx = atoi(short2str(cp + 1));
1792
1793	for (pp = proclist.p_next; pp; pp = pp->p_next)
1794	    if (pp->p_index == idx && pp->p_procid == pp->p_jobid)
1795		return (pp);
1796	stderror(ERR_NAME | ERR_NOSUCHJOB);
1797    }
1798    np = NULL;
1799    for (pp = proclist.p_next; pp; pp = pp->p_next)
1800	if (pp->p_procid == pp->p_jobid) {
1801	    if (cp[1] == '?') {
1802		register Char *dp;
1803
1804		for (dp = pp->p_command; *dp; dp++) {
1805		    if (*dp != cp[2])
1806			continue;
1807		    if (prefix(cp + 2, dp))
1808			goto match;
1809		}
1810	    }
1811	    else if (prefix(cp + 1, pp->p_command)) {
1812	match:
1813		if (np)
1814		    stderror(ERR_NAME | ERR_AMBIG);
1815		np = pp;
1816	    }
1817	}
1818    if (np)
1819	return (np);
1820    stderror(ERR_NAME | (cp[1] == '?' ? ERR_JOBPAT : ERR_NOSUCHJOB));
1821    /* NOTREACHED */
1822    return (0);
1823}
1824
1825
1826/*
1827 * pgetcurr - find most recent job that is not pp, preferably stopped
1828 */
1829static struct process *
1830pgetcurr(pp)
1831    register struct process *pp;
1832{
1833    register struct process *np;
1834    register struct process *xp = NULL;
1835
1836    for (np = proclist.p_next; np; np = np->p_next)
1837	if (np != pcurrent && np != pp && np->p_procid &&
1838	    np->p_procid == np->p_jobid) {
1839	    if (np->p_flags & PSTOPPED)
1840		return (np);
1841	    if (xp == NULL)
1842		xp = np;
1843	}
1844    return (xp);
1845}
1846
1847/*
1848 * donotify - flag the job so as to report termination asynchronously
1849 */
1850/*ARGSUSED*/
1851void
1852donotify(v, c)
1853    Char  **v;
1854    struct command *c;
1855{
1856    register struct process *pp;
1857
1858    USE(c);
1859    pp = pfind(*++v);
1860    pp->p_flags |= PNOTIFY;
1861}
1862
1863/*
1864 * Do the fork and whatever should be done in the child side that
1865 * should not be done if we are not forking at all (like for simple builtin's)
1866 * Also do everything that needs any signals fiddled with in the parent side
1867 *
1868 * Wanttty tells whether process and/or tty pgrps are to be manipulated:
1869 *	-1:	leave tty alone; inherit pgrp from parent
1870 *	 0:	already have tty; manipulate process pgrps only
1871 *	 1:	want to claim tty; manipulate process and tty pgrps
1872 * It is usually just the value of tpgrp.
1873 */
1874
1875int
1876pfork(t, wanttty)
1877    struct command *t;		/* command we are forking for */
1878    int     wanttty;
1879{
1880    register int pid;
1881    bool    ignint = 0;
1882    int     pgrp;
1883#ifdef BSDSIGS
1884    sigmask_t omask = 0;
1885#endif /* BSDSIGS */
1886#ifdef SIGSYNCH
1887    sigvec_t osv;
1888    static sigvec_t nsv = {synch_handler, (sigset_t) ~0, 0};
1889#endif /* SIGSYNCH */
1890
1891    /*
1892     * A child will be uninterruptible only under very special conditions.
1893     * Remember that the semantics of '&' is implemented by disconnecting the
1894     * process from the tty so signals do not need to ignored just for '&'.
1895     * Thus signals are set to default action for children unless: we have had
1896     * an "onintr -" (then specifically ignored) we are not playing with
1897     * signals (inherit action)
1898     */
1899    if (setintr)
1900	ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT))
1901	    || (gointr && eq(gointr, STRminus));
1902
1903#ifdef COHERENT
1904    ignint |= gointr && eq(gointr, STRminus);
1905#endif /* COHERENT */
1906
1907    /*
1908     * Check for maximum nesting of 16 processes to avoid Forking loops
1909     */
1910    if (child == 16)
1911	stderror(ERR_NESTING, 16);
1912#ifdef SIGSYNCH
1913    if (mysigvec(SIGSYNCH, &nsv, &osv))
1914	stderror(ERR_SYSTEM, "pfork: sigvec set", strerror(errno));
1915#endif /* SIGSYNCH */
1916    /*
1917     * Hold SIGCHLD until we have the process installed in our table.
1918     */
1919    if (wanttty < 0) {
1920#ifdef BSDSIGS
1921	omask = sigblock(sigmask(SIGCHLD));
1922#else /* !BSDSIGS */
1923	(void) sighold(SIGCHLD);
1924#endif /* !BSDSIGS */
1925    }
1926    while ((pid = fork()) == -1)
1927	if (setintr == 0)
1928	    (void) sleep(FORKSLEEP);
1929	else {
1930	    if (wanttty < 0)
1931#ifdef BSDSIGS
1932		(void) sigsetmask(omask);
1933#else /* !BSDSIGS */
1934		(void) sigrelse(SIGCHLD);
1935	    (void) sigrelse(SIGINT);
1936#endif /* !BSDSIGS */
1937	    stderror(ERR_NOPROC);
1938	}
1939    if (pid == 0) {
1940	settimes();
1941	pgrp = pcurrjob ? pcurrjob->p_jobid : getpid();
1942	pflushall();
1943	pcurrjob = NULL;
1944#if !defined(BSDTIMES) && !defined(_SEQUENT_)
1945	timesdone = 0;
1946#endif /* !defined(BSDTIMES) && !defined(_SEQUENT_) */
1947	child++;
1948	if (setintr) {
1949	    setintr = 0;	/* until I think otherwise */
1950#ifndef BSDSIGS
1951	    if (wanttty < 0)
1952		(void) sigrelse(SIGCHLD);
1953#endif /* !BSDSIGS */
1954	    /*
1955	     * Children just get blown away on SIGINT, SIGQUIT unless "onintr
1956	     * -" seen.
1957	     */
1958	    (void) signal(SIGINT, ignint ? SIG_IGN : SIG_DFL);
1959	    (void) signal(SIGQUIT, ignint ? SIG_IGN : SIG_DFL);
1960#ifdef BSDJOBS
1961	    if (wanttty >= 0) {
1962		/* make stoppable */
1963		(void) signal(SIGTSTP, SIG_DFL);
1964		(void) signal(SIGTTIN, SIG_DFL);
1965		(void) signal(SIGTTOU, SIG_DFL);
1966	    }
1967#endif /* BSDJOBS */
1968	    (void) signal(SIGTERM, parterm);
1969	}
1970	else if (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) {
1971	    (void) signal(SIGINT, SIG_IGN);
1972	    (void) signal(SIGQUIT, SIG_IGN);
1973	}
1974#ifdef OREO
1975	sigignore(SIGIO);	/* ignore SIGIO in child too */
1976#endif /* OREO */
1977
1978	pgetty(wanttty, pgrp);
1979	/*
1980	 * Nohup and nice apply only to NODE_COMMAND's but it would be nice
1981	 * (?!?) if you could say "nohup (foo;bar)" Then the parser would have
1982	 * to know about nice/nohup/time
1983	 */
1984	if (t->t_dflg & F_NOHUP)
1985	    (void) signal(SIGHUP, SIG_IGN);
1986	if (t->t_dflg & F_NICE) {
1987	    int nval = SIGN_EXTEND_CHAR(t->t_nice);
1988#ifdef BSDNICE
1989	    (void) setpriority(PRIO_PROCESS, 0, nval);
1990#else /* !BSDNICE */
1991	    (void) nice(nval);
1992#endif /* !BSDNICE */
1993	}
1994#ifdef F_VER
1995        if (t->t_dflg & F_VER) {
1996	    tsetenv(STRSYSTYPE, t->t_systype ? STRbsd43 : STRsys53);
1997	    dohash(NULL, NULL);
1998	}
1999#endif /* F_VER */
2000#ifdef SIGSYNCH
2001	/* rfw 8/89 now parent can continue */
2002	if (kill(getppid(), SIGSYNCH))
2003	    stderror(ERR_SYSTEM, "pfork child: kill", strerror(errno));
2004#endif /* SIGSYNCH */
2005
2006    }
2007    else {
2008#ifdef POSIXJOBS
2009        if (wanttty >= 0) {
2010	    /*
2011	     * `Walking' process group fix from Beto Appleton.
2012	     * (beto@aixwiz.austin.ibm.com)
2013	     * If setpgid fails at this point that means that
2014	     * our process leader has died. We flush the current
2015	     * job and become the process leader ourselves.
2016	     * The parent will figure that out later.
2017	     */
2018	    pgrp = pcurrjob ? pcurrjob->p_jobid : pid;
2019	    if (setpgid(pid, pgrp) == -1 && errno == EPERM) {
2020		pcurrjob = NULL;
2021		/*
2022		 * We don't care if this causes an error here;
2023		 * then we are already in the right process group
2024		 */
2025		(void) setpgid(pid, pgrp = pid);
2026	    }
2027	}
2028#endif /* POSIXJOBS */
2029	palloc(pid, t);
2030#ifdef SIGSYNCH
2031	/*
2032	 * rfw 8/89 Wait for child to own terminal.  Solves half of ugly
2033	 * synchronization problem.  With this change, we know that the only
2034	 * reason setpgrp to a previous process in a pipeline can fail is that
2035	 * the previous process has already exited. Without this hack, he may
2036	 * either have exited or not yet started to run.  Two uglies become
2037	 * one.
2038	 */
2039	(void) sigpause(omask & ~SYNCHMASK);
2040	if (mysigvec(SIGSYNCH, &osv, NULL))
2041	    stderror(ERR_SYSTEM, "pfork parent: sigvec restore",
2042		     strerror(errno));
2043#endif /* SIGSYNCH */
2044
2045	if (wanttty < 0) {
2046#ifdef BSDSIGS
2047	    (void) sigsetmask(omask);
2048#else /* !BSDSIGS */
2049	    (void) sigrelse(SIGCHLD);
2050#endif /* !BSDSIGS */
2051	}
2052    }
2053    return (pid);
2054}
2055
2056static void
2057okpcntl()
2058{
2059    if (tpgrp == -1)
2060	stderror(ERR_JOBCONTROL);
2061    if (tpgrp == 0)
2062	stderror(ERR_JOBCTRLSUB);
2063}
2064
2065
2066static void
2067setttypgrp(pgrp)
2068    int pgrp;
2069{
2070    /*
2071     * If we are piping out a builtin, eg. 'echo | more' things can go
2072     * out of sequence, i.e. the more can run before the echo. This
2073     * can happen even if we have vfork, since the echo will be forked
2074     * with the regular fork. In this case, we need to set the tty
2075     * pgrp ourselves. If that happens, then the process will be still
2076     * alive. And the tty process group will already be set.
2077     * This should fix the famous sequent problem as a side effect:
2078     *    The controlling terminal is lost if all processes in the
2079     *    terminal process group are zombies. In this case tcgetpgrp()
2080     *    returns 0. If this happens we must set the terminal process
2081     *    group again.
2082     */
2083    if (tcgetpgrp(FSHTTY) != pgrp) {
2084#ifdef POSIXJOBS
2085        /*
2086	 * tcsetpgrp will set SIGTTOU to all the the processes in
2087	 * the background according to POSIX... We ignore this here.
2088	 */
2089	signalfun_t old = sigset(SIGTTOU, SIG_IGN);
2090#endif
2091	(void) tcsetpgrp(FSHTTY, pgrp);
2092# ifdef POSIXJOBS
2093	(void) sigset(SIGTTOU, old);
2094# endif
2095
2096    }
2097}
2098
2099
2100/*
2101 * if we don't have vfork(), things can still go in the wrong order
2102 * resulting in the famous 'Stopped (tty output)'. But some systems
2103 * don't permit the setpgid() call, (these are more recent secure
2104 * systems such as ibm's aix), when they do. Then we'd rather print
2105 * an error message than hang the shell!
2106 * I am open to suggestions how to fix that.
2107 */
2108void
2109pgetty(wanttty, pgrp)
2110    int     wanttty, pgrp;
2111{
2112#ifdef BSDJOBS
2113# if defined(BSDSIGS) && defined(POSIXJOBS)
2114    sigmask_t omask = 0;
2115# endif /* BSDSIGS && POSIXJOBS */
2116
2117# ifdef JOBDEBUG
2118    xprintf("wanttty %d pid %d opgrp%d pgrp %d tpgrp %d\n",
2119	    wanttty, getpid(), pgrp, mygetpgrp(), tcgetpgrp(FSHTTY));
2120# endif /* JOBDEBUG */
2121# ifdef POSIXJOBS
2122    /*
2123     * christos: I am blocking the tty signals till I've set things
2124     * correctly....
2125     */
2126    if (wanttty > 0)
2127#  ifdef BSDSIGS
2128	omask = sigblock(sigmask(SIGTSTP)|sigmask(SIGTTIN));
2129#  else /* !BSDSIGS */
2130    {
2131	(void) sighold(SIGTSTP);
2132	(void) sighold(SIGTTIN);
2133    }
2134#  endif /* !BSDSIGS */
2135# endif /* POSIXJOBS */
2136
2137# ifndef POSIXJOBS
2138    if (wanttty > 0)
2139	setttypgrp(pgrp);
2140# endif /* !POSIXJOBS */
2141
2142    /*
2143     * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
2144     * Don't check for tpgrp >= 0 so even non-interactive shells give
2145     * background jobs process groups Same for the comparison in the other part
2146     * of the #ifdef
2147     */
2148    if (wanttty >= 0) {
2149	if (setpgid(0, pgrp) == -1) {
2150# ifdef POSIXJOBS
2151	    /* Walking process group fix; see above */
2152	    if (setpgid(0, pgrp = getpid()) == -1) {
2153# endif /* POSIXJOBS */
2154		stderror(ERR_SYSTEM, "setpgid child:\n", strerror(errno));
2155		xexit(0);
2156# ifdef POSIXJOBS
2157	    }
2158	    wanttty = pgrp;  /* Now we really want the tty, since we became the
2159			      * the process group leader
2160			      */
2161# endif /* POSIXJOBS */
2162	}
2163    }
2164
2165# ifdef POSIXJOBS
2166    if (wanttty > 0)
2167	setttypgrp(pgrp);
2168#  ifdef BSDSIGS
2169    (void) sigsetmask(omask);
2170#  else /* BSDSIGS */
2171    (void) sigrelse(SIGTSTP);
2172    (void) sigrelse(SIGTTIN);
2173#  endif /* !BSDSIGS */
2174# endif /* POSIXJOBS */
2175
2176# ifdef JOBDEBUG
2177    xprintf("wanttty %d pid %d pgrp %d tpgrp %d\n",
2178	    wanttty, getpid(), mygetpgrp(), tcgetpgrp(FSHTTY));
2179# endif /* JOBDEBUG */
2180
2181    if (tpgrp > 0)
2182	tpgrp = 0;		/* gave tty away */
2183#endif /* BSDJOBS */
2184}
2185