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