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