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