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