loksh-noxz

[fork] a Linux port of OpenBSD's ksh
git clone https://noxz.tech/git/loksh-noxz.git
Log | Files | README

jobs.c
1/*	$OpenBSD: jobs.c,v 1.62 2020/07/07 10:33:58 jca Exp $	*/
2
3/*
4 * Process and job control
5 */
6
7/*
8 * Reworked/Rewritten version of Eric Gisin's/Ron Natalie's code by
9 * Larry Bouzane (larry@cs.mun.ca) and hacked again by
10 * Michael Rendell (michael@cs.mun.ca)
11 *
12 * The interface to the rest of the shell should probably be changed
13 * to allow use of vfork() when available but that would be way too much
14 * work :)
15 *
16 */
17
18#include <sys/resource.h>
19#include <sys/stat.h>
20#include <sys/time.h>
21#include <sys/wait.h>
22
23#include <ctype.h>
24#include <errno.h>
25#include <fcntl.h>
26#include <limits.h>
27#include <stdlib.h>
28#include <string.h>
29#include <unistd.h>
30
31#include "sh.h"
32#include "tty.h"
33
34/* Order important! */
35#define PRUNNING	0
36#define PEXITED		1
37#define PSIGNALLED	2
38#define PSTOPPED	3
39
40typedef struct proc	Proc;
41struct proc {
42	Proc	*next;		/* next process in pipeline (if any) */
43	int	state;
44	int	status;		/* wait status */
45	pid_t	pid;		/* process id */
46	char	command[48];	/* process command string */
47};
48
49/* Notify/print flag - j_print() argument */
50#define JP_NONE		0	/* don't print anything */
51#define JP_SHORT	1	/* print signals processes were killed by */
52#define JP_MEDIUM	2	/* print [job-num] -/+ command */
53#define JP_LONG		3	/* print [job-num] -/+ pid command */
54#define JP_PGRP		4	/* print pgrp */
55
56/* put_job() flags */
57#define PJ_ON_FRONT	0	/* at very front */
58#define PJ_PAST_STOPPED	1	/* just past any stopped jobs */
59
60/* Job.flags values */
61#define JF_STARTED	0x001	/* set when all processes in job are started */
62#define JF_WAITING	0x002	/* set if j_waitj() is waiting on job */
63#define JF_W_ASYNCNOTIFY 0x004	/* set if waiting and async notification ok */
64#define JF_XXCOM	0x008	/* set for `command` jobs */
65#define JF_FG		0x010	/* running in foreground (also has tty pgrp) */
66#define JF_SAVEDTTY	0x020	/* j->ttystate is valid */
67#define JF_CHANGED	0x040	/* process has changed state */
68#define JF_KNOWN	0x080	/* $! referenced */
69#define JF_ZOMBIE	0x100	/* known, unwaited process */
70#define JF_REMOVE	0x200	/* flagged for removal (j_jobs()/j_notify()) */
71#define JF_USETTYMODE	0x400	/* tty mode saved if process exits normally */
72#define JF_SAVEDTTYPGRP	0x800	/* j->saved_ttypgrp is valid */
73#define JF_PIPEFAIL	0x1000	/* pipefail on when job was started */
74
75typedef struct job Job;
76struct job {
77	Job	*next;		/* next job in list */
78	int	job;		/* job number: %n */
79	int	flags;		/* see JF_* */
80	int	state;		/* job state */
81	int	status;		/* exit status of last process */
82	pid_t	pgrp;		/* process group of job */
83	pid_t	ppid;		/* pid of process that forked job */
84	int	age;		/* number of jobs started */
85	struct timeval systime;	/* system time used by job */
86	struct timeval usrtime;	/* user time used by job */
87	Proc	*proc_list;	/* process list */
88	Proc	*last_proc;	/* last process in list */
89	Coproc_id coproc_id;	/* 0 or id of coprocess output pipe */
90	struct termios ttystate;/* saved tty state for stopped jobs */
91	pid_t	saved_ttypgrp;	/* saved tty process group for stopped jobs */
92};
93
94/* Flags for j_waitj() */
95#define JW_NONE		0x00
96#define JW_INTERRUPT	0x01	/* ^C will stop the wait */
97#define JW_ASYNCNOTIFY	0x02	/* asynchronous notification during wait ok */
98#define JW_STOPPEDWAIT	0x04	/* wait even if job stopped */
99
100/* Error codes for j_lookup() */
101#define JL_OK		0
102#define JL_NOSUCH	1	/* no such job */
103#define JL_AMBIG	2	/* %foo or %?foo is ambiguous */
104#define JL_INVALID	3	/* non-pid, non-% job id */
105
106static const char	*const lookup_msgs[] = {
107	null,
108	"no such job",
109	"ambiguous",
110	"argument must be %job or process id",
111	NULL
112};
113
114struct timeval	j_systime, j_usrtime;	/* user and system time of last j_waitjed job */
115
116static Job		*job_list;	/* job list */
117static Job		*last_job;
118static Job		*async_job;
119static pid_t		async_pid;
120
121static int		nzombie;	/* # of zombies owned by this process */
122int			njobs;		/* # of jobs started */
123static int		child_max;	/* CHILD_MAX */
124
125
126/* held_sigchld is set if sigchld occurs before a job is completely started */
127static volatile sig_atomic_t held_sigchld;
128
129static struct shf	*shl_j;
130static int		ttypgrp_ok;	/* set if can use tty pgrps */
131static pid_t		restore_ttypgrp = -1;
132static pid_t		our_pgrp;
133static int const	tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
134
135static void		j_set_async(Job *);
136static void		j_startjob(Job *);
137static int		j_waitj(Job *, int, const char *);
138static void		j_sigchld(int);
139static void		j_print(Job *, int, struct shf *);
140static Job		*j_lookup(const char *, int *);
141static Job		*new_job(void);
142static Proc		*new_proc(void);
143static void		check_job(Job *);
144static void		put_job(Job *, int);
145static void		remove_job(Job *, const char *);
146static int		kill_job(Job *, int);
147
148/* initialize job control */
149void
150j_init(int mflagset)
151{
152	child_max = CHILD_MAX; /* so syscon() isn't always being called */
153
154	sigemptyset(&sm_default);
155	sigprocmask(SIG_SETMASK, &sm_default, NULL);
156
157	sigemptyset(&sm_sigchld);
158	sigaddset(&sm_sigchld, SIGCHLD);
159
160	setsig(&sigtraps[SIGCHLD], j_sigchld,
161	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
162
163	if (!mflagset && Flag(FTALKING))
164		Flag(FMONITOR) = 1;
165
166	/* shl_j is used to do asynchronous notification (used in
167	 * an interrupt handler, so need a distinct shf)
168	 */
169	shl_j = shf_fdopen(2, SHF_WR, NULL);
170
171	if (Flag(FMONITOR) || Flag(FTALKING)) {
172		int i;
173
174		/* the TF_SHELL_USES test is a kludge that lets us know if
175		 * if the signals have been changed by the shell.
176		 */
177		for (i = NELEM(tt_sigs); --i >= 0; ) {
178			sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
179			/* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
180			setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
181			    SS_RESTORE_IGN|SS_FORCE);
182		}
183	}
184
185	/* j_change() calls tty_init() */
186	if (Flag(FMONITOR))
187		j_change();
188	else if (Flag(FTALKING))
189		tty_init(true);
190}
191
192/* suspend the shell */
193void
194j_suspend(void)
195{
196	struct sigaction sa, osa;
197
198	/* Restore tty and pgrp. */
199	if (ttypgrp_ok) {
200		tcsetattr(tty_fd, TCSADRAIN, &tty_state);
201		if (restore_ttypgrp >= 0) {
202			if (tcsetpgrp(tty_fd, restore_ttypgrp) == -1) {
203				warningf(false, "%s: tcsetpgrp() failed: %s",
204				    __func__, strerror(errno));
205			} else {
206				if (setpgid(0, restore_ttypgrp) == -1) {
207					warningf(false,
208					    "%s: setpgid() failed: %s",
209					    __func__, strerror(errno));
210				}
211			}
212		}
213	}
214
215	/* Suspend the shell. */
216	memset(&sa, 0, sizeof(sa));
217	sigemptyset(&sa.sa_mask);
218	sa.sa_handler = SIG_DFL;
219	sigaction(SIGTSTP, &sa, &osa);
220	kill(0, SIGTSTP);
221
222	/* Back from suspend, reset signals, pgrp and tty. */
223	sigaction(SIGTSTP, &osa, NULL);
224	if (ttypgrp_ok) {
225		if (restore_ttypgrp >= 0) {
226			if (setpgid(0, kshpid) == -1) {
227				warningf(false, "%s: setpgid() failed: %s",
228				    __func__, strerror(errno));
229				ttypgrp_ok = 0;
230			} else {
231				if (tcsetpgrp(tty_fd, kshpid) == -1) {
232					warningf(false,
233					    "%s: tcsetpgrp() failed: %s",
234					    __func__, strerror(errno));
235					ttypgrp_ok = 0;
236				}
237			}
238		}
239		tty_init(true);
240	}
241}
242
243/* job cleanup before shell exit */
244void
245j_exit(void)
246{
247	/* kill stopped, and possibly running, jobs */
248	Job	*j;
249	int	killed = 0;
250
251	for (j = job_list; j != NULL; j = j->next) {
252		if (j->ppid == procpid &&
253		    (j->state == PSTOPPED ||
254		    (j->state == PRUNNING &&
255		    ((j->flags & JF_FG) ||
256		    (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
257			killed = 1;
258			if (j->pgrp == 0)
259				kill_job(j, SIGHUP);
260			else
261				killpg(j->pgrp, SIGHUP);
262			if (j->state == PSTOPPED) {
263				if (j->pgrp == 0)
264					kill_job(j, SIGCONT);
265				else
266					killpg(j->pgrp, SIGCONT);
267			}
268		}
269	}
270	if (killed)
271		sleep(1);
272	j_notify();
273
274	if (kshpid == procpid && restore_ttypgrp >= 0) {
275		/* Need to restore the tty pgrp to what it was when the
276		 * shell started up, so that the process that started us
277		 * will be able to access the tty when we are done.
278		 * Also need to restore our process group in case we are
279		 * about to do an exec so that both our parent and the
280		 * process we are to become will be able to access the tty.
281		 */
282		tcsetpgrp(tty_fd, restore_ttypgrp);
283		setpgid(0, restore_ttypgrp);
284	}
285	if (Flag(FMONITOR)) {
286		Flag(FMONITOR) = 0;
287		j_change();
288	}
289}
290
291/* turn job control on or off according to Flag(FMONITOR) */
292void
293j_change(void)
294{
295	int i;
296
297	if (Flag(FMONITOR)) {
298		int use_tty;
299
300		if (Flag(FTALKING)) {
301			/* Don't call tcgetattr() 'til we own the tty process group */
302			use_tty = 1;
303			tty_init(false);
304		} else
305			use_tty = 0;
306
307		/* no controlling tty, no SIGT* */
308		ttypgrp_ok = use_tty && tty_fd >= 0 && tty_devtty;
309
310		if (ttypgrp_ok && (our_pgrp = getpgrp()) < 0) {
311			warningf(false, "%s: getpgrp() failed: %s",
312			    __func__, strerror(errno));
313			ttypgrp_ok = 0;
314		}
315		if (ttypgrp_ok) {
316			setsig(&sigtraps[SIGTTIN], SIG_DFL,
317			    SS_RESTORE_ORIG|SS_FORCE);
318			/* wait to be given tty (POSIX.1, B.2, job control) */
319			while (1) {
320				pid_t ttypgrp;
321
322				if ((ttypgrp = tcgetpgrp(tty_fd)) == -1) {
323					warningf(false,
324					    "%s: tcgetpgrp() failed: %s",
325					    __func__, strerror(errno));
326					ttypgrp_ok = 0;
327					break;
328				}
329				if (ttypgrp == our_pgrp)
330					break;
331				kill(0, SIGTTIN);
332			}
333		}
334		for (i = NELEM(tt_sigs); --i >= 0; )
335			setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
336			    SS_RESTORE_DFL|SS_FORCE);
337		if (ttypgrp_ok && our_pgrp != kshpid) {
338			if (setpgid(0, kshpid) == -1) {
339				warningf(false, "%s: setpgid() failed: %s",
340				    __func__, strerror(errno));
341				ttypgrp_ok = 0;
342			} else {
343				if (tcsetpgrp(tty_fd, kshpid) == -1) {
344					warningf(false,
345					    "%s: tcsetpgrp() failed: %s",
346					    __func__, strerror(errno));
347					ttypgrp_ok = 0;
348				} else
349					restore_ttypgrp = our_pgrp;
350				our_pgrp = kshpid;
351			}
352		}
353		if (use_tty) {
354			if (!ttypgrp_ok)
355				warningf(false,
356				    "warning: won't have full job control");
357		}
358		if (tty_fd >= 0)
359			tcgetattr(tty_fd, &tty_state);
360	} else {
361		ttypgrp_ok = 0;
362		if (Flag(FTALKING))
363			for (i = NELEM(tt_sigs); --i >= 0; )
364				setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
365				    SS_RESTORE_IGN|SS_FORCE);
366		else
367			for (i = NELEM(tt_sigs); --i >= 0; ) {
368				if (sigtraps[tt_sigs[i]].flags &
369				    (TF_ORIG_IGN | TF_ORIG_DFL))
370					setsig(&sigtraps[tt_sigs[i]],
371					    (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
372					    SIG_IGN : SIG_DFL,
373					    SS_RESTORE_ORIG|SS_FORCE);
374			}
375		if (!Flag(FTALKING))
376			tty_close();
377	}
378}
379
380/* execute tree in child subprocess */
381int
382exchild(struct op *t, int flags, volatile int *xerrok,
383    int close_fd)	/* used if XPCLOSE or XCCLOSE */
384{
385	static Proc	*last_proc;	/* for pipelines */
386
387	int		i;
388	sigset_t	omask;
389	Proc		*p;
390	Job		*j;
391	int		rv = 0;
392	int		forksleep;
393	int		ischild;
394
395	if (flags & XEXEC)
396		/* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
397		 * (also done in another execute() below)
398		 */
399		return execute(t, flags & (XEXEC | XERROK), xerrok);
400
401	/* no SIGCHLD's while messing with job and process lists */
402	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
403
404	p = new_proc();
405	p->next = NULL;
406	p->state = PRUNNING;
407	p->status = 0;
408	p->pid = 0;
409
410	/* link process into jobs list */
411	if (flags&XPIPEI) {	/* continuing with a pipe */
412		if (!last_job)
413			internal_errorf("%s: XPIPEI and no last_job - pid %d",
414			    __func__, (int) procpid);
415		j = last_job;
416		last_proc->next = p;
417		last_proc = p;
418	} else {
419		j = new_job(); /* fills in j->job */
420		/* we don't consider XXCOM's foreground since they don't get
421		 * tty process group and we don't save or restore tty modes.
422		 */
423		j->flags = (flags & XXCOM) ? JF_XXCOM :
424		    ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
425		if (Flag(FPIPEFAIL))
426			j->flags |= JF_PIPEFAIL;
427		timerclear(&j->usrtime);
428		timerclear(&j->systime);
429		j->state = PRUNNING;
430		j->pgrp = 0;
431		j->ppid = procpid;
432		j->age = ++njobs;
433		j->proc_list = p;
434		j->coproc_id = 0;
435		last_job = j;
436		last_proc = p;
437		put_job(j, PJ_PAST_STOPPED);
438	}
439
440	snptreef(p->command, sizeof(p->command), "%T", t);
441
442	/* create child process */
443	forksleep = 1;
444	while ((i = fork()) == -1 && errno == EAGAIN && forksleep < 32) {
445		if (intrsig)	 /* allow user to ^C out... */
446			break;
447		sleep(forksleep);
448		forksleep <<= 1;
449	}
450	if (i == -1) {
451		kill_job(j, SIGKILL);
452		remove_job(j, "fork failed");
453		sigprocmask(SIG_SETMASK, &omask, NULL);
454		errorf("cannot fork - try again");
455	}
456	ischild = i == 0;
457	if (ischild)
458		p->pid = procpid = getpid();
459	else
460		p->pid = i;
461
462	/* job control set up */
463	if (Flag(FMONITOR) && !(flags&XXCOM)) {
464		int	dotty = 0;
465		if (j->pgrp == 0) {	/* First process */
466			j->pgrp = p->pid;
467			dotty = 1;
468		}
469
470		/* set pgrp in both parent and child to deal with race
471		 * condition
472		 */
473		setpgid(p->pid, j->pgrp);
474		/* YYY: should this be
475		   if (ttypgrp_ok && ischild && !(flags&XBGND))
476			tcsetpgrp(tty_fd, j->pgrp);
477		   instead? (see also YYY below)
478		 */
479		if (ttypgrp_ok && dotty && !(flags & XBGND))
480			tcsetpgrp(tty_fd, j->pgrp);
481	}
482
483	/* used to close pipe input fd */
484	if (close_fd >= 0 && (((flags & XPCLOSE) && !ischild) ||
485	    ((flags & XCCLOSE) && ischild)))
486		close(close_fd);
487	if (ischild) {		/* child */
488		/* Do this before restoring signal */
489		if (flags & XCOPROC)
490			coproc_cleanup(false);
491		sigprocmask(SIG_SETMASK, &omask, NULL);
492		cleanup_parents_env();
493		/* If FMONITOR or FTALKING is set, these signals are ignored,
494		 * if neither FMONITOR nor FTALKING are set, the signals have
495		 * their inherited values.
496		 */
497		if (Flag(FMONITOR) && !(flags & XXCOM)) {
498			for (i = NELEM(tt_sigs); --i >= 0; )
499				setsig(&sigtraps[tt_sigs[i]], SIG_DFL,
500				    SS_RESTORE_DFL|SS_FORCE);
501		}
502		if (Flag(FBGNICE) && (flags & XBGND))
503			nice(4);
504		if ((flags & XBGND) && !Flag(FMONITOR)) {
505			setsig(&sigtraps[SIGINT], SIG_IGN,
506			    SS_RESTORE_IGN|SS_FORCE);
507			setsig(&sigtraps[SIGQUIT], SIG_IGN,
508			    SS_RESTORE_IGN|SS_FORCE);
509			if (!(flags & (XPIPEI | XCOPROC))) {
510				int fd = open("/dev/null", O_RDONLY);
511				if (fd != 0) {
512					(void) ksh_dup2(fd, 0, true);
513					close(fd);
514				}
515			}
516		}
517		remove_job(j, "child");	/* in case of `jobs` command */
518		nzombie = 0;
519		ttypgrp_ok = 0;
520		Flag(FMONITOR) = 0;
521		Flag(FTALKING) = 0;
522		tty_close();
523		cleartraps();
524		execute(t, (flags & XERROK) | XEXEC, NULL); /* no return */
525		internal_warningf("%s: execute() returned", __func__);
526		unwind(LLEAVE);
527		/* NOTREACHED */
528	}
529
530	/* shell (parent) stuff */
531	/* Ensure next child gets a (slightly) different $RANDOM sequence */
532	change_random();
533	if (!(flags & XPIPEO)) {	/* last process in a job */
534		/* YYY: Is this needed? (see also YYY above)
535		   if (Flag(FMONITOR) && !(flags&(XXCOM|XBGND)))
536			tcsetpgrp(tty_fd, j->pgrp);
537		*/
538		j_startjob(j);
539		if (flags & XCOPROC) {
540			j->coproc_id = coproc.id;
541			coproc.njobs++; /* n jobs using co-process output */
542			coproc.job = (void *) j; /* j using co-process input */
543		}
544		if (flags & XBGND) {
545			j_set_async(j);
546			if (Flag(FTALKING)) {
547				shf_fprintf(shl_out, "[%d]", j->job);
548				for (p = j->proc_list; p; p = p->next)
549					shf_fprintf(shl_out, " %d", p->pid);
550				shf_putchar('\n', shl_out);
551				shf_flush(shl_out);
552			}
553		} else
554			rv = j_waitj(j, JW_NONE, "jw:last proc");
555	}
556
557	sigprocmask(SIG_SETMASK, &omask, NULL);
558
559	return rv;
560}
561
562/* start the last job: only used for `command` jobs */
563void
564startlast(void)
565{
566	sigset_t omask;
567
568	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
569
570	if (last_job) { /* no need to report error - waitlast() will do it */
571		/* ensure it isn't removed by check_job() */
572		last_job->flags |= JF_WAITING;
573		j_startjob(last_job);
574	}
575	sigprocmask(SIG_SETMASK, &omask, NULL);
576}
577
578/* wait for last job: only used for `command` jobs */
579int
580waitlast(void)
581{
582	int	rv;
583	Job	*j;
584	sigset_t omask;
585
586	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
587
588	j = last_job;
589	if (!j || !(j->flags & JF_STARTED)) {
590		if (!j)
591			warningf(true, "%s: no last job", __func__);
592		else
593			internal_warningf("%s: not started", __func__);
594		sigprocmask(SIG_SETMASK, &omask, NULL);
595		return 125; /* not so arbitrary, non-zero value */
596	}
597
598	rv = j_waitj(j, JW_NONE, "jw:waitlast");
599
600	sigprocmask(SIG_SETMASK, &omask, NULL);
601
602	return rv;
603}
604
605/* wait for child, interruptable. */
606int
607waitfor(const char *cp, int *sigp)
608{
609	int	rv;
610	Job	*j;
611	int	ecode;
612	int	flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
613	sigset_t omask;
614
615	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
616
617	*sigp = 0;
618
619	if (cp == NULL) {
620		/* wait for an unspecified job - always returns 0, so
621		 * don't have to worry about exited/signaled jobs
622		 */
623		for (j = job_list; j; j = j->next)
624			/* at&t ksh will wait for stopped jobs - we don't */
625			if (j->ppid == procpid && j->state == PRUNNING)
626				break;
627		if (!j) {
628			sigprocmask(SIG_SETMASK, &omask, NULL);
629			return -1;
630		}
631	} else if ((j = j_lookup(cp, &ecode))) {
632		/* don't report normal job completion */
633		flags &= ~JW_ASYNCNOTIFY;
634		if (j->ppid != procpid) {
635			sigprocmask(SIG_SETMASK, &omask, NULL);
636			return -1;
637		}
638	} else {
639		sigprocmask(SIG_SETMASK, &omask, NULL);
640		if (ecode != JL_NOSUCH)
641			bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
642		return -1;
643	}
644
645	/* at&t ksh will wait for stopped jobs - we don't */
646	rv = j_waitj(j, flags, "jw:waitfor");
647
648	sigprocmask(SIG_SETMASK, &omask, NULL);
649
650	if (rv < 0) /* we were interrupted */
651		*sigp = 128 + -rv;
652
653	return rv;
654}
655
656/* kill (built-in) a job */
657int
658j_kill(const char *cp, int sig)
659{
660	Job	*j;
661	int	rv = 0;
662	int	ecode;
663	sigset_t omask;
664
665	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
666
667	if ((j = j_lookup(cp, &ecode)) == NULL) {
668		sigprocmask(SIG_SETMASK, &omask, NULL);
669		bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
670		return 1;
671	}
672
673	if (j->pgrp == 0) {	/* started when !Flag(FMONITOR) */
674		if (kill_job(j, sig) < 0) {
675			bi_errorf("%s: %s", cp, strerror(errno));
676			rv = 1;
677		}
678	} else {
679		if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
680			(void) killpg(j->pgrp, SIGCONT);
681		if (killpg(j->pgrp, sig) == -1) {
682			bi_errorf("%s: %s", cp, strerror(errno));
683			rv = 1;
684		}
685	}
686
687	sigprocmask(SIG_SETMASK, &omask, NULL);
688
689	return rv;
690}
691
692/* fg and bg built-ins: called only if Flag(FMONITOR) set */
693int
694j_resume(const char *cp, int bg)
695{
696	Job	*j;
697	Proc	*p;
698	int	ecode;
699	int	running;
700	int	rv = 0;
701	sigset_t omask;
702
703	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
704
705	if ((j = j_lookup(cp, &ecode)) == NULL) {
706		sigprocmask(SIG_SETMASK, &omask, NULL);
707		bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
708		return 1;
709	}
710
711	if (j->pgrp == 0) {
712		sigprocmask(SIG_SETMASK, &omask, NULL);
713		bi_errorf("job not job-controlled");
714		return 1;
715	}
716
717	if (bg)
718		shprintf("[%d] ", j->job);
719
720	running = 0;
721	for (p = j->proc_list; p != NULL; p = p->next) {
722		if (p->state == PSTOPPED) {
723			p->state = PRUNNING;
724			p->status = 0;
725			running = 1;
726		}
727		shprintf("%s%s", p->command, p->next ? "| " : "");
728	}
729	shprintf("\n");
730	shf_flush(shl_stdout);
731	if (running)
732		j->state = PRUNNING;
733
734	put_job(j, PJ_PAST_STOPPED);
735	if (bg)
736		j_set_async(j);
737	else {
738		/* attach tty to job */
739		if (j->state == PRUNNING) {
740			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
741				tcsetattr(tty_fd, TCSADRAIN, &j->ttystate);
742			/* See comment in j_waitj regarding saved_ttypgrp. */
743			if (ttypgrp_ok &&
744			    tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
745			    j->saved_ttypgrp : j->pgrp) == -1) {
746				if (j->flags & JF_SAVEDTTY)
747					tcsetattr(tty_fd, TCSADRAIN, &tty_state);
748				sigprocmask(SIG_SETMASK, &omask, NULL);
749				bi_errorf("1st tcsetpgrp(%d, %d) failed: %s",
750				    tty_fd,
751				    (int) ((j->flags & JF_SAVEDTTYPGRP) ?
752				    j->saved_ttypgrp : j->pgrp),
753				    strerror(errno));
754				return 1;
755			}
756		}
757		j->flags |= JF_FG;
758		j->flags &= ~JF_KNOWN;
759		if (j == async_job)
760			async_job = NULL;
761	}
762
763	if (j->state == PRUNNING && killpg(j->pgrp, SIGCONT) == -1) {
764		int	err = errno;
765
766		if (!bg) {
767			j->flags &= ~JF_FG;
768			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
769				tcsetattr(tty_fd, TCSADRAIN, &tty_state);
770			if (ttypgrp_ok && tcsetpgrp(tty_fd, our_pgrp) == -1) {
771				warningf(true,
772				    "fg: 2nd tcsetpgrp(%d, %d) failed: %s",
773				    tty_fd, (int) our_pgrp,
774				    strerror(errno));
775			}
776		}
777		sigprocmask(SIG_SETMASK, &omask, NULL);
778		bi_errorf("cannot continue job %s: %s",
779		    cp, strerror(err));
780		return 1;
781	}
782	if (!bg) {
783		if (ttypgrp_ok) {
784			j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
785		}
786		rv = j_waitj(j, JW_NONE, "jw:resume");
787	}
788	sigprocmask(SIG_SETMASK, &omask, NULL);
789	return rv;
790}
791
792/* are there any running or stopped jobs ? */
793int
794j_stopped_running(void)
795{
796	Job	*j;
797	int	which = 0;
798
799	for (j = job_list; j != NULL; j = j->next) {
800		if (j->ppid == procpid && j->state == PSTOPPED)
801			which |= 1;
802		if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
803		    j->ppid == procpid && j->state == PRUNNING)
804			which |= 2;
805	}
806	if (which) {
807		shellf("You have %s%s%s jobs\n",
808		    which & 1 ? "stopped" : "",
809		    which == 3 ? " and " : "",
810		    which & 2 ? "running" : "");
811		return 1;
812	}
813
814	return 0;
815}
816
817int
818j_njobs(void)
819{
820	Job *j;
821	int nj = 0;
822	sigset_t omask;
823
824	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
825	for (j = job_list; j; j = j->next)
826		nj++;
827
828	sigprocmask(SIG_SETMASK, &omask, NULL);
829	return nj;
830}
831
832
833/* list jobs for jobs built-in */
834int
835j_jobs(const char *cp, int slp,
836    int nflag)		/* 0: short, 1: long, 2: pgrp */
837{
838	Job	*j, *tmp;
839	int	how;
840	int	zflag = 0;
841	sigset_t omask;
842
843	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
844
845	if (nflag < 0) { /* kludge: print zombies */
846		nflag = 0;
847		zflag = 1;
848	}
849	if (cp) {
850		int	ecode;
851
852		if ((j = j_lookup(cp, &ecode)) == NULL) {
853			sigprocmask(SIG_SETMASK, &omask, NULL);
854			bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
855			return 1;
856		}
857	} else
858		j = job_list;
859	how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
860	for (; j; j = j->next) {
861		if ((!(j->flags & JF_ZOMBIE) || zflag) &&
862		    (!nflag || (j->flags & JF_CHANGED))) {
863			j_print(j, how, shl_stdout);
864			if (j->state == PEXITED || j->state == PSIGNALLED)
865				j->flags |= JF_REMOVE;
866		}
867		if (cp)
868			break;
869	}
870	/* Remove jobs after printing so there won't be multiple + or - jobs */
871	for (j = job_list; j; j = tmp) {
872		tmp = j->next;
873		if (j->flags & JF_REMOVE)
874			remove_job(j, "jobs");
875	}
876	sigprocmask(SIG_SETMASK, &omask, NULL);
877	return 0;
878}
879
880/* list jobs for top-level notification */
881void
882j_notify(void)
883{
884	Job	*j, *tmp;
885	sigset_t omask;
886
887	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
888	for (j = job_list; j; j = j->next) {
889		if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
890			j_print(j, JP_MEDIUM, shl_out);
891		/* Remove job after doing reports so there aren't
892		 * multiple +/- jobs.
893		 */
894		if (j->state == PEXITED || j->state == PSIGNALLED)
895			j->flags |= JF_REMOVE;
896	}
897	for (j = job_list; j; j = tmp) {
898		tmp = j->next;
899		if (j->flags & JF_REMOVE)
900			remove_job(j, "notify");
901	}
902	shf_flush(shl_out);
903	sigprocmask(SIG_SETMASK, &omask, NULL);
904}
905
906/* Return pid of last process in last asynchronous job */
907pid_t
908j_async(void)
909{
910	sigset_t omask;
911
912	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
913
914	if (async_job)
915		async_job->flags |= JF_KNOWN;
916
917	sigprocmask(SIG_SETMASK, &omask, NULL);
918
919	return async_pid;
920}
921
922/* Make j the last async process
923 *
924 * Expects sigchld to be blocked.
925 */
926static void
927j_set_async(Job *j)
928{
929	Job	*jl, *oldest;
930
931	if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
932		remove_job(async_job, "async");
933	if (!(j->flags & JF_STARTED)) {
934		internal_warningf("%s: job not started", __func__);
935		return;
936	}
937	async_job = j;
938	async_pid = j->last_proc->pid;
939	while (nzombie > child_max) {
940		oldest = NULL;
941		for (jl = job_list; jl; jl = jl->next)
942			if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
943			    (!oldest || jl->age < oldest->age))
944				oldest = jl;
945		if (!oldest) {
946			/* XXX debugging */
947			if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
948				internal_warningf("%s: bad nzombie (%d)",
949				    __func__, nzombie);
950				nzombie = 0;
951			}
952			break;
953		}
954		remove_job(oldest, "zombie");
955	}
956}
957
958/* Start a job: set STARTED, check for held signals and set j->last_proc
959 *
960 * Expects sigchld to be blocked.
961 */
962static void
963j_startjob(Job *j)
964{
965	Proc	*p;
966
967	j->flags |= JF_STARTED;
968	for (p = j->proc_list; p->next; p = p->next)
969		;
970	j->last_proc = p;
971
972	if (held_sigchld) {
973		held_sigchld = 0;
974		/* Don't call j_sigchld() as it may remove job... */
975		kill(procpid, SIGCHLD);
976	}
977}
978
979/*
980 * wait for job to complete or change state
981 *
982 * Expects sigchld to be blocked.
983 */
984static int
985j_waitj(Job *j,
986    int flags,			/* see JW_* */
987    const char *where)
988{
989	int	rv;
990
991	/*
992	 * No auto-notify on the job we are waiting on.
993	 */
994	j->flags |= JF_WAITING;
995	if (flags & JW_ASYNCNOTIFY)
996		j->flags |= JF_W_ASYNCNOTIFY;
997
998	if (!Flag(FMONITOR))
999		flags |= JW_STOPPEDWAIT;
1000
1001	while ((volatile int) j->state == PRUNNING ||
1002	    ((flags & JW_STOPPEDWAIT) && (volatile int) j->state == PSTOPPED)) {
1003		sigsuspend(&sm_default);
1004		if (fatal_trap) {
1005			int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1006			j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1007			runtraps(TF_FATAL);
1008			j->flags |= oldf; /* not reached... */
1009		}
1010		if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1011			j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1012			return -rv;
1013		}
1014	}
1015	j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1016
1017	if (j->flags & JF_FG) {
1018		int	status;
1019
1020		j->flags &= ~JF_FG;
1021		if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1022			/*
1023			 * Save the tty's current pgrp so it can be restored
1024			 * when the job is foregrounded.  This is to
1025			 * deal with things like the GNU su which does
1026			 * a fork/exec instead of an exec (the fork means
1027			 * the execed shell gets a different pid from its
1028			 * pgrp, so naturally it sets its pgrp and gets hosed
1029			 * when it gets foregrounded by the parent shell, which
1030			 * has restored the tty's pgrp to that of the su
1031			 * process).
1032			 */
1033			if (j->state == PSTOPPED &&
1034			    (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1035				j->flags |= JF_SAVEDTTYPGRP;
1036			if (tcsetpgrp(tty_fd, our_pgrp) == -1) {
1037				warningf(true,
1038				    "%s: tcsetpgrp(%d, %d) failed: %s",
1039				    __func__, tty_fd, (int)our_pgrp,
1040					strerror(errno));
1041			}
1042			if (j->state == PSTOPPED) {
1043				j->flags |= JF_SAVEDTTY;
1044				tcgetattr(tty_fd, &j->ttystate);
1045			}
1046		}
1047		if (tty_fd >= 0) {
1048			/* Only restore tty settings if job was originally
1049			 * started in the foreground.  Problems can be
1050			 * caused by things like `more foobar &' which will
1051			 * typically get and save the shell's vi/emacs tty
1052			 * settings before setting up the tty for itself;
1053			 * when more exits, it restores the `original'
1054			 * settings, and things go down hill from there...
1055			 */
1056			if (j->state == PEXITED && j->status == 0 &&
1057			    (j->flags & JF_USETTYMODE)) {
1058				tcgetattr(tty_fd, &tty_state);
1059			} else {
1060				tcsetattr(tty_fd, TCSADRAIN, &tty_state);
1061				/* Don't use tty mode if job is stopped and
1062				 * later restarted and exits.  Consider
1063				 * the sequence:
1064				 *	vi foo (stopped)
1065				 *	...
1066				 *	stty something
1067				 *	...
1068				 *	fg (vi; ZZ)
1069				 * mode should be that of the stty, not what
1070				 * was before the vi started.
1071				 */
1072				if (j->state == PSTOPPED)
1073					j->flags &= ~JF_USETTYMODE;
1074			}
1075		}
1076		/* If it looks like user hit ^C to kill a job, pretend we got
1077		 * one too to break out of for loops, etc.  (at&t ksh does this
1078		 * even when not monitoring, but this doesn't make sense since
1079		 * a tty generated ^C goes to the whole process group)
1080		 */
1081		status = j->last_proc->status;
1082		if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1083		    WIFSIGNALED(status) &&
1084		    (sigtraps[WTERMSIG(status)].flags & TF_TTY_INTR))
1085			trapsig(WTERMSIG(status));
1086	}
1087
1088	j_usrtime = j->usrtime;
1089	j_systime = j->systime;
1090
1091	if (j->flags & JF_PIPEFAIL) {
1092		Proc *p;
1093		int status;
1094
1095		rv = 0;
1096		for (p = j->proc_list; p != NULL; p = p->next) {
1097			switch (p->state) {
1098			case PEXITED:
1099				status = WEXITSTATUS(p->status);
1100				break;
1101			case PSIGNALLED:
1102				status = 128 + WTERMSIG(p->status);
1103				break;
1104			default:
1105				status = 0;
1106				break;
1107			}
1108			if (status)
1109				rv = status;
1110		}
1111	} else
1112		rv = j->status;
1113
1114
1115	if (!(flags & JW_ASYNCNOTIFY) &&
1116	    (!Flag(FMONITOR) || j->state != PSTOPPED)) {
1117		j_print(j, JP_SHORT, shl_out);
1118		shf_flush(shl_out);
1119	}
1120	if (j->state != PSTOPPED &&
1121	    (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY)))
1122		remove_job(j, where);
1123
1124	return rv;
1125}
1126
1127/* SIGCHLD handler to reap children and update job states
1128 *
1129 * Expects sigchld to be blocked.
1130 */
1131static void
1132j_sigchld(int sig)
1133{
1134	int		errno_ = errno;
1135	Job		*j;
1136	Proc		*p = NULL;
1137	int		pid;
1138	int		status;
1139	struct rusage	ru0, ru1;
1140
1141	/* Don't wait for any processes if a job is partially started.
1142	 * This is so we don't do away with the process group leader
1143	 * before all the processes in a pipe line are started (so the
1144	 * setpgid() won't fail)
1145	 */
1146	for (j = job_list; j; j = j->next)
1147		if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1148			held_sigchld = 1;
1149			goto finished;
1150		}
1151
1152	getrusage(RUSAGE_CHILDREN, &ru0);
1153	do {
1154		pid = waitpid(-1, &status, (WNOHANG|WUNTRACED));
1155
1156		if (pid <= 0)	/* return if would block (0) ... */
1157			break;	/* ... or no children or interrupted (-1) */
1158
1159		getrusage(RUSAGE_CHILDREN, &ru1);
1160
1161		/* find job and process structures for this pid */
1162		for (j = job_list; j != NULL; j = j->next)
1163			for (p = j->proc_list; p != NULL; p = p->next)
1164				if (p->pid == pid)
1165					goto found;
1166found:
1167		if (j == NULL) {
1168			/* Can occur if process has kids, then execs shell
1169			warningf(true, "bad process waited for (pid = %d)",
1170				pid);
1171			 */
1172			ru0 = ru1;
1173			continue;
1174		}
1175
1176		timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1177		timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1178		timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1179		timersub(&j->systime, &ru0.ru_stime, &j->systime);
1180		ru0 = ru1;
1181		p->status = status;
1182		if (WIFSTOPPED(status))
1183			p->state = PSTOPPED;
1184		else if (WIFSIGNALED(status))
1185			p->state = PSIGNALLED;
1186		else
1187			p->state = PEXITED;
1188
1189		check_job(j);	/* check to see if entire job is done */
1190	} while (1);
1191
1192finished:
1193	errno = errno_;
1194}
1195
1196/*
1197 * Called only when a process in j has exited/stopped (ie, called only
1198 * from j_sigchld()).  If no processes are running, the job status
1199 * and state are updated, asynchronous job notification is done and,
1200 * if unneeded, the job is removed.
1201 *
1202 * Expects sigchld to be blocked.
1203 */
1204static void
1205check_job(Job *j)
1206{
1207	int	jstate;
1208	Proc	*p;
1209
1210	/* XXX debugging (nasty - interrupt routine using shl_out) */
1211	if (!(j->flags & JF_STARTED)) {
1212		internal_warningf("%s: job started (flags 0x%x)",
1213		    __func__, j->flags);
1214		return;
1215	}
1216
1217	jstate = PRUNNING;
1218	for (p=j->proc_list; p != NULL; p = p->next) {
1219		if (p->state == PRUNNING)
1220			return;	/* some processes still running */
1221		if (p->state > jstate)
1222			jstate = p->state;
1223	}
1224	j->state = jstate;
1225
1226	switch (j->last_proc->state) {
1227	case PEXITED:
1228		j->status = WEXITSTATUS(j->last_proc->status);
1229		break;
1230	case PSIGNALLED:
1231		j->status = 128 + WTERMSIG(j->last_proc->status);
1232		break;
1233	default:
1234		j->status = 0;
1235		break;
1236	}
1237
1238	/* Note when co-process dies: can't be done in j_wait() nor
1239	 * remove_job() since neither may be called for non-interactive
1240	 * shells.
1241	 */
1242	if (j->state == PEXITED || j->state == PSIGNALLED) {
1243		/* No need to keep co-process input any more
1244		 * (at least, this is what ksh93d thinks)
1245		 */
1246		if (coproc.job == j) {
1247			coproc.job = NULL;
1248			/* XXX would be nice to get the closes out of here
1249			 * so they aren't done in the signal handler.
1250			 * Would mean a check in coproc_getfd() to
1251			 * do "if job == 0 && write >= 0, close write".
1252			 */
1253			coproc_write_close(coproc.write);
1254		}
1255		/* Do we need to keep the output? */
1256		if (j->coproc_id && j->coproc_id == coproc.id &&
1257		    --coproc.njobs == 0)
1258			coproc_readw_close(coproc.read);
1259	}
1260
1261	j->flags |= JF_CHANGED;
1262	if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1263		/* Only put stopped jobs at the front to avoid confusing
1264		 * the user (don't want finished jobs effecting %+ or %-)
1265		 */
1266		if (j->state == PSTOPPED)
1267			put_job(j, PJ_ON_FRONT);
1268		if (Flag(FNOTIFY) &&
1269		    (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1270			/* Look for the real file descriptor 2 */
1271			{
1272				struct env *ep;
1273				int fd = 2;
1274
1275				for (ep = genv; ep; ep = ep->oenv)
1276					if (ep->savefd && ep->savefd[2])
1277						fd = ep->savefd[2];
1278				shf_reopen(fd, SHF_WR, shl_j);
1279			}
1280			/* Can't call j_notify() as it removes jobs.  The job
1281			 * must stay in the job list as j_waitj() may be
1282			 * running with this job.
1283			 */
1284			j_print(j, JP_MEDIUM, shl_j);
1285			shf_flush(shl_j);
1286			if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1287				remove_job(j, "notify");
1288		}
1289	}
1290	if (!Flag(FMONITOR) && !(j->flags & (JF_WAITING|JF_FG)) &&
1291	    j->state != PSTOPPED) {
1292		if (j == async_job || (j->flags & JF_KNOWN)) {
1293			j->flags |= JF_ZOMBIE;
1294			j->job = -1;
1295			nzombie++;
1296		} else
1297			remove_job(j, "checkjob");
1298	}
1299}
1300
1301/*
1302 * Print job status in either short, medium or long format.
1303 *
1304 * Expects sigchld to be blocked.
1305 */
1306static void
1307j_print(Job *j, int how, struct shf *shf)
1308{
1309	Proc	*p;
1310	int	state;
1311	int	status;
1312	int	coredumped;
1313	char	jobchar = ' ';
1314	char	buf[64];
1315	const char *filler;
1316	int	output = 0;
1317
1318	if (how == JP_PGRP) {
1319		/* POSIX doesn't say what to do if there is no process
1320		 * group leader (ie, !FMONITOR).  We arbitrarily return
1321		 * last pid (which is what $! returns).
1322		 */
1323		shf_fprintf(shf, "%d\n", j->pgrp ? j->pgrp :
1324		    (j->last_proc ? j->last_proc->pid : 0));
1325		return;
1326	}
1327	j->flags &= ~JF_CHANGED;
1328	filler = j->job > 10 ?  "\n       " : "\n      ";
1329	if (j == job_list)
1330		jobchar = '+';
1331	else if (j == job_list->next)
1332		jobchar = '-';
1333
1334	for (p = j->proc_list; p != NULL;) {
1335		coredumped = 0;
1336		switch (p->state) {
1337		case PRUNNING:
1338			strlcpy(buf, "Running", sizeof buf);
1339			break;
1340		case PSTOPPED:
1341			strlcpy(buf, sigtraps[WSTOPSIG(p->status)].mess,
1342			    sizeof buf);
1343			break;
1344		case PEXITED:
1345			if (how == JP_SHORT)
1346				buf[0] = '\0';
1347			else if (WEXITSTATUS(p->status) == 0)
1348				strlcpy(buf, "Done", sizeof buf);
1349			else
1350				shf_snprintf(buf, sizeof(buf), "Done (%d)",
1351				    WEXITSTATUS(p->status));
1352			break;
1353		case PSIGNALLED:
1354			if (WCOREDUMP(p->status))
1355				coredumped = 1;
1356			/* kludge for not reporting `normal termination signals'
1357			 * (ie, SIGINT, SIGPIPE)
1358			 */
1359			if (how == JP_SHORT && !coredumped &&
1360			    (WTERMSIG(p->status) == SIGINT ||
1361			    WTERMSIG(p->status) == SIGPIPE)) {
1362				buf[0] = '\0';
1363			} else
1364				strlcpy(buf, sigtraps[WTERMSIG(p->status)].mess,
1365				    sizeof buf);
1366			break;
1367		}
1368
1369		if (how != JP_SHORT) {
1370			if (p == j->proc_list)
1371				shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1372			else
1373				shf_fprintf(shf, "%s", filler);
1374		}
1375
1376		if (how == JP_LONG)
1377			shf_fprintf(shf, "%5d ", p->pid);
1378
1379		if (how == JP_SHORT) {
1380			if (buf[0]) {
1381				output = 1;
1382				shf_fprintf(shf, "%s%s ",
1383				    buf, coredumped ? " (core dumped)" : "");
1384			}
1385		} else {
1386			output = 1;
1387			shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1388			    p->next ? "|" : "",
1389			    coredumped ? " (core dumped)" : "");
1390		}
1391
1392		state = p->state;
1393		status = p->status;
1394		p = p->next;
1395		while (p && p->state == state && p->status == status) {
1396			if (how == JP_LONG)
1397				shf_fprintf(shf, "%s%5d %-20s %s%s", filler, p->pid,
1398				    " ", p->command, p->next ? "|" : "");
1399			else if (how == JP_MEDIUM)
1400				shf_fprintf(shf, " %s%s", p->command,
1401				    p->next ? "|" : "");
1402			p = p->next;
1403		}
1404	}
1405	if (output)
1406		shf_fprintf(shf, "\n");
1407}
1408
1409/* Convert % sequence to job
1410 *
1411 * Expects sigchld to be blocked.
1412 */
1413static Job *
1414j_lookup(const char *cp, int *ecodep)
1415{
1416	Job		*j, *last_match;
1417	const char	*errstr;
1418	Proc		*p;
1419	int		len, job = 0;
1420
1421	if (digit(*cp)) {
1422		job = strtonum(cp, 1, INT_MAX, &errstr);
1423		if (errstr) {
1424			if (ecodep)
1425				*ecodep = JL_NOSUCH;
1426			return NULL;
1427		}
1428		/* Look for last_proc->pid (what $! returns) first... */
1429		for (j = job_list; j != NULL; j = j->next)
1430			if (j->last_proc && j->last_proc->pid == job)
1431				return j;
1432		/* ...then look for process group (this is non-POSIX),
1433		 * but should not break anything (so FPOSIX isn't used).
1434		 */
1435		for (j = job_list; j != NULL; j = j->next)
1436			if (j->pgrp && j->pgrp == job)
1437				return j;
1438		if (ecodep)
1439			*ecodep = JL_NOSUCH;
1440		return NULL;
1441	}
1442	if (*cp != '%') {
1443		if (ecodep)
1444			*ecodep = JL_INVALID;
1445		return NULL;
1446	}
1447	switch (*++cp) {
1448	case '\0': /* non-standard */
1449	case '+':
1450	case '%':
1451		if (job_list != NULL)
1452			return job_list;
1453		break;
1454
1455	case '-':
1456		if (job_list != NULL && job_list->next)
1457			return job_list->next;
1458		break;
1459
1460	case '0': case '1': case '2': case '3': case '4':
1461	case '5': case '6': case '7': case '8': case '9':
1462		job = strtonum(cp, 1, INT_MAX, &errstr);
1463		if (errstr)
1464			break;
1465		for (j = job_list; j != NULL; j = j->next)
1466			if (j->job == job)
1467				return j;
1468		break;
1469
1470	case '?':		/* %?string */
1471		last_match = NULL;
1472		for (j = job_list; j != NULL; j = j->next)
1473			for (p = j->proc_list; p != NULL; p = p->next)
1474				if (strstr(p->command, cp+1) != NULL) {
1475					if (last_match) {
1476						if (ecodep)
1477							*ecodep = JL_AMBIG;
1478						return NULL;
1479					}
1480					last_match = j;
1481				}
1482		if (last_match)
1483			return last_match;
1484		break;
1485
1486	default:		/* %string */
1487		len = strlen(cp);
1488		last_match = NULL;
1489		for (j = job_list; j != NULL; j = j->next)
1490			if (strncmp(cp, j->proc_list->command, len) == 0) {
1491				if (last_match) {
1492					if (ecodep)
1493						*ecodep = JL_AMBIG;
1494					return NULL;
1495				}
1496				last_match = j;
1497			}
1498		if (last_match)
1499			return last_match;
1500		break;
1501	}
1502	if (ecodep)
1503		*ecodep = JL_NOSUCH;
1504	return NULL;
1505}
1506
1507static Job	*free_jobs;
1508static Proc	*free_procs;
1509
1510/* allocate a new job and fill in the job number.
1511 *
1512 * Expects sigchld to be blocked.
1513 */
1514static Job *
1515new_job(void)
1516{
1517	int	i;
1518	Job	*newj, *j;
1519
1520	if (free_jobs != NULL) {
1521		newj = free_jobs;
1522		free_jobs = free_jobs->next;
1523	} else
1524		newj = alloc(sizeof(Job), APERM);
1525
1526	/* brute force method */
1527	for (i = 1; ; i++) {
1528		for (j = job_list; j && j->job != i; j = j->next)
1529			;
1530		if (j == NULL)
1531			break;
1532	}
1533	newj->job = i;
1534
1535	return newj;
1536}
1537
1538/* Allocate new process struct
1539 *
1540 * Expects sigchld to be blocked.
1541 */
1542static Proc *
1543new_proc(void)
1544{
1545	Proc	*p;
1546
1547	if (free_procs != NULL) {
1548		p = free_procs;
1549		free_procs = free_procs->next;
1550	} else
1551		p = alloc(sizeof(Proc), APERM);
1552
1553	return p;
1554}
1555
1556/* Take job out of job_list and put old structures into free list.
1557 * Keeps nzombies, last_job and async_job up to date.
1558 *
1559 * Expects sigchld to be blocked.
1560 */
1561static void
1562remove_job(Job *j, const char *where)
1563{
1564	Proc	*p, *tmp;
1565	Job	**prev, *curr;
1566
1567	prev = &job_list;
1568	curr = *prev;
1569	for (; curr != NULL && curr != j; prev = &curr->next, curr = *prev)
1570		;
1571	if (curr != j) {
1572		internal_warningf("%s: job not found (%s)", __func__, where);
1573		return;
1574	}
1575	*prev = curr->next;
1576
1577	/* free up proc structures */
1578	for (p = j->proc_list; p != NULL; ) {
1579		tmp = p;
1580		p = p->next;
1581		tmp->next = free_procs;
1582		free_procs = tmp;
1583	}
1584
1585	if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1586		--nzombie;
1587	j->next = free_jobs;
1588	free_jobs = j;
1589
1590	if (j == last_job)
1591		last_job = NULL;
1592	if (j == async_job)
1593		async_job = NULL;
1594}
1595
1596/* Put j in a particular location (taking it out of job_list if it is
1597 * there already)
1598 *
1599 * Expects sigchld to be blocked.
1600 */
1601static void
1602put_job(Job *j, int where)
1603{
1604	Job	**prev, *curr;
1605
1606	/* Remove job from list (if there) */
1607	prev = &job_list;
1608	curr = job_list;
1609	for (; curr && curr != j; prev = &curr->next, curr = *prev)
1610		;
1611	if (curr == j)
1612		*prev = curr->next;
1613
1614	switch (where) {
1615	case PJ_ON_FRONT:
1616		j->next = job_list;
1617		job_list = j;
1618		break;
1619
1620	case PJ_PAST_STOPPED:
1621		prev = &job_list;
1622		curr = job_list;
1623		for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1624		    curr = *prev)
1625			;
1626		j->next = curr;
1627		*prev = j;
1628		break;
1629	}
1630}
1631
1632/* nuke a job (called when unable to start full job).
1633 *
1634 * Expects sigchld to be blocked.
1635 */
1636static int
1637kill_job(Job *j, int sig)
1638{
1639	Proc	*p;
1640	int	rval = 0;
1641
1642	for (p = j->proc_list; p != NULL; p = p->next)
1643		if (p->pid != 0)
1644			if (kill(p->pid, sig) == -1)
1645				rval = -1;
1646	return rval;
1647}