changelog for 0.9.1
[posh.git] / jobs.c
blob8e6cd4505e03708e2fbcd8f3641f2ce4c04ea61a
1 /*
2 * Process and job control
3 */
5 /*
6 * Reworked/Rewritten version of Eric Gisin's/Ron Natalie's code by
7 * Larry Bouzane (larry@cs.mun.ca) and hacked again by
8 * Michael Rendell (michael@cs.mun.ca)
10 * The interface to the rest of the shell should probably be changed
11 * to allow use of vfork() when available but that would be way too much
12 * work :)
14 * Notes regarding the copious ifdefs:
15 * - TTY_PGRP defined iff JOBS is defined - defined if there are tty
16 * process groups
17 * - NEED_PGRP_SYNC defined iff JOBS is defined - see comment below
20 #include <ctype.h>
22 #include "sh.h"
23 #include "ksh_stat.h"
24 #include "ksh_wait.h"
25 #include <sys/times.h>
26 #include "tty.h"
28 /* Start of system configuration stuff */
30 #ifdef JOBS
31 # if defined(HAVE_TCSETPGRP) || defined(TIOCSPGRP)
32 # define TTY_PGRP
33 # endif
34 # ifdef BSD_PGRP
35 # define setpgid setpgrp
36 # define getpgID() getpgrp(0)
37 # else
38 # define getpgID() getpgrp()
39 # endif
40 #else /* JOBS */
41 /* These so we can use ifdef xxx instead of if defined(JOBS) && defined(xxx) */
42 # undef TTY_PGRP
43 # undef NEED_PGRP_SYNC
44 #endif /* JOBS */
46 /* End of system configuration stuff */
49 /* Order important! */
50 #define PRUNNING 0
51 #define PEXITED 1
52 #define PSIGNALLED 2
53 #define PSTOPPED 3
55 typedef struct proc Proc;
56 struct proc {
57 Proc *next; /* next process in pipeline (if any) */
58 pid_t pid; /* process id */
59 int state;
60 int status; /* wait status */
61 char command[48]; /* process command string */
64 /* Notify/print flag - j_print() argument */
65 #define JP_NONE 0 /* don't print anything */
66 #define JP_SHORT 1 /* print signals processes were killed by */
67 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
68 #define JP_LONG 3 /* print [job-num] -/+ pid command */
69 #define JP_PGRP 4 /* print pgrp */
71 /* put_job() flags */
72 #define PJ_ON_FRONT 0 /* at very front */
73 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
75 /* Job.flags values */
76 #define JF_STARTED 0x001 /* set when all processes in job are started */
77 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
78 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
79 #define JF_XXCOM 0x008 /* set for $(command) jobs */
80 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
81 #define JF_SAVEDTTY 0x020 /* j->ttystate is valid */
82 #define JF_CHANGED 0x040 /* process has changed state */
83 #define JF_KNOWN 0x080 /* $! referenced */
84 #define JF_ZOMBIE 0x100 /* known, unwaited process */
85 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_noityf()) */
86 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
87 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
89 typedef struct job Job;
90 struct job {
91 Job *next; /* next job in list */
92 Proc *proc_list; /* process list */
93 Proc *last_proc; /* last process in list */
94 struct timeval systime; /* system time used by job */
95 struct timeval usrtime; /* user time used by job */
96 pid_t pgrp; /* process group of job */
97 pid_t ppid; /* pid of process that forked job */
98 int job; /* job number: %n */
99 int flags; /* see JF_* */
100 volatile int state; /* job state */
101 int status; /* exit status of last process */
102 int32_t age; /* number of jobs started */
103 #ifdef SILLY_FEATURES
104 Coproc_id coproc_id; /* 0 or id of coprocess output pipe */
105 struct termios ttystate;/* saved tty state for stopped jobs */
106 pid_t saved_ttypgrp; /* saved tty process group for stopped jobs */
107 #endif
110 /* Flags for j_waitj() */
111 #define JW_NONE 0x00
112 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
113 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
114 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
116 /* Error codes for j_lookup() */
117 #define JL_OK 0
118 #define JL_NOSUCH 1 /* no such job */
119 #define JL_AMBIG 2 /* %foo or %?foo is ambiguous */
120 #define JL_INVALID 3 /* non-pid, non-% job id */
122 static const char *const lookup_msgs[] = {
123 null,
124 "no such job",
125 "ambiguous",
126 "argument must be %job or process id",
127 NULL
130 static Job *job_list; /* job list */
131 static Job *last_job;
132 static Job *async_job;
133 static pid_t async_pid;
135 static int nzombie; /* # of zombies owned by this process */
136 static int32_t njobs; /* # of jobs started */
137 static long child_max; /* CHILD_MAX */
140 #ifdef JOB_SIGS
141 /* held_sigchld is set if sigchld occurs before a job is completely started */
142 static volatile sig_atomic_t held_sigchld;
143 #endif /* JOB_SIGS */
145 #ifdef SILLY_FEATURES
146 static struct shf *shl_j;
147 static bool ttypgrp_ok; /* set if can use tty pgrps */
148 static pid_t restore_ttypgrp = -1;
149 static int const tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
150 #endif
152 static void j_set_async(Job *);
153 static void j_startjob(Job *);
154 static int j_waitj(Job *, int, const char *);
155 static void j_sigchld(int);
156 static void j_print(Job *, int, struct shf *);
157 static Job *j_lookup(const char *, int *);
158 static Job *new_job(void);
159 static Proc *new_proc(void);
160 static void check_job(Job *);
161 static void put_job(Job *, int);
162 static void remove_job(Job *, const char *);
163 static int kill_job(Job *, int);
165 /* initialize job control */
166 void
167 j_init(void)
169 child_max = sysconf(_SC_CHILD_MAX);
170 if (child_max == -1)
171 child_max = 25;
172 Flag(FMONITOR) = 0;
174 #ifdef JOBS_SIGS
175 (void)sigemptyset(&sm_default);
176 sigprocmask(SIG_SETMASK, &sm_default, NULL);
178 (void)sigemptyset(&sm_sigchld);
179 (void)sigaddset(&sm_sigchld, SIGCHLD);
181 setsig(&sigtraps[SIGCHLD], j_sigchld,
182 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
183 #else /* JOB_SIGS */
184 /* Make sure SIGCHLD isn't ignored - can do odd things under SYSV */
185 setsig(&sigtraps[SIGCHLD], SIG_DFL, SS_RESTORE_ORIG|SS_FORCE);
186 #endif /* JOB_SIGS */
188 #ifdef SILLY_FEATURES
189 if (!mflagset && Flag(FTALKING))
190 Flag(FMONITOR) = 1;
192 /* shl_j is used to do asynchronous notification (used in
193 * an interrupt handler, so need a distinct shf)
195 shl_j = shf_fdopen(2, SHF_WR, NULL);
197 if (Flag(FMONITOR) || Flag(FTALKING)) {
198 int i;
200 /* the TF_SHELL_USES test is a kludge that lets us know if
201 * if the signals have been changed by the shell.
203 for (i = NELEM(tt_sigs); --i >= 0; ) {
204 sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
205 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
206 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
207 SS_RESTORE_IGN|SS_FORCE);
211 /* j_change() calls tty_init() */
212 if (Flag(FMONITOR))
213 j_change();
214 else
215 #endif
216 if (Flag(FTALKING))
217 tty_init(TRUE);
220 /* job cleanup before shell exit */
221 void
222 j_exit(void)
224 /* kill stopped, and possibly running, jobs */
225 Job *j;
226 int killed = 0;
228 for (j = job_list; j != NULL; j = j->next) {
229 if (j->ppid == procpid &&
230 (j->state == PSTOPPED ||
231 (j->state == PRUNNING &&
232 ((j->flags & JF_FG) ||
233 (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
234 killed = 1;
235 if (j->pgrp == 0)
236 kill_job(j, SIGHUP);
237 else
238 killpg(j->pgrp, SIGHUP);
239 #ifdef SILLY_FEATURES
240 if (j->state == PSTOPPED) {
241 if (j->pgrp == 0)
242 kill_job(j, SIGCONT);
243 else
244 killpg(j->pgrp, SIGCONT);
246 #endif
249 if (killed)
250 sleep(1);
251 j_notify();
253 #ifdef SILLY_FEATURES
254 if (kshpid == procpid && restore_ttypgrp >= 0) {
255 /* Need to restore the tty pgrp to what it was when the
256 * shell started up, so that the process that started us
257 * will be able to access the tty when we are done.
258 * Also need to restore our process group in case we are
259 * about to do an exec so that both our parent and the
260 * process we are to become will be able to access the tty.
262 tcsetpgrp(tty_fd, restore_ttypgrp);
263 setpgid(0, restore_ttypgrp);
265 if (Flag(FMONITOR)) {
266 Flag(FMONITOR) = 0;
267 j_change();
269 #endif
272 #ifdef SILLY_FEATURES
273 /* turn job control on or off according to Flag(FMONITOR) */
274 void
275 j_change(void)
277 int i;
279 if (Flag(FMONITOR)) {
280 /* Don't call get_tty() 'til we own the tty process group */
281 tty_init(FALSE);
283 # ifdef TTY_PGRP
284 /* no controlling tty, no SIGT* */
285 ttypgrp_ok = tty_fd >= 0 && tty_devtty;
287 if (ttypgrp_ok && (our_pgrp = getpgID()) < 0) {
288 warningf(FALSE, "j_init: getpgrp() failed: %s",
289 strerror(errno));
290 ttypgrp_ok = 0;
292 if (ttypgrp_ok) {
293 setsig(&sigtraps[SIGTTIN], SIG_DFL,
294 SS_RESTORE_ORIG|SS_FORCE);
295 /* wait to be given tty (POSIX.1, B.2, job control) */
296 while (1) {
297 pid_t ttypgrp;
299 if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
300 warningf(FALSE,
301 "j_init: tcgetpgrp() failed: %s",
302 strerror(errno));
303 ttypgrp_ok = 0;
304 break;
306 if (ttypgrp == our_pgrp)
307 break;
308 kill(0, SIGTTIN);
311 for (i = NELEM(tt_sigs); --i >= 0; )
312 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
313 SS_RESTORE_DFL|SS_FORCE);
314 if (ttypgrp_ok && our_pgrp != kshpid) {
315 if (setpgid(0, kshpid) < 0) {
316 warningf(FALSE,
317 "j_init: setpgid() failed: %s",
318 strerror(errno));
319 ttypgrp_ok = 0;
320 } else {
321 if (tcsetpgrp(tty_fd, kshpid) < 0) {
322 warningf(FALSE,
323 "j_init: tcsetpgrp() failed: %s",
324 strerror(errno));
325 ttypgrp_ok = 0;
326 } else
327 restore_ttypgrp = our_pgrp;
328 our_pgrp = kshpid;
331 # if defined(NTTYDISC) && defined(TIOCSETD) && !defined(HAVE_TERMIOS_H) && !defined(HAVE_TERMIO_H)
332 if (ttypgrp_ok) {
333 int ldisc = NTTYDISC;
335 if (ioctl(tty_fd, TIOCSETD, &ldisc) < 0)
336 warningf(FALSE,
337 "j_init: can't set new line discipline: %s",
338 strerror(errno));
340 # endif /* NTTYDISC && TIOCSETD */
341 if (!ttypgrp_ok)
342 warningf(FALSE, "warning: won't have full job control");
343 # endif /* TTY_PGRP */
344 if (tty_fd >= 0)
345 get_tty(tty_fd, &tty_state);
346 } else {
347 # ifdef TTY_PGRP
348 ttypgrp_ok = 0;
349 if (Flag(FTALKING))
350 for (i = NELEM(tt_sigs); --i >= 0; )
351 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
352 SS_RESTORE_IGN|SS_FORCE);
353 else
354 for (i = NELEM(tt_sigs); --i >= 0; ) {
355 if (sigtraps[tt_sigs[i]].flags &
356 (TF_ORIG_IGN | TF_ORIG_DFL))
357 setsig(&sigtraps[tt_sigs[i]],
358 (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
359 SIG_IGN : SIG_DFL,
360 SS_RESTORE_ORIG|SS_FORCE);
362 # endif /* TTY_PGRP */
363 if (!Flag(FTALKING))
364 tty_close();
367 #endif /* JOBS */
369 /* execute tree in child subprocess */
371 exchild(struct op *t, int flags, volatile int *xerrok, int close_fd)
373 static Proc *last_proc; /* for pipelines */
375 int i;
376 #ifdef JOB_SIGS
377 sigset_t omask;
378 #endif /* JOB_SIGS */
379 Proc *p;
380 Job *j;
381 int rv = 0;
382 int forksleep;
383 int ischild;
385 if (flags & XEXEC)
386 /* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
387 * (also done in another execute() below)
389 return (execute(t, flags & (XEXEC | XERROK), xerrok));
391 /* no SIGCHLDs while messing with job and process lists */
392 #ifdef JOB_SIGS
393 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
394 #endif
396 p = new_proc();
397 p->next = NULL;
398 p->state = PRUNNING;
399 WSTATUS(p->status) = 0;
400 p->pid = 0;
402 /* link process into jobs list */
403 if (flags & XPIPEI) { /* continuing with a pipe */
404 if (!last_job)
405 internal_errorf(1,
406 "exchild: XPIPEI and no last_job - pid %d",
407 (int)procpid);
408 j = last_job;
409 if (last_proc)
410 last_proc->next = p;
411 last_proc = p;
412 } else {
413 j = new_job(); /* fills in j->job */
414 /* we don't consider XXCOMs foreground since they don't get
415 * tty process group and we don't save or restore tty modes.
417 j->flags = (flags & XXCOM) ? JF_XXCOM :
418 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
419 timerclear(&j->usrtime);
420 timerclear(&j->systime);
421 j->state = PRUNNING;
422 j->pgrp = 0;
423 j->ppid = procpid;
424 j->age = ++njobs;
425 j->proc_list = p;
426 #ifdef SILLY_FEATURES
427 j->coproc_id = 0;
428 #endif /* KSH */
429 last_job = j;
430 last_proc = p;
431 put_job(j, PJ_PAST_STOPPED);
434 snptreef(p->command, sizeof(p->command), "%T", t);
436 /* create child process */
437 forksleep = 1;
438 while ((i = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
439 if (intrsig) /* allow user to ^C out... */
440 break;
441 sleep(forksleep);
442 forksleep <<= 1;
444 if (i < 0) {
445 kill_job(j, SIGKILL);
446 remove_job(j, "fork failed");
447 #ifdef JOB_SIGS
448 sigprocmask(SIG_SETMASK, &omask, NULL);
449 #endif
450 errorf("cannot fork - try again");
452 ischild = i == 0;
453 if (ischild)
454 p->pid = procpid = getpid();
455 else
456 p->pid = i;
458 #ifdef SILLY_FEATURES
459 /* job control set up */
460 if (Flag(FMONITOR) && !(flags&XXCOM)) {
461 int dotty = 0;
462 if (j->pgrp == 0) { /* First process */
463 j->pgrp = p->pid;
464 dotty = 1;
467 /* set pgrp in both parent and child to deal with race
468 * condition
470 setpgid(p->pid, j->pgrp);
471 if (ttypgrp_ok && dotty && !(flags & XBGND))
472 tcsetpgrp(tty_fd, j->pgrp);
474 #endif
476 /* used to close pipe input fd */
477 if (close_fd >= 0 && (((flags & XPCLOSE) && !ischild) ||
478 ((flags & XCCLOSE) && ischild)))
479 close(close_fd);
480 if (ischild) { /* child */
481 #ifdef SILLY_FEATURES
482 /* Do this before restoring signal */
483 if (flags & XCOPROC)
484 coproc_cleanup(FALSE);
485 #endif /* KSH */
486 #ifdef JOB_SIGS
487 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
488 #endif /* JOB_SIGS */
489 cleanup_parents_env();
490 #ifdef SILLY_FEATURES
491 /* If FMONITOR or FTALKING is set, these signals are ignored,
492 * if neither FMONITOR nor FTALKING are set, the signals have
493 * their inherited values.
495 if (Flag(FMONITOR) && !(flags & XXCOM)) {
496 for (i = NELEM(tt_sigs); --i >= 0; )
497 setsig(&sigtraps[tt_sigs[i]], SIG_DFL,
498 SS_RESTORE_DFL|SS_FORCE);
500 #endif /* TTY_PGRP */
501 if ((flags & XBGND) && !Flag(FMONITOR)) {
502 setsig(&sigtraps[SIGINT], SIG_IGN,
503 SS_RESTORE_IGN|SS_FORCE);
504 setsig(&sigtraps[SIGQUIT], SIG_IGN,
505 SS_RESTORE_IGN|SS_FORCE);
506 if (!(flags & (XPIPEI | XCOPROC))) {
507 int fd = open("/dev/null", 0);
508 (void) ksh_dup2(fd, 0, TRUE);
509 close(fd);
512 remove_job(j, "child"); /* in case of $(jobs) command */
513 nzombie = 0;
514 #ifdef SILLY_FEATURES
515 ttypgrp_ok = 0;
516 Flag(FMONITOR) = 0;
517 #endif
518 Flag(FTALKING) = 0;
519 tty_close();
520 cleartraps();
521 execute(t, (flags & XERROK) | XEXEC, NULL); /* no return */
522 internal_errorf(0, "exchild: execute() returned");
523 unwind(LLEAVE);
524 /* NOTREACHED */
527 /* shell (parent) stuff */
528 /* Ensure next child gets a (slightly) different $RANDOM sequence */
529 change_random();
530 if (!(flags & XPIPEO)) { /* last process in a job */
531 j_startjob(j);
532 #ifdef SILLY_FEATURES
533 if (flags & XCOPROC) {
534 j->coproc_id = coproc.id;
535 coproc.njobs++; /* n jobs using co-process output */
536 coproc.job = (void *) j; /* j using co-process input */
538 #endif /* KSH */
539 if (flags & XBGND) {
540 j_set_async(j);
541 if (Flag(FTALKING)) {
542 shf_fprintf(shl_out, "[%d]", j->job);
543 for (p = j->proc_list; p; p = p->next)
544 shf_fprintf(shl_out, " %d",
545 (int)p->pid);
546 shf_putchar('\n', shl_out);
547 shf_flush(shl_out);
549 } else
550 rv = j_waitj(j, JW_NONE, "jw:last proc");
553 #ifdef JOB_SIGS
554 sigprocmask(SIG_SETMASK, &omask, NULL);
555 #endif /* JOB_SIGS */
557 return (rv);
560 /* start the last job: only used for $(command) jobs */
561 void
562 startlast(void)
564 #ifdef JOB_SIGS
565 sigset_t omask;
567 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
568 #endif /* JOB_SIGS */
570 if (last_job) { /* no need to report error - waitlast() will do it */
571 /* ensure it isn't removed by check_job() */
572 last_job->flags |= JF_WAITING;
573 j_startjob(last_job);
575 #ifdef JOB_SIGS
576 sigprocmask(SIG_SETMASK, &omask, NULL);
577 #endif
580 /* wait for last job: only used for $(command) jobs */
582 waitlast(void)
584 int rv;
585 Job *j;
586 #ifdef JOB_SIGS
587 sigset_t omask;
589 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
590 #endif /* JOB_SIGS */
592 j = last_job;
593 if (!j || !(j->flags & JF_STARTED)) {
594 if (!j)
595 warningf(TRUE, "waitlast: no last job");
596 else
597 internal_errorf(0, "waitlast: not started");
598 #ifdef JOB_SIGS
599 sigprocmask(SIG_SETMASK, &omask, NULL);
600 #endif /* JOB_SIGS */
601 return (125); /* not so arbitrary, non-zero value */
604 rv = j_waitj(j, JW_NONE, "jw:waitlast");
606 #ifdef JOB_SIGS
607 sigprocmask(SIG_SETMASK, &omask, NULL);
608 #endif
610 return (rv);
613 /* wait for child, interruptable. */
615 waitfor(const char *cp, int *sigp)
617 int rv;
618 Job *j;
619 int ecode;
620 int flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
621 #ifdef JOB_SIGS
622 sigset_t omask;
624 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
625 #endif /* JOB_SIGS */
627 *sigp = 0;
629 if (cp == NULL) {
630 /* wait for an unspecified job - always returns 0, so
631 * don't have to worry about exited/signaled jobs
633 for (j = job_list; j; j = j->next)
634 /* at&t ksh will wait for stopped jobs - we don't */
635 if (j->ppid == procpid && j->state == PRUNNING)
636 break;
637 if (!j) {
638 #ifdef JOB_SIGS
639 sigprocmask(SIG_SETMASK, &omask, NULL);
640 #endif /* JOB_SIGS */
641 return (-1);
643 } else if ((j = j_lookup(cp, &ecode))) {
644 /* don't report normal job completion */
645 flags &= ~JW_ASYNCNOTIFY;
646 if (j->ppid != procpid) {
647 #ifdef JOB_SIGS
648 sigprocmask(SIG_SETMASK, &omask, NULL);
649 #endif /* JOB_SIGS */
650 return (-1);
652 } else {
653 #ifdef JOB_SIGS
654 sigprocmask(SIG_SETMASK, &omask, NULL);
655 #endif /* JOB_SIGS */
656 if (ecode != JL_NOSUCH)
657 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
658 return (-1);
661 /* at&t ksh will wait for stopped jobs - we don't */
662 rv = j_waitj(j, flags, "jw:waitfor");
664 #ifdef JOB_SIGS
665 sigprocmask(SIG_SETMASK, &omask, NULL);
666 #endif /* JOB_SIGS */
668 if (rv < 0) /* we were interrupted */
669 *sigp = 128 + -rv;
671 return (rv);
674 /* kill (built-in) a job */
676 j_kill(const char *cp, int sig)
678 Job *j;
679 int rv = 0;
680 int ecode;
681 #ifdef JOB_SIGS
682 sigset_t omask;
684 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
685 #endif /* JOB_SIGS */
687 if ((j = j_lookup(cp, &ecode)) == NULL) {
688 #ifdef JOB_SIGS
689 sigprocmask(SIG_SETMASK, &omask, NULL);
690 #endif /* JOB_SIGS */
691 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
692 return (1);
695 if (j->pgrp == 0) { /* started when !Flag(FMONITOR) */
696 if (kill_job(j, sig) < 0) {
697 bi_errorf("%s: %s", cp, strerror(errno));
698 rv = 1;
700 } else {
701 #ifdef SILLY_FEATURE
702 if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
703 (void) killpg(j->pgrp, SIGCONT);
704 #endif /* JOBS */
705 if (killpg(j->pgrp, sig) < 0) {
706 bi_errorf("%s: %s", cp, strerror(errno));
707 rv = 1;
711 #ifdef JOB_SIGS
712 sigprocmask(SIG_SETMASK, &omask, NULL);
713 #endif /* JOB_SIGS */
715 return (rv);
718 #ifdef SILLY_FEATURE
719 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
721 j_resume(const char *cp, int bg)
723 Job *j;
724 Proc *p;
725 int ecode;
726 int running;
727 int rv = 0;
728 sigset_t omask;
730 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
732 if ((j = j_lookup(cp, &ecode)) == NULL) {
733 sigprocmask(SIG_SETMASK, &omask, NULL);
734 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
735 return (1);
738 if (j->pgrp == 0) {
739 sigprocmask(SIG_SETMASK, &omask, NULL);
740 bi_errorf("job not job-controlled");
741 return (1);
744 if (bg)
745 shprintf("[%d] ", j->job);
747 running = 0;
748 for (p = j->proc_list; p != NULL; p = p->next) {
749 if (p->state == PSTOPPED) {
750 p->state = PRUNNING;
751 WSTATUS(p->status) = 0;
752 running = 1;
754 shprintf("%s%s", p->command, p->next ? "| " : null);
756 shprintf('\n');
757 shf_flush(shl_stdout);
758 if (running)
759 j->state = PRUNNING;
761 put_job(j, PJ_PAST_STOPPED);
762 if (bg)
763 j_set_async(j);
764 else {
765 /* attach tty to job */
766 if (j->state == PRUNNING) {
767 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
768 tcsetattr(tty_fd, TCSADRAIN, &j->ttystate);
769 /* See comment in j_waitj regarding saved_ttypgrp. */
770 if (ttypgrp_ok &&
771 tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
772 j->saved_ttypgrp : j->pgrp) < 0) {
773 rv = errno;
774 if (j->flags & JF_SAVEDTTY)
775 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
776 sigprocmask(SIG_SETMASK, &omask,
777 NULL);
778 bi_errorf("1st tcsetpgrp(%d, %d) failed: %s",
779 tty_fd,
780 (int)((j->flags & JF_SAVEDTTYPGRP) ?
781 j->saved_ttypgrp : j->pgrp),
782 strerror(rv));
783 return (1);
786 j->flags |= JF_FG;
787 j->flags &= ~JF_KNOWN;
788 if (j == async_job)
789 async_job = NULL;
792 if (j->state == PRUNNING && killpg(j->pgrp, SIGCONT) < 0) {
793 int err = errno;
795 if (!bg) {
796 j->flags &= ~JF_FG;
797 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
798 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
799 if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
800 warningf(true,
801 "fg: 2nd tcsetpgrp(%d, %ld) failed: %s",
802 tty_fd, (long)kshpgrp, strerror(errno));
804 sigprocmask(SIG_SETMASK, &omask, NULL);
805 bi_errorf("cannot continue job %s: %s",
806 cp, strerror(err));
807 return (1);
809 if (!bg) {
810 if (ttypgrp_ok) {
811 j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
813 rv = j_waitj(j, JW_NONE, "jw:resume");
815 sigprocmask(SIG_SETMASK, &omask, NULL);
816 return (rv);
818 #endif /* JOBS */
820 /* are there any running or stopped jobs ? */
822 j_stopped_running(void)
824 Job *j;
825 int which = 0;
827 for (j = job_list; j != NULL; j = j->next) {
828 #ifdef SILLY_FEATURES
829 if (j->ppid == procpid && j->state == PSTOPPED)
830 which |= 1;
831 #endif
832 if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
833 j->ppid == procpid && j->state == PRUNNING)
834 which |= 2;
836 if (which) {
837 shellf("You have %s%s%s jobs\n",
838 which & 1 ? "stopped" : "",
839 which == 3 ? " and " : "",
840 which & 2 ? "running" : "");
841 return (1);
844 return (0);
847 #ifdef SILLY_FEATURES
850 j_njobs(void)
852 Job *j;
853 int nj = 0;
854 sigset_t omask;
856 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
857 for (j = job_list; j; j = j->next)
858 nj++;
860 sigprocmask(SIG_SETMASK, &omask, NULL);
861 return (nj);
865 /* list jobs for jobs built-in */
867 j_jobs(const char *cp, int slp,
868 int nflag) /* 0: short, 1: long, 2: pgrp */
870 Job *j, *tmp;
871 int how;
872 int zflag = 0;
873 #ifdef JOB_SIGS
874 sigset_t omask;
876 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
877 #endif /* JOB_SIGS */
879 if (nflag < 0) { /* kludge: print zombies */
880 nflag = 0;
881 zflag = 1;
883 if (cp) {
884 int ecode;
886 if ((j = j_lookup(cp, &ecode)) == NULL) {
887 #ifdef JOB_SIGS
888 sigprocmask(SIG_SETMASK, &omask, NULL);
889 #endif /* JOB_SIGS */
890 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
891 return (1);
893 } else
894 j = job_list;
895 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
896 for (; j; j = j->next) {
897 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
898 (!nflag || (j->flags & JF_CHANGED))) {
899 j_print(j, how, shl_stdout);
900 if (j->state == PEXITED || j->state == PSIGNALLED)
901 j->flags |= JF_REMOVE;
903 if (cp)
904 break;
906 /* Remove jobs after printing so there won't be multiple + or - jobs */
907 for (j = job_list; j; j = tmp) {
908 tmp = j->next;
909 if (j->flags & JF_REMOVE)
910 remove_job(j, "jobs");
912 #ifdef JOB_SIGS
913 sigprocmask(SIG_SETMASK, &omask, NULL);
914 #endif /* JOB_SIGS */
915 return (0);
917 #endif /* SILLY_FEATURES */
919 /* list jobs for top-level notification */
920 void
921 j_notify(void)
923 Job *j, *tmp;
924 #ifdef JOB_SIGS
925 sigset_t omask;
927 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
928 #endif /* JOB_SIGS */
929 for (j = job_list; j; j = j->next) {
930 #ifdef SILLY_FEATURES
931 if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
932 j_print(j, JP_MEDIUM, shl_out);
933 #endif /* JOBS */
934 /* Remove job after doing reports so there aren't
935 * multiple +/- jobs.
937 if (j->state == PEXITED || j->state == PSIGNALLED)
938 j->flags |= JF_REMOVE;
940 for (j = job_list; j; j = tmp) {
941 tmp = j->next;
942 if (j->flags & JF_REMOVE)
943 remove_job(j, "notify");
945 shf_flush(shl_out);
946 #ifdef JOB_SIGS
947 sigprocmask(SIG_SETMASK, &omask, NULL);
948 #endif /* JOB_SIGS */
951 /* Return pid of last process in last asynchronous job */
952 pid_t
953 j_async(void)
955 #ifdef JOB_SIGS
956 sigset_t omask;
958 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
959 #endif /* JOB_SIGS */
961 if (async_job)
962 async_job->flags |= JF_KNOWN;
964 #ifdef JOB_SIGS
965 sigprocmask(SIG_SETMASK, &omask, NULL);
966 #endif /* JOB_SIGS */
968 return (async_pid);
971 /* Make j the last async process
973 * If jobs are compiled in then this routine expects sigchld to be blocked.
975 static void
976 j_set_async(Job *j)
978 Job *jl, *oldest;
980 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
981 remove_job(async_job, "async");
982 if (!(j->flags & JF_STARTED)) {
983 internal_errorf(0, "j_async: job not started");
984 return;
986 async_job = j;
987 async_pid = j->last_proc->pid;
988 while (nzombie > child_max) {
989 oldest = NULL;
990 for (jl = job_list; jl; jl = jl->next)
991 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
992 (!oldest || jl->age < oldest->age))
993 oldest = jl;
994 if (!oldest) {
995 /* XXX debugging */
996 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
997 internal_errorf(0, "j_async: bad nzombie (%d)", nzombie);
998 nzombie = 0;
1000 break;
1002 remove_job(oldest, "zombie");
1006 /* Start a job: set STARTED, check for held signals and set j->last_proc
1008 * If jobs are compiled in then this routine expects sigchld to be blocked.
1010 static void
1011 j_startjob(Job *j)
1013 Proc *p;
1015 j->flags |= JF_STARTED;
1016 for (p = j->proc_list; p->next; p = p->next)
1018 j->last_proc = p;
1020 #ifdef JOB_SIGS
1021 if (held_sigchld) {
1022 held_sigchld = 0;
1023 /* Don't call j_sigchld() as it may remove job... */
1024 kill(procpid, SIGCHLD);
1026 #endif /* JOB_SIGS */
1030 * wait for job to complete or change state
1032 * If jobs are compiled in then this routine expects sigchld to be blocked.
1034 static int
1035 j_waitj(j, flags, where)
1036 Job *j;
1037 int flags; /* see JW_* */
1038 const char *where;
1040 int rv;
1043 * No auto-notify on the job we are waiting on.
1045 j->flags |= JF_WAITING;
1046 if (flags & JW_ASYNCNOTIFY)
1047 j->flags |= JF_W_ASYNCNOTIFY;
1049 if (!Flag(FMONITOR))
1050 flags |= JW_STOPPEDWAIT;
1052 while ((volatile int) j->state == PRUNNING
1053 || ((flags & JW_STOPPEDWAIT)
1054 && (volatile int) j->state == PSTOPPED))
1056 #ifdef JOB_SIGS
1057 sigsuspend(&sm_default);
1058 #else /* JOB_SIGS */
1059 j_sigchld(SIGCHLD);
1060 #endif /* JOB_SIGS */
1061 if (fatal_trap) {
1062 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1063 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1064 runtraps(TF_FATAL);
1065 j->flags |= oldf; /* not reached... */
1067 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1068 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1069 return (-rv);
1072 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1074 if (j->flags & JF_FG) {
1075 int status;
1077 j->flags &= ~JF_FG;
1078 #ifdef SILLY_FEATURES
1079 if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1081 * Save the tty's current pgrp so it can be restored
1082 * when the job is foregrounded. This is to
1083 * deal with things like the GNU su which does
1084 * a fork/exec instead of an exec (the fork means
1085 * the execed shell gets a different pid from its
1086 * pgrp, so naturally it sets its pgrp and gets hosed
1087 * when it gets foregrounded by the parent shell which
1088 * has restored the tty's pgrp to that of the su
1089 * process).
1091 if (j->state == PSTOPPED &&
1092 (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1093 j->flags |= JF_SAVEDTTYPGRP;
1094 if (tcsetpgrp(tty_fd, our_pgrp) < 0) {
1095 warningf(TRUE,
1096 "j_waitj: tcsetpgrp(%d, %d) failed: %s",
1097 tty_fd, (int) our_pgrp,
1098 strerror(errno));
1100 if (j->state == PSTOPPED) {
1101 j->flags |= JF_SAVEDTTY;
1102 get_tty(tty_fd, &j->ttystate);
1105 #endif /* TTY_PGRP */
1106 if (tty_fd >= 0) {
1107 /* Only restore tty settings if job was originally
1108 * started in the foreground. Problems can be
1109 * caused by things like 'more foobar &' which will
1110 * typically get and save the shell's vi/emacs tty
1111 * settings before setting up the tty for itself;
1112 * when more exits, it restores the `original'
1113 * settings, and things go down hill from there...
1115 if (j->state == PEXITED && j->status == 0
1116 && (j->flags & JF_USETTYMODE))
1118 get_tty(tty_fd, &tty_state);
1119 } else {
1120 set_tty(tty_fd, &tty_state,
1121 (j->state == PEXITED) ? 0 : TF_MIPSKLUDGE);
1122 /* Don't use tty mode if job is stopped and
1123 * later restarted and exits. Consider
1124 * the sequence:
1125 * vi foo (stopped)
1126 * ...
1127 * stty something
1128 * ...
1129 * fg (vi; ZZ)
1130 * mode should be that of the stty, not what
1131 * was before the vi started.
1133 if (j->state == PSTOPPED)
1134 j->flags &= ~JF_USETTYMODE;
1137 #ifdef SILLY_FEATURES
1138 /* If it looks like user hit ^C to kill a job, pretend we got
1139 * one too to break out of for loops, etc. (at&t ksh does this
1140 * even when not monitoring, but this doesn't make sense since
1141 * a tty generated ^C goes to the whole process group)
1143 status = j->last_proc->status;
1144 if (Flag(FMONITOR) && j->state == PSIGNALLED
1145 && WIFSIGNALED(status)
1146 && (sigtraps[WTERMSIG(status)].flags & TF_TTY_INTR))
1147 trapsig(WTERMSIG(status));
1148 #endif /* JOBS */
1151 j_usrtime = j->usrtime;
1152 j_systime = j->systime;
1153 rv = j->status;
1155 if (!(flags & JW_ASYNCNOTIFY)
1156 && (!Flag(FMONITOR) || j->state != PSTOPPED))
1158 j_print(j, JP_SHORT, shl_out);
1159 shf_flush(shl_out);
1161 if (j->state != PSTOPPED
1162 && (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY)))
1163 remove_job(j, where);
1165 return (rv);
1168 /* SIGCHLD handler to reap children and update job states
1170 * If jobs are compiled in then this routine expects sigchld to be blocked.
1172 /* ARGSUSED */
1173 static void
1174 j_sigchld(int UNUSED(sig))
1176 int errno_ = errno;
1177 Job *j;
1178 Proc *p = NULL;
1179 int pid;
1180 int status;
1181 struct rusage ru0, ru1;
1183 #ifdef JOB_SIGS
1184 /* Don't wait for any processes if a job is partially started.
1185 * This is so we don't do away with the process group leader
1186 * before all the processes in a pipe line are started (so the
1187 * setpgid() won't fail)
1189 for (j = job_list; j; j = j->next)
1190 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1191 held_sigchld = 1;
1192 return;
1194 #endif /* JOB_SIGS */
1196 getrusage(RUSAGE_CHILDREN, &ru0);
1197 do {
1198 #ifdef JOB_SIGS
1199 pid = waitpid(-1, &status, (WNOHANG|WUNTRACED));
1200 #else /* JOB_SIGS */
1201 pid = wait(&status);
1202 #endif /* JOB_SIGS */
1204 if (pid <= 0) /* return if would block (0) ... */
1205 break; /* ... or no children or interrupted (-1) */
1207 getrusage(RUSAGE_CHILDREN, &ru1);
1209 /* find job and process structures for this pid */
1210 for (j = job_list; j != NULL; j = j->next)
1211 for (p = j->proc_list; p != NULL; p = p->next)
1212 if (p->pid == pid)
1213 goto found;
1214 found:
1215 if (j == NULL) {
1216 /* Can occur if process has kids, then execs shell
1217 warningf(true, "bad process waited for (pid = %d)",
1218 pid);
1220 ru0 = ru1;
1221 continue;
1224 timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1225 timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1226 timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1227 timersub(&j->systime, &ru0.ru_stime, &j->systime);
1228 ru0 = ru1;
1229 p->status = status;
1230 #ifdef SILLY_FEATURES
1231 if (WIFSTOPPED(status))
1232 p->state = PSTOPPED;
1233 else
1234 #endif /* JOBS */
1235 if (WIFSIGNALED(status))
1236 p->state = PSIGNALLED;
1237 else
1238 p->state = PEXITED;
1240 check_job(j); /* check to see if entire job is done */
1242 #ifdef JOB_SIGS
1243 while (1);
1244 #else /* JOB_SIGS */
1245 while (0);
1246 #endif /* JOB_SIGS */
1248 errno = errno_;
1252 * Called only when a process in j has exited/stopped (ie, called only
1253 * from j_sigchld()). If no processes are running, the job status
1254 * and state are updated, asynchronous job notification is done and,
1255 * if unneeded, the job is removed.
1257 * If jobs are compiled in then this routine expects sigchld to be blocked.
1259 static void
1260 check_job(Job *j)
1262 int jstate;
1263 Proc *p;
1265 /* XXX debugging (nasty - interrupt routine using shl_out) */
1266 if (!(j->flags & JF_STARTED)) {
1267 internal_errorf(0, "check_job: job started (flags 0x%x)",
1268 j->flags);
1269 return;
1272 jstate = PRUNNING;
1273 for (p=j->proc_list; p != NULL; p = p->next) {
1274 if (p->state == PRUNNING)
1275 return; /* some processes still running */
1276 if (p->state > jstate)
1277 jstate = p->state;
1279 j->state = jstate;
1281 switch (j->last_proc->state) {
1282 case PEXITED:
1283 j->status = WEXITSTATUS(j->last_proc->status);
1284 break;
1285 case PSIGNALLED:
1286 j->status = 128 + WTERMSIG(j->last_proc->status);
1287 break;
1288 default:
1289 j->status = 0;
1290 break;
1293 #ifdef SILLY_FEATURES
1294 /* Note when co-process dies: can't be done in j_wait() nor
1295 * remove_job() since neither may be called for non-interactive
1296 * shells.
1298 if (j->state == PEXITED || j->state == PSIGNALLED) {
1299 /* No need to keep co-process input any more
1300 * (at least, this is what ksh93d thinks)
1302 if (coproc.job == j) {
1303 coproc.job = NULL;
1304 /* XXX would be nice to get the closes out of here
1305 * so they aren't done in the signal handler.
1306 * Would mean a check in coproc_getfd() to
1307 * do "if job == 0 && write >= 0, close write".
1309 coproc_write_close(coproc.write);
1311 /* Do we need to keep the output? */
1312 if (j->coproc_id && j->coproc_id == coproc.id &&
1313 --coproc.njobs == 0)
1314 coproc_readw_close(coproc.read);
1316 #endif /* KSH */
1318 j->flags |= JF_CHANGED;
1319 #ifdef SILLY_FEATURES
1320 if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1321 /* Only put stopped jobs at the front to avoid confusing
1322 * the user (don't want finished jobs effecting %+ or %-)
1324 if (j->state == PSTOPPED)
1325 put_job(j, PJ_ON_FRONT);
1326 if (Flag(FNOTIFY)
1327 && (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING)
1329 /* Look for the real file descriptor 2 */
1331 struct env *ep;
1332 int fd = 2;
1334 for (ep = e; ep; ep = ep->oenv)
1335 if (ep->savefd && ep->savefd[2])
1336 fd = ep->savefd[2];
1337 shf_reopen(fd, SHF_WR, shl_j);
1339 /* Can't call j_notify() as it removes jobs. The job
1340 * must stay in the job list as j_waitj() may be
1341 * running with this job.
1343 j_print(j, JP_MEDIUM, shl_j);
1344 shf_flush(shl_j);
1345 if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1346 remove_job(j, "notify");
1349 #endif /* JOBS */
1350 if (!Flag(FMONITOR) && !(j->flags & (JF_WAITING|JF_FG))
1351 && j->state != PSTOPPED)
1353 if (j == async_job || (j->flags & JF_KNOWN)) {
1354 j->flags |= JF_ZOMBIE;
1355 j->job = -1;
1356 nzombie++;
1357 } else
1358 remove_job(j, "checkjob");
1363 * Print job status in either short, medium or long format.
1365 * If jobs are compiled in then this routine expects sigchld to be blocked.
1367 static void
1368 j_print(Job *j, int how, struct shf *shf)
1370 Proc *p;
1371 int state;
1372 int status;
1373 int coredumped;
1374 char jobchar = ' ';
1375 char buf[64];
1376 const char *filler;
1377 int output = 0;
1379 if (how == JP_PGRP) {
1380 /* POSIX doesn't say what to do it there is no process
1381 * group leader (ie, !FMONITOR). We arbitrarily return
1382 * last pid (which is what $! returns).
1384 shf_fprintf(shf, "%d\n", (int)(j->pgrp ? j->pgrp :
1385 (j->last_proc ? j->last_proc->pid : 0)));
1386 return;
1388 j->flags &= ~JF_CHANGED;
1389 filler = j->job > 10 ? "\n " : "\n ";
1390 if (j == job_list)
1391 jobchar = '+';
1392 else if (j == job_list->next)
1393 jobchar = '-';
1395 for (p = j->proc_list; p != NULL;) {
1396 coredumped = 0;
1397 switch (p->state) {
1398 case PRUNNING:
1399 memcpy(buf, "Running", 8);
1400 break;
1401 case PSTOPPED:
1402 strcpy(buf, sigtraps[WSTOPSIG(p->status)].mess);
1403 break;
1404 case PEXITED:
1405 if (how == JP_SHORT)
1406 buf[0] = '\0';
1407 else if (WEXITSTATUS(p->status) == 0)
1408 memcpy(buf, "Done", 5);
1409 else
1410 snprintf(buf, sizeof(buf), "Done (%d)",
1411 WEXITSTATUS(p->status));
1412 break;
1413 case PSIGNALLED:
1414 if (WIFCORED(p->status))
1415 coredumped = 1;
1416 /* kludge for not reporting `normal termination signals'
1417 * (ie, SIGINT, SIGPIPE)
1419 if (how == JP_SHORT && !coredumped
1420 && (WTERMSIG(p->status) == SIGINT
1421 || WTERMSIG(p->status) == SIGPIPE)) {
1422 buf[0] = '\0';
1423 } else
1424 strcpy(buf, sigtraps[WTERMSIG(p->status)].mess);
1425 break;
1428 if (how != JP_SHORT) {
1429 if (p == j->proc_list)
1430 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1431 else
1432 shf_fprintf(shf, "%s", filler);
1435 if (how == JP_LONG)
1436 shf_fprintf(shf, "%5d ", (int)p->pid);
1438 if (how == JP_SHORT) {
1439 if (buf[0]) {
1440 output = 1;
1441 shf_fprintf(shf, "%s%s ",
1442 buf, coredumped ? " (core dumped)" : null);
1444 } else {
1445 output = 1;
1446 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1447 p->next ? "|" : null,
1448 coredumped ? " (core dumped)" : null);
1451 state = p->state;
1452 status = p->status;
1453 p = p->next;
1454 while (p && p->state == state
1455 && WSTATUS(p->status) == WSTATUS(status))
1457 if (how == JP_LONG)
1458 shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
1459 (int)p->pid, " ", p->command,
1460 p->next ? "|" : null);
1461 else if (how == JP_MEDIUM)
1462 shf_fprintf(shf, " %s%s", p->command,
1463 p->next ? "|" : null);
1464 p = p->next;
1467 if (output)
1468 shf_fprintf(shf, "\n");
1471 /* Convert % sequence to job
1473 * If jobs are compiled in then this routine expects sigchld to be blocked.
1475 static Job *
1476 j_lookup(const char *cp, int *ecodep)
1478 Job *j, *last_match;
1479 Proc *p;
1480 int len, job = 0;
1482 if (isdigit(*cp)) {
1483 job = strtol(cp, (char **)NULL, 10);
1484 /* Look for last_proc->pid (what $! returns) first... */
1485 for (j = job_list; j != NULL; j = j->next)
1486 if (j->last_proc && j->last_proc->pid == job)
1487 return (j);
1488 /* ...then look for process group (this is non-POSIX,
1489 * but should not break anything) */
1490 for (j = job_list; j != NULL; j = j->next)
1491 if (j->pgrp && j->pgrp == job)
1492 return (j);
1493 if (ecodep)
1494 *ecodep = JL_NOSUCH;
1495 return (NULL);
1497 if (*cp != '%') {
1498 if (ecodep)
1499 *ecodep = JL_INVALID;
1500 return (NULL);
1502 switch (*++cp) {
1503 case '\0': /* non-standard */
1504 case '+':
1505 case '%':
1506 if (job_list != NULL)
1507 return (job_list);
1508 break;
1510 case '-':
1511 if (job_list != NULL && job_list->next)
1512 return job_list->next;
1513 break;
1515 case '0': case '1': case '2': case '3': case '4':
1516 case '5': case '6': case '7': case '8': case '9':
1517 job = strtol(cp, (char **)NULL, 10);
1518 for (j = job_list; j != NULL; j = j->next)
1519 if (j->job == job)
1520 return j;
1521 break;
1523 case '?': /* %?string */
1524 last_match = NULL;
1525 for (j = job_list; j != NULL; j = j->next)
1526 for (p = j->proc_list; p != NULL; p = p->next)
1527 if (strstr(p->command, cp+1) != NULL) {
1528 if (last_match) {
1529 if (ecodep)
1530 *ecodep = JL_AMBIG;
1531 return (NULL);
1533 last_match = j;
1535 if (last_match)
1536 return (last_match);
1537 break;
1539 default: /* %string */
1540 len = strlen(cp);
1541 last_match = NULL;
1542 for (j = job_list; j != NULL; j = j->next)
1543 if (strncmp(cp, j->proc_list->command, len) == 0) {
1544 if (last_match) {
1545 if (ecodep)
1546 *ecodep = JL_AMBIG;
1547 return (NULL);
1549 last_match = j;
1551 if (last_match)
1552 return (last_match);
1553 break;
1555 if (ecodep)
1556 *ecodep = JL_NOSUCH;
1557 return (NULL);
1560 static Job *free_jobs;
1561 static Proc *free_procs;
1563 /* allocate a new job and fill in the job number.
1565 * If jobs are compiled in then this routine expects sigchld to be blocked.
1567 static Job *
1568 new_job(void)
1570 int i;
1571 Job *newj, *j;
1573 if (free_jobs != NULL) {
1574 newj = free_jobs;
1575 free_jobs = free_jobs->next;
1576 } else
1577 newj = (Job *) alloc(sizeof(Job), APERM);
1579 /* brute force method */
1580 for (i = 1; ; i++) {
1581 for (j = job_list; j && j->job != i; j = j->next)
1583 if (j == NULL)
1584 break;
1586 newj->job = i;
1588 return (newj);
1591 /* Allocate new process struct
1593 * If jobs are compiled in then this routine expects sigchld to be blocked.
1595 static Proc *
1596 new_proc(void)
1598 Proc *p;
1600 if (free_procs != NULL) {
1601 p = free_procs;
1602 free_procs = free_procs->next;
1603 } else
1604 p = (Proc *) alloc(sizeof(Proc), APERM);
1606 return (p);
1609 /* Take job out of job_list and put old structures into free list.
1610 * Keeps nzombies, last_job and async_job up to date.
1612 * If jobs are compiled in then this routine expects sigchld to be blocked.
1614 static void
1615 remove_job(Job *j, const char *where)
1617 Proc *p, *tmp;
1618 Job **prev, *curr;
1620 prev = &job_list;
1621 curr = *prev;
1622 for (; curr != NULL && curr != j; prev = &curr->next, curr = *prev)
1624 if (curr != j) {
1625 internal_errorf(0, "remove_job: job not found (%s)", where);
1626 return;
1628 *prev = curr->next;
1630 /* free up proc structures */
1631 for (p = j->proc_list; p != NULL; ) {
1632 tmp = p;
1633 p = p->next;
1634 tmp->next = free_procs;
1635 free_procs = tmp;
1638 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1639 --nzombie;
1640 j->next = free_jobs;
1641 free_jobs = j;
1643 if (j == last_job)
1644 last_job = NULL;
1645 if (j == async_job)
1646 async_job = NULL;
1649 /* put j in a particular location (taking it out job_list if it is there
1650 * already)
1652 * If jobs are compiled in then this routine expects sigchld to be blocked.
1654 static void
1655 put_job(Job *j, int where)
1657 Job **prev, *curr;
1659 /* Remove job from list (if there) */
1660 prev = &job_list;
1661 curr = job_list;
1662 for (; curr && curr != j; prev = &curr->next, curr = *prev)
1664 if (curr == j)
1665 *prev = curr->next;
1667 switch (where) {
1668 case PJ_ON_FRONT:
1669 j->next = job_list;
1670 job_list = j;
1671 break;
1673 case PJ_PAST_STOPPED:
1674 prev = &job_list;
1675 curr = job_list;
1676 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1677 curr = *prev)
1679 j->next = curr;
1680 *prev = j;
1681 break;
1685 /* nuke a job (called when unable to start full job).
1687 * If jobs are compiled in then this routine expects sigchld to be blocked.
1689 static int
1690 kill_job(Job *j, int sig)
1692 Proc *p;
1693 int rval = 0;
1695 for (p = j->proc_list; p != NULL; p = p->next)
1696 if (p->pid != 0)
1697 if (kill(p->pid, sig) < 0)
1698 rval = -1;
1699 return (rval);