• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*	$OpenBSD: jobs.c,v 1.43 2015/09/10 22:48:58 nicm Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
5  *		 2012, 2013, 2014, 2015, 2016, 2018
6  *	mirabilos <m@mirbsd.org>
7  *
8  * Provided that these terms and disclaimer and all copyright notices
9  * are retained or reproduced in an accompanying document, permission
10  * is granted to deal in this work without restriction, including un-
11  * limited rights to use, publicly perform, distribute, sell, modify,
12  * merge, give away, or sublicence.
13  *
14  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15  * the utmost extent permitted by applicable law, neither express nor
16  * implied; without malicious intent or gross negligence. In no event
17  * may a licensor, author or contributor be held liable for indirect,
18  * direct, other damage, loss, or other issues arising in any way out
19  * of dealing in the work, even if advised of the possibility of such
20  * damage or existence of a defect, except proven that it results out
21  * of said person's immediate fault when using the work as intended.
22  */
23 
24 #include "sh.h"
25 
26 __RCSID("$MirOS: src/bin/mksh/jobs.c,v 1.127 2018/07/15 16:23:10 tg Exp $");
27 
28 #if HAVE_KILLPG
29 #define mksh_killpg		killpg
30 #else
31 /* cross fingers and hope kill is killpg-endowed */
32 #define mksh_killpg(p,s)	kill(-(p), (s))
33 #endif
34 
35 /* Order important! */
36 #define PRUNNING	0
37 #define PEXITED		1
38 #define PSIGNALLED	2
39 #define PSTOPPED	3
40 
41 typedef struct proc Proc;
42 /* to take alignment into consideration */
43 struct proc_dummy {
44 	Proc *next;
45 	pid_t pid;
46 	int state;
47 	int status;
48 	char command[128];
49 };
50 /* real structure */
51 struct proc {
52 	/* next process in pipeline (if any) */
53 	Proc *next;
54 	/* process id of this Unix process in the job */
55 	pid_t pid;
56 	/* one of the four P… above */
57 	int state;
58 	/* wait status */
59 	int status;
60 	/* process command string from vistree */
61 	char command[256 - (ALLOC_OVERHEAD +
62 	    offsetof(struct proc_dummy, command[0]))];
63 };
64 
65 /* Notify/print flag - j_print() argument */
66 #define JP_SHORT	1	/* print signals processes were killed by */
67 #define JP_MEDIUM	2	/* print [job-num] -/+ command */
68 #define JP_LONG		3	/* print [job-num] -/+ pid command */
69 #define JP_PGRP		4	/* print pgrp */
70 
71 /* put_job() flags */
72 #define PJ_ON_FRONT	0	/* at very front */
73 #define PJ_PAST_STOPPED	1	/* just past any stopped jobs */
74 
75 /* Job.flags values */
76 #define JF_STARTED	0x001	/* set when all processes in job are started */
77 #define JF_WAITING	0x002	/* set if j_waitj() is waiting on job */
78 #define JF_W_ASYNCNOTIFY 0x004	/* set if waiting and async notification ok */
79 #define JF_XXCOM	0x008	/* set for $(command) jobs */
80 #define JF_FG		0x010	/* running in foreground (also has tty pgrp) */
81 #define JF_SAVEDTTY	0x020	/* j->ttystat is valid */
82 #define JF_CHANGED	0x040	/* process has changed state */
83 #define JF_KNOWN	0x080	/* $! referenced */
84 #define JF_ZOMBIE	0x100	/* known, unwaited process */
85 #define JF_REMOVE	0x200	/* flagged for removal (j_jobs()/j_noityf()) */
86 #define JF_USETTYMODE	0x400	/* tty mode saved if process exits normally */
87 #define JF_SAVEDTTYPGRP	0x800	/* j->saved_ttypgrp is valid */
88 
89 typedef struct job Job;
90 struct job {
91 	Job *next;		/* next job in list */
92 	Proc *proc_list;	/* process list */
93 	Proc *last_proc;	/* last process in list */
94 	struct timeval systime;	/* system time used by job */
95 	struct timeval usrtime;	/* user time used by job */
96 	pid_t pgrp;		/* process group of job */
97 	pid_t ppid;		/* pid of process that forked job */
98 	int job;		/* job number: %n */
99 	int flags;		/* see JF_* */
100 	volatile int state;	/* job state */
101 	int status;		/* exit status of last process */
102 	int age;		/* number of jobs started */
103 	Coproc_id coproc_id;	/* 0 or id of coprocess output pipe */
104 #ifndef MKSH_UNEMPLOYED
105 	mksh_ttyst ttystat;	/* saved tty state for stopped jobs */
106 	pid_t saved_ttypgrp;	/* saved tty process group for stopped jobs */
107 #endif
108 };
109 
110 /* Flags for j_waitj() */
111 #define JW_NONE		0x00
112 #define JW_INTERRUPT	0x01	/* ^C will stop the wait */
113 #define JW_ASYNCNOTIFY	0x02	/* asynchronous notification during wait ok */
114 #define JW_STOPPEDWAIT	0x04	/* wait even if job stopped */
115 #define JW_PIPEST	0x08	/* want PIPESTATUS */
116 
117 /* Error codes for j_lookup() */
118 #define JL_NOSUCH	0	/* no such job */
119 #define JL_AMBIG	1	/* %foo or %?foo is ambiguous */
120 #define JL_INVALID	2	/* non-pid, non-% job id */
121 
122 static const char * const lookup_msgs[] = {
123 	"no such job",
124 	"ambiguous",
125 	"argument must be %job or process id"
126 };
127 
128 static Job *job_list;		/* job list */
129 static Job *last_job;
130 static Job *async_job;
131 static pid_t async_pid;
132 
133 static int nzombie;		/* # of zombies owned by this process */
134 static int njobs;		/* # of jobs started */
135 
136 #ifndef CHILD_MAX
137 #define CHILD_MAX	25
138 #endif
139 
140 #ifndef MKSH_NOPROSPECTOFWORK
141 /* held_sigchld is set if sigchld occurs before a job is completely started */
142 static volatile sig_atomic_t held_sigchld;
143 #endif
144 
145 #ifndef MKSH_UNEMPLOYED
146 static struct shf	*shl_j;
147 static bool		ttypgrp_ok;	/* set if can use tty pgrps */
148 static pid_t		restore_ttypgrp = -1;
149 static int const	tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
150 #endif
151 
152 static void		j_set_async(Job *);
153 static void		j_startjob(Job *);
154 static int		j_waitj(Job *, int, const char *);
155 static void		j_sigchld(int);
156 static void		j_print(Job *, int, struct shf *);
157 static Job		*j_lookup(const char *, int *);
158 static Job		*new_job(void);
159 static Proc		*new_proc(void);
160 static void		check_job(Job *);
161 static void		put_job(Job *, int);
162 static void		remove_job(Job *, const char *);
163 static int		kill_job(Job *, int);
164 
165 static void tty_init_talking(void);
166 static void tty_init_state(void);
167 
168 /* initialise job control */
169 void
j_init(void)170 j_init(void)
171 {
172 #ifndef MKSH_NOPROSPECTOFWORK
173 	(void)sigemptyset(&sm_default);
174 	sigprocmask(SIG_SETMASK, &sm_default, NULL);
175 
176 	(void)sigemptyset(&sm_sigchld);
177 	(void)sigaddset(&sm_sigchld, SIGCHLD);
178 
179 	setsig(&sigtraps[SIGCHLD], j_sigchld,
180 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
181 #else
182 	/* Make sure SIGCHLD isn't ignored - can do odd things under SYSV */
183 	setsig(&sigtraps[SIGCHLD], SIG_DFL, SS_RESTORE_ORIG|SS_FORCE);
184 #endif
185 
186 #ifndef MKSH_UNEMPLOYED
187 	if (Flag(FMONITOR) == 127)
188 		Flag(FMONITOR) = Flag(FTALKING);
189 
190 	/*
191 	 * shl_j is used to do asynchronous notification (used in
192 	 * an interrupt handler, so need a distinct shf)
193 	 */
194 	shl_j = shf_fdopen(2, SHF_WR, NULL);
195 
196 	if (Flag(FMONITOR) || Flag(FTALKING)) {
197 		int i;
198 
199 		/*
200 		 * the TF_SHELL_USES test is a kludge that lets us know if
201 		 * if the signals have been changed by the shell.
202 		 */
203 		for (i = NELEM(tt_sigs); --i >= 0; ) {
204 			sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
205 			/* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
206 			setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
207 			    SS_RESTORE_IGN|SS_FORCE);
208 		}
209 	}
210 
211 	/* j_change() calls tty_init_talking() and tty_init_state() */
212 	if (Flag(FMONITOR))
213 		j_change();
214 	else
215 #endif
216 	  if (Flag(FTALKING)) {
217 		tty_init_talking();
218 		tty_init_state();
219 	}
220 }
221 
222 static int
proc_errorlevel(Proc * p)223 proc_errorlevel(Proc *p)
224 {
225 	switch (p->state) {
226 	case PEXITED:
227 		return ((WEXITSTATUS(p->status)) & 255);
228 	case PSIGNALLED:
229 		return (ksh_sigmask(WTERMSIG(p->status)));
230 	default:
231 		return (0);
232 	}
233 }
234 
235 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
236 /* suspend the shell */
237 void
j_suspend(void)238 j_suspend(void)
239 {
240 	struct sigaction sa, osa;
241 
242 	/* Restore tty and pgrp. */
243 	if (ttypgrp_ok) {
244 		if (tty_hasstate)
245 			mksh_tcset(tty_fd, &tty_state);
246 		if (restore_ttypgrp >= 0) {
247 			if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
248 				warningf(false, Tf_ssfaileds,
249 				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
250 			} else if (setpgid(0, restore_ttypgrp) < 0) {
251 				warningf(false, Tf_ssfaileds,
252 				    Tj_suspend, "setpgid", cstrerror(errno));
253 			}
254 		}
255 	}
256 
257 	/* Suspend the shell. */
258 	memset(&sa, 0, sizeof(sa));
259 	sigemptyset(&sa.sa_mask);
260 	sa.sa_handler = SIG_DFL;
261 	sigaction(SIGTSTP, &sa, &osa);
262 	kill(0, SIGTSTP);
263 
264 	/* Back from suspend, reset signals, pgrp and tty. */
265 	sigaction(SIGTSTP, &osa, NULL);
266 	if (ttypgrp_ok) {
267 		if (restore_ttypgrp >= 0) {
268 			if (setpgid(0, kshpid) < 0) {
269 				warningf(false, Tf_ssfaileds,
270 				    Tj_suspend, "setpgid", cstrerror(errno));
271 				ttypgrp_ok = false;
272 			} else if (tcsetpgrp(tty_fd, kshpid) < 0) {
273 				warningf(false, Tf_ssfaileds,
274 				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
275 				ttypgrp_ok = false;
276 			}
277 		}
278 		tty_init_state();
279 	}
280 }
281 #endif
282 
283 /* job cleanup before shell exit */
284 void
j_exit(void)285 j_exit(void)
286 {
287 	/* kill stopped, and possibly running, jobs */
288 	Job *j;
289 	bool killed = false;
290 
291 	for (j = job_list; j != NULL; j = j->next) {
292 		if (j->ppid == procpid &&
293 		    (j->state == PSTOPPED ||
294 		    (j->state == PRUNNING &&
295 		    ((j->flags & JF_FG) ||
296 		    (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
297 			killed = true;
298 			if (j->pgrp == 0)
299 				kill_job(j, SIGHUP);
300 			else
301 				mksh_killpg(j->pgrp, SIGHUP);
302 #ifndef MKSH_UNEMPLOYED
303 			if (j->state == PSTOPPED) {
304 				if (j->pgrp == 0)
305 					kill_job(j, SIGCONT);
306 				else
307 					mksh_killpg(j->pgrp, SIGCONT);
308 			}
309 #endif
310 		}
311 	}
312 	if (killed)
313 		sleep(1);
314 	j_notify();
315 
316 #ifndef MKSH_UNEMPLOYED
317 	if (kshpid == procpid && restore_ttypgrp >= 0) {
318 		/*
319 		 * Need to restore the tty pgrp to what it was when the
320 		 * shell started up, so that the process that started us
321 		 * will be able to access the tty when we are done.
322 		 * Also need to restore our process group in case we are
323 		 * about to do an exec so that both our parent and the
324 		 * process we are to become will be able to access the tty.
325 		 */
326 		tcsetpgrp(tty_fd, restore_ttypgrp);
327 		setpgid(0, restore_ttypgrp);
328 	}
329 	if (Flag(FMONITOR)) {
330 		Flag(FMONITOR) = 0;
331 		j_change();
332 	}
333 #endif
334 }
335 
336 #ifndef MKSH_UNEMPLOYED
337 /* turn job control on or off according to Flag(FMONITOR) */
338 void
j_change(void)339 j_change(void)
340 {
341 	int i;
342 
343 	if (Flag(FMONITOR)) {
344 		bool use_tty = Flag(FTALKING);
345 
346 		/* don't call mksh_tcget until we own the tty process group */
347 		if (use_tty)
348 			tty_init_talking();
349 
350 		/* no controlling tty, no SIGT* */
351 #ifndef ADAPT_FOR_LITEOS_A
352 		if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
353 #else // ADAPT_FOR_LITEOS_A
354 		if ((ttypgrp_ok = (use_tty && tty_fd >= 0))) {
355 #endif // ADAPT_FOR_LITEOS_A
356 			setsig(&sigtraps[SIGTTIN], SIG_DFL,
357 			    SS_RESTORE_ORIG|SS_FORCE);
358 			/* wait to be given tty (POSIX.1, B.2, job control) */
359 			while (/* CONSTCOND */ 1) {
360 				pid_t ttypgrp;
361 
362 				if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
363 					warningf(false, Tf_ssfaileds,
364 					    "j_init", "tcgetpgrp",
365 					    cstrerror(errno));
366 					ttypgrp_ok = false;
367 					break;
368 				}
369 				if (ttypgrp == kshpgrp)
370 					break;
371 				kill(0, SIGTTIN);
372 			}
373 		}
374 		for (i = NELEM(tt_sigs); --i >= 0; )
375 			setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
376 			    SS_RESTORE_DFL|SS_FORCE);
377 		if (ttypgrp_ok && kshpgrp != kshpid) {
378 			if (setpgid(0, kshpid) < 0) {
379 				warningf(false, Tf_ssfaileds,
380 				    "j_init", "setpgid", cstrerror(errno));
381 				ttypgrp_ok = false;
382 			} else {
383 				if (tcsetpgrp(tty_fd, kshpid) < 0) {
384 					warningf(false, Tf_ssfaileds,
385 					    "j_init", "tcsetpgrp",
386 					    cstrerror(errno));
387 					ttypgrp_ok = false;
388 				} else
389 					restore_ttypgrp = kshpgrp;
390 				kshpgrp = kshpid;
391 			}
392 		}
393 #ifndef MKSH_DISABLE_TTY_WARNING
394 		if (use_tty && !ttypgrp_ok)
395 			warningf(false, Tf_sD_s, "warning",
396 			    "won't have full job control");
397 #endif
398 	} else {
399 		ttypgrp_ok = false;
400 		if (Flag(FTALKING))
401 			for (i = NELEM(tt_sigs); --i >= 0; )
402 				setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
403 				    SS_RESTORE_IGN|SS_FORCE);
404 		else
405 			for (i = NELEM(tt_sigs); --i >= 0; ) {
406 				if (sigtraps[tt_sigs[i]].flags &
407 				    (TF_ORIG_IGN | TF_ORIG_DFL))
408 					setsig(&sigtraps[tt_sigs[i]],
409 					    (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
410 					    SIG_IGN : SIG_DFL,
411 					    SS_RESTORE_ORIG|SS_FORCE);
412 			}
413 	}
414 	tty_init_state();
415 }
416 #endif
417 
418 #if HAVE_NICE
419 /* run nice(3) and ignore the result */
420 static void
421 ksh_nice(int ness)
422 {
423 #if defined(__USE_FORTIFY_LEVEL) && (__USE_FORTIFY_LEVEL > 0)
424 	int eno;
425 
426 	errno = 0;
427 	/* this is gonna annoy users; complain to your distro, people! */
428 	if (nice(ness) == -1 && (eno = errno) != 0)
429 		warningf(false, Tf_sD_s, "bgnice", cstrerror(eno));
430 #else
431 	(void)nice(ness);
432 #endif
433 }
434 #endif
435 
436 /* execute tree in child subprocess */
437 int
438 exchild(struct op *t, int flags,
439     volatile int *xerrok,
440     /* used if XPCLOSE or XCCLOSE */
441     int close_fd)
442 {
443 	/* for pipelines */
444 	static Proc *last_proc;
445 
446 	int rv = 0, forksleep, jwflags = JW_NONE;
447 #ifndef MKSH_NOPROSPECTOFWORK
448 	sigset_t omask;
449 #endif
450 	Proc *p;
451 	Job *j;
452 	pid_t cldpid;
453 
454 	if (flags & XPIPEST) {
455 		flags &= ~XPIPEST;
456 		jwflags |= JW_PIPEST;
457 	}
458 
459 	if (flags & XEXEC)
460 		/*
461 		 * Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
462 		 * (also done in another execute() below)
463 		 */
464 		return (execute(t, flags & (XEXEC | XERROK), xerrok));
465 
466 #ifndef MKSH_NOPROSPECTOFWORK
467 	/* no SIGCHLDs while messing with job and process lists */
468 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
469 #endif
470 
471 	p = new_proc();
472 	p->next = NULL;
473 	p->state = PRUNNING;
474 	p->status = 0;
475 	p->pid = 0;
476 
477 	/* link process into jobs list */
478 	if (flags & XPIPEI) {
479 		/* continuing with a pipe */
480 		if (!last_job)
481 			internal_errorf("exchild: XPIPEI and no last_job - pid %d",
482 			    (int)procpid);
483 		j = last_job;
484 		if (last_proc)
485 			last_proc->next = p;
486 		last_proc = p;
487 	} else {
488 		/* fills in j->job */
489 		j = new_job();
490 		/*
491 		 * we don't consider XXCOMs foreground since they don't get
492 		 * tty process group and we don't save or restore tty modes.
493 		 */
494 		j->flags = (flags & XXCOM) ? JF_XXCOM :
495 		    ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
496 		timerclear(&j->usrtime);
497 		timerclear(&j->systime);
498 		j->state = PRUNNING;
499 		j->pgrp = 0;
500 		j->ppid = procpid;
501 		j->age = ++njobs;
502 		j->proc_list = p;
503 		j->coproc_id = 0;
504 		last_job = j;
505 		last_proc = p;
506 		put_job(j, PJ_PAST_STOPPED);
507 	}
508 
509 	vistree(p->command, sizeof(p->command), t);
510 
511 	/* create child process */
512 	forksleep = 1;
513 	while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
514 		if (intrsig)
515 			/* allow user to ^C out... */
516 			break;
517 		sleep(forksleep);
518 		forksleep <<= 1;
519 	}
520 	/* ensure $RANDOM changes between parent and child */
521 	rndset((unsigned long)cldpid);
522 	/* fork failed? */
523 	if (cldpid < 0) {
524 		kill_job(j, SIGKILL);
525 		remove_job(j, "fork failed");
526 #ifndef MKSH_NOPROSPECTOFWORK
527 		sigprocmask(SIG_SETMASK, &omask, NULL);
528 #endif
529 		errorf("can't fork - try again");
530 	}
531 	p->pid = cldpid ? cldpid : (procpid = getpid());
532 
533 #ifndef MKSH_UNEMPLOYED
534 	/* job control set up */
535 	if (Flag(FMONITOR) && !(flags&XXCOM)) {
536 		bool dotty = false;
537 
538 		if (j->pgrp == 0) {
539 			/* First process */
540 			j->pgrp = p->pid;
541 			dotty = true;
542 		}
543 
544 		/*
545 		 * set pgrp in both parent and child to deal with race
546 		 * condition
547 		 */
548 		setpgid(p->pid, j->pgrp);
549 		if (ttypgrp_ok && dotty && !(flags & XBGND))
550 			tcsetpgrp(tty_fd, j->pgrp);
551 	}
552 #endif
553 
554 	/* used to close pipe input fd */
555 	if (close_fd >= 0 && (((flags & XPCLOSE) && cldpid) ||
556 	    ((flags & XCCLOSE) && !cldpid)))
557 		close(close_fd);
558 	if (!cldpid) {
559 		/* child */
560 
561 		/* Do this before restoring signal */
562 		if (flags & XCOPROC)
563 			coproc_cleanup(false);
564 		cleanup_parents_env();
565 #ifndef MKSH_UNEMPLOYED
566 		/*
567 		 * If FMONITOR or FTALKING is set, these signals are ignored,
568 		 * if neither FMONITOR nor FTALKING are set, the signals have
569 		 * their inherited values.
570 		 */
571 		if (Flag(FMONITOR) && !(flags & XXCOM)) {
572 			for (forksleep = NELEM(tt_sigs); --forksleep >= 0; )
573 				setsig(&sigtraps[tt_sigs[forksleep]], SIG_DFL,
574 				    SS_RESTORE_DFL|SS_FORCE);
575 		}
576 #endif
577 #if HAVE_NICE
578 		if (Flag(FBGNICE) && (flags & XBGND))
579 			ksh_nice(4);
580 #endif
581 		if ((flags & XBGND)
582 #ifndef MKSH_UNEMPLOYED
583 		    && !Flag(FMONITOR)
584 #endif
585 		    ) {
586 			setsig(&sigtraps[SIGINT], SIG_IGN,
587 			    SS_RESTORE_IGN|SS_FORCE);
588 			setsig(&sigtraps[SIGQUIT], SIG_IGN,
589 			    SS_RESTORE_IGN|SS_FORCE);
590 			if ((!(flags & (XPIPEI | XCOPROC))) &&
591 			    ((forksleep = open("/dev/null", 0)) > 0)) {
592 				(void)ksh_dup2(forksleep, 0, true);
593 				close(forksleep);
594 			}
595 		}
596 		/* in case of $(jobs) command */
597 		remove_job(j, "child");
598 #ifndef MKSH_NOPROSPECTOFWORK
599 		/* remove_job needs SIGCHLD blocked still */
600 		sigprocmask(SIG_SETMASK, &omask, NULL);
601 #endif
602 		nzombie = 0;
603 #ifndef MKSH_UNEMPLOYED
604 		ttypgrp_ok = false;
605 		Flag(FMONITOR) = 0;
606 #endif
607 		Flag(FTALKING) = 0;
608 		cleartraps();
609 		/* no return */
610 		execute(t, (flags & XERROK) | XEXEC, NULL);
611 #ifndef MKSH_SMALL
612 		if (t->type == TPIPE)
613 			unwind(LLEAVE);
614 		internal_warningf("%s: execute() returned", "exchild");
615 		fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
616 		    "exchild", t);
617 		shf_flush(shl_out);
618 #endif
619 		unwind(LLEAVE);
620 		/* NOTREACHED */
621 	}
622 
623 	/* shell (parent) stuff */
624 	if (!(flags & XPIPEO)) {
625 		/* last process in a job */
626 		j_startjob(j);
627 		if (flags & XCOPROC) {
628 			j->coproc_id = coproc.id;
629 			/* n jobs using co-process output */
630 			coproc.njobs++;
631 			/* j using co-process input */
632 			coproc.job = (void *)j;
633 		}
634 		if (flags & XBGND) {
635 			j_set_async(j);
636 			if (Flag(FTALKING)) {
637 				shf_fprintf(shl_out, "[%d]", j->job);
638 				for (p = j->proc_list; p; p = p->next)
639 					shf_fprintf(shl_out, Tf__d,
640 					    (int)p->pid);
641 				shf_putchar('\n', shl_out);
642 				shf_flush(shl_out);
643 			}
644 		} else
645 			rv = j_waitj(j, jwflags, "jw:last proc");
646 	}
647 
648 #ifndef MKSH_NOPROSPECTOFWORK
649 	sigprocmask(SIG_SETMASK, &omask, NULL);
650 #endif
651 
652 	return (rv);
653 }
654 
655 /* start the last job: only used for $(command) jobs */
656 void
657 startlast(void)
658 {
659 #ifndef MKSH_NOPROSPECTOFWORK
660 	sigset_t omask;
661 
662 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
663 #endif
664 
665 	/* no need to report error - waitlast() will do it */
666 	if (last_job) {
667 		/* ensure it isn't removed by check_job() */
668 		last_job->flags |= JF_WAITING;
669 		j_startjob(last_job);
670 	}
671 #ifndef MKSH_NOPROSPECTOFWORK
672 	sigprocmask(SIG_SETMASK, &omask, NULL);
673 #endif
674 }
675 
676 /* wait for last job: only used for $(command) jobs */
677 int
678 waitlast(void)
679 {
680 	int rv;
681 	Job *j;
682 #ifndef MKSH_NOPROSPECTOFWORK
683 	sigset_t omask;
684 
685 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
686 #endif
687 
688 	j = last_job;
689 	if (!j || !(j->flags & JF_STARTED)) {
690 		if (!j)
691 			warningf(true, Tf_sD_s, "waitlast", "no last job");
692 		else
693 			internal_warningf(Tf_sD_s, "waitlast", Tnot_started);
694 #ifndef MKSH_NOPROSPECTOFWORK
695 		sigprocmask(SIG_SETMASK, &omask, NULL);
696 #endif
697 		/* not so arbitrary, non-zero value */
698 		return (125);
699 	}
700 
701 	rv = j_waitj(j, JW_NONE, "waitlast");
702 
703 #ifndef MKSH_NOPROSPECTOFWORK
704 	sigprocmask(SIG_SETMASK, &omask, NULL);
705 #endif
706 
707 	return (rv);
708 }
709 
710 /* wait for child, interruptable. */
711 int
712 waitfor(const char *cp, int *sigp)
713 {
714 	int rv, ecode, flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
715 	Job *j;
716 #ifndef MKSH_NOPROSPECTOFWORK
717 	sigset_t omask;
718 
719 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
720 #endif
721 
722 	*sigp = 0;
723 
724 	if (cp == NULL) {
725 		/*
726 		 * wait for an unspecified job - always returns 0, so
727 		 * don't have to worry about exited/signaled jobs
728 		 */
729 		for (j = job_list; j; j = j->next)
730 			/* AT&T ksh will wait for stopped jobs - we don't */
731 			if (j->ppid == procpid && j->state == PRUNNING)
732 				break;
733 		if (!j) {
734 #ifndef MKSH_NOPROSPECTOFWORK
735 			sigprocmask(SIG_SETMASK, &omask, NULL);
736 #endif
737 			return (-1);
738 		}
739 	} else if ((j = j_lookup(cp, &ecode))) {
740 		/* don't report normal job completion */
741 		flags &= ~JW_ASYNCNOTIFY;
742 		if (j->ppid != procpid) {
743 #ifndef MKSH_NOPROSPECTOFWORK
744 			sigprocmask(SIG_SETMASK, &omask, NULL);
745 #endif
746 			return (-1);
747 		}
748 	} else {
749 #ifndef MKSH_NOPROSPECTOFWORK
750 		sigprocmask(SIG_SETMASK, &omask, NULL);
751 #endif
752 		if (ecode != JL_NOSUCH)
753 			bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
754 		return (-1);
755 	}
756 
757 	/* AT&T ksh will wait for stopped jobs - we don't */
758 	rv = j_waitj(j, flags, "jw:waitfor");
759 
760 #ifndef MKSH_NOPROSPECTOFWORK
761 	sigprocmask(SIG_SETMASK, &omask, NULL);
762 #endif
763 
764 	if (rv < 0)
765 		/* we were interrupted */
766 		*sigp = ksh_sigmask(-rv);
767 
768 	return (rv);
769 }
770 
771 /* kill (built-in) a job */
772 int
773 j_kill(const char *cp, int sig)
774 {
775 	Job *j;
776 	int rv = 0, ecode;
777 #ifndef MKSH_NOPROSPECTOFWORK
778 	sigset_t omask;
779 
780 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
781 #endif
782 
783 	if ((j = j_lookup(cp, &ecode)) == NULL) {
784 #ifndef MKSH_NOPROSPECTOFWORK
785 		sigprocmask(SIG_SETMASK, &omask, NULL);
786 #endif
787 		bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
788 		return (1);
789 	}
790 
791 	if (j->pgrp == 0) {
792 		/* started when !Flag(FMONITOR) */
793 		if (kill_job(j, sig) < 0) {
794 			bi_errorf(Tf_sD_s, cp, cstrerror(errno));
795 			rv = 1;
796 		}
797 	} else {
798 #ifndef MKSH_UNEMPLOYED
799 		if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
800 			mksh_killpg(j->pgrp, SIGCONT);
801 #endif
802 		if (mksh_killpg(j->pgrp, sig) < 0) {
803 			bi_errorf(Tf_sD_s, cp, cstrerror(errno));
804 			rv = 1;
805 		}
806 	}
807 
808 #ifndef MKSH_NOPROSPECTOFWORK
809 	sigprocmask(SIG_SETMASK, &omask, NULL);
810 #endif
811 
812 	return (rv);
813 }
814 
815 #ifndef MKSH_UNEMPLOYED
816 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
817 int
818 j_resume(const char *cp, int bg)
819 {
820 	Job *j;
821 	Proc *p;
822 	int ecode, rv = 0;
823 	bool running;
824 	sigset_t omask;
825 
826 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
827 
828 	if ((j = j_lookup(cp, &ecode)) == NULL) {
829 		sigprocmask(SIG_SETMASK, &omask, NULL);
830 		bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
831 		return (1);
832 	}
833 
834 	if (j->pgrp == 0) {
835 		sigprocmask(SIG_SETMASK, &omask, NULL);
836 		bi_errorf("job not job-controlled");
837 		return (1);
838 	}
839 
840 	if (bg)
841 		shprintf("[%d] ", j->job);
842 
843 	running = false;
844 	for (p = j->proc_list; p != NULL; p = p->next) {
845 		if (p->state == PSTOPPED) {
846 			p->state = PRUNNING;
847 			p->status = 0;
848 			running = true;
849 		}
850 		shf_puts(p->command, shl_stdout);
851 		if (p->next)
852 			shf_puts("| ", shl_stdout);
853 	}
854 	shf_putc('\n', shl_stdout);
855 	shf_flush(shl_stdout);
856 	if (running)
857 		j->state = PRUNNING;
858 
859 	put_job(j, PJ_PAST_STOPPED);
860 	if (bg)
861 		j_set_async(j);
862 	else {
863 		/* attach tty to job */
864 		if (j->state == PRUNNING) {
865 			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
866 				mksh_tcset(tty_fd, &j->ttystat);
867 			/* See comment in j_waitj regarding saved_ttypgrp. */
868 			if (ttypgrp_ok &&
869 			    tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
870 			    j->saved_ttypgrp : j->pgrp) < 0) {
871 				rv = errno;
872 				if (j->flags & JF_SAVEDTTY)
873 					mksh_tcset(tty_fd, &tty_state);
874 				sigprocmask(SIG_SETMASK, &omask, NULL);
875 				bi_errorf(Tf_ldfailed,
876 				    "fg: 1st", "tcsetpgrp", tty_fd,
877 				    (long)((j->flags & JF_SAVEDTTYPGRP) ?
878 				    j->saved_ttypgrp : j->pgrp),
879 				    cstrerror(rv));
880 				return (1);
881 			}
882 		}
883 		j->flags |= JF_FG;
884 		j->flags &= ~JF_KNOWN;
885 		if (j == async_job)
886 			async_job = NULL;
887 	}
888 
889 	if (j->state == PRUNNING && mksh_killpg(j->pgrp, SIGCONT) < 0) {
890 		int eno = errno;
891 
892 		if (!bg) {
893 			j->flags &= ~JF_FG;
894 			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
895 				mksh_tcset(tty_fd, &tty_state);
896 			if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
897 				warningf(true, Tf_ldfailed,
898 				    "fg: 2nd", "tcsetpgrp", tty_fd,
899 				    (long)kshpgrp, cstrerror(errno));
900 		}
901 		sigprocmask(SIG_SETMASK, &omask, NULL);
902 		bi_errorf(Tf_s_sD_s, "can't continue job",
903 		    cp, cstrerror(eno));
904 		return (1);
905 	}
906 	if (!bg) {
907 		if (ttypgrp_ok) {
908 			j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
909 		}
910 		rv = j_waitj(j, JW_NONE, "jw:resume");
911 	}
912 	sigprocmask(SIG_SETMASK, &omask, NULL);
913 	return (rv);
914 }
915 #endif
916 
917 /* are there any running or stopped jobs ? */
918 int
919 j_stopped_running(void)
920 {
921 	Job *j;
922 	int which = 0;
923 
924 	for (j = job_list; j != NULL; j = j->next) {
925 #ifndef MKSH_UNEMPLOYED
926 		if (j->ppid == procpid && j->state == PSTOPPED)
927 			which |= 1;
928 #endif
929 		if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
930 		    j->ppid == procpid && j->state == PRUNNING)
931 			which |= 2;
932 	}
933 	if (which) {
934 		shellf("You have %s%s%s jobs\n",
935 		    which & 1 ? "stopped" : "",
936 		    which == 3 ? " and " : "",
937 		    which & 2 ? "running" : "");
938 		return (1);
939 	}
940 
941 	return (0);
942 }
943 
944 
945 /* list jobs for jobs built-in */
946 int
947 j_jobs(const char *cp, int slp,
948     /* 0: short, 1: long, 2: pgrp */
949     int nflag)
950 {
951 	Job *j, *tmp;
952 	int how, zflag = 0;
953 #ifndef MKSH_NOPROSPECTOFWORK
954 	sigset_t omask;
955 
956 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
957 #endif
958 
959 	if (nflag < 0) {
960 		/* kludge: print zombies */
961 		nflag = 0;
962 		zflag = 1;
963 	}
964 	if (cp) {
965 		int ecode;
966 
967 		if ((j = j_lookup(cp, &ecode)) == NULL) {
968 #ifndef MKSH_NOPROSPECTOFWORK
969 			sigprocmask(SIG_SETMASK, &omask, NULL);
970 #endif
971 			bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
972 			return (1);
973 		}
974 	} else
975 		j = job_list;
976 	how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
977 	for (; j; j = j->next) {
978 		if ((!(j->flags & JF_ZOMBIE) || zflag) &&
979 		    (!nflag || (j->flags & JF_CHANGED))) {
980 			j_print(j, how, shl_stdout);
981 			if (j->state == PEXITED || j->state == PSIGNALLED)
982 				j->flags |= JF_REMOVE;
983 		}
984 		if (cp)
985 			break;
986 	}
987 	/* Remove jobs after printing so there won't be multiple + or - jobs */
988 	for (j = job_list; j; j = tmp) {
989 		tmp = j->next;
990 		if (j->flags & JF_REMOVE)
991 			remove_job(j, Tjobs);
992 	}
993 #ifndef MKSH_NOPROSPECTOFWORK
994 	sigprocmask(SIG_SETMASK, &omask, NULL);
995 #endif
996 	return (0);
997 }
998 
999 /* list jobs for top-level notification */
1000 void
1001 j_notify(void)
1002 {
1003 	Job *j, *tmp;
1004 #ifndef MKSH_NOPROSPECTOFWORK
1005 	sigset_t omask;
1006 
1007 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1008 #endif
1009 	for (j = job_list; j; j = j->next) {
1010 #ifndef MKSH_UNEMPLOYED
1011 		if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
1012 			j_print(j, JP_MEDIUM, shl_out);
1013 #endif
1014 		/*
1015 		 * Remove job after doing reports so there aren't
1016 		 * multiple +/- jobs.
1017 		 */
1018 		if (j->state == PEXITED || j->state == PSIGNALLED)
1019 			j->flags |= JF_REMOVE;
1020 	}
1021 	for (j = job_list; j; j = tmp) {
1022 		tmp = j->next;
1023 		if (j->flags & JF_REMOVE) {
1024 			if (j == async_job || (j->flags & JF_KNOWN)) {
1025 				j->flags = (j->flags & ~JF_REMOVE) | JF_ZOMBIE;
1026 				j->job = -1;
1027 				nzombie++;
1028 			} else
1029 				remove_job(j, "notify");
1030 		}
1031 	}
1032 	shf_flush(shl_out);
1033 #ifndef MKSH_NOPROSPECTOFWORK
1034 	sigprocmask(SIG_SETMASK, &omask, NULL);
1035 #endif
1036 }
1037 
1038 /* Return pid of last process in last asynchronous job */
1039 pid_t
1040 j_async(void)
1041 {
1042 #ifndef MKSH_NOPROSPECTOFWORK
1043 	sigset_t omask;
1044 
1045 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1046 #endif
1047 
1048 	if (async_job)
1049 		async_job->flags |= JF_KNOWN;
1050 
1051 #ifndef MKSH_NOPROSPECTOFWORK
1052 	sigprocmask(SIG_SETMASK, &omask, NULL);
1053 #endif
1054 
1055 	return (async_pid);
1056 }
1057 
1058 /*
1059  * Make j the last async process
1060  *
1061  * If jobs are compiled in then this routine expects sigchld to be blocked.
1062  */
1063 static void
1064 j_set_async(Job *j)
1065 {
1066 	Job *jl, *oldest;
1067 
1068 	if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
1069 		remove_job(async_job, "async");
1070 	if (!(j->flags & JF_STARTED)) {
1071 		internal_warningf(Tf_sD_s, "j_async", Tjob_not_started);
1072 		return;
1073 	}
1074 	async_job = j;
1075 	async_pid = j->last_proc->pid;
1076 	while (nzombie > CHILD_MAX) {
1077 		oldest = NULL;
1078 		for (jl = job_list; jl; jl = jl->next)
1079 			if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
1080 			    (!oldest || jl->age < oldest->age))
1081 				oldest = jl;
1082 		if (!oldest) {
1083 			/* XXX debugging */
1084 			if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
1085 				internal_warningf("%s: bad nzombie (%d)",
1086 				    "j_async", nzombie);
1087 				nzombie = 0;
1088 			}
1089 			break;
1090 		}
1091 		remove_job(oldest, "zombie");
1092 	}
1093 }
1094 
1095 /*
1096  * Start a job: set STARTED, check for held signals and set j->last_proc
1097  *
1098  * If jobs are compiled in then this routine expects sigchld to be blocked.
1099  */
1100 static void
1101 j_startjob(Job *j)
1102 {
1103 	Proc *p;
1104 
1105 	j->flags |= JF_STARTED;
1106 	for (p = j->proc_list; p->next; p = p->next)
1107 		;
1108 	j->last_proc = p;
1109 
1110 #ifndef MKSH_NOPROSPECTOFWORK
1111 	if (held_sigchld) {
1112 		held_sigchld = 0;
1113 		/* Don't call j_sigchld() as it may remove job... */
1114 		kill(procpid, SIGCHLD);
1115 	}
1116 #endif
1117 }
1118 
1119 /*
1120  * wait for job to complete or change state
1121  *
1122  * If jobs are compiled in then this routine expects sigchld to be blocked.
1123  */
1124 static int
1125 j_waitj(Job *j,
1126     /* see JW_* */
1127     int flags,
1128     const char *where)
1129 {
1130 	Proc *p;
1131 	int rv;
1132 #ifdef MKSH_NO_SIGSUSPEND
1133 	sigset_t omask;
1134 #endif
1135 
1136 	/*
1137 	 * No auto-notify on the job we are waiting on.
1138 	 */
1139 	j->flags |= JF_WAITING;
1140 	if (flags & JW_ASYNCNOTIFY)
1141 		j->flags |= JF_W_ASYNCNOTIFY;
1142 
1143 #ifndef MKSH_UNEMPLOYED
1144 	if (!Flag(FMONITOR))
1145 #endif
1146 		flags |= JW_STOPPEDWAIT;
1147 
1148 	while (j->state == PRUNNING ||
1149 	    ((flags & JW_STOPPEDWAIT) && j->state == PSTOPPED)) {
1150 #ifndef MKSH_NOPROSPECTOFWORK
1151 #ifdef MKSH_NO_SIGSUSPEND
1152 		sigprocmask(SIG_SETMASK, &sm_default, &omask);
1153 		pause();
1154 		/* note that handlers may run here so they need to know */
1155 		sigprocmask(SIG_SETMASK, &omask, NULL);
1156 #else
1157 		sigsuspend(&sm_default);
1158 #endif
1159 #else
1160 		j_sigchld(SIGCHLD);
1161 #endif
1162 		if (fatal_trap) {
1163 			int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1164 			j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1165 			runtraps(TF_FATAL);
1166 			/* not reached... */
1167 			j->flags |= oldf;
1168 		}
1169 		if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1170 			j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1171 			return (-rv);
1172 		}
1173 	}
1174 	j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1175 
1176 	if (j->flags & JF_FG) {
1177 		j->flags &= ~JF_FG;
1178 #ifndef MKSH_UNEMPLOYED
1179 		if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1180 			/*
1181 			 * Save the tty's current pgrp so it can be restored
1182 			 * when the job is foregrounded. This is to
1183 			 * deal with things like the GNU su which does
1184 			 * a fork/exec instead of an exec (the fork means
1185 			 * the execed shell gets a different pid from its
1186 			 * pgrp, so naturally it sets its pgrp and gets hosed
1187 			 * when it gets foregrounded by the parent shell which
1188 			 * has restored the tty's pgrp to that of the su
1189 			 * process).
1190 			 */
1191 			if (j->state == PSTOPPED &&
1192 			    (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1193 				j->flags |= JF_SAVEDTTYPGRP;
1194 			if (tcsetpgrp(tty_fd, kshpgrp) < 0)
1195 				warningf(true, Tf_ldfailed,
1196 				    "j_waitj:", "tcsetpgrp", tty_fd,
1197 				    (long)kshpgrp, cstrerror(errno));
1198 			if (j->state == PSTOPPED) {
1199 				j->flags |= JF_SAVEDTTY;
1200 				mksh_tcget(tty_fd, &j->ttystat);
1201 			}
1202 		}
1203 #endif
1204 		if (tty_hasstate) {
1205 			/*
1206 			 * Only restore tty settings if job was originally
1207 			 * started in the foreground. Problems can be
1208 			 * caused by things like 'more foobar &' which will
1209 			 * typically get and save the shell's vi/emacs tty
1210 			 * settings before setting up the tty for itself;
1211 			 * when more exits, it restores the 'original'
1212 			 * settings, and things go down hill from there...
1213 			 */
1214 			if (j->state == PEXITED && j->status == 0 &&
1215 			    (j->flags & JF_USETTYMODE)) {
1216 				mksh_tcget(tty_fd, &tty_state);
1217 			} else {
1218 				mksh_tcset(tty_fd, &tty_state);
1219 				/*-
1220 				 * Don't use tty mode if job is stopped and
1221 				 * later restarted and exits. Consider
1222 				 * the sequence:
1223 				 *	vi foo (stopped)
1224 				 *	...
1225 				 *	stty something
1226 				 *	...
1227 				 *	fg (vi; ZZ)
1228 				 * mode should be that of the stty, not what
1229 				 * was before the vi started.
1230 				 */
1231 				if (j->state == PSTOPPED)
1232 					j->flags &= ~JF_USETTYMODE;
1233 			}
1234 		}
1235 #ifndef MKSH_UNEMPLOYED
1236 		/*
1237 		 * If it looks like user hit ^C to kill a job, pretend we got
1238 		 * one too to break out of for loops, etc. (AT&T ksh does this
1239 		 * even when not monitoring, but this doesn't make sense since
1240 		 * a tty generated ^C goes to the whole process group)
1241 		 */
1242 		if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1243 		    WIFSIGNALED(j->last_proc->status)) {
1244 			int termsig;
1245 
1246 			if ((termsig = WTERMSIG(j->last_proc->status)) > 0 &&
1247 			    termsig < ksh_NSIG &&
1248 			    (sigtraps[termsig].flags & TF_TTY_INTR))
1249 				trapsig(termsig);
1250 		}
1251 #endif
1252 	}
1253 
1254 	j_usrtime = j->usrtime;
1255 	j_systime = j->systime;
1256 	rv = j->status;
1257 
1258 	if (!(p = j->proc_list)) {
1259 		;	/* nothing */
1260 	} else if (flags & JW_PIPEST) {
1261 		uint32_t num = 0;
1262 		struct tbl *vp;
1263 
1264 		unset(vp_pipest, 1);
1265 		vp = vp_pipest;
1266 		vp->flag = DEFINED | ISSET | INTEGER | RDONLY | ARRAY | INT_U;
1267 		goto got_array;
1268 
1269 		while (p != NULL) {
1270 			{
1271 				struct tbl *vq;
1272 
1273 				/* strlen(vp_pipest->name) == 10 */
1274 				vq = alloc(offsetof(struct tbl, name[0]) + 11,
1275 				    vp_pipest->areap);
1276 				memset(vq, 0, offsetof(struct tbl, name[0]));
1277 				memcpy(vq->name, vp_pipest->name, 11);
1278 				vp->u.array = vq;
1279 				vp = vq;
1280 			}
1281 			vp->areap = vp_pipest->areap;
1282 			vp->ua.index = ++num;
1283 			vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
1284 			    ARRAY | INT_U | AINDEX;
1285  got_array:
1286 			vp->val.i = proc_errorlevel(p);
1287 			if (Flag(FPIPEFAIL) && vp->val.i)
1288 				rv = vp->val.i;
1289 			p = p->next;
1290 		}
1291 	} else if (Flag(FPIPEFAIL)) {
1292 		do {
1293 			const int i = proc_errorlevel(p);
1294 
1295 			if (i)
1296 				rv = i;
1297 		} while ((p = p->next));
1298 	}
1299 
1300 	if (!(flags & JW_ASYNCNOTIFY)
1301 #ifndef MKSH_UNEMPLOYED
1302 	    && (!Flag(FMONITOR) || j->state != PSTOPPED)
1303 #endif
1304 	    ) {
1305 		j_print(j, JP_SHORT, shl_out);
1306 		shf_flush(shl_out);
1307 	}
1308 	if (j->state != PSTOPPED
1309 #ifndef MKSH_UNEMPLOYED
1310 	    && (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY))
1311 #endif
1312 	    )
1313 		remove_job(j, where);
1314 
1315 	return (rv);
1316 }
1317 
1318 /*
1319  * SIGCHLD handler to reap children and update job states
1320  *
1321  * If jobs are compiled in then this routine expects sigchld to be blocked.
1322  */
1323 /* ARGSUSED */
1324 static void
1325 j_sigchld(int sig MKSH_A_UNUSED)
1326 {
1327 	int saved_errno = errno;
1328 	Job *j;
1329 	Proc *p = NULL;
1330 	pid_t pid;
1331 	int status;
1332 	struct rusage ru0, ru1;
1333 #ifdef MKSH_NO_SIGSUSPEND
1334 	sigset_t omask;
1335 
1336 	/* this handler can run while SIGCHLD is not blocked, so block it now */
1337 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1338 #endif
1339 
1340 #ifndef MKSH_NOPROSPECTOFWORK
1341 	/*
1342 	 * Don't wait for any processes if a job is partially started.
1343 	 * This is so we don't do away with the process group leader
1344 	 * before all the processes in a pipe line are started (so the
1345 	 * setpgid() won't fail)
1346 	 */
1347 	for (j = job_list; j; j = j->next)
1348 		if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1349 			held_sigchld = 1;
1350 			goto j_sigchld_out;
1351 		}
1352 #endif
1353 
1354 	getrusage(RUSAGE_CHILDREN, &ru0);
1355 	do {
1356 #ifdef ADAPT_FOR_LITEOS_A
1357 		pid = waitpid(-1, &status, WNOHANG);
1358 #else // ADAPT_FOR_LITEOS_A
1359 #ifndef MKSH_NOPROSPECTOFWORK
1360 		pid = waitpid(-1, &status, (WNOHANG |
1361 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1362 		    WCONTINUED |
1363 #endif
1364 		    WUNTRACED));
1365 #else
1366 		pid = wait(&status);
1367 #endif
1368 #endif // ADAPT_FOR_LITEOS_A
1369 
1370 		/*
1371 		 * return if this would block (0) or no children
1372 		 * or interrupted (-1)
1373 		 */
1374 		if (pid <= 0)
1375 			goto j_sigchld_out;
1376 
1377 		getrusage(RUSAGE_CHILDREN, &ru1);
1378 
1379 		/* find job and process structures for this pid */
1380 		for (j = job_list; j != NULL; j = j->next)
1381 			for (p = j->proc_list; p != NULL; p = p->next)
1382 				if (p->pid == pid)
1383 					goto found;
1384  found:
1385 		if (j == NULL) {
1386 			/* Can occur if process has kids, then execs shell
1387 			warningf(true, "bad process waited for (pid = %d)",
1388 				pid);
1389 			 */
1390 			ru0 = ru1;
1391 			continue;
1392 		}
1393 
1394 		timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1395 		timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1396 		timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1397 		timersub(&j->systime, &ru0.ru_stime, &j->systime);
1398 		ru0 = ru1;
1399 		p->status = status;
1400 #ifndef MKSH_UNEMPLOYED
1401 		if (WIFSTOPPED(status))
1402 			p->state = PSTOPPED;
1403 		else
1404 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1405 		  if (WIFCONTINUED(status)) {
1406 			p->state = j->state = PRUNNING;
1407 			/* skip check_job(), no-op in this case */
1408 			continue;
1409 		} else
1410 #endif
1411 #endif
1412 		  if (WIFSIGNALED(status))
1413 			p->state = PSIGNALLED;
1414 		else
1415 			p->state = PEXITED;
1416 
1417 		/* check to see if entire job is done */
1418 		check_job(j);
1419 	}
1420 #ifndef MKSH_NOPROSPECTOFWORK
1421 	    while (/* CONSTCOND */ 1);
1422 #else
1423 	    while (/* CONSTCOND */ 0);
1424 #endif
1425 
1426  j_sigchld_out:
1427 #ifdef MKSH_NO_SIGSUSPEND
1428 	sigprocmask(SIG_SETMASK, &omask, NULL);
1429 #endif
1430 	errno = saved_errno;
1431 }
1432 
1433 /*
1434  * Called only when a process in j has exited/stopped (ie, called only
1435  * from j_sigchld()). If no processes are running, the job status
1436  * and state are updated, asynchronous job notification is done and,
1437  * if unneeded, the job is removed.
1438  *
1439  * If jobs are compiled in then this routine expects sigchld to be blocked.
1440  */
1441 static void
1442 check_job(Job *j)
1443 {
1444 	int jstate;
1445 	Proc *p;
1446 
1447 	/* XXX debugging (nasty - interrupt routine using shl_out) */
1448 	if (!(j->flags & JF_STARTED)) {
1449 		internal_warningf("check_job: job started (flags 0x%X)",
1450 		    (unsigned int)j->flags);
1451 		return;
1452 	}
1453 
1454 	jstate = PRUNNING;
1455 	for (p=j->proc_list; p != NULL; p = p->next) {
1456 		if (p->state == PRUNNING)
1457 			/* some processes still running */
1458 			return;
1459 		if (p->state > jstate)
1460 			jstate = p->state;
1461 	}
1462 	j->state = jstate;
1463 	j->status = proc_errorlevel(j->last_proc);
1464 
1465 	/*
1466 	 * Note when co-process dies: can't be done in j_wait() nor
1467 	 * remove_job() since neither may be called for non-interactive
1468 	 * shells.
1469 	 */
1470 	if (j->state == PEXITED || j->state == PSIGNALLED) {
1471 		/*
1472 		 * No need to keep co-process input any more
1473 		 * (at least, this is what ksh93d thinks)
1474 		 */
1475 		if (coproc.job == j) {
1476 			coproc.job = NULL;
1477 			/*
1478 			 * XXX would be nice to get the closes out of here
1479 			 * so they aren't done in the signal handler.
1480 			 * Would mean a check in coproc_getfd() to
1481 			 * do "if job == 0 && write >= 0, close write".
1482 			 */
1483 			coproc_write_close(coproc.write);
1484 		}
1485 		/* Do we need to keep the output? */
1486 		if (j->coproc_id && j->coproc_id == coproc.id &&
1487 		    --coproc.njobs == 0)
1488 			coproc_readw_close(coproc.read);
1489 	}
1490 
1491 	j->flags |= JF_CHANGED;
1492 #ifndef MKSH_UNEMPLOYED
1493 	if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1494 		/*
1495 		 * Only put stopped jobs at the front to avoid confusing
1496 		 * the user (don't want finished jobs effecting %+ or %-)
1497 		 */
1498 		if (j->state == PSTOPPED)
1499 			put_job(j, PJ_ON_FRONT);
1500 		if (Flag(FNOTIFY) &&
1501 		    (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1502 			/* Look for the real file descriptor 2 */
1503 			{
1504 				struct env *ep;
1505 				int fd = 2;
1506 
1507 				for (ep = e; ep; ep = ep->oenv)
1508 					if (ep->savefd && ep->savefd[2])
1509 						fd = ep->savefd[2];
1510 				shf_reopen(fd, SHF_WR, shl_j);
1511 			}
1512 			/*
1513 			 * Can't call j_notify() as it removes jobs. The job
1514 			 * must stay in the job list as j_waitj() may be
1515 			 * running with this job.
1516 			 */
1517 			j_print(j, JP_MEDIUM, shl_j);
1518 			shf_flush(shl_j);
1519 			if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1520 				remove_job(j, "notify");
1521 		}
1522 	}
1523 #endif
1524 	if (
1525 #ifndef MKSH_UNEMPLOYED
1526 	    !Flag(FMONITOR) &&
1527 #endif
1528 	    !(j->flags & (JF_WAITING|JF_FG)) &&
1529 	    j->state != PSTOPPED) {
1530 		if (j == async_job || (j->flags & JF_KNOWN)) {
1531 			j->flags |= JF_ZOMBIE;
1532 			j->job = -1;
1533 			nzombie++;
1534 		} else
1535 			remove_job(j, "checkjob");
1536 	}
1537 }
1538 
1539 /*
1540  * Print job status in either short, medium or long format.
1541  *
1542  * If jobs are compiled in then this routine expects sigchld to be blocked.
1543  */
1544 static void
1545 j_print(Job *j, int how, struct shf *shf)
1546 {
1547 	Proc *p;
1548 	int state;
1549 	int status;
1550 #ifdef WCOREDUMP
1551 	bool coredumped;
1552 #endif
1553 	char jobchar = ' ';
1554 	char buf[64];
1555 	const char *filler;
1556 	int output = 0;
1557 
1558 	if (how == JP_PGRP) {
1559 		/*
1560 		 * POSIX doesn't say what to do it there is no process
1561 		 * group leader (ie, !FMONITOR). We arbitrarily return
1562 		 * last pid (which is what $! returns).
1563 		 */
1564 		shf_fprintf(shf, Tf_dN, (int)(j->pgrp ? j->pgrp :
1565 		    (j->last_proc ? j->last_proc->pid : 0)));
1566 		return;
1567 	}
1568 	j->flags &= ~JF_CHANGED;
1569 	filler = j->job > 10 ? "\n       " : "\n      ";
1570 	if (j == job_list)
1571 		jobchar = '+';
1572 	else if (j == job_list->next)
1573 		jobchar = '-';
1574 
1575 	for (p = j->proc_list; p != NULL;) {
1576 #ifdef WCOREDUMP
1577 		coredumped = false;
1578 #endif
1579 		switch (p->state) {
1580 		case PRUNNING:
1581 			memcpy(buf, "Running", 8);
1582 			break;
1583 		case PSTOPPED: {
1584 			int stopsig = WSTOPSIG(p->status);
1585 
1586 			strlcpy(buf, stopsig > 0 && stopsig < ksh_NSIG ?
1587 			    sigtraps[stopsig].mess : "Stopped", sizeof(buf));
1588 			break;
1589 		}
1590 		case PEXITED: {
1591 			int exitstatus = (WEXITSTATUS(p->status)) & 255;
1592 
1593 			if (how == JP_SHORT)
1594 				buf[0] = '\0';
1595 			else if (exitstatus == 0)
1596 				memcpy(buf, "Done", 5);
1597 			else
1598 				shf_snprintf(buf, sizeof(buf), "Done (%d)",
1599 				    exitstatus);
1600 			break;
1601 		}
1602 		case PSIGNALLED: {
1603 			int termsig = WTERMSIG(p->status);
1604 #ifdef WCOREDUMP
1605 			if (WCOREDUMP(p->status))
1606 				coredumped = true;
1607 #endif
1608 			/*
1609 			 * kludge for not reporting 'normal termination
1610 			 * signals' (i.e. SIGINT, SIGPIPE)
1611 			 */
1612 			if (how == JP_SHORT &&
1613 #ifdef WCOREDUMP
1614 			    !coredumped &&
1615 #endif
1616 			    (termsig == SIGINT || termsig == SIGPIPE)) {
1617 				buf[0] = '\0';
1618 			} else
1619 				strlcpy(buf, termsig > 0 && termsig < ksh_NSIG ?
1620 				    sigtraps[termsig].mess : "Signalled",
1621 				    sizeof(buf));
1622 			break;
1623 		}
1624 		default:
1625 			buf[0] = '\0';
1626 		}
1627 
1628 		if (how != JP_SHORT) {
1629 			if (p == j->proc_list)
1630 				shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1631 			else
1632 				shf_puts(filler, shf);
1633 		}
1634 
1635 		if (how == JP_LONG)
1636 			shf_fprintf(shf, "%5d ", (int)p->pid);
1637 
1638 		if (how == JP_SHORT) {
1639 			if (buf[0]) {
1640 				output = 1;
1641 #ifdef WCOREDUMP
1642 				shf_fprintf(shf, "%s%s ",
1643 				    buf, coredumped ? " (core dumped)" : null);
1644 #else
1645 				shf_puts(buf, shf);
1646 				shf_putchar(' ', shf);
1647 #endif
1648 			}
1649 		} else {
1650 			output = 1;
1651 			shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1652 			    p->next ? "|" : null,
1653 #ifdef WCOREDUMP
1654 			    coredumped ? " (core dumped)" :
1655 #endif
1656 			     null);
1657 		}
1658 
1659 		state = p->state;
1660 		status = p->status;
1661 		p = p->next;
1662 		while (p && p->state == state && p->status == status) {
1663 			if (how == JP_LONG)
1664 				shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
1665 				    (int)p->pid, T1space, p->command,
1666 				    p->next ? "|" : null);
1667 			else if (how == JP_MEDIUM)
1668 				shf_fprintf(shf, Tf__ss, p->command,
1669 				    p->next ? "|" : null);
1670 			p = p->next;
1671 		}
1672 	}
1673 	if (output)
1674 		shf_putc('\n', shf);
1675 }
1676 
1677 /*
1678  * Convert % sequence to job
1679  *
1680  * If jobs are compiled in then this routine expects sigchld to be blocked.
1681  */
1682 static Job *
1683 j_lookup(const char *cp, int *ecodep)
1684 {
1685 	Job *j, *last_match;
1686 	Proc *p;
1687 	size_t len;
1688 	int job = 0;
1689 
1690 	if (ctype(*cp, C_DIGIT) && getn(cp, &job)) {
1691 		/* Look for last_proc->pid (what $! returns) first... */
1692 		for (j = job_list; j != NULL; j = j->next)
1693 			if (j->last_proc && j->last_proc->pid == job)
1694 				return (j);
1695 		/*
1696 		 * ...then look for process group (this is non-POSIX,
1697 		 * but should not break anything
1698 		 */
1699 		for (j = job_list; j != NULL; j = j->next)
1700 			if (j->pgrp && j->pgrp == job)
1701 				return (j);
1702 		goto j_lookup_nosuch;
1703 	}
1704 	if (*cp != '%') {
1705  j_lookup_invalid:
1706 		if (ecodep)
1707 			*ecodep = JL_INVALID;
1708 		return (NULL);
1709 	}
1710 	switch (*++cp) {
1711 	case '\0': /* non-standard */
1712 	case '+':
1713 	case '%':
1714 		if (job_list != NULL)
1715 			return (job_list);
1716 		break;
1717 
1718 	case '-':
1719 		if (job_list != NULL && job_list->next)
1720 			return (job_list->next);
1721 		break;
1722 
1723 	case '0': case '1': case '2': case '3': case '4':
1724 	case '5': case '6': case '7': case '8': case '9':
1725 		if (!getn(cp, &job))
1726 			goto j_lookup_invalid;
1727 		for (j = job_list; j != NULL; j = j->next)
1728 			if (j->job == job)
1729 				return (j);
1730 		break;
1731 
1732 	/* %?string */
1733 	case '?':
1734 		last_match = NULL;
1735 		for (j = job_list; j != NULL; j = j->next)
1736 			for (p = j->proc_list; p != NULL; p = p->next)
1737 				if (strstr(p->command, cp+1) != NULL) {
1738 					if (last_match) {
1739 						if (ecodep)
1740 							*ecodep = JL_AMBIG;
1741 						return (NULL);
1742 					}
1743 					last_match = j;
1744 				}
1745 		if (last_match)
1746 			return (last_match);
1747 		break;
1748 
1749 	/* %string */
1750 	default:
1751 		len = strlen(cp);
1752 		last_match = NULL;
1753 		for (j = job_list; j != NULL; j = j->next)
1754 			if (strncmp(cp, j->proc_list->command, len) == 0) {
1755 				if (last_match) {
1756 					if (ecodep)
1757 						*ecodep = JL_AMBIG;
1758 					return (NULL);
1759 				}
1760 				last_match = j;
1761 			}
1762 		if (last_match)
1763 			return (last_match);
1764 		break;
1765 	}
1766  j_lookup_nosuch:
1767 	if (ecodep)
1768 		*ecodep = JL_NOSUCH;
1769 	return (NULL);
1770 }
1771 
1772 static Job	*free_jobs;
1773 static Proc	*free_procs;
1774 
1775 /*
1776  * allocate a new job and fill in the job number.
1777  *
1778  * If jobs are compiled in then this routine expects sigchld to be blocked.
1779  */
1780 static Job *
1781 new_job(void)
1782 {
1783 	int i;
1784 	Job *newj, *j;
1785 
1786 	if (free_jobs != NULL) {
1787 		newj = free_jobs;
1788 		free_jobs = free_jobs->next;
1789 	} else
1790 		newj = alloc(sizeof(Job), APERM);
1791 
1792 	/* brute force method */
1793 	for (i = 1; ; i++) {
1794 		for (j = job_list; j && j->job != i; j = j->next)
1795 			;
1796 		if (j == NULL)
1797 			break;
1798 	}
1799 	newj->job = i;
1800 
1801 	return (newj);
1802 }
1803 
1804 /*
1805  * Allocate new process struct
1806  *
1807  * If jobs are compiled in then this routine expects sigchld to be blocked.
1808  */
1809 static Proc *
1810 new_proc(void)
1811 {
1812 	Proc *p;
1813 
1814 	if (free_procs != NULL) {
1815 		p = free_procs;
1816 		free_procs = free_procs->next;
1817 	} else
1818 		p = alloc(sizeof(Proc), APERM);
1819 
1820 	return (p);
1821 }
1822 
1823 /*
1824  * Take job out of job_list and put old structures into free list.
1825  * Keeps nzombies, last_job and async_job up to date.
1826  *
1827  * If jobs are compiled in then this routine expects sigchld to be blocked.
1828  */
1829 static void
1830 remove_job(Job *j, const char *where)
1831 {
1832 	Proc *p, *tmp;
1833 	Job **prev, *curr;
1834 
1835 	prev = &job_list;
1836 	curr = job_list;
1837 	while (curr && curr != j) {
1838 		prev = &curr->next;
1839 		curr = *prev;
1840 	}
1841 	if (curr != j) {
1842 		internal_warningf("remove_job: job %s (%s)", Tnot_found, where);
1843 		return;
1844 	}
1845 	*prev = curr->next;
1846 
1847 	/* free up proc structures */
1848 	for (p = j->proc_list; p != NULL; ) {
1849 		tmp = p;
1850 		p = p->next;
1851 		tmp->next = free_procs;
1852 		free_procs = tmp;
1853 	}
1854 
1855 	if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1856 		--nzombie;
1857 	j->next = free_jobs;
1858 	free_jobs = j;
1859 
1860 	if (j == last_job)
1861 		last_job = NULL;
1862 	if (j == async_job)
1863 		async_job = NULL;
1864 }
1865 
1866 /*
1867  * put j in a particular location (taking it out job_list if it is there
1868  * already)
1869  *
1870  * If jobs are compiled in then this routine expects sigchld to be blocked.
1871  */
1872 static void
1873 put_job(Job *j, int where)
1874 {
1875 	Job **prev, *curr;
1876 
1877 	/* Remove job from list (if there) */
1878 	prev = &job_list;
1879 	curr = job_list;
1880 	while (curr && curr != j) {
1881 		prev = &curr->next;
1882 		curr = *prev;
1883 	}
1884 	if (curr == j)
1885 		*prev = curr->next;
1886 
1887 	switch (where) {
1888 	case PJ_ON_FRONT:
1889 		j->next = job_list;
1890 		job_list = j;
1891 		break;
1892 
1893 	case PJ_PAST_STOPPED:
1894 		prev = &job_list;
1895 		curr = job_list;
1896 		for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1897 		    curr = *prev)
1898 			;
1899 		j->next = curr;
1900 		*prev = j;
1901 		break;
1902 	}
1903 }
1904 
1905 /*
1906  * nuke a job (called when unable to start full job).
1907  *
1908  * If jobs are compiled in then this routine expects sigchld to be blocked.
1909  */
1910 static int
1911 kill_job(Job *j, int sig)
1912 {
1913 	Proc *p;
1914 	int rval = 0;
1915 
1916 	for (p = j->proc_list; p != NULL; p = p->next)
1917 		if (p->pid != 0)
1918 			if (kill(p->pid, sig) < 0)
1919 				rval = -1;
1920 	return (rval);
1921 }
1922 
1923 static void
1924 tty_init_talking(void)
1925 {
1926 	switch (tty_init_fd()) {
1927 	case 0:
1928 		break;
1929 	case 1:
1930 #ifndef MKSH_DISABLE_TTY_WARNING
1931 		warningf(false, Tf_sD_s_sD_s,
1932 		    "No controlling tty", Topen, T_devtty, cstrerror(errno));
1933 #endif
1934 		break;
1935 	case 2:
1936 #ifndef MKSH_DISABLE_TTY_WARNING
1937 		warningf(false, Tf_s_sD_s, Tcant_find, Ttty_fd,
1938 		    cstrerror(errno));
1939 #endif
1940 		break;
1941 	case 3:
1942 		warningf(false, Tf_ssfaileds, "j_ttyinit",
1943 		    Ttty_fd_dupof, cstrerror(errno));
1944 		break;
1945 	case 4:
1946 		warningf(false, Tf_sD_sD_s, "j_ttyinit",
1947 		    "can't set close-on-exec flag", cstrerror(errno));
1948 		break;
1949 	}
1950 }
1951 
1952 static void
1953 tty_init_state(void)
1954 {
1955 	if (tty_fd >= 0) {
1956 		mksh_tcget(tty_fd, &tty_state);
1957 		tty_hasstate = true;
1958 	}
1959 }
1960