xref: /openbsd-src/bin/csh/proc.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: proc.c,v 1.23 2014/07/14 05:53:29 guenther Exp $	*/
2 /*	$NetBSD: proc.c,v 1.9 1995/04/29 23:21:33 mycroft Exp $	*/
3 
4 /*-
5  * Copyright (c) 1980, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <stdarg.h>
40 
41 #include "csh.h"
42 #include "dir.h"
43 #include "proc.h"
44 #include "extern.h"
45 
46 #define BIGINDEX	9	/* largest desirable job index */
47 
48 static struct rusage zru;
49 
50 static void	 pflushall(void);
51 static void	 pflush(struct process *);
52 static void	 pclrcurr(struct process *);
53 static void	 padd(struct command *);
54 static int	 pprint(struct process *, int);
55 static void	 ptprint(struct process *);
56 static void	 pads(Char *);
57 static void	 pkill(Char **v, int);
58 static struct	process
59 		*pgetcurr(struct process *);
60 static void	 okpcntl(void);
61 
62 /*
63  * pchild - called at interrupt level by the SIGCHLD signal
64  *	indicating that at least one child has terminated or stopped
65  *	thus at least one wait system call will definitely return a
66  *	childs status.  Top level routines (like pwait) must be sure
67  *	to mask interrupts when playing with the proclist data structures!
68  */
69 /* ARGUSED */
70 void
71 pchild(int notused)
72 {
73     struct process *pp;
74     struct process *fp;
75     int pid;
76     extern int insource;
77     int save_errno = errno;
78     int w;
79     int     jobflags;
80     struct rusage ru;
81 
82 loop:
83     errno = 0;			/* reset, just in case */
84     pid = wait3(&w,
85        (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru);
86 
87     if (pid <= 0) {
88 	if (errno == EINTR) {
89 	    errno = 0;
90 	    goto loop;
91 	}
92 	pnoprocesses = pid == -1;
93 	errno = save_errno;
94 	return;
95     }
96     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
97 	if (pid == pp->p_pid)
98 	    goto found;
99     goto loop;
100 found:
101     if (pid == atoi(short2str(value(STRchild))))
102 	unsetv(STRchild);
103     pp->p_flags &= ~(PRUNNING | PSTOPPED | PREPORTED);
104     if (WIFSTOPPED(w)) {
105 	pp->p_flags |= PSTOPPED;
106 	pp->p_reason = WSTOPSIG(w);
107     }
108     else {
109 	if (pp->p_flags & (PTIME | PPTIME) || adrof(STRtime))
110 	    (void) gettimeofday(&pp->p_etime, NULL);
111 
112 	pp->p_rusage = ru;
113 	if (WIFSIGNALED(w)) {
114 	    if (WTERMSIG(w) == SIGINT)
115 		pp->p_flags |= PINTERRUPTED;
116 	    else
117 		pp->p_flags |= PSIGNALED;
118 	    if (WCOREDUMP(w))
119 		pp->p_flags |= PDUMPED;
120 	    pp->p_reason = WTERMSIG(w);
121 	}
122 	else {
123 	    pp->p_reason = WEXITSTATUS(w);
124 	    if (pp->p_reason != 0)
125 		pp->p_flags |= PAEXITED;
126 	    else
127 		pp->p_flags |= PNEXITED;
128 	}
129     }
130     jobflags = 0;
131     fp = pp;
132     do {
133 	if ((fp->p_flags & (PPTIME | PRUNNING | PSTOPPED)) == 0 &&
134 	    !child && adrof(STRtime) &&
135 	    fp->p_rusage.ru_utime.tv_sec + fp->p_rusage.ru_stime.tv_sec
136 	    >= atoi(short2str(value(STRtime))))
137 	    fp->p_flags |= PTIME;
138 	jobflags |= fp->p_flags;
139     } while ((fp = fp->p_friends) != pp);
140     pp->p_flags &= ~PFOREGND;
141     if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
142 	pp->p_flags &= ~PPTIME;
143 	pp->p_flags |= PTIME;
144     }
145     if ((jobflags & (PRUNNING | PREPORTED)) == 0) {
146 	fp = pp;
147 	do {
148 	    if (fp->p_flags & PSTOPPED)
149 		fp->p_flags |= PREPORTED;
150 	} while ((fp = fp->p_friends) != pp);
151 	while (fp->p_pid != fp->p_jobid)
152 	    fp = fp->p_friends;
153 	if (jobflags & PSTOPPED) {
154 	    if (pcurrent && pcurrent != fp)
155 		pprevious = pcurrent;
156 	    pcurrent = fp;
157 	}
158 	else
159 	    pclrcurr(fp);
160 	if (jobflags & PFOREGND) {
161 	    if (jobflags & (PSIGNALED | PSTOPPED | PPTIME) ||
162 #ifdef IIASA
163 		jobflags & PAEXITED ||
164 #endif
165 		!eq(dcwd->di_name, fp->p_cwd->di_name)) {
166 		;		/* print in pjwait */
167 	    }
168 	    /* PWP: print a newline after ^C */
169 	    else if (jobflags & PINTERRUPTED) {
170 		(void) vis_fputc('\r' | QUOTE, cshout);
171 		(void) fputc('\n', cshout);
172 	    }
173 	}
174 	else {
175 	    if (jobflags & PNOTIFY || adrof(STRnotify)) {
176 		(void) vis_fputc('\r' | QUOTE, cshout);
177 		(void) fputc('\n', cshout);
178 		(void) pprint(pp, NUMBER | NAME | REASON);
179 		if ((jobflags & PSTOPPED) == 0)
180 		    pflush(pp);
181 	    }
182 	    else {
183 		fp->p_flags |= PNEEDNOTE;
184 		neednote++;
185 	    }
186 	}
187     }
188     goto loop;
189 }
190 
191 void
192 pnote(void)
193 {
194     struct process *pp;
195     int     flags;
196     sigset_t sigset, osigset;
197 
198     neednote = 0;
199     sigemptyset(&sigset);
200     sigaddset(&sigset, SIGCHLD);
201     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next) {
202 	if (pp->p_flags & PNEEDNOTE) {
203 	    sigprocmask(SIG_BLOCK, &sigset, &osigset);
204 	    pp->p_flags &= ~PNEEDNOTE;
205 	    flags = pprint(pp, NUMBER | NAME | REASON);
206 	    if ((flags & (PRUNNING | PSTOPPED)) == 0)
207 		pflush(pp);
208 	    sigprocmask(SIG_SETMASK, &osigset, NULL);
209 	}
210     }
211 }
212 
213 /*
214  * pwait - wait for current job to terminate, maintaining integrity
215  *	of current and previous job indicators.
216  */
217 void
218 pwait(void)
219 {
220     struct process *fp, *pp;
221     sigset_t sigset, osigset;
222 
223     /*
224      * Here's where dead procs get flushed.
225      */
226     sigemptyset(&sigset);
227     sigaddset(&sigset, SIGCHLD);
228     sigprocmask(SIG_BLOCK, &sigset, &osigset);
229     for (pp = (fp = &proclist)->p_next; pp != NULL; pp = (fp = pp)->p_next)
230 	if (pp->p_pid == 0) {
231 	    fp->p_next = pp->p_next;
232 	    xfree((ptr_t) pp->p_command);
233 	    if (pp->p_cwd && --pp->p_cwd->di_count == 0)
234 		if (pp->p_cwd->di_next == 0)
235 		    dfree(pp->p_cwd);
236 	    xfree((ptr_t) pp);
237 	    pp = fp;
238 	}
239     sigprocmask(SIG_SETMASK, &osigset, NULL);
240     pjwait(pcurrjob);
241 }
242 
243 
244 /*
245  * pjwait - wait for a job to finish or become stopped
246  *	It is assumed to be in the foreground state (PFOREGND)
247  */
248 void
249 pjwait(struct process *pp)
250 {
251     struct process *fp;
252     int     jobflags, reason;
253     sigset_t sigset, osigset;
254 
255     while (pp->p_pid != pp->p_jobid)
256 	pp = pp->p_friends;
257     fp = pp;
258 
259     do {
260 	if ((fp->p_flags & (PFOREGND | PRUNNING)) == PRUNNING)
261 	    (void) fprintf(csherr, "BUG: waiting for background job!\n");
262     } while ((fp = fp->p_friends) != pp);
263     /*
264      * Now keep pausing as long as we are not interrupted (SIGINT), and the
265      * target process, or any of its friends, are running
266      */
267     fp = pp;
268     sigemptyset(&sigset);
269     sigaddset(&sigset, SIGCHLD);
270     sigprocmask(SIG_BLOCK, &sigset, &osigset);
271     for (;;) {
272 	sigemptyset(&sigset);
273 	sigaddset(&sigset, SIGCHLD);
274 	sigprocmask(SIG_BLOCK, &sigset, NULL);
275 	jobflags = 0;
276 	do
277 	    jobflags |= fp->p_flags;
278 	while ((fp = (fp->p_friends)) != pp);
279 	if ((jobflags & PRUNNING) == 0)
280 	    break;
281 #ifdef JOBDEBUG
282 	(void) fprintf(csherr, "starting to sigsuspend for  SIGCHLD on %d\n",
283 		       fp->p_pid);
284 #endif				/* JOBDEBUG */
285 	sigset = osigset;
286 	sigdelset(&sigset, SIGCHLD);
287 	sigsuspend(&sigset);
288     }
289     sigprocmask(SIG_SETMASK, &osigset, NULL);
290     if (tpgrp > 0)		/* get tty back */
291 	(void) tcsetpgrp(FSHTTY, tpgrp);
292     if ((jobflags & (PSIGNALED | PSTOPPED | PTIME)) ||
293 	!eq(dcwd->di_name, fp->p_cwd->di_name)) {
294 	if (jobflags & PSTOPPED) {
295 	    (void) fputc('\n', cshout);
296 	    if (adrof(STRlistjobs)) {
297 		Char   *jobcommand[3];
298 
299 		jobcommand[0] = STRjobs;
300 		if (eq(value(STRlistjobs), STRlong))
301 		    jobcommand[1] = STRml;
302 		else
303 		    jobcommand[1] = NULL;
304 		jobcommand[2] = NULL;
305 
306 		dojobs(jobcommand, NULL);
307 		(void) pprint(pp, SHELLDIR);
308 	    }
309 	    else
310 		(void) pprint(pp, AREASON | SHELLDIR);
311 	}
312 	else
313 	    (void) pprint(pp, AREASON | SHELLDIR);
314     }
315     if ((jobflags & (PINTERRUPTED | PSTOPPED)) && setintr &&
316 	(!gointr || !eq(gointr, STRminus))) {
317 	if ((jobflags & PSTOPPED) == 0)
318 	    pflush(pp);
319 	pintr1(0);
320 	/* NOTREACHED */
321     }
322     reason = 0;
323     fp = pp;
324     do {
325 	if (fp->p_reason)
326 	    reason = fp->p_flags & (PSIGNALED | PINTERRUPTED) ?
327 		fp->p_reason | META : fp->p_reason;
328     } while ((fp = fp->p_friends) != pp);
329     if ((reason != 0) && (adrof(STRprintexitvalue))) {
330 	(void) fprintf(cshout, "Exit %d\n", reason);
331     }
332     set(STRstatus, putn(reason));
333     if (reason && exiterr)
334 	exitstat();
335     pflush(pp);
336 }
337 
338 /*
339  * dowait - wait for all processes to finish
340  */
341 void
342 /*ARGSUSED*/
343 dowait(Char **v, struct command *t)
344 {
345     struct process *pp;
346     sigset_t sigset, osigset;
347 
348     pjobs++;
349     sigemptyset(&sigset);
350     sigaddset(&sigset, SIGCHLD);
351     sigprocmask(SIG_BLOCK, &sigset, &osigset);
352 loop:
353     for (pp = proclist.p_next; pp; pp = pp->p_next)
354 	if (pp->p_pid &&	/* pp->p_pid == pp->p_jobid && */
355 	    pp->p_flags & PRUNNING) {
356 	    sigemptyset(&sigset);
357 	    sigsuspend(&sigset);
358 	    goto loop;
359 	}
360     sigprocmask(SIG_SETMASK, &osigset, NULL);
361     pjobs = 0;
362 }
363 
364 /*
365  * pflushall - flush all jobs from list (e.g. at fork())
366  */
367 static void
368 pflushall(void)
369 {
370     struct process *pp;
371 
372     for (pp = proclist.p_next; pp != NULL; pp = pp->p_next)
373 	if (pp->p_pid)
374 	    pflush(pp);
375 }
376 
377 /*
378  * pflush - flag all process structures in the same job as the
379  *	the argument process for deletion.  The actual free of the
380  *	space is not done here since pflush is called at interrupt level.
381  */
382 static void
383 pflush(struct process *pp)
384 {
385     struct process *np;
386     int idx;
387 
388     if (pp->p_pid == 0) {
389 	(void) fprintf(csherr, "BUG: process flushed twice");
390 	return;
391     }
392     while (pp->p_pid != pp->p_jobid)
393 	pp = pp->p_friends;
394     pclrcurr(pp);
395     if (pp == pcurrjob)
396 	pcurrjob = 0;
397     idx = pp->p_index;
398     np = pp;
399     do {
400 	np->p_index = np->p_pid = 0;
401 	np->p_flags &= ~PNEEDNOTE;
402     } while ((np = np->p_friends) != pp);
403     if (idx == pmaxindex) {
404 	for (np = proclist.p_next, idx = 0; np; np = np->p_next)
405 	    if (np->p_index > idx)
406 		idx = np->p_index;
407 	pmaxindex = idx;
408     }
409 }
410 
411 /*
412  * pclrcurr - make sure the given job is not the current or previous job;
413  *	pp MUST be the job leader
414  */
415 static void
416 pclrcurr(struct process *pp)
417 {
418 
419     if (pp == pcurrent)
420 	if (pprevious != NULL) {
421 	    pcurrent = pprevious;
422 	    pprevious = pgetcurr(pp);
423 	}
424 	else {
425 	    pcurrent = pgetcurr(pp);
426 	    pprevious = pgetcurr(pp);
427 	}
428     else if (pp == pprevious)
429 	pprevious = pgetcurr(pp);
430 }
431 
432 /* +4 here is 1 for '\0', 1 ea for << >& >> */
433 static Char command[PMAXLEN + 4];
434 static int cmdlen;
435 static Char *cmdp;
436 
437 /*
438  * palloc - allocate a process structure and fill it up.
439  *	an important assumption is made that the process is running.
440  */
441 void
442 palloc(int pid, struct command *t)
443 {
444     struct process *pp;
445     int     i;
446 
447     pp = (struct process *) xcalloc(1, (size_t) sizeof(struct process));
448     pp->p_pid = pid;
449     pp->p_flags = t->t_dflg & F_AMPERSAND ? PRUNNING : PRUNNING | PFOREGND;
450     if (t->t_dflg & F_TIME)
451 	pp->p_flags |= PPTIME;
452     cmdp = command;
453     cmdlen = 0;
454     padd(t);
455     *cmdp++ = 0;
456     if (t->t_dflg & F_PIPEOUT) {
457 	pp->p_flags |= PPOU;
458 	if (t->t_dflg & F_STDERR)
459 	    pp->p_flags |= PERR;
460     }
461     pp->p_command = Strsave(command);
462     if (pcurrjob) {
463 	struct process *fp;
464 
465 	/* careful here with interrupt level */
466 	pp->p_cwd = 0;
467 	pp->p_index = pcurrjob->p_index;
468 	pp->p_friends = pcurrjob;
469 	pp->p_jobid = pcurrjob->p_pid;
470 	for (fp = pcurrjob; fp->p_friends != pcurrjob; fp = fp->p_friends)
471 	    continue;
472 	fp->p_friends = pp;
473     }
474     else {
475 	pcurrjob = pp;
476 	pp->p_jobid = pid;
477 	pp->p_friends = pp;
478 	pp->p_cwd = dcwd;
479 	dcwd->di_count++;
480 	if (pmaxindex < BIGINDEX)
481 	    pp->p_index = ++pmaxindex;
482 	else {
483 	    struct process *np;
484 
485 	    for (i = 1;; i++) {
486 		for (np = proclist.p_next; np; np = np->p_next)
487 		    if (np->p_index == i)
488 			goto tryagain;
489 		pp->p_index = i;
490 		if (i > pmaxindex)
491 		    pmaxindex = i;
492 		break;
493 	tryagain:;
494 	    }
495 	}
496 	if (pcurrent == NULL)
497 	    pcurrent = pp;
498 	else if (pprevious == NULL)
499 	    pprevious = pp;
500     }
501     pp->p_next = proclist.p_next;
502     proclist.p_next = pp;
503     (void) gettimeofday(&pp->p_btime, NULL);
504 }
505 
506 static void
507 padd(struct command *t)
508 {
509     Char  **argp;
510 
511     if (t == 0)
512 	return;
513     switch (t->t_dtyp) {
514 
515     case NODE_PAREN:
516 	pads(STRLparensp);
517 	padd(t->t_dspr);
518 	pads(STRspRparen);
519 	break;
520 
521     case NODE_COMMAND:
522 	for (argp = t->t_dcom; *argp; argp++) {
523 	    pads(*argp);
524 	    if (argp[1])
525 		pads(STRspace);
526 	}
527 	break;
528 
529     case NODE_OR:
530     case NODE_AND:
531     case NODE_PIPE:
532     case NODE_LIST:
533 	padd(t->t_dcar);
534 	switch (t->t_dtyp) {
535 	case NODE_OR:
536 	    pads(STRspor2sp);
537 	    break;
538 	case NODE_AND:
539 	    pads(STRspand2sp);
540 	    break;
541 	case NODE_PIPE:
542 	    pads(STRsporsp);
543 	    break;
544 	case NODE_LIST:
545 	    pads(STRsemisp);
546 	    break;
547 	}
548 	padd(t->t_dcdr);
549 	return;
550     }
551     if ((t->t_dflg & F_PIPEIN) == 0 && t->t_dlef) {
552 	pads((t->t_dflg & F_READ) ? STRspLarrow2sp : STRspLarrowsp);
553 	pads(t->t_dlef);
554     }
555     if ((t->t_dflg & F_PIPEOUT) == 0 && t->t_drit) {
556 	pads((t->t_dflg & F_APPEND) ? STRspRarrow2 : STRspRarrow);
557 	if (t->t_dflg & F_STDERR)
558 	    pads(STRand);
559 	pads(STRspace);
560 	pads(t->t_drit);
561     }
562 }
563 
564 static void
565 pads(Char *cp)
566 {
567     int i;
568 
569     /*
570      * Avoid the Quoted Space alias hack! Reported by:
571      * sam@john-bigboote.ICS.UCI.EDU (Sam Horrocks)
572      */
573     if (cp[0] == STRQNULL[0])
574 	cp++;
575 
576     i = Strlen(cp);
577 
578     if (cmdlen >= PMAXLEN)
579 	return;
580     if (cmdlen + i >= PMAXLEN) {
581 	(void) Strlcpy(cmdp, STRsp3dots, PMAXLEN - cmdlen);
582 	cmdlen = PMAXLEN;
583 	cmdp += 4;
584 	return;
585     }
586     (void) Strlcpy(cmdp, cp, PMAXLEN - cmdlen);
587     cmdp += i;
588     cmdlen += i;
589 }
590 
591 /*
592  * psavejob - temporarily save the current job on a one level stack
593  *	so another job can be created.  Used for { } in exp6
594  *	and `` in globbing.
595  */
596 void
597 psavejob(void)
598 {
599 
600     pholdjob = pcurrjob;
601     pcurrjob = NULL;
602 }
603 
604 /*
605  * prestjob - opposite of psavejob.  This may be missed if we are interrupted
606  *	somewhere, but pendjob cleans up anyway.
607  */
608 void
609 prestjob(void)
610 {
611 
612     pcurrjob = pholdjob;
613     pholdjob = NULL;
614 }
615 
616 /*
617  * pendjob - indicate that a job (set of commands) has been completed
618  *	or is about to begin.
619  */
620 void
621 pendjob(void)
622 {
623     struct process *pp, *tp;
624 
625     if (pcurrjob && (pcurrjob->p_flags & (PFOREGND | PSTOPPED)) == 0) {
626 	pp = pcurrjob;
627 	while (pp->p_pid != pp->p_jobid)
628 	    pp = pp->p_friends;
629 	(void) fprintf(cshout, "[%d]", pp->p_index);
630 	tp = pp;
631 	do {
632 	    (void) fprintf(cshout, " %d", pp->p_pid);
633 	    pp = pp->p_friends;
634 	} while (pp != tp);
635 	(void) fputc('\n', cshout);
636     }
637     pholdjob = pcurrjob = 0;
638 }
639 
640 /*
641  * pprint - print a job
642  */
643 static int
644 pprint(struct process *pp, bool flag)
645 {
646     int status, reason;
647     struct process *tp;
648     int     jobflags, pstatus;
649     bool hadnl = 1;	/* did we just have a newline */
650     char   *format;
651 
652     (void) fpurge(cshout);
653 
654     while (pp->p_pid != pp->p_jobid)
655 	pp = pp->p_friends;
656     if (pp == pp->p_friends && (pp->p_flags & PPTIME)) {
657 	pp->p_flags &= ~PPTIME;
658 	pp->p_flags |= PTIME;
659     }
660     tp = pp;
661     status = reason = -1;
662     jobflags = 0;
663     do {
664 	jobflags |= pp->p_flags;
665 	pstatus = pp->p_flags & PALLSTATES;
666 	if (tp != pp && !hadnl && !(flag & FANCY) &&
667 	    ((pstatus == status && pp->p_reason == reason) ||
668 	     !(flag & REASON))) {
669 	    (void) fputc(' ', cshout);
670 	    hadnl = 0;
671 	}
672 	else {
673 	    if (tp != pp && !hadnl) {
674 		(void) fputc('\n', cshout);
675 		hadnl = 1;
676 	    }
677 	    if (flag & NUMBER) {
678 		if (pp == tp)
679 		    (void) fprintf(cshout, "[%d]%s %c ", pp->p_index,
680 			    pp->p_index < 10 ? " " : "",
681 			    pp == pcurrent ? '+' :
682 			    (pp == pprevious ? '-' : ' '));
683 		else
684 		    (void) fprintf(cshout, "       ");
685 		hadnl = 0;
686 	    }
687 	    if (flag & FANCY) {
688 		(void) fprintf(cshout, "%5d ", pp->p_pid);
689 		hadnl = 0;
690 	    }
691 	    if (flag & (REASON | AREASON)) {
692 		int width = 0;
693 		if (flag & NAME)
694 		    width = -23;
695 		if (pstatus == status)
696 		    if (pp->p_reason == reason) {
697 			(void) fprintf(cshout, "%*s", width, "");
698 			hadnl = 0;
699 			goto prcomd;
700 		    }
701 		    else
702 			reason = pp->p_reason;
703 		else {
704 		    status = pstatus;
705 		    reason = pp->p_reason;
706 		}
707 		switch (status) {
708 
709 		case PRUNNING:
710 		    (void) fprintf(cshout, "%*s", width, "Running ");
711 		    hadnl = 0;
712 		    break;
713 
714 		case PINTERRUPTED:
715 		case PSTOPPED:
716 		case PSIGNALED:
717 		    /*
718 		     * tell what happened to the background job
719 		     * From: Michael Schroeder
720 		     * <mlschroe@immd4.informatik.uni-erlangen.de>
721 		     */
722 		    if ((flag & REASON)
723 			|| ((flag & AREASON)
724 			    && reason != SIGINT
725 			    && (reason != SIGPIPE
726 				|| (pp->p_flags & PPOU) == 0))) {
727 			(void) fprintf(cshout, "%*s", width,
728 				       sys_siglist[(unsigned char)
729 						   pp->p_reason]);
730 			hadnl = 0;
731 		    }
732 		    break;
733 
734 		case PNEXITED:
735 		case PAEXITED:
736 		    if (flag & REASON) {
737 			if (pp->p_reason)
738 			    (void) fprintf(cshout, "Exit %-18d", pp->p_reason);
739 			else
740 			    (void) fprintf(cshout, "%*s", width, "Done");
741 			hadnl = 0;
742 		    }
743 		    break;
744 
745 		default:
746 		    (void) fprintf(csherr, "BUG: status=%-9o", status);
747 		}
748 	    }
749 	}
750 prcomd:
751 	if (flag & NAME) {
752 	    (void) fprintf(cshout, "%s", vis_str(pp->p_command));
753 	    if (pp->p_flags & PPOU)
754 		(void) fprintf(cshout, " |");
755 	    if (pp->p_flags & PERR)
756 		(void) fputc('&', cshout);
757 	    hadnl = 0;
758 	}
759 	if (flag & (REASON | AREASON) && pp->p_flags & PDUMPED) {
760 	    (void) fprintf(cshout, " (core dumped)");
761 	    hadnl = 0;
762 	}
763 	if (tp == pp->p_friends) {
764 	    if (flag & AMPERSAND) {
765 		(void) fprintf(cshout, " &");
766 		hadnl = 0;
767 	    }
768 	    if (flag & JOBDIR &&
769 		!eq(tp->p_cwd->di_name, dcwd->di_name)) {
770 		(void) fprintf(cshout, " (wd: ");
771 		dtildepr(value(STRhome), tp->p_cwd->di_name);
772 		(void) fputc(')', cshout);
773 		hadnl = 0;
774 	    }
775 	}
776 	if (pp->p_flags & PPTIME && !(status & (PSTOPPED | PRUNNING))) {
777 	    if (!hadnl)
778 		(void) fprintf(cshout, "\n\t");
779 	    prusage(&zru, &pp->p_rusage, &pp->p_etime,
780 		    &pp->p_btime);
781 	    hadnl = 1;
782 	}
783 	if (tp == pp->p_friends) {
784 	    if (!hadnl) {
785 		(void) fputc('\n', cshout);
786 		hadnl = 1;
787 	    }
788 	    if (flag & SHELLDIR && !eq(tp->p_cwd->di_name, dcwd->di_name)) {
789 		(void) fprintf(cshout, "(wd now: ");
790 		dtildepr(value(STRhome), dcwd->di_name);
791 		(void) fprintf(cshout, ")\n");
792 		hadnl = 1;
793 	    }
794 	}
795     } while ((pp = pp->p_friends) != tp);
796     if (jobflags & PTIME && (jobflags & (PSTOPPED | PRUNNING)) == 0) {
797 	if (jobflags & NUMBER)
798 	    (void) fprintf(cshout, "       ");
799 	ptprint(tp);
800 	hadnl = 1;
801     }
802     (void) fflush(cshout);
803     return (jobflags);
804 }
805 
806 static void
807 ptprint(struct process *tp)
808 {
809     struct timeval tetime, diff;
810     static struct timeval ztime;
811     struct rusage ru;
812     static struct rusage zru;
813     struct process *pp = tp;
814 
815     ru = zru;
816     tetime = ztime;
817     do {
818 	ruadd(&ru, &pp->p_rusage);
819 	timersub(&pp->p_etime, &pp->p_btime, &diff);
820 	if (timercmp(&diff, &tetime, >))
821 	    tetime = diff;
822     } while ((pp = pp->p_friends) != tp);
823     prusage(&zru, &ru, &tetime, &ztime);
824 }
825 
826 /*
827  * dojobs - print all jobs
828  */
829 void
830 /*ARGSUSED*/
831 dojobs(Char **v, struct command *t)
832 {
833     struct process *pp;
834     int flag = NUMBER | NAME | REASON;
835     int     i;
836 
837     if (chkstop)
838 	chkstop = 2;
839     if (*++v) {
840 	if (v[1] || !eq(*v, STRml))
841 	    stderror(ERR_JOBS);
842 	flag |= FANCY | JOBDIR;
843     }
844     for (i = 1; i <= pmaxindex; i++)
845 	for (pp = proclist.p_next; pp; pp = pp->p_next)
846 	    if (pp->p_index == i && pp->p_pid == pp->p_jobid) {
847 		pp->p_flags &= ~PNEEDNOTE;
848 		if (!(pprint(pp, flag) & (PRUNNING | PSTOPPED)))
849 		    pflush(pp);
850 		break;
851 	    }
852 }
853 
854 /*
855  * dofg - builtin - put the job into the foreground
856  */
857 void
858 /*ARGSUSED*/
859 dofg(Char **v, struct command *t)
860 {
861     struct process *pp;
862 
863     okpcntl();
864     ++v;
865     do {
866 	pp = pfind(*v);
867 	pstart(pp, 1);
868 	pjwait(pp);
869     } while (*v && *++v);
870 }
871 
872 /*
873  * %... - builtin - put the job into the foreground
874  */
875 void
876 /*ARGSUSED*/
877 dofg1(Char **v, struct command *t)
878 {
879     struct process *pp;
880 
881     okpcntl();
882     pp = pfind(v[0]);
883     pstart(pp, 1);
884     pjwait(pp);
885 }
886 
887 /*
888  * dobg - builtin - put the job into the background
889  */
890 void
891 /*ARGSUSED*/
892 dobg(Char **v, struct command *t)
893 {
894     struct process *pp;
895 
896     okpcntl();
897     ++v;
898     do {
899 	pp = pfind(*v);
900 	pstart(pp, 0);
901     } while (*v && *++v);
902 }
903 
904 /*
905  * %... & - builtin - put the job into the background
906  */
907 void
908 /*ARGSUSED*/
909 dobg1(Char **v, struct command *t)
910 {
911     struct process *pp;
912 
913     pp = pfind(v[0]);
914     pstart(pp, 0);
915 }
916 
917 /*
918  * dostop - builtin - stop the job
919  */
920 void
921 /*ARGSUSED*/
922 dostop(Char **v, struct command *t)
923 {
924     pkill(++v, SIGSTOP);
925 }
926 
927 /*
928  * dokill - builtin - superset of kill (1)
929  */
930 void
931 /*ARGSUSED*/
932 dokill(Char **v, struct command *t)
933 {
934     int signum = SIGTERM;
935     char *name;
936 
937     v++;
938     if (v[0] && v[0][0] == '-') {
939 	if (v[0][1] == 'l') {
940 	    if (v[1]) {
941 		if (!Isdigit(v[1][0]))
942 		    stderror(ERR_NAME | ERR_BADSIG);
943 
944 		signum = atoi(short2str(v[1]));
945 		if (signum < 0 || signum >= NSIG)
946 		    stderror(ERR_NAME | ERR_BADSIG);
947 		else if (signum == 0)
948 		    (void) fputc('0', cshout); /* 0's symbolic name is '0' */
949 		else
950 		    (void) fprintf(cshout, "%s ", sys_signame[signum]);
951 	    } else {
952 		for (signum = 1; signum < NSIG; signum++) {
953 		    (void) fprintf(cshout, "%s ", sys_signame[signum]);
954 		    if (signum == NSIG / 2)
955 			(void) fputc('\n', cshout);
956 	    	}
957 	    }
958 	    (void) fputc('\n', cshout);
959 	    return;
960 	}
961 	if (Isdigit(v[0][1])) {
962 	    signum = atoi(short2str(v[0] + 1));
963 	    if (signum < 0 || signum >= NSIG)
964 		stderror(ERR_NAME | ERR_BADSIG);
965 	}
966 	else {
967 	    if (v[0][1] == 's' && (Isspace(v[0][2]) || v[0][2] == '\0')) {
968 		v++;
969 		name = short2str(&v[0][0]);
970 	    } else {
971 		name = short2str(&v[0][1]);
972 	    }
973 
974 	    if (v[0] == NULL || v[1] == NULL) {
975 		stderror(ERR_NAME | ERR_TOOFEW);
976 		return;
977 	    }
978 
979 	    for (signum = 1; signum < NSIG; signum++)
980 		if (!strcasecmp(sys_signame[signum], name) ||
981 		    (strlen(name) > 3 && !strncasecmp("SIG", name, 3) &&
982 		     !strcasecmp(sys_signame[signum], name + 3)))
983 			break;
984 
985 	    if (signum == NSIG) {
986 		if (name[0] == '0')
987 		    signum = 0;
988 		else {
989 		    setname(vis_str(&v[0][0]));
990 		    stderror(ERR_NAME | ERR_UNKSIG);
991 		}
992 	    }
993 	}
994 	v++;
995     }
996     pkill(v, signum);
997 }
998 
999 static void
1000 pkill(Char **v, int signum)
1001 {
1002     struct process *pp, *np;
1003     int jobflags = 0;
1004     int     pid, err1 = 0;
1005     sigset_t sigset;
1006     Char   *cp;
1007 
1008     sigemptyset(&sigset);
1009     sigaddset(&sigset, SIGCHLD);
1010     if (setintr)
1011 	sigaddset(&sigset, SIGINT);
1012     sigprocmask(SIG_BLOCK, &sigset, NULL);
1013     gflag = 0, tglob(v);
1014     if (gflag) {
1015 	v = globall(v);
1016 	if (v == 0)
1017 	    stderror(ERR_NAME | ERR_NOMATCH);
1018     }
1019     else {
1020 	v = gargv = saveblk(v);
1021 	trim(v);
1022     }
1023 
1024     while (v && (cp = *v)) {
1025 	if (*cp == '%') {
1026 	    np = pp = pfind(cp);
1027 	    do
1028 		jobflags |= np->p_flags;
1029 	    while ((np = np->p_friends) != pp);
1030 	    switch (signum) {
1031 
1032 	    case SIGSTOP:
1033 	    case SIGTSTP:
1034 	    case SIGTTIN:
1035 	    case SIGTTOU:
1036 		if ((jobflags & PRUNNING) == 0) {
1037 		    (void) fprintf(csherr, "%s: Already suspended\n",
1038 				   vis_str(cp));
1039 		    err1++;
1040 		    goto cont;
1041 		}
1042 		break;
1043 		/*
1044 		 * suspend a process, kill -CONT %, then type jobs; the shell
1045 		 * says it is suspended, but it is running; thanks jaap..
1046 		 */
1047 	    case SIGCONT:
1048 		pstart(pp, 0);
1049 		goto cont;
1050 	    }
1051 	    if (kill(-pp->p_jobid, signum) < 0) {
1052 		(void) fprintf(csherr, "%s: %s\n", vis_str(cp),
1053 			       strerror(errno));
1054 		err1++;
1055 	    }
1056 	    if (signum == SIGTERM || signum == SIGHUP)
1057 		(void) kill(-pp->p_jobid, SIGCONT);
1058 	}
1059 	else if (!(Isdigit(*cp) || *cp == '-'))
1060 	    stderror(ERR_NAME | ERR_JOBARGS);
1061 	else {
1062 	    char *ep;
1063 	    char *pidnam = short2str(cp);
1064 
1065 	    pid = strtol(pidnam, &ep, 10);
1066 	    if (!*pidnam || *ep) {
1067 		(void) fprintf(csherr, "%s: illegal process id\n", pidnam);
1068 		err1++;
1069 		goto cont;
1070 	    }
1071 	    if (kill((pid_t) pid, signum) < 0) {
1072 		(void) fprintf(csherr, "%d: %s\n", pid, strerror(errno));
1073 		err1++;
1074 		goto cont;
1075 	    }
1076 	    if (signum == SIGTERM || signum == SIGHUP)
1077 		(void) kill((pid_t) pid, SIGCONT);
1078 	}
1079 cont:
1080 	v++;
1081     }
1082     if (gargv)
1083 	blkfree(gargv), gargv = 0;
1084     sigprocmask(SIG_UNBLOCK, &sigset, NULL);
1085     if (err1)
1086 	stderror(ERR_SILENT);
1087 }
1088 
1089 /*
1090  * pstart - start the job in foreground/background
1091  */
1092 void
1093 pstart(struct process *pp, int foregnd)
1094 {
1095     struct process *np;
1096     sigset_t sigset, osigset;
1097     long    jobflags = 0;
1098 
1099     sigemptyset(&sigset);
1100     sigaddset(&sigset, SIGCHLD);
1101     sigprocmask(SIG_BLOCK, &sigset, &osigset);
1102     np = pp;
1103     do {
1104 	jobflags |= np->p_flags;
1105 	if (np->p_flags & (PRUNNING | PSTOPPED)) {
1106 	    np->p_flags |= PRUNNING;
1107 	    np->p_flags &= ~PSTOPPED;
1108 	    if (foregnd)
1109 		np->p_flags |= PFOREGND;
1110 	    else
1111 		np->p_flags &= ~PFOREGND;
1112 	}
1113     } while ((np = np->p_friends) != pp);
1114     if (!foregnd)
1115 	pclrcurr(pp);
1116     (void) pprint(pp, foregnd ? NAME | JOBDIR : NUMBER | NAME | AMPERSAND);
1117     if (foregnd)
1118 	(void) tcsetpgrp(FSHTTY, pp->p_jobid);
1119     if (jobflags & PSTOPPED)
1120 	(void) kill(-pp->p_jobid, SIGCONT);
1121     sigprocmask(SIG_SETMASK, &osigset, NULL);
1122 }
1123 
1124 void
1125 panystop(bool neednl)
1126 {
1127     struct process *pp;
1128 
1129     chkstop = 2;
1130     for (pp = proclist.p_next; pp; pp = pp->p_next)
1131 	if (pp->p_flags & PSTOPPED)
1132 	    stderror(ERR_STOPPED, neednl ? "\n" : "");
1133 }
1134 
1135 struct process *
1136 pfind(Char *cp)
1137 {
1138     struct process *pp, *np;
1139 
1140     if (cp == 0 || cp[1] == 0 || eq(cp, STRcent2) || eq(cp, STRcentplus)) {
1141 	if (pcurrent == NULL)
1142 	    stderror(ERR_NAME | ERR_JOBCUR);
1143 	return (pcurrent);
1144     }
1145     if (eq(cp, STRcentminus) || eq(cp, STRcenthash)) {
1146 	if (pprevious == NULL)
1147 	    stderror(ERR_NAME | ERR_JOBPREV);
1148 	return (pprevious);
1149     }
1150     if (Isdigit(cp[1])) {
1151 	int     idx = atoi(short2str(cp + 1));
1152 
1153 	for (pp = proclist.p_next; pp; pp = pp->p_next)
1154 	    if (pp->p_index == idx && pp->p_pid == pp->p_jobid)
1155 		return (pp);
1156 	stderror(ERR_NAME | ERR_NOSUCHJOB);
1157     }
1158     np = NULL;
1159     for (pp = proclist.p_next; pp; pp = pp->p_next)
1160 	if (pp->p_pid == pp->p_jobid) {
1161 	    if (cp[1] == '?') {
1162 		Char *dp;
1163 
1164 		for (dp = pp->p_command; *dp; dp++) {
1165 		    if (*dp != cp[2])
1166 			continue;
1167 		    if (prefix(cp + 2, dp))
1168 			goto match;
1169 		}
1170 	    }
1171 	    else if (prefix(cp + 1, pp->p_command)) {
1172 	match:
1173 		if (np)
1174 		    stderror(ERR_NAME | ERR_AMBIG);
1175 		np = pp;
1176 	    }
1177 	}
1178     if (np)
1179 	return (np);
1180     stderror(ERR_NAME | (cp[1] == '?' ? ERR_JOBPAT : ERR_NOSUCHJOB));
1181     /* NOTREACHED */
1182     return (0);
1183 }
1184 
1185 
1186 /*
1187  * pgetcurr - find most recent job that is not pp, preferably stopped
1188  */
1189 static struct process *
1190 pgetcurr(struct process *pp)
1191 {
1192     struct process *np;
1193     struct process *xp = NULL;
1194 
1195     for (np = proclist.p_next; np; np = np->p_next)
1196 	if (np != pcurrent && np != pp && np->p_pid &&
1197 	    np->p_pid == np->p_jobid) {
1198 	    if (np->p_flags & PSTOPPED)
1199 		return (np);
1200 	    if (xp == NULL)
1201 		xp = np;
1202 	}
1203     return (xp);
1204 }
1205 
1206 /*
1207  * donotify - flag the job so as to report termination asynchronously
1208  */
1209 void
1210 /*ARGSUSED*/
1211 donotify(Char **v, struct command *t)
1212 {
1213     struct process *pp;
1214 
1215     pp = pfind(*++v);
1216     pp->p_flags |= PNOTIFY;
1217 }
1218 
1219 /*
1220  * Do the fork and whatever should be done in the child side that
1221  * should not be done if we are not forking at all (like for simple builtin's)
1222  * Also do everything that needs any signals fiddled with in the parent side
1223  *
1224  * Wanttty tells whether process and/or tty pgrps are to be manipulated:
1225  *	-1:	leave tty alone; inherit pgrp from parent
1226  *	 0:	already have tty; manipulate process pgrps only
1227  *	 1:	want to claim tty; manipulate process and tty pgrps
1228  * It is usually just the value of tpgrp.
1229  */
1230 
1231 int
1232 pfork(struct command *t, int wanttty)
1233 {
1234     int pid;
1235     bool    ignint = 0;
1236     int     pgrp;
1237     sigset_t sigset, osigset;
1238 
1239     /*
1240      * A child will be uninterruptible only under very special conditions.
1241      * Remember that the semantics of '&' is implemented by disconnecting the
1242      * process from the tty so signals do not need to ignored just for '&'.
1243      * Thus signals are set to default action for children unless: we have had
1244      * an "onintr -" (then specifically ignored) we are not playing with
1245      * signals (inherit action)
1246      */
1247     if (setintr)
1248 	ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT))
1249 	    || (gointr && eq(gointr, STRminus));
1250     /*
1251      * Check for maximum nesting of 16 processes to avoid Forking loops
1252      */
1253     if (child == 16)
1254 	stderror(ERR_NESTING, 16);
1255     /*
1256      * Hold SIGCHLD until we have the process installed in our table.
1257      */
1258     sigemptyset(&sigset);
1259     sigaddset(&sigset, SIGCHLD);
1260     sigprocmask(SIG_BLOCK, &sigset, &osigset);
1261     while ((pid = fork()) < 0)
1262 	if (setintr == 0)
1263 	    (void) sleep(FORKSLEEP);
1264 	else {
1265 	    sigprocmask(SIG_SETMASK, &osigset, NULL);
1266 	    stderror(ERR_NOPROC);
1267 	}
1268     if (pid == 0) {
1269 	settimes();
1270 	pgrp = pcurrjob ? pcurrjob->p_jobid : getpid();
1271 	pflushall();
1272 	pcurrjob = NULL;
1273 	child++;
1274 	if (setintr) {
1275 	    setintr = 0;	/* until I think otherwise */
1276 	    /*
1277 	     * Children just get blown away on SIGINT, SIGQUIT unless "onintr
1278 	     * -" seen.
1279 	     */
1280 	    (void) signal(SIGINT, ignint ? SIG_IGN : SIG_DFL);
1281 	    (void) signal(SIGQUIT, ignint ? SIG_IGN : SIG_DFL);
1282 	    if (wanttty >= 0) {
1283 		/* make stoppable */
1284 		(void) signal(SIGTSTP, SIG_DFL);
1285 		(void) signal(SIGTTIN, SIG_DFL);
1286 		(void) signal(SIGTTOU, SIG_DFL);
1287 	    }
1288 	    (void) signal(SIGTERM, parterm);
1289 	}
1290 	else if (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) {
1291 	    (void) signal(SIGINT, SIG_IGN);
1292 	    (void) signal(SIGQUIT, SIG_IGN);
1293 	}
1294 	pgetty(wanttty, pgrp);
1295 	/*
1296 	 * Nohup and nice apply only to NODE_COMMAND's but it would be nice
1297 	 * (?!?) if you could say "nohup (foo;bar)" Then the parser would have
1298 	 * to know about nice/nohup/time
1299 	 */
1300 	if (t->t_dflg & F_NOHUP)
1301 	    (void) signal(SIGHUP, SIG_IGN);
1302 	if (t->t_dflg & F_NICE)
1303 	    (void) setpriority(PRIO_PROCESS, 0, t->t_nice);
1304     }
1305     else {
1306 	if (wanttty >= 0)
1307 	    (void) setpgid(pid, pcurrjob ? pcurrjob->p_jobid : pid);
1308 	palloc(pid, t);
1309 	sigprocmask(SIG_SETMASK, &osigset, NULL);
1310     }
1311 
1312     return (pid);
1313 }
1314 
1315 static void
1316 okpcntl(void)
1317 {
1318     if (tpgrp == -1)
1319 	stderror(ERR_JOBCONTROL);
1320     if (tpgrp == 0)
1321 	stderror(ERR_JOBCTRLSUB);
1322 }
1323 
1324 /*
1325  * if we don't have vfork(), things can still go in the wrong order
1326  * resulting in the famous 'Stopped (tty output)'. But some systems
1327  * don't permit the setpgid() call, (these are more recent secure
1328  * systems such as ibm's aix). Then we'd rather print an error message
1329  * than hang the shell!
1330  * I am open to suggestions how to fix that.
1331  */
1332 void
1333 pgetty(int wanttty, int pgrp)
1334 {
1335     sigset_t sigset, osigset;
1336 
1337     /*
1338      * christos: I am blocking the tty signals till I've set things
1339      * correctly....
1340      */
1341     if (wanttty > 0) {
1342 	sigemptyset(&sigset);
1343 	sigaddset(&sigset, SIGTSTP);
1344 	sigaddset(&sigset, SIGTTIN);
1345 	sigaddset(&sigset, SIGTTOU);
1346 	sigprocmask(SIG_BLOCK, &sigset, &osigset);
1347     }
1348     /*
1349      * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
1350      * Don't check for tpgrp >= 0 so even non-interactive shells give
1351      * background jobs process groups Same for the comparison in the other part
1352      * of the #ifdef
1353      */
1354     if (wanttty >= 0)
1355 	if (setpgid(0, pgrp) == -1) {
1356 	    (void) fprintf(csherr, "csh: setpgid error.\n");
1357 	    xexit(0);
1358 	}
1359 
1360     if (wanttty > 0) {
1361 	(void) tcsetpgrp(FSHTTY, pgrp);
1362 	sigprocmask(SIG_SETMASK, &osigset, NULL);
1363     }
1364 
1365     if (tpgrp > 0)
1366 	tpgrp = 0;		/* gave tty away */
1367 }
1368