sync
[bitrig.git] / bin / ksh / jobs.c
blob67d07263a81c68a9f9fd733580a76033a4d0ad5d
1 /* $OpenBSD: jobs.c,v 1.39 2009/12/13 04:36:48 deraadt Exp $ */
3 /*
4 * Process and job control
5 */
7 /*
8 * Reworked/Rewritten version of Eric Gisin's/Ron Natalie's code by
9 * Larry Bouzane (larry@cs.mun.ca) and hacked again by
10 * Michael Rendell (michael@cs.mun.ca)
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 :)
18 #include "sh.h"
19 #include <sys/stat.h>
20 #include <sys/wait.h>
21 #include <sys/time.h>
22 #include <sys/resource.h>
23 #include "tty.h"
25 /* Order important! */
26 #define PRUNNING 0
27 #define PEXITED 1
28 #define PSIGNALLED 2
29 #define PSTOPPED 3
31 typedef struct proc Proc;
32 struct proc {
33 Proc *next; /* next process in pipeline (if any) */
34 int state;
35 int status; /* wait status */
36 pid_t pid; /* process id */
37 char command[48]; /* process command string */
40 /* Notify/print flag - j_print() argument */
41 #define JP_NONE 0 /* don't print anything */
42 #define JP_SHORT 1 /* print signals processes were killed by */
43 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
44 #define JP_LONG 3 /* print [job-num] -/+ pid command */
45 #define JP_PGRP 4 /* print pgrp */
47 /* put_job() flags */
48 #define PJ_ON_FRONT 0 /* at very front */
49 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
51 /* Job.flags values */
52 #define JF_STARTED 0x001 /* set when all processes in job are started */
53 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
54 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
55 #define JF_XXCOM 0x008 /* set for `command` jobs */
56 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
57 #define JF_SAVEDTTY 0x020 /* j->ttystate is valid */
58 #define JF_CHANGED 0x040 /* process has changed state */
59 #define JF_KNOWN 0x080 /* $! referenced */
60 #define JF_ZOMBIE 0x100 /* known, unwaited process */
61 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_noityf()) */
62 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
63 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
65 typedef struct job Job;
66 struct job {
67 Job *next; /* next job in list */
68 int job; /* job number: %n */
69 int flags; /* see JF_* */
70 int state; /* job state */
71 int status; /* exit status of last process */
72 pid_t pgrp; /* process group of job */
73 pid_t ppid; /* pid of process that forked job */
74 INT32 age; /* number of jobs started */
75 struct timeval systime; /* system time used by job */
76 struct timeval usrtime; /* user time used by job */
77 Proc *proc_list; /* process list */
78 Proc *last_proc; /* last process in list */
79 Coproc_id coproc_id; /* 0 or id of coprocess output pipe */
80 #ifdef JOBS
81 struct termios ttystate;/* saved tty state for stopped jobs */
82 pid_t saved_ttypgrp; /* saved tty process group for stopped jobs */
83 #endif /* JOBS */
86 /* Flags for j_waitj() */
87 #define JW_NONE 0x00
88 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
89 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
90 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
92 /* Error codes for j_lookup() */
93 #define JL_OK 0
94 #define JL_NOSUCH 1 /* no such job */
95 #define JL_AMBIG 2 /* %foo or %?foo is ambiguous */
96 #define JL_INVALID 3 /* non-pid, non-% job id */
98 static const char *const lookup_msgs[] = {
99 null,
100 "no such job",
101 "ambiguous",
102 "argument must be %job or process id",
103 (char *) 0
106 struct timeval j_systime, j_usrtime; /* user and system time of last j_waitjed job */
108 static Job *job_list; /* job list */
109 static Job *last_job;
110 static Job *async_job;
111 static pid_t async_pid;
113 static int nzombie; /* # of zombies owned by this process */
114 INT32 njobs; /* # of jobs started */
115 static int child_max; /* CHILD_MAX */
118 /* held_sigchld is set if sigchld occurs before a job is completely started */
119 static volatile sig_atomic_t held_sigchld;
121 #ifdef JOBS
122 static struct shf *shl_j;
123 static int ttypgrp_ok; /* set if can use tty pgrps */
124 static pid_t restore_ttypgrp = -1;
125 static pid_t our_pgrp;
126 static int const tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
127 #endif /* JOBS */
129 static void j_set_async(Job *);
130 static void j_startjob(Job *);
131 static int j_waitj(Job *, int, const char *);
132 static void j_sigchld(int);
133 static void j_print(Job *, int, struct shf *);
134 static Job *j_lookup(const char *, int *);
135 static Job *new_job(void);
136 static Proc *new_proc(void);
137 static void check_job(Job *);
138 static void put_job(Job *, int);
139 static void remove_job(Job *, const char *);
140 static int kill_job(Job *, int);
142 /* initialize job control */
143 void
144 j_init(int mflagset)
146 child_max = CHILD_MAX; /* so syscon() isn't always being called */
148 sigemptyset(&sm_default);
149 sigprocmask(SIG_SETMASK, &sm_default, (sigset_t *) 0);
151 sigemptyset(&sm_sigchld);
152 sigaddset(&sm_sigchld, SIGCHLD);
154 setsig(&sigtraps[SIGCHLD], j_sigchld,
155 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
157 #ifdef JOBS
158 if (!mflagset && Flag(FTALKING))
159 Flag(FMONITOR) = 1;
161 /* shl_j is used to do asynchronous notification (used in
162 * an interrupt handler, so need a distinct shf)
164 shl_j = shf_fdopen(2, SHF_WR, (struct shf *) 0);
166 if (Flag(FMONITOR) || Flag(FTALKING)) {
167 int i;
169 /* the TF_SHELL_USES test is a kludge that lets us know if
170 * if the signals have been changed by the shell.
172 for (i = NELEM(tt_sigs); --i >= 0; ) {
173 sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
174 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
175 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
176 SS_RESTORE_IGN|SS_FORCE);
180 /* j_change() calls tty_init() */
181 if (Flag(FMONITOR))
182 j_change();
183 else
184 #endif /* JOBS */
185 if (Flag(FTALKING))
186 tty_init(true);
189 /* job cleanup before shell exit */
190 void
191 j_exit(void)
193 /* kill stopped, and possibly running, jobs */
194 Job *j;
195 int killed = 0;
197 for (j = job_list; j != (Job *) 0; j = j->next) {
198 if (j->ppid == procpid &&
199 (j->state == PSTOPPED ||
200 (j->state == PRUNNING &&
201 ((j->flags & JF_FG) ||
202 (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
203 killed = 1;
204 if (j->pgrp == 0)
205 kill_job(j, SIGHUP);
206 else
207 killpg(j->pgrp, SIGHUP);
208 #ifdef JOBS
209 if (j->state == PSTOPPED) {
210 if (j->pgrp == 0)
211 kill_job(j, SIGCONT);
212 else
213 killpg(j->pgrp, SIGCONT);
215 #endif /* JOBS */
218 if (killed)
219 sleep(1);
220 j_notify();
222 #ifdef JOBS
223 if (kshpid == procpid && restore_ttypgrp >= 0) {
224 /* Need to restore the tty pgrp to what it was when the
225 * shell started up, so that the process that started us
226 * will be able to access the tty when we are done.
227 * Also need to restore our process group in case we are
228 * about to do an exec so that both our parent and the
229 * process we are to become will be able to access the tty.
231 tcsetpgrp(tty_fd, restore_ttypgrp);
232 setpgid(0, restore_ttypgrp);
234 if (Flag(FMONITOR)) {
235 Flag(FMONITOR) = 0;
236 j_change();
238 #endif /* JOBS */
241 #ifdef JOBS
242 /* turn job control on or off according to Flag(FMONITOR) */
243 void
244 j_change(void)
246 int i;
248 if (Flag(FMONITOR)) {
249 int use_tty;
251 if (Flag(FTALKING)) {
252 /* Don't call tcgetattr() 'til we own the tty process group */
253 use_tty = 1;
254 tty_init(false);
255 } else
256 use_tty = 0;
258 /* no controlling tty, no SIGT* */
259 ttypgrp_ok = use_tty && tty_fd >= 0 && tty_devtty;
261 if (ttypgrp_ok && (our_pgrp = getpgrp()) < 0) {
262 warningf(false, "j_init: getpgrp() failed: %s",
263 strerror(errno));
264 ttypgrp_ok = 0;
266 if (ttypgrp_ok) {
267 setsig(&sigtraps[SIGTTIN], SIG_DFL,
268 SS_RESTORE_ORIG|SS_FORCE);
269 /* wait to be given tty (POSIX.1, B.2, job control) */
270 while (1) {
271 pid_t ttypgrp;
273 if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
274 warningf(false,
275 "j_init: tcgetpgrp() failed: %s",
276 strerror(errno));
277 ttypgrp_ok = 0;
278 break;
280 if (ttypgrp == our_pgrp)
281 break;
282 kill(0, SIGTTIN);
285 for (i = NELEM(tt_sigs); --i >= 0; )
286 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
287 SS_RESTORE_DFL|SS_FORCE);
288 if (ttypgrp_ok && our_pgrp != kshpid) {
289 if (setpgid(0, kshpid) < 0) {
290 warningf(false,
291 "j_init: setpgid() failed: %s",
292 strerror(errno));
293 ttypgrp_ok = 0;
294 } else {
295 if (tcsetpgrp(tty_fd, kshpid) < 0) {
296 warningf(false,
297 "j_init: tcsetpgrp() failed: %s",
298 strerror(errno));
299 ttypgrp_ok = 0;
300 } else
301 restore_ttypgrp = our_pgrp;
302 our_pgrp = kshpid;
305 if (use_tty) {
306 if (!ttypgrp_ok)
307 warningf(false, "warning: won't have full job control");
309 if (tty_fd >= 0)
310 tcgetattr(tty_fd, &tty_state);
311 } else {
312 ttypgrp_ok = 0;
313 if (Flag(FTALKING))
314 for (i = NELEM(tt_sigs); --i >= 0; )
315 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
316 SS_RESTORE_IGN|SS_FORCE);
317 else
318 for (i = NELEM(tt_sigs); --i >= 0; ) {
319 if (sigtraps[tt_sigs[i]].flags &
320 (TF_ORIG_IGN | TF_ORIG_DFL))
321 setsig(&sigtraps[tt_sigs[i]],
322 (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
323 SIG_IGN : SIG_DFL,
324 SS_RESTORE_ORIG|SS_FORCE);
326 if (!Flag(FTALKING))
327 tty_close();
330 #endif /* JOBS */
332 /* execute tree in child subprocess */
334 exchild(struct op *t, int flags, volatile int *xerrok,
335 int close_fd) /* used if XPCLOSE or XCCLOSE */
337 static Proc *last_proc; /* for pipelines */
339 int i;
340 sigset_t omask;
341 Proc *p;
342 Job *j;
343 int rv = 0;
344 int forksleep;
345 int ischild;
347 if (flags & XEXEC)
348 /* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
349 * (also done in another execute() below)
351 return execute(t, flags & (XEXEC | XERROK), xerrok);
353 /* no SIGCHLD's while messing with job and process lists */
354 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
356 p = new_proc();
357 p->next = (Proc *) 0;
358 p->state = PRUNNING;
359 p->status = 0;
360 p->pid = 0;
362 /* link process into jobs list */
363 if (flags&XPIPEI) { /* continuing with a pipe */
364 if (!last_job)
365 internal_errorf(1,
366 "exchild: XPIPEI and no last_job - pid %d",
367 (int) procpid);
368 j = last_job;
369 last_proc->next = p;
370 last_proc = p;
371 } else {
372 j = new_job(); /* fills in j->job */
373 /* we don't consider XXCOM's foreground since they don't get
374 * tty process group and we don't save or restore tty modes.
376 j->flags = (flags & XXCOM) ? JF_XXCOM :
377 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
378 timerclear(&j->usrtime);
379 timerclear(&j->systime);
380 j->state = PRUNNING;
381 j->pgrp = 0;
382 j->ppid = procpid;
383 j->age = ++njobs;
384 j->proc_list = p;
385 j->coproc_id = 0;
386 last_job = j;
387 last_proc = p;
388 put_job(j, PJ_PAST_STOPPED);
391 snptreef(p->command, sizeof(p->command), "%T", t);
393 /* create child process */
394 forksleep = 1;
395 while ((i = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
396 if (intrsig) /* allow user to ^C out... */
397 break;
398 sleep(forksleep);
399 forksleep <<= 1;
401 if (i < 0) {
402 kill_job(j, SIGKILL);
403 remove_job(j, "fork failed");
404 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
405 errorf("cannot fork - try again");
407 ischild = i == 0;
408 if (ischild)
409 p->pid = procpid = getpid();
410 else
411 p->pid = i;
413 #ifdef JOBS
414 /* job control set up */
415 if (Flag(FMONITOR) && !(flags&XXCOM)) {
416 int dotty = 0;
417 if (j->pgrp == 0) { /* First process */
418 j->pgrp = p->pid;
419 dotty = 1;
422 /* set pgrp in both parent and child to deal with race
423 * condition
425 setpgid(p->pid, j->pgrp);
426 /* YYY: should this be
427 if (ttypgrp_ok && ischild && !(flags&XBGND))
428 tcsetpgrp(tty_fd, j->pgrp);
429 instead? (see also YYY below)
431 if (ttypgrp_ok && dotty && !(flags & XBGND))
432 tcsetpgrp(tty_fd, j->pgrp);
434 #endif /* JOBS */
436 /* used to close pipe input fd */
437 if (close_fd >= 0 && (((flags & XPCLOSE) && !ischild) ||
438 ((flags & XCCLOSE) && ischild)))
439 close(close_fd);
440 if (ischild) { /* child */
441 /* Do this before restoring signal */
442 if (flags & XCOPROC)
443 coproc_cleanup(false);
444 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
445 cleanup_parents_env();
446 #ifdef JOBS
447 /* If FMONITOR or FTALKING is set, these signals are ignored,
448 * if neither FMONITOR nor FTALKING are set, the signals have
449 * their inherited values.
451 if (Flag(FMONITOR) && !(flags & XXCOM)) {
452 for (i = NELEM(tt_sigs); --i >= 0; )
453 setsig(&sigtraps[tt_sigs[i]], SIG_DFL,
454 SS_RESTORE_DFL|SS_FORCE);
456 #endif /* JOBS */
457 if (Flag(FBGNICE) && (flags & XBGND))
458 nice(4);
459 if ((flags & XBGND) && !Flag(FMONITOR)) {
460 setsig(&sigtraps[SIGINT], SIG_IGN,
461 SS_RESTORE_IGN|SS_FORCE);
462 setsig(&sigtraps[SIGQUIT], SIG_IGN,
463 SS_RESTORE_IGN|SS_FORCE);
464 if (!(flags & (XPIPEI | XCOPROC))) {
465 int fd = open("/dev/null", 0);
466 if (fd != 0) {
467 (void) ksh_dup2(fd, 0, true);
468 close(fd);
472 remove_job(j, "child"); /* in case of `jobs` command */
473 nzombie = 0;
474 #ifdef JOBS
475 ttypgrp_ok = 0;
476 Flag(FMONITOR) = 0;
477 #endif /* JOBS */
478 Flag(FTALKING) = 0;
479 tty_close();
480 cleartraps();
481 execute(t, (flags & XERROK) | XEXEC, NULL); /* no return */
482 internal_errorf(0, "exchild: execute() returned");
483 unwind(LLEAVE);
484 /* NOTREACHED */
487 /* shell (parent) stuff */
488 /* Ensure next child gets a (slightly) different $RANDOM sequence */
489 change_random();
490 if (!(flags & XPIPEO)) { /* last process in a job */
491 #ifdef JOBS
492 /* YYY: Is this needed? (see also YYY above)
493 if (Flag(FMONITOR) && !(flags&(XXCOM|XBGND)))
494 tcsetpgrp(tty_fd, j->pgrp);
496 #endif /* JOBS */
497 j_startjob(j);
498 if (flags & XCOPROC) {
499 j->coproc_id = coproc.id;
500 coproc.njobs++; /* n jobs using co-process output */
501 coproc.job = (void *) j; /* j using co-process input */
503 if (flags & XBGND) {
504 j_set_async(j);
505 if (Flag(FTALKING)) {
506 shf_fprintf(shl_out, "[%d]", j->job);
507 for (p = j->proc_list; p; p = p->next)
508 shf_fprintf(shl_out, " %d", p->pid);
509 shf_putchar('\n', shl_out);
510 shf_flush(shl_out);
512 } else
513 rv = j_waitj(j, JW_NONE, "jw:last proc");
516 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
518 return rv;
521 /* start the last job: only used for `command` jobs */
522 void
523 startlast(void)
525 sigset_t omask;
527 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
529 if (last_job) { /* no need to report error - waitlast() will do it */
530 /* ensure it isn't removed by check_job() */
531 last_job->flags |= JF_WAITING;
532 j_startjob(last_job);
534 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
537 /* wait for last job: only used for `command` jobs */
539 waitlast(void)
541 int rv;
542 Job *j;
543 sigset_t omask;
545 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
547 j = last_job;
548 if (!j || !(j->flags & JF_STARTED)) {
549 if (!j)
550 warningf(true, "waitlast: no last job");
551 else
552 internal_errorf(0, "waitlast: not started");
553 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
554 return 125; /* not so arbitrary, non-zero value */
557 rv = j_waitj(j, JW_NONE, "jw:waitlast");
559 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
561 return rv;
564 /* wait for child, interruptable. */
566 waitfor(const char *cp, int *sigp)
568 int rv;
569 Job *j;
570 int ecode;
571 int flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
572 sigset_t omask;
574 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
576 *sigp = 0;
578 if (cp == (char *) 0) {
579 /* wait for an unspecified job - always returns 0, so
580 * don't have to worry about exited/signaled jobs
582 for (j = job_list; j; j = j->next)
583 /* at&t ksh will wait for stopped jobs - we don't */
584 if (j->ppid == procpid && j->state == PRUNNING)
585 break;
586 if (!j) {
587 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
588 return -1;
590 } else if ((j = j_lookup(cp, &ecode))) {
591 /* don't report normal job completion */
592 flags &= ~JW_ASYNCNOTIFY;
593 if (j->ppid != procpid) {
594 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
595 return -1;
597 } else {
598 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
599 if (ecode != JL_NOSUCH)
600 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
601 return -1;
604 /* at&t ksh will wait for stopped jobs - we don't */
605 rv = j_waitj(j, flags, "jw:waitfor");
607 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
609 if (rv < 0) /* we were interrupted */
610 *sigp = 128 + -rv;
612 return rv;
615 /* kill (built-in) a job */
617 j_kill(const char *cp, int sig)
619 Job *j;
620 int rv = 0;
621 int ecode;
622 sigset_t omask;
624 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
626 if ((j = j_lookup(cp, &ecode)) == (Job *) 0) {
627 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
628 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
629 return 1;
632 if (j->pgrp == 0) { /* started when !Flag(FMONITOR) */
633 if (kill_job(j, sig) < 0) {
634 bi_errorf("%s: %s", cp, strerror(errno));
635 rv = 1;
637 } else {
638 #ifdef JOBS
639 if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
640 (void) killpg(j->pgrp, SIGCONT);
641 #endif /* JOBS */
642 if (killpg(j->pgrp, sig) < 0) {
643 bi_errorf("%s: %s", cp, strerror(errno));
644 rv = 1;
648 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
650 return rv;
653 #ifdef JOBS
654 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
656 j_resume(const char *cp, int bg)
658 Job *j;
659 Proc *p;
660 int ecode;
661 int running;
662 int rv = 0;
663 sigset_t omask;
665 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
667 if ((j = j_lookup(cp, &ecode)) == (Job *) 0) {
668 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
669 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
670 return 1;
673 if (j->pgrp == 0) {
674 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
675 bi_errorf("job not job-controlled");
676 return 1;
679 if (bg)
680 shprintf("[%d] ", j->job);
682 running = 0;
683 for (p = j->proc_list; p != (Proc *) 0; p = p->next) {
684 if (p->state == PSTOPPED) {
685 p->state = PRUNNING;
686 p->status = 0;
687 running = 1;
689 shprintf("%s%s", p->command, p->next ? "| " : null);
691 shprintf(newline);
692 shf_flush(shl_stdout);
693 if (running)
694 j->state = PRUNNING;
696 put_job(j, PJ_PAST_STOPPED);
697 if (bg)
698 j_set_async(j);
699 else {
700 # ifdef JOBS
701 /* attach tty to job */
702 if (j->state == PRUNNING) {
703 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
704 tcsetattr(tty_fd, TCSADRAIN, &j->ttystate);
705 /* See comment in j_waitj regarding saved_ttypgrp. */
706 if (ttypgrp_ok &&
707 tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
708 j->saved_ttypgrp : j->pgrp) < 0) {
709 if (j->flags & JF_SAVEDTTY)
710 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
711 sigprocmask(SIG_SETMASK, &omask,
712 (sigset_t *) 0);
713 bi_errorf("1st tcsetpgrp(%d, %d) failed: %s",
714 tty_fd,
715 (int) ((j->flags & JF_SAVEDTTYPGRP) ?
716 j->saved_ttypgrp : j->pgrp),
717 strerror(errno));
718 return 1;
721 # endif /* JOBS */
722 j->flags |= JF_FG;
723 j->flags &= ~JF_KNOWN;
724 if (j == async_job)
725 async_job = (Job *) 0;
728 if (j->state == PRUNNING && killpg(j->pgrp, SIGCONT) < 0) {
729 int err = errno;
731 if (!bg) {
732 j->flags &= ~JF_FG;
733 # ifdef JOBS
734 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
735 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
736 if (ttypgrp_ok && tcsetpgrp(tty_fd, our_pgrp) < 0) {
737 warningf(true,
738 "fg: 2nd tcsetpgrp(%d, %d) failed: %s",
739 tty_fd, (int) our_pgrp,
740 strerror(errno));
742 # endif /* JOBS */
744 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
745 bi_errorf("cannot continue job %s: %s",
746 cp, strerror(err));
747 return 1;
749 if (!bg) {
750 # ifdef JOBS
751 if (ttypgrp_ok) {
752 j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
754 # endif /* JOBS */
755 rv = j_waitj(j, JW_NONE, "jw:resume");
757 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
758 return rv;
760 #endif /* JOBS */
762 /* are there any running or stopped jobs ? */
764 j_stopped_running(void)
766 Job *j;
767 int which = 0;
769 for (j = job_list; j != (Job *) 0; j = j->next) {
770 #ifdef JOBS
771 if (j->ppid == procpid && j->state == PSTOPPED)
772 which |= 1;
773 #endif /* JOBS */
774 if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
775 j->ppid == procpid && j->state == PRUNNING)
776 which |= 2;
778 if (which) {
779 shellf("You have %s%s%s jobs\n",
780 which & 1 ? "stopped" : "",
781 which == 3 ? " and " : "",
782 which & 2 ? "running" : "");
783 return 1;
786 return 0;
790 j_njobs(void)
792 Job *j;
793 int nj = 0;
794 sigset_t omask;
796 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
797 for (j = job_list; j; j = j->next)
798 nj++;
800 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
801 return nj;
805 /* list jobs for jobs built-in */
807 j_jobs(const char *cp, int slp,
808 int nflag) /* 0: short, 1: long, 2: pgrp */
810 Job *j, *tmp;
811 int how;
812 int zflag = 0;
813 sigset_t omask;
815 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
817 if (nflag < 0) { /* kludge: print zombies */
818 nflag = 0;
819 zflag = 1;
821 if (cp) {
822 int ecode;
824 if ((j = j_lookup(cp, &ecode)) == (Job *) 0) {
825 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
826 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
827 return 1;
829 } else
830 j = job_list;
831 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
832 for (; j; j = j->next) {
833 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
834 (!nflag || (j->flags & JF_CHANGED))) {
835 j_print(j, how, shl_stdout);
836 if (j->state == PEXITED || j->state == PSIGNALLED)
837 j->flags |= JF_REMOVE;
839 if (cp)
840 break;
842 /* Remove jobs after printing so there won't be multiple + or - jobs */
843 for (j = job_list; j; j = tmp) {
844 tmp = j->next;
845 if (j->flags & JF_REMOVE)
846 remove_job(j, "jobs");
848 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
849 return 0;
852 /* list jobs for top-level notification */
853 void
854 j_notify(void)
856 Job *j, *tmp;
857 sigset_t omask;
859 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
860 for (j = job_list; j; j = j->next) {
861 #ifdef JOBS
862 if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
863 j_print(j, JP_MEDIUM, shl_out);
864 #endif /* JOBS */
865 /* Remove job after doing reports so there aren't
866 * multiple +/- jobs.
868 if (j->state == PEXITED || j->state == PSIGNALLED)
869 j->flags |= JF_REMOVE;
871 for (j = job_list; j; j = tmp) {
872 tmp = j->next;
873 if (j->flags & JF_REMOVE)
874 remove_job(j, "notify");
876 shf_flush(shl_out);
877 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
880 /* Return pid of last process in last asynchronous job */
881 pid_t
882 j_async(void)
884 sigset_t omask;
886 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
888 if (async_job)
889 async_job->flags |= JF_KNOWN;
891 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
893 return async_pid;
896 /* Make j the last async process
898 * If jobs are compiled in then this routine expects sigchld to be blocked.
900 static void
901 j_set_async(Job *j)
903 Job *jl, *oldest;
905 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
906 remove_job(async_job, "async");
907 if (!(j->flags & JF_STARTED)) {
908 internal_errorf(0, "j_async: job not started");
909 return;
911 async_job = j;
912 async_pid = j->last_proc->pid;
913 while (nzombie > child_max) {
914 oldest = (Job *) 0;
915 for (jl = job_list; jl; jl = jl->next)
916 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
917 (!oldest || jl->age < oldest->age))
918 oldest = jl;
919 if (!oldest) {
920 /* XXX debugging */
921 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
922 internal_errorf(0,
923 "j_async: bad nzombie (%d)", nzombie);
924 nzombie = 0;
926 break;
928 remove_job(oldest, "zombie");
932 /* Start a job: set STARTED, check for held signals and set j->last_proc
934 * If jobs are compiled in then this routine expects sigchld to be blocked.
936 static void
937 j_startjob(Job *j)
939 Proc *p;
941 j->flags |= JF_STARTED;
942 for (p = j->proc_list; p->next; p = p->next)
944 j->last_proc = p;
946 if (held_sigchld) {
947 held_sigchld = 0;
948 /* Don't call j_sigchld() as it may remove job... */
949 kill(procpid, SIGCHLD);
954 * wait for job to complete or change state
956 * If jobs are compiled in then this routine expects sigchld to be blocked.
958 static int
959 j_waitj(Job *j,
960 int flags, /* see JW_* */
961 const char *where)
963 int rv;
966 * No auto-notify on the job we are waiting on.
968 j->flags |= JF_WAITING;
969 if (flags & JW_ASYNCNOTIFY)
970 j->flags |= JF_W_ASYNCNOTIFY;
972 if (!Flag(FMONITOR))
973 flags |= JW_STOPPEDWAIT;
975 while ((volatile int) j->state == PRUNNING ||
976 ((flags & JW_STOPPEDWAIT) && (volatile int) j->state == PSTOPPED)) {
977 sigsuspend(&sm_default);
978 if (fatal_trap) {
979 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
980 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
981 runtraps(TF_FATAL);
982 j->flags |= oldf; /* not reached... */
984 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
985 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
986 return -rv;
989 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
991 if (j->flags & JF_FG) {
992 int status;
994 j->flags &= ~JF_FG;
995 #ifdef JOBS
996 if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
998 * Save the tty's current pgrp so it can be restored
999 * when the job is foregrounded. This is to
1000 * deal with things like the GNU su which does
1001 * a fork/exec instead of an exec (the fork means
1002 * the execed shell gets a different pid from its
1003 * pgrp, so naturally it sets its pgrp and gets hosed
1004 * when it gets foregrounded by the parent shell, which
1005 * has restored the tty's pgrp to that of the su
1006 * process).
1008 if (j->state == PSTOPPED &&
1009 (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1010 j->flags |= JF_SAVEDTTYPGRP;
1011 if (tcsetpgrp(tty_fd, our_pgrp) < 0) {
1012 warningf(true,
1013 "j_waitj: tcsetpgrp(%d, %d) failed: %s",
1014 tty_fd, (int) our_pgrp,
1015 strerror(errno));
1017 if (j->state == PSTOPPED) {
1018 j->flags |= JF_SAVEDTTY;
1019 tcgetattr(tty_fd, &j->ttystate);
1022 #endif /* JOBS */
1023 if (tty_fd >= 0) {
1024 /* Only restore tty settings if job was originally
1025 * started in the foreground. Problems can be
1026 * caused by things like `more foobar &' which will
1027 * typically get and save the shell's vi/emacs tty
1028 * settings before setting up the tty for itself;
1029 * when more exits, it restores the `original'
1030 * settings, and things go down hill from there...
1032 if (j->state == PEXITED && j->status == 0 &&
1033 (j->flags & JF_USETTYMODE)) {
1034 tcgetattr(tty_fd, &tty_state);
1035 } else {
1036 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
1037 /* Don't use tty mode if job is stopped and
1038 * later restarted and exits. Consider
1039 * the sequence:
1040 * vi foo (stopped)
1041 * ...
1042 * stty something
1043 * ...
1044 * fg (vi; ZZ)
1045 * mode should be that of the stty, not what
1046 * was before the vi started.
1048 if (j->state == PSTOPPED)
1049 j->flags &= ~JF_USETTYMODE;
1052 #ifdef JOBS
1053 /* If it looks like user hit ^C to kill a job, pretend we got
1054 * one too to break out of for loops, etc. (at&t ksh does this
1055 * even when not monitoring, but this doesn't make sense since
1056 * a tty generated ^C goes to the whole process group)
1058 status = j->last_proc->status;
1059 if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1060 WIFSIGNALED(status) &&
1061 (sigtraps[WTERMSIG(status)].flags & TF_TTY_INTR))
1062 trapsig(WTERMSIG(status));
1063 #endif /* JOBS */
1066 j_usrtime = j->usrtime;
1067 j_systime = j->systime;
1068 rv = j->status;
1070 if (!(flags & JW_ASYNCNOTIFY) &&
1071 (!Flag(FMONITOR) || j->state != PSTOPPED)) {
1072 j_print(j, JP_SHORT, shl_out);
1073 shf_flush(shl_out);
1075 if (j->state != PSTOPPED &&
1076 (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY)))
1077 remove_job(j, where);
1079 return rv;
1082 /* SIGCHLD handler to reap children and update job states
1084 * If jobs are compiled in then this routine expects sigchld to be blocked.
1086 /* ARGSUSED */
1087 static void
1088 j_sigchld(int sig)
1090 int errno_ = errno;
1091 Job *j;
1092 Proc *p = NULL;
1093 int pid;
1094 int status;
1095 struct rusage ru0, ru1;
1097 /* Don't wait for any processes if a job is partially started.
1098 * This is so we don't do away with the process group leader
1099 * before all the processes in a pipe line are started (so the
1100 * setpgid() won't fail)
1102 for (j = job_list; j; j = j->next)
1103 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1104 held_sigchld = 1;
1105 goto finished;
1108 getrusage(RUSAGE_CHILDREN, &ru0);
1109 do {
1110 pid = waitpid(-1, &status, (WNOHANG|WUNTRACED));
1112 if (pid <= 0) /* return if would block (0) ... */
1113 break; /* ... or no children or interrupted (-1) */
1115 getrusage(RUSAGE_CHILDREN, &ru1);
1117 /* find job and process structures for this pid */
1118 for (j = job_list; j != (Job *) 0; j = j->next)
1119 for (p = j->proc_list; p != (Proc *) 0; p = p->next)
1120 if (p->pid == pid)
1121 goto found;
1122 found:
1123 if (j == (Job *) 0) {
1124 /* Can occur if process has kids, then execs shell
1125 warningf(true, "bad process waited for (pid = %d)",
1126 pid);
1128 ru0 = ru1;
1129 continue;
1132 timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1133 timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1134 timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1135 timersub(&j->systime, &ru0.ru_stime, &j->systime);
1136 ru0 = ru1;
1137 p->status = status;
1138 #ifdef JOBS
1139 if (WIFSTOPPED(status))
1140 p->state = PSTOPPED;
1141 else
1142 #endif /* JOBS */
1143 if (WIFSIGNALED(status))
1144 p->state = PSIGNALLED;
1145 else
1146 p->state = PEXITED;
1148 check_job(j); /* check to see if entire job is done */
1149 } while (1);
1151 finished:
1152 errno = errno_;
1156 * Called only when a process in j has exited/stopped (ie, called only
1157 * from j_sigchld()). If no processes are running, the job status
1158 * and state are updated, asynchronous job notification is done and,
1159 * if unneeded, the job is removed.
1161 * If jobs are compiled in then this routine expects sigchld to be blocked.
1163 static void
1164 check_job(Job *j)
1166 int jstate;
1167 Proc *p;
1169 /* XXX debugging (nasty - interrupt routine using shl_out) */
1170 if (!(j->flags & JF_STARTED)) {
1171 internal_errorf(0, "check_job: job started (flags 0x%x)",
1172 j->flags);
1173 return;
1176 jstate = PRUNNING;
1177 for (p=j->proc_list; p != (Proc *) 0; p = p->next) {
1178 if (p->state == PRUNNING)
1179 return; /* some processes still running */
1180 if (p->state > jstate)
1181 jstate = p->state;
1183 j->state = jstate;
1185 switch (j->last_proc->state) {
1186 case PEXITED:
1187 j->status = WEXITSTATUS(j->last_proc->status);
1188 break;
1189 case PSIGNALLED:
1190 j->status = 128 + WTERMSIG(j->last_proc->status);
1191 break;
1192 default:
1193 j->status = 0;
1194 break;
1197 /* Note when co-process dies: can't be done in j_wait() nor
1198 * remove_job() since neither may be called for non-interactive
1199 * shells.
1201 if (j->state == PEXITED || j->state == PSIGNALLED) {
1202 /* No need to keep co-process input any more
1203 * (at least, this is what ksh93d thinks)
1205 if (coproc.job == j) {
1206 coproc.job = (void *) 0;
1207 /* XXX would be nice to get the closes out of here
1208 * so they aren't done in the signal handler.
1209 * Would mean a check in coproc_getfd() to
1210 * do "if job == 0 && write >= 0, close write".
1212 coproc_write_close(coproc.write);
1214 /* Do we need to keep the output? */
1215 if (j->coproc_id && j->coproc_id == coproc.id &&
1216 --coproc.njobs == 0)
1217 coproc_readw_close(coproc.read);
1220 j->flags |= JF_CHANGED;
1221 #ifdef JOBS
1222 if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1223 /* Only put stopped jobs at the front to avoid confusing
1224 * the user (don't want finished jobs effecting %+ or %-)
1226 if (j->state == PSTOPPED)
1227 put_job(j, PJ_ON_FRONT);
1228 if (Flag(FNOTIFY) &&
1229 (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1230 /* Look for the real file descriptor 2 */
1232 struct env *ep;
1233 int fd = 2;
1235 for (ep = e; ep; ep = ep->oenv)
1236 if (ep->savefd && ep->savefd[2])
1237 fd = ep->savefd[2];
1238 shf_reopen(fd, SHF_WR, shl_j);
1240 /* Can't call j_notify() as it removes jobs. The job
1241 * must stay in the job list as j_waitj() may be
1242 * running with this job.
1244 j_print(j, JP_MEDIUM, shl_j);
1245 shf_flush(shl_j);
1246 if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1247 remove_job(j, "notify");
1250 #endif /* JOBS */
1251 if (!Flag(FMONITOR) && !(j->flags & (JF_WAITING|JF_FG)) &&
1252 j->state != PSTOPPED) {
1253 if (j == async_job || (j->flags & JF_KNOWN)) {
1254 j->flags |= JF_ZOMBIE;
1255 j->job = -1;
1256 nzombie++;
1257 } else
1258 remove_job(j, "checkjob");
1263 * Print job status in either short, medium or long format.
1265 * If jobs are compiled in then this routine expects sigchld to be blocked.
1267 static void
1268 j_print(Job *j, int how, struct shf *shf)
1270 Proc *p;
1271 int state;
1272 int status;
1273 int coredumped;
1274 char jobchar = ' ';
1275 char buf[64];
1276 const char *filler;
1277 int output = 0;
1279 if (how == JP_PGRP) {
1280 /* POSIX doesn't say what to do it there is no process
1281 * group leader (ie, !FMONITOR). We arbitrarily return
1282 * last pid (which is what $! returns).
1284 shf_fprintf(shf, "%d\n", j->pgrp ? j->pgrp :
1285 (j->last_proc ? j->last_proc->pid : 0));
1286 return;
1288 j->flags &= ~JF_CHANGED;
1289 filler = j->job > 10 ? "\n " : "\n ";
1290 if (j == job_list)
1291 jobchar = '+';
1292 else if (j == job_list->next)
1293 jobchar = '-';
1295 for (p = j->proc_list; p != (Proc *) 0;) {
1296 coredumped = 0;
1297 switch (p->state) {
1298 case PRUNNING:
1299 strlcpy(buf, "Running", sizeof buf);
1300 break;
1301 case PSTOPPED:
1302 strlcpy(buf, sigtraps[WSTOPSIG(p->status)].mess,
1303 sizeof buf);
1304 break;
1305 case PEXITED:
1306 if (how == JP_SHORT)
1307 buf[0] = '\0';
1308 else if (WEXITSTATUS(p->status) == 0)
1309 strlcpy(buf, "Done", sizeof buf);
1310 else
1311 shf_snprintf(buf, sizeof(buf), "Done (%d)",
1312 WEXITSTATUS(p->status));
1313 break;
1314 case PSIGNALLED:
1315 if (WCOREDUMP(p->status))
1316 coredumped = 1;
1317 /* kludge for not reporting `normal termination signals'
1318 * (ie, SIGINT, SIGPIPE)
1320 if (how == JP_SHORT && !coredumped &&
1321 (WTERMSIG(p->status) == SIGINT ||
1322 WTERMSIG(p->status) == SIGPIPE)) {
1323 buf[0] = '\0';
1324 } else
1325 strlcpy(buf, sigtraps[WTERMSIG(p->status)].mess,
1326 sizeof buf);
1327 break;
1330 if (how != JP_SHORT) {
1331 if (p == j->proc_list)
1332 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1333 else
1334 shf_fprintf(shf, "%s", filler);
1337 if (how == JP_LONG)
1338 shf_fprintf(shf, "%5d ", p->pid);
1340 if (how == JP_SHORT) {
1341 if (buf[0]) {
1342 output = 1;
1343 shf_fprintf(shf, "%s%s ",
1344 buf, coredumped ? " (core dumped)" : null);
1346 } else {
1347 output = 1;
1348 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1349 p->next ? "|" : null,
1350 coredumped ? " (core dumped)" : null);
1353 state = p->state;
1354 status = p->status;
1355 p = p->next;
1356 while (p && p->state == state && p->status == status) {
1357 if (how == JP_LONG)
1358 shf_fprintf(shf, "%s%5d %-20s %s%s", filler, p->pid,
1359 space, p->command, p->next ? "|" : null);
1360 else if (how == JP_MEDIUM)
1361 shf_fprintf(shf, " %s%s", p->command,
1362 p->next ? "|" : null);
1363 p = p->next;
1366 if (output)
1367 shf_fprintf(shf, newline);
1370 /* Convert % sequence to job
1372 * If jobs are compiled in then this routine expects sigchld to be blocked.
1374 static Job *
1375 j_lookup(const char *cp, int *ecodep)
1377 Job *j, *last_match;
1378 Proc *p;
1379 int len, job = 0;
1381 if (digit(*cp)) {
1382 job = atoi(cp);
1383 /* Look for last_proc->pid (what $! returns) first... */
1384 for (j = job_list; j != (Job *) 0; j = j->next)
1385 if (j->last_proc && j->last_proc->pid == job)
1386 return j;
1387 /* ...then look for process group (this is non-POSIX),
1388 * but should not break anything (so FPOSIX isn't used).
1390 for (j = job_list; j != (Job *) 0; j = j->next)
1391 if (j->pgrp && j->pgrp == job)
1392 return j;
1393 if (ecodep)
1394 *ecodep = JL_NOSUCH;
1395 return (Job *) 0;
1397 if (*cp != '%') {
1398 if (ecodep)
1399 *ecodep = JL_INVALID;
1400 return (Job *) 0;
1402 switch (*++cp) {
1403 case '\0': /* non-standard */
1404 case '+':
1405 case '%':
1406 if (job_list != (Job *) 0)
1407 return job_list;
1408 break;
1410 case '-':
1411 if (job_list != (Job *) 0 && job_list->next)
1412 return job_list->next;
1413 break;
1415 case '0': case '1': case '2': case '3': case '4':
1416 case '5': case '6': case '7': case '8': case '9':
1417 job = atoi(cp);
1418 for (j = job_list; j != (Job *) 0; j = j->next)
1419 if (j->job == job)
1420 return j;
1421 break;
1423 case '?': /* %?string */
1424 last_match = (Job *) 0;
1425 for (j = job_list; j != (Job *) 0; j = j->next)
1426 for (p = j->proc_list; p != (Proc *) 0; p = p->next)
1427 if (strstr(p->command, cp+1) != (char *) 0) {
1428 if (last_match) {
1429 if (ecodep)
1430 *ecodep = JL_AMBIG;
1431 return (Job *) 0;
1433 last_match = j;
1435 if (last_match)
1436 return last_match;
1437 break;
1439 default: /* %string */
1440 len = strlen(cp);
1441 last_match = (Job *) 0;
1442 for (j = job_list; j != (Job *) 0; j = j->next)
1443 if (strncmp(cp, j->proc_list->command, len) == 0) {
1444 if (last_match) {
1445 if (ecodep)
1446 *ecodep = JL_AMBIG;
1447 return (Job *) 0;
1449 last_match = j;
1451 if (last_match)
1452 return last_match;
1453 break;
1455 if (ecodep)
1456 *ecodep = JL_NOSUCH;
1457 return (Job *) 0;
1460 static Job *free_jobs;
1461 static Proc *free_procs;
1463 /* allocate a new job and fill in the job number.
1465 * If jobs are compiled in then this routine expects sigchld to be blocked.
1467 static Job *
1468 new_job(void)
1470 int i;
1471 Job *newj, *j;
1473 if (free_jobs != (Job *) 0) {
1474 newj = free_jobs;
1475 free_jobs = free_jobs->next;
1476 } else
1477 newj = (Job *) alloc(sizeof(Job), APERM);
1479 /* brute force method */
1480 for (i = 1; ; i++) {
1481 for (j = job_list; j && j->job != i; j = j->next)
1483 if (j == (Job *) 0)
1484 break;
1486 newj->job = i;
1488 return newj;
1491 /* Allocate new process struct
1493 * If jobs are compiled in then this routine expects sigchld to be blocked.
1495 static Proc *
1496 new_proc(void)
1498 Proc *p;
1500 if (free_procs != (Proc *) 0) {
1501 p = free_procs;
1502 free_procs = free_procs->next;
1503 } else
1504 p = (Proc *) alloc(sizeof(Proc), APERM);
1506 return p;
1509 /* Take job out of job_list and put old structures into free list.
1510 * Keeps nzombies, last_job and async_job up to date.
1512 * If jobs are compiled in then this routine expects sigchld to be blocked.
1514 static void
1515 remove_job(Job *j, const char *where)
1517 Proc *p, *tmp;
1518 Job **prev, *curr;
1520 prev = &job_list;
1521 curr = *prev;
1522 for (; curr != (Job *) 0 && curr != j; prev = &curr->next, curr = *prev)
1524 if (curr != j) {
1525 internal_errorf(0, "remove_job: job not found (%s)", where);
1526 return;
1528 *prev = curr->next;
1530 /* free up proc structures */
1531 for (p = j->proc_list; p != (Proc *) 0; ) {
1532 tmp = p;
1533 p = p->next;
1534 tmp->next = free_procs;
1535 free_procs = tmp;
1538 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1539 --nzombie;
1540 j->next = free_jobs;
1541 free_jobs = j;
1543 if (j == last_job)
1544 last_job = (Job *) 0;
1545 if (j == async_job)
1546 async_job = (Job *) 0;
1549 /* put j in a particular location (taking it out job_list if it is there
1550 * already)
1552 * If jobs are compiled in then this routine expects sigchld to be blocked.
1554 static void
1555 put_job(Job *j, int where)
1557 Job **prev, *curr;
1559 /* Remove job from list (if there) */
1560 prev = &job_list;
1561 curr = job_list;
1562 for (; curr && curr != j; prev = &curr->next, curr = *prev)
1564 if (curr == j)
1565 *prev = curr->next;
1567 switch (where) {
1568 case PJ_ON_FRONT:
1569 j->next = job_list;
1570 job_list = j;
1571 break;
1573 case PJ_PAST_STOPPED:
1574 prev = &job_list;
1575 curr = job_list;
1576 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1577 curr = *prev)
1579 j->next = curr;
1580 *prev = j;
1581 break;
1585 /* nuke a job (called when unable to start full job).
1587 * If jobs are compiled in then this routine expects sigchld to be blocked.
1589 static int
1590 kill_job(Job *j, int sig)
1592 Proc *p;
1593 int rval = 0;
1595 for (p = j->proc_list; p != (Proc *) 0; p = p->next)
1596 if (p->pid != 0)
1597 if (kill(p->pid, sig) < 0)
1598 rval = -1;
1599 return rval;