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