don't bother resolving onbld python module deps
[unleashed.git] / bin / ksh / jobs.c
blobba7386633909f68ac94787be905a3dd9beae2407
1 /* $OpenBSD: jobs.c,v 1.60 2018/03/15 16:51:29 anton 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 <sys/resource.h>
19 #include <sys/stat.h>
20 #include <sys/time.h>
21 #include <sys/wait.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
31 #include "sh.h"
32 #include "tty.h"
34 /* Order important! */
35 #define PRUNNING 0
36 #define PEXITED 1
37 #define PSIGNALLED 2
38 #define PSTOPPED 3
40 typedef struct proc Proc;
41 struct proc {
42 Proc *next; /* next process in pipeline (if any) */
43 int state;
44 int status; /* wait status */
45 pid_t pid; /* process id */
46 char command[48]; /* process command string */
49 /* Notify/print flag - j_print() argument */
50 #define JP_NONE 0 /* don't print anything */
51 #define JP_SHORT 1 /* print signals processes were killed by */
52 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
53 #define JP_LONG 3 /* print [job-num] -/+ pid command */
54 #define JP_PGRP 4 /* print pgrp */
56 /* put_job() flags */
57 #define PJ_ON_FRONT 0 /* at very front */
58 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
60 /* Job.flags values */
61 #define JF_STARTED 0x001 /* set when all processes in job are started */
62 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
63 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
64 #define JF_XXCOM 0x008 /* set for `command` jobs */
65 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
66 #define JF_SAVEDTTY 0x020 /* j->ttystate is valid */
67 #define JF_CHANGED 0x040 /* process has changed state */
68 #define JF_KNOWN 0x080 /* $! referenced */
69 #define JF_ZOMBIE 0x100 /* known, unwaited process */
70 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_notify()) */
71 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
72 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
74 typedef struct job Job;
75 struct job {
76 Job *next; /* next job in list */
77 int job; /* job number: %n */
78 int flags; /* see JF_* */
79 int state; /* job state */
80 int status; /* exit status of last process */
81 pid_t pgrp; /* process group of job */
82 pid_t ppid; /* pid of process that forked job */
83 int age; /* number of jobs started */
84 struct timeval systime; /* system time used by job */
85 struct timeval usrtime; /* user time used by job */
86 Proc *proc_list; /* process list */
87 Proc *last_proc; /* last process in list */
88 Coproc_id coproc_id; /* 0 or id of coprocess output pipe */
89 struct termios ttystate;/* saved tty state for stopped jobs */
90 pid_t saved_ttypgrp; /* saved tty process group for stopped jobs */
93 /* Flags for j_waitj() */
94 #define JW_NONE 0x00
95 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
96 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
97 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
99 /* Error codes for j_lookup() */
100 #define JL_OK 0
101 #define JL_NOSUCH 1 /* no such job */
102 #define JL_AMBIG 2 /* %foo or %?foo is ambiguous */
103 #define JL_INVALID 3 /* non-pid, non-% job id */
105 static const char *const lookup_msgs[] = {
106 null,
107 "no such job",
108 "ambiguous",
109 "argument must be %job or process id",
110 NULL
113 struct timeval j_systime, j_usrtime; /* user and system time of last j_waitjed job */
115 static Job *job_list; /* job list */
116 static Job *last_job;
117 static Job *async_job;
118 static pid_t async_pid;
120 static int nzombie; /* # of zombies owned by this process */
121 int njobs; /* # of jobs started */
122 static int child_max; /* CHILD_MAX */
125 /* held_sigchld is set if sigchld occurs before a job is completely started */
126 static volatile sig_atomic_t held_sigchld;
128 static struct shf *shl_j;
129 static int ttypgrp_ok; /* set if can use tty pgrps */
130 static pid_t restore_ttypgrp = -1;
131 static pid_t our_pgrp;
132 static int const tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
134 static void j_set_async(Job *);
135 static void j_startjob(Job *);
136 static int j_waitj(Job *, int, const char *);
137 static void j_sigchld(int);
138 static void j_print(Job *, int, struct shf *);
139 static Job *j_lookup(const char *, int *);
140 static Job *new_job(void);
141 static Proc *new_proc(void);
142 static void check_job(Job *);
143 static void put_job(Job *, int);
144 static void remove_job(Job *, const char *);
145 static int kill_job(Job *, int);
147 /* initialize job control */
148 void
149 j_init(int mflagset)
151 child_max = CHILD_MAX; /* so syscon() isn't always being called */
153 sigemptyset(&sm_default);
154 sigprocmask(SIG_SETMASK, &sm_default, NULL);
156 sigemptyset(&sm_sigchld);
157 sigaddset(&sm_sigchld, SIGCHLD);
159 setsig(&sigtraps[SIGCHLD], j_sigchld,
160 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
162 if (!mflagset && Flag(FTALKING))
163 Flag(FMONITOR) = 1;
165 /* shl_j is used to do asynchronous notification (used in
166 * an interrupt handler, so need a distinct shf)
168 shl_j = shf_fdopen(2, SHF_WR, NULL);
170 if (Flag(FMONITOR) || Flag(FTALKING)) {
171 int i;
173 /* the TF_SHELL_USES test is a kludge that lets us know if
174 * if the signals have been changed by the shell.
176 for (i = NELEM(tt_sigs); --i >= 0; ) {
177 sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
178 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
179 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
180 SS_RESTORE_IGN|SS_FORCE);
184 /* j_change() calls tty_init() */
185 if (Flag(FMONITOR))
186 j_change();
187 else if (Flag(FTALKING))
188 tty_init(true);
191 /* suspend the shell */
192 void
193 j_suspend(void)
195 struct sigaction sa, osa;
197 /* Restore tty and pgrp. */
198 if (ttypgrp_ok) {
199 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
200 if (restore_ttypgrp >= 0) {
201 if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
202 warningf(false, "%s: tcsetpgrp() failed: %s",
203 __func__, strerror(errno));
204 } else {
205 if (setpgid(0, restore_ttypgrp) < 0) {
206 warningf(false,
207 "%s: setpgid() failed: %s",
208 __func__, strerror(errno));
214 /* Suspend the shell. */
215 memset(&sa, 0, sizeof(sa));
216 sigemptyset(&sa.sa_mask);
217 sa.sa_handler = SIG_DFL;
218 sigaction(SIGTSTP, &sa, &osa);
219 kill(0, SIGTSTP);
221 /* Back from suspend, reset signals, pgrp and tty. */
222 sigaction(SIGTSTP, &osa, NULL);
223 if (ttypgrp_ok) {
224 if (restore_ttypgrp >= 0) {
225 if (setpgid(0, kshpid) < 0) {
226 warningf(false, "%s: setpgid() failed: %s",
227 __func__, strerror(errno));
228 ttypgrp_ok = 0;
229 } else {
230 if (tcsetpgrp(tty_fd, kshpid) < 0) {
231 warningf(false,
232 "%s: tcsetpgrp() failed: %s",
233 __func__, strerror(errno));
234 ttypgrp_ok = 0;
238 tty_init(true);
242 /* job cleanup before shell exit */
243 void
244 j_exit(void)
246 /* kill stopped, and possibly running, jobs */
247 Job *j;
248 int killed = 0;
250 for (j = job_list; j != NULL; j = j->next) {
251 if (j->ppid == procpid &&
252 (j->state == PSTOPPED ||
253 (j->state == PRUNNING &&
254 ((j->flags & JF_FG) ||
255 (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
256 killed = 1;
257 if (j->pgrp == 0)
258 kill_job(j, SIGHUP);
259 else
260 killpg(j->pgrp, SIGHUP);
261 if (j->state == PSTOPPED) {
262 if (j->pgrp == 0)
263 kill_job(j, SIGCONT);
264 else
265 killpg(j->pgrp, SIGCONT);
269 if (killed)
270 sleep(1);
271 j_notify();
273 if (kshpid == procpid && restore_ttypgrp >= 0) {
274 /* Need to restore the tty pgrp to what it was when the
275 * shell started up, so that the process that started us
276 * will be able to access the tty when we are done.
277 * Also need to restore our process group in case we are
278 * about to do an exec so that both our parent and the
279 * process we are to become will be able to access the tty.
281 tcsetpgrp(tty_fd, restore_ttypgrp);
282 setpgid(0, restore_ttypgrp);
284 if (Flag(FMONITOR)) {
285 Flag(FMONITOR) = 0;
286 j_change();
290 /* turn job control on or off according to Flag(FMONITOR) */
291 void
292 j_change(void)
294 int i;
296 if (Flag(FMONITOR)) {
297 int use_tty;
299 if (Flag(FTALKING)) {
300 /* Don't call tcgetattr() 'til we own the tty process group */
301 use_tty = 1;
302 tty_init(false);
303 } else
304 use_tty = 0;
306 /* no controlling tty, no SIGT* */
307 ttypgrp_ok = use_tty && tty_fd >= 0 && tty_devtty;
309 if (ttypgrp_ok && (our_pgrp = getpgrp()) < 0) {
310 warningf(false, "%s: getpgrp() failed: %s",
311 __func__, strerror(errno));
312 ttypgrp_ok = 0;
314 if (ttypgrp_ok) {
315 setsig(&sigtraps[SIGTTIN], SIG_DFL,
316 SS_RESTORE_ORIG|SS_FORCE);
317 /* wait to be given tty (POSIX.1, B.2, job control) */
318 while (1) {
319 pid_t ttypgrp;
321 if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
322 warningf(false,
323 "%s: tcgetpgrp() failed: %s",
324 __func__, strerror(errno));
325 ttypgrp_ok = 0;
326 break;
328 if (ttypgrp == our_pgrp)
329 break;
330 kill(0, SIGTTIN);
333 for (i = NELEM(tt_sigs); --i >= 0; )
334 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
335 SS_RESTORE_DFL|SS_FORCE);
336 if (ttypgrp_ok && our_pgrp != kshpid) {
337 if (setpgid(0, kshpid) < 0) {
338 warningf(false, "%s: setpgid() failed: %s",
339 __func__, strerror(errno));
340 ttypgrp_ok = 0;
341 } else {
342 if (tcsetpgrp(tty_fd, kshpid) < 0) {
343 warningf(false,
344 "%s: tcsetpgrp() failed: %s",
345 __func__, strerror(errno));
346 ttypgrp_ok = 0;
347 } else
348 restore_ttypgrp = our_pgrp;
349 our_pgrp = kshpid;
352 if (use_tty) {
353 if (!ttypgrp_ok)
354 warningf(false,
355 "warning: won't have full job control");
357 if (tty_fd >= 0)
358 tcgetattr(tty_fd, &tty_state);
359 } else {
360 ttypgrp_ok = 0;
361 if (Flag(FTALKING))
362 for (i = NELEM(tt_sigs); --i >= 0; )
363 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
364 SS_RESTORE_IGN|SS_FORCE);
365 else
366 for (i = NELEM(tt_sigs); --i >= 0; ) {
367 if (sigtraps[tt_sigs[i]].flags &
368 (TF_ORIG_IGN | TF_ORIG_DFL))
369 setsig(&sigtraps[tt_sigs[i]],
370 (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
371 SIG_IGN : SIG_DFL,
372 SS_RESTORE_ORIG|SS_FORCE);
374 if (!Flag(FTALKING))
375 tty_close();
379 /* execute tree in child subprocess */
381 exchild(struct op *t, int flags, volatile int *xerrok,
382 int close_fd) /* used if XPCLOSE or XCCLOSE */
384 static Proc *last_proc; /* for pipelines */
386 int i;
387 sigset_t omask;
388 Proc *p;
389 Job *j;
390 int rv = 0;
391 int forksleep;
392 int ischild;
394 if (flags & XEXEC)
395 /* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
396 * (also done in another execute() below)
398 return execute(t, flags & (XEXEC | XERROK), xerrok);
400 /* no SIGCHLD's while messing with job and process lists */
401 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
403 p = new_proc();
404 p->next = NULL;
405 p->state = PRUNNING;
406 p->status = 0;
407 p->pid = 0;
409 /* link process into jobs list */
410 if (flags&XPIPEI) { /* continuing with a pipe */
411 if (!last_job)
412 internal_errorf("%s: XPIPEI and no last_job - pid %d",
413 __func__, (int) procpid);
414 j = last_job;
415 last_proc->next = p;
416 last_proc = p;
417 } else {
418 j = new_job(); /* fills in j->job */
419 /* we don't consider XXCOM's foreground since they don't get
420 * tty process group and we don't save or restore tty modes.
422 j->flags = (flags & XXCOM) ? JF_XXCOM :
423 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
424 timerclear(&j->usrtime);
425 timerclear(&j->systime);
426 j->state = PRUNNING;
427 j->pgrp = 0;
428 j->ppid = procpid;
429 j->age = ++njobs;
430 j->proc_list = p;
431 j->coproc_id = 0;
432 last_job = j;
433 last_proc = p;
434 put_job(j, PJ_PAST_STOPPED);
437 snptreef(p->command, sizeof(p->command), "%T", t);
439 /* create child process */
440 forksleep = 1;
441 while ((i = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
442 if (intrsig) /* allow user to ^C out... */
443 break;
444 sleep(forksleep);
445 forksleep <<= 1;
447 if (i < 0) {
448 kill_job(j, SIGKILL);
449 remove_job(j, "fork failed");
450 sigprocmask(SIG_SETMASK, &omask, NULL);
451 errorf("cannot fork - try again");
453 ischild = i == 0;
454 if (ischild)
455 p->pid = procpid = getpid();
456 else
457 p->pid = i;
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 /* YYY: should this be
472 if (ttypgrp_ok && ischild && !(flags&XBGND))
473 tcsetpgrp(tty_fd, j->pgrp);
474 instead? (see also YYY below)
476 if (ttypgrp_ok && dotty && !(flags & XBGND))
477 tcsetpgrp(tty_fd, j->pgrp);
480 /* used to close pipe input fd */
481 if (close_fd >= 0 && (((flags & XPCLOSE) && !ischild) ||
482 ((flags & XCCLOSE) && ischild)))
483 close(close_fd);
484 if (ischild) { /* child */
485 /* Do this before restoring signal */
486 if (flags & XCOPROC)
487 coproc_cleanup(false);
488 sigprocmask(SIG_SETMASK, &omask, NULL);
489 cleanup_parents_env();
490 /* If FMONITOR or FTALKING is set, these signals are ignored,
491 * if neither FMONITOR nor FTALKING are set, the signals have
492 * their inherited values.
494 if (Flag(FMONITOR) && !(flags & XXCOM)) {
495 for (i = NELEM(tt_sigs); --i >= 0; )
496 setsig(&sigtraps[tt_sigs[i]], SIG_DFL,
497 SS_RESTORE_DFL|SS_FORCE);
499 if (Flag(FBGNICE) && (flags & XBGND))
500 nice(4);
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", O_RDONLY);
508 if (fd != 0) {
509 (void) ksh_dup2(fd, 0, true);
510 close(fd);
514 remove_job(j, "child"); /* in case of `jobs` command */
515 nzombie = 0;
516 ttypgrp_ok = 0;
517 Flag(FMONITOR) = 0;
518 Flag(FTALKING) = 0;
519 tty_close();
520 cleartraps();
521 execute(t, (flags & XERROK) | XEXEC, NULL); /* no return */
522 internal_warningf("%s: execute() returned", __func__);
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 /* YYY: Is this needed? (see also YYY above)
532 if (Flag(FMONITOR) && !(flags&(XXCOM|XBGND)))
533 tcsetpgrp(tty_fd, j->pgrp);
535 j_startjob(j);
536 if (flags & XCOPROC) {
537 j->coproc_id = coproc.id;
538 coproc.njobs++; /* n jobs using co-process output */
539 coproc.job = (void *) j; /* j using co-process input */
541 if (flags & XBGND) {
542 j_set_async(j);
543 if (Flag(FTALKING)) {
544 shf_fprintf(shl_out, "[%d]", j->job);
545 for (p = j->proc_list; p; p = p->next)
546 shf_fprintf(shl_out, " %d", p->pid);
547 shf_putchar('\n', shl_out);
548 shf_flush(shl_out);
550 } else
551 rv = j_waitj(j, JW_NONE, "jw:last proc");
554 sigprocmask(SIG_SETMASK, &omask, NULL);
556 return rv;
559 /* start the last job: only used for `command` jobs */
560 void
561 startlast(void)
563 sigset_t omask;
565 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
567 if (last_job) { /* no need to report error - waitlast() will do it */
568 /* ensure it isn't removed by check_job() */
569 last_job->flags |= JF_WAITING;
570 j_startjob(last_job);
572 sigprocmask(SIG_SETMASK, &omask, NULL);
575 /* wait for last job: only used for `command` jobs */
577 waitlast(void)
579 int rv;
580 Job *j;
581 sigset_t omask;
583 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
585 j = last_job;
586 if (!j || !(j->flags & JF_STARTED)) {
587 if (!j)
588 warningf(true, "%s: no last job", __func__);
589 else
590 internal_warningf("%s: not started", __func__);
591 sigprocmask(SIG_SETMASK, &omask, NULL);
592 return 125; /* not so arbitrary, non-zero value */
595 rv = j_waitj(j, JW_NONE, "jw:waitlast");
597 sigprocmask(SIG_SETMASK, &omask, NULL);
599 return rv;
602 /* wait for child, interruptable. */
604 waitfor(const char *cp, int *sigp)
606 int rv;
607 Job *j;
608 int ecode;
609 int flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
610 sigset_t omask;
612 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
614 *sigp = 0;
616 if (cp == NULL) {
617 /* wait for an unspecified job - always returns 0, so
618 * don't have to worry about exited/signaled jobs
620 for (j = job_list; j; j = j->next)
621 /* at&t ksh will wait for stopped jobs - we don't */
622 if (j->ppid == procpid && j->state == PRUNNING)
623 break;
624 if (!j) {
625 sigprocmask(SIG_SETMASK, &omask, NULL);
626 return -1;
628 } else if ((j = j_lookup(cp, &ecode))) {
629 /* don't report normal job completion */
630 flags &= ~JW_ASYNCNOTIFY;
631 if (j->ppid != procpid) {
632 sigprocmask(SIG_SETMASK, &omask, NULL);
633 return -1;
635 } else {
636 sigprocmask(SIG_SETMASK, &omask, NULL);
637 if (ecode != JL_NOSUCH)
638 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
639 return -1;
642 /* at&t ksh will wait for stopped jobs - we don't */
643 rv = j_waitj(j, flags, "jw:waitfor");
645 sigprocmask(SIG_SETMASK, &omask, NULL);
647 if (rv < 0) /* we were interrupted */
648 *sigp = 128 + -rv;
650 return rv;
653 /* kill (built-in) a job */
655 j_kill(const char *cp, int sig)
657 Job *j;
658 int rv = 0;
659 int ecode;
660 sigset_t omask;
662 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
664 if ((j = j_lookup(cp, &ecode)) == NULL) {
665 sigprocmask(SIG_SETMASK, &omask, NULL);
666 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
667 return 1;
670 if (j->pgrp == 0) { /* started when !Flag(FMONITOR) */
671 if (kill_job(j, sig) < 0) {
672 bi_errorf("%s: %s", cp, strerror(errno));
673 rv = 1;
675 } else {
676 if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
677 (void) killpg(j->pgrp, SIGCONT);
678 if (killpg(j->pgrp, sig) < 0) {
679 bi_errorf("%s: %s", cp, strerror(errno));
680 rv = 1;
684 sigprocmask(SIG_SETMASK, &omask, NULL);
686 return rv;
689 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
691 j_resume(const char *cp, int bg)
693 Job *j;
694 Proc *p;
695 int ecode;
696 int running;
697 int rv = 0;
698 sigset_t omask;
700 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
702 if ((j = j_lookup(cp, &ecode)) == NULL) {
703 sigprocmask(SIG_SETMASK, &omask, NULL);
704 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
705 return 1;
708 if (j->pgrp == 0) {
709 sigprocmask(SIG_SETMASK, &omask, NULL);
710 bi_errorf("job not job-controlled");
711 return 1;
714 if (bg)
715 shprintf("[%d] ", j->job);
717 running = 0;
718 for (p = j->proc_list; p != NULL; p = p->next) {
719 if (p->state == PSTOPPED) {
720 p->state = PRUNNING;
721 p->status = 0;
722 running = 1;
724 shprintf("%s%s", p->command, p->next ? "| " : "");
726 shprintf("\n");
727 shf_flush(shl_stdout);
728 if (running)
729 j->state = PRUNNING;
731 put_job(j, PJ_PAST_STOPPED);
732 if (bg)
733 j_set_async(j);
734 else {
735 /* attach tty to job */
736 if (j->state == PRUNNING) {
737 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
738 tcsetattr(tty_fd, TCSADRAIN, &j->ttystate);
739 /* See comment in j_waitj regarding saved_ttypgrp. */
740 if (ttypgrp_ok &&
741 tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
742 j->saved_ttypgrp : j->pgrp) < 0) {
743 if (j->flags & JF_SAVEDTTY)
744 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
745 sigprocmask(SIG_SETMASK, &omask, NULL);
746 bi_errorf("1st tcsetpgrp(%d, %d) failed: %s",
747 tty_fd,
748 (int) ((j->flags & JF_SAVEDTTYPGRP) ?
749 j->saved_ttypgrp : j->pgrp),
750 strerror(errno));
751 return 1;
754 j->flags |= JF_FG;
755 j->flags &= ~JF_KNOWN;
756 if (j == async_job)
757 async_job = NULL;
760 if (j->state == PRUNNING && killpg(j->pgrp, SIGCONT) < 0) {
761 int err = errno;
763 if (!bg) {
764 j->flags &= ~JF_FG;
765 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
766 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
767 if (ttypgrp_ok && tcsetpgrp(tty_fd, our_pgrp) < 0) {
768 warningf(true,
769 "fg: 2nd tcsetpgrp(%d, %d) failed: %s",
770 tty_fd, (int) our_pgrp,
771 strerror(errno));
774 sigprocmask(SIG_SETMASK, &omask, NULL);
775 bi_errorf("cannot continue job %s: %s",
776 cp, strerror(err));
777 return 1;
779 if (!bg) {
780 if (ttypgrp_ok) {
781 j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
783 rv = j_waitj(j, JW_NONE, "jw:resume");
785 sigprocmask(SIG_SETMASK, &omask, NULL);
786 return rv;
789 /* are there any running or stopped jobs ? */
791 j_stopped_running(void)
793 Job *j;
794 int which = 0;
796 for (j = job_list; j != NULL; j = j->next) {
797 if (j->ppid == procpid && j->state == PSTOPPED)
798 which |= 1;
799 if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
800 j->ppid == procpid && j->state == PRUNNING)
801 which |= 2;
803 if (which) {
804 shellf("You have %s%s%s jobs\n",
805 which & 1 ? "stopped" : "",
806 which == 3 ? " and " : "",
807 which & 2 ? "running" : "");
808 return 1;
811 return 0;
815 j_njobs(void)
817 Job *j;
818 int nj = 0;
819 sigset_t omask;
821 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
822 for (j = job_list; j; j = j->next)
823 nj++;
825 sigprocmask(SIG_SETMASK, &omask, NULL);
826 return nj;
830 /* list jobs for jobs built-in */
832 j_jobs(const char *cp, int slp,
833 int nflag) /* 0: short, 1: long, 2: pgrp */
835 Job *j, *tmp;
836 int how;
837 int zflag = 0;
838 sigset_t omask;
840 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
842 if (nflag < 0) { /* kludge: print zombies */
843 nflag = 0;
844 zflag = 1;
846 if (cp) {
847 int ecode;
849 if ((j = j_lookup(cp, &ecode)) == NULL) {
850 sigprocmask(SIG_SETMASK, &omask, NULL);
851 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
852 return 1;
854 } else
855 j = job_list;
856 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
857 for (; j; j = j->next) {
858 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
859 (!nflag || (j->flags & JF_CHANGED))) {
860 j_print(j, how, shl_stdout);
861 if (j->state == PEXITED || j->state == PSIGNALLED)
862 j->flags |= JF_REMOVE;
864 if (cp)
865 break;
867 /* Remove jobs after printing so there won't be multiple + or - jobs */
868 for (j = job_list; j; j = tmp) {
869 tmp = j->next;
870 if (j->flags & JF_REMOVE)
871 remove_job(j, "jobs");
873 sigprocmask(SIG_SETMASK, &omask, NULL);
874 return 0;
877 /* list jobs for top-level notification */
878 void
879 j_notify(void)
881 Job *j, *tmp;
882 sigset_t omask;
884 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
885 for (j = job_list; j; j = j->next) {
886 if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
887 j_print(j, JP_MEDIUM, shl_out);
888 /* Remove job after doing reports so there aren't
889 * multiple +/- jobs.
891 if (j->state == PEXITED || j->state == PSIGNALLED)
892 j->flags |= JF_REMOVE;
894 for (j = job_list; j; j = tmp) {
895 tmp = j->next;
896 if (j->flags & JF_REMOVE)
897 remove_job(j, "notify");
899 shf_flush(shl_out);
900 sigprocmask(SIG_SETMASK, &omask, NULL);
903 /* Return pid of last process in last asynchronous job */
904 pid_t
905 j_async(void)
907 sigset_t omask;
909 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
911 if (async_job)
912 async_job->flags |= JF_KNOWN;
914 sigprocmask(SIG_SETMASK, &omask, NULL);
916 return async_pid;
919 /* Make j the last async process
921 * Expects sigchld to be blocked.
923 static void
924 j_set_async(Job *j)
926 Job *jl, *oldest;
928 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
929 remove_job(async_job, "async");
930 if (!(j->flags & JF_STARTED)) {
931 internal_warningf("%s: job not started", __func__);
932 return;
934 async_job = j;
935 async_pid = j->last_proc->pid;
936 while (nzombie > child_max) {
937 oldest = NULL;
938 for (jl = job_list; jl; jl = jl->next)
939 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
940 (!oldest || jl->age < oldest->age))
941 oldest = jl;
942 if (!oldest) {
943 /* XXX debugging */
944 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
945 internal_warningf("%s: bad nzombie (%d)",
946 __func__, nzombie);
947 nzombie = 0;
949 break;
951 remove_job(oldest, "zombie");
955 /* Start a job: set STARTED, check for held signals and set j->last_proc
957 * Expects sigchld to be blocked.
959 static void
960 j_startjob(Job *j)
962 Proc *p;
964 j->flags |= JF_STARTED;
965 for (p = j->proc_list; p->next; p = p->next)
967 j->last_proc = p;
969 if (held_sigchld) {
970 held_sigchld = 0;
971 /* Don't call j_sigchld() as it may remove job... */
972 kill(procpid, SIGCHLD);
977 * wait for job to complete or change state
979 * Expects sigchld to be blocked.
981 static int
982 j_waitj(Job *j,
983 int flags, /* see JW_* */
984 const char *where)
986 int rv;
989 * No auto-notify on the job we are waiting on.
991 j->flags |= JF_WAITING;
992 if (flags & JW_ASYNCNOTIFY)
993 j->flags |= JF_W_ASYNCNOTIFY;
995 if (!Flag(FMONITOR))
996 flags |= JW_STOPPEDWAIT;
998 while ((volatile int) j->state == PRUNNING ||
999 ((flags & JW_STOPPEDWAIT) && (volatile int) j->state == PSTOPPED)) {
1000 sigsuspend(&sm_default);
1001 if (fatal_trap) {
1002 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1003 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1004 runtraps(TF_FATAL);
1005 j->flags |= oldf; /* not reached... */
1007 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1008 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1009 return -rv;
1012 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1014 if (j->flags & JF_FG) {
1015 int status;
1017 j->flags &= ~JF_FG;
1018 if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1020 * Save the tty's current pgrp so it can be restored
1021 * when the job is foregrounded. This is to
1022 * deal with things like the GNU su which does
1023 * a fork/exec instead of an exec (the fork means
1024 * the execed shell gets a different pid from its
1025 * pgrp, so naturally it sets its pgrp and gets hosed
1026 * when it gets foregrounded by the parent shell, which
1027 * has restored the tty's pgrp to that of the su
1028 * process).
1030 if (j->state == PSTOPPED &&
1031 (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1032 j->flags |= JF_SAVEDTTYPGRP;
1033 if (tcsetpgrp(tty_fd, our_pgrp) < 0) {
1034 warningf(true,
1035 "%s: tcsetpgrp(%d, %d) failed: %s",
1036 __func__, tty_fd, (int)our_pgrp,
1037 strerror(errno));
1039 if (j->state == PSTOPPED) {
1040 j->flags |= JF_SAVEDTTY;
1041 tcgetattr(tty_fd, &j->ttystate);
1044 if (tty_fd >= 0) {
1045 /* Only restore tty settings if job was originally
1046 * started in the foreground. Problems can be
1047 * caused by things like `more foobar &' which will
1048 * typically get and save the shell's vi/emacs tty
1049 * settings before setting up the tty for itself;
1050 * when more exits, it restores the `original'
1051 * settings, and things go down hill from there...
1053 if (j->state == PEXITED && j->status == 0 &&
1054 (j->flags & JF_USETTYMODE)) {
1055 tcgetattr(tty_fd, &tty_state);
1056 } else {
1057 tcsetattr(tty_fd, TCSADRAIN, &tty_state);
1058 /* Don't use tty mode if job is stopped and
1059 * later restarted and exits. Consider
1060 * the sequence:
1061 * vi foo (stopped)
1062 * ...
1063 * stty something
1064 * ...
1065 * fg (vi; ZZ)
1066 * mode should be that of the stty, not what
1067 * was before the vi started.
1069 if (j->state == PSTOPPED)
1070 j->flags &= ~JF_USETTYMODE;
1073 /* If it looks like user hit ^C to kill a job, pretend we got
1074 * one too to break out of for loops, etc. (at&t ksh does this
1075 * even when not monitoring, but this doesn't make sense since
1076 * a tty generated ^C goes to the whole process group)
1078 status = j->last_proc->status;
1079 if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1080 WIFSIGNALED(status) &&
1081 (sigtraps[WTERMSIG(status)].flags & TF_TTY_INTR))
1082 trapsig(WTERMSIG(status));
1085 j_usrtime = j->usrtime;
1086 j_systime = j->systime;
1087 rv = j->status;
1089 if (!(flags & JW_ASYNCNOTIFY) &&
1090 (!Flag(FMONITOR) || j->state != PSTOPPED)) {
1091 j_print(j, JP_SHORT, shl_out);
1092 shf_flush(shl_out);
1094 if (j->state != PSTOPPED &&
1095 (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY)))
1096 remove_job(j, where);
1098 return rv;
1101 /* SIGCHLD handler to reap children and update job states
1103 * Expects sigchld to be blocked.
1105 static void
1106 j_sigchld(int sig)
1108 int errno_ = errno;
1109 Job *j;
1110 Proc *p = NULL;
1111 int pid;
1112 int status;
1113 struct rusage ru0, ru1;
1115 /* Don't wait for any processes if a job is partially started.
1116 * This is so we don't do away with the process group leader
1117 * before all the processes in a pipe line are started (so the
1118 * setpgid() won't fail)
1120 for (j = job_list; j; j = j->next)
1121 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1122 held_sigchld = 1;
1123 goto finished;
1126 getrusage(RUSAGE_CHILDREN, &ru0);
1127 do {
1128 pid = waitpid(-1, &status, (WNOHANG|WUNTRACED));
1130 if (pid <= 0) /* return if would block (0) ... */
1131 break; /* ... or no children or interrupted (-1) */
1133 getrusage(RUSAGE_CHILDREN, &ru1);
1135 /* find job and process structures for this pid */
1136 for (j = job_list; j != NULL; j = j->next)
1137 for (p = j->proc_list; p != NULL; p = p->next)
1138 if (p->pid == pid)
1139 goto found;
1140 found:
1141 if (j == NULL) {
1142 /* Can occur if process has kids, then execs shell
1143 warningf(true, "bad process waited for (pid = %d)",
1144 pid);
1146 ru0 = ru1;
1147 continue;
1150 timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1151 timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1152 timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1153 timersub(&j->systime, &ru0.ru_stime, &j->systime);
1154 ru0 = ru1;
1155 p->status = status;
1156 if (WIFSTOPPED(status))
1157 p->state = PSTOPPED;
1158 else if (WIFSIGNALED(status))
1159 p->state = PSIGNALLED;
1160 else
1161 p->state = PEXITED;
1163 check_job(j); /* check to see if entire job is done */
1164 } while (1);
1166 finished:
1167 errno = errno_;
1171 * Called only when a process in j has exited/stopped (ie, called only
1172 * from j_sigchld()). If no processes are running, the job status
1173 * and state are updated, asynchronous job notification is done and,
1174 * if unneeded, the job is removed.
1176 * Expects sigchld to be blocked.
1178 static void
1179 check_job(Job *j)
1181 int jstate;
1182 Proc *p;
1184 /* XXX debugging (nasty - interrupt routine using shl_out) */
1185 if (!(j->flags & JF_STARTED)) {
1186 internal_warningf("%s: job started (flags 0x%x)",
1187 __func__, j->flags);
1188 return;
1191 jstate = PRUNNING;
1192 for (p=j->proc_list; p != NULL; p = p->next) {
1193 if (p->state == PRUNNING)
1194 return; /* some processes still running */
1195 if (p->state > jstate)
1196 jstate = p->state;
1198 j->state = jstate;
1200 switch (j->last_proc->state) {
1201 case PEXITED:
1202 j->status = WEXITSTATUS(j->last_proc->status);
1203 break;
1204 case PSIGNALLED:
1205 j->status = 128 + WTERMSIG(j->last_proc->status);
1206 break;
1207 default:
1208 j->status = 0;
1209 break;
1212 /* Note when co-process dies: can't be done in j_wait() nor
1213 * remove_job() since neither may be called for non-interactive
1214 * shells.
1216 if (j->state == PEXITED || j->state == PSIGNALLED) {
1217 /* No need to keep co-process input any more
1218 * (at least, this is what ksh93d thinks)
1220 if (coproc.job == j) {
1221 coproc.job = NULL;
1222 /* XXX would be nice to get the closes out of here
1223 * so they aren't done in the signal handler.
1224 * Would mean a check in coproc_getfd() to
1225 * do "if job == 0 && write >= 0, close write".
1227 coproc_write_close(coproc.write);
1229 /* Do we need to keep the output? */
1230 if (j->coproc_id && j->coproc_id == coproc.id &&
1231 --coproc.njobs == 0)
1232 coproc_readw_close(coproc.read);
1235 j->flags |= JF_CHANGED;
1236 if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1237 /* Only put stopped jobs at the front to avoid confusing
1238 * the user (don't want finished jobs effecting %+ or %-)
1240 if (j->state == PSTOPPED)
1241 put_job(j, PJ_ON_FRONT);
1242 if (Flag(FNOTIFY) &&
1243 (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1244 /* Look for the real file descriptor 2 */
1246 struct env *ep;
1247 int fd = 2;
1249 for (ep = genv; ep; ep = ep->oenv)
1250 if (ep->savefd && ep->savefd[2])
1251 fd = ep->savefd[2];
1252 shf_reopen(fd, SHF_WR, shl_j);
1254 /* Can't call j_notify() as it removes jobs. The job
1255 * must stay in the job list as j_waitj() may be
1256 * running with this job.
1258 j_print(j, JP_MEDIUM, shl_j);
1259 shf_flush(shl_j);
1260 if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1261 remove_job(j, "notify");
1264 if (!Flag(FMONITOR) && !(j->flags & (JF_WAITING|JF_FG)) &&
1265 j->state != PSTOPPED) {
1266 if (j == async_job || (j->flags & JF_KNOWN)) {
1267 j->flags |= JF_ZOMBIE;
1268 j->job = -1;
1269 nzombie++;
1270 } else
1271 remove_job(j, "checkjob");
1276 * Print job status in either short, medium or long format.
1278 * Expects sigchld to be blocked.
1280 static void
1281 j_print(Job *j, int how, struct shf *shf)
1283 Proc *p;
1284 int state;
1285 int status;
1286 int coredumped;
1287 char jobchar = ' ';
1288 char buf[64];
1289 const char *filler;
1290 int output = 0;
1292 if (how == JP_PGRP) {
1293 /* POSIX doesn't say what to do if there is no process
1294 * group leader (ie, !FMONITOR). We arbitrarily return
1295 * last pid (which is what $! returns).
1297 shf_fprintf(shf, "%d\n", j->pgrp ? j->pgrp :
1298 (j->last_proc ? j->last_proc->pid : 0));
1299 return;
1301 j->flags &= ~JF_CHANGED;
1302 filler = j->job > 10 ? "\n " : "\n ";
1303 if (j == job_list)
1304 jobchar = '+';
1305 else if (j == job_list->next)
1306 jobchar = '-';
1308 for (p = j->proc_list; p != NULL;) {
1309 coredumped = 0;
1310 switch (p->state) {
1311 case PRUNNING:
1312 strlcpy(buf, "Running", sizeof buf);
1313 break;
1314 case PSTOPPED:
1315 strlcpy(buf, sigtraps[WSTOPSIG(p->status)].mess,
1316 sizeof buf);
1317 break;
1318 case PEXITED:
1319 if (how == JP_SHORT)
1320 buf[0] = '\0';
1321 else if (WEXITSTATUS(p->status) == 0)
1322 strlcpy(buf, "Done", sizeof buf);
1323 else
1324 shf_snprintf(buf, sizeof(buf), "Done (%d)",
1325 WEXITSTATUS(p->status));
1326 break;
1327 case PSIGNALLED:
1328 if (WCOREDUMP(p->status))
1329 coredumped = 1;
1330 /* kludge for not reporting `normal termination signals'
1331 * (ie, SIGINT, SIGPIPE)
1333 if (how == JP_SHORT && !coredumped &&
1334 (WTERMSIG(p->status) == SIGINT ||
1335 WTERMSIG(p->status) == SIGPIPE)) {
1336 buf[0] = '\0';
1337 } else
1338 strlcpy(buf, sigtraps[WTERMSIG(p->status)].mess,
1339 sizeof buf);
1340 break;
1343 if (how != JP_SHORT) {
1344 if (p == j->proc_list)
1345 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1346 else
1347 shf_fprintf(shf, "%s", filler);
1350 if (how == JP_LONG)
1351 shf_fprintf(shf, "%5d ", p->pid);
1353 if (how == JP_SHORT) {
1354 if (buf[0]) {
1355 output = 1;
1356 shf_fprintf(shf, "%s%s ",
1357 buf, coredumped ? " (core dumped)" : "");
1359 } else {
1360 output = 1;
1361 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1362 p->next ? "|" : "",
1363 coredumped ? " (core dumped)" : "");
1366 state = p->state;
1367 status = p->status;
1368 p = p->next;
1369 while (p && p->state == state && p->status == status) {
1370 if (how == JP_LONG)
1371 shf_fprintf(shf, "%s%5d %-20s %s%s", filler, p->pid,
1372 " ", p->command, p->next ? "|" : "");
1373 else if (how == JP_MEDIUM)
1374 shf_fprintf(shf, " %s%s", p->command,
1375 p->next ? "|" : "");
1376 p = p->next;
1379 if (output)
1380 shf_fprintf(shf, "\n");
1383 /* Convert % sequence to job
1385 * Expects sigchld to be blocked.
1387 static Job *
1388 j_lookup(const char *cp, int *ecodep)
1390 Job *j, *last_match;
1391 const char *errstr;
1392 Proc *p;
1393 int len, job = 0;
1395 if (digit(*cp)) {
1396 job = strtonum(cp, 1, INT_MAX, &errstr);
1397 if (errstr) {
1398 if (ecodep)
1399 *ecodep = JL_NOSUCH;
1400 return NULL;
1402 /* Look for last_proc->pid (what $! returns) first... */
1403 for (j = job_list; j != NULL; j = j->next)
1404 if (j->last_proc && j->last_proc->pid == job)
1405 return j;
1406 /* ...then look for process group (this is non-POSIX),
1407 * but should not break anything (so FPOSIX isn't used).
1409 for (j = job_list; j != NULL; j = j->next)
1410 if (j->pgrp && j->pgrp == job)
1411 return j;
1412 if (ecodep)
1413 *ecodep = JL_NOSUCH;
1414 return NULL;
1416 if (*cp != '%') {
1417 if (ecodep)
1418 *ecodep = JL_INVALID;
1419 return NULL;
1421 switch (*++cp) {
1422 case '\0': /* non-standard */
1423 case '+':
1424 case '%':
1425 if (job_list != NULL)
1426 return job_list;
1427 break;
1429 case '-':
1430 if (job_list != NULL && job_list->next)
1431 return job_list->next;
1432 break;
1434 case '0': case '1': case '2': case '3': case '4':
1435 case '5': case '6': case '7': case '8': case '9':
1436 job = strtonum(cp, 1, INT_MAX, &errstr);
1437 if (errstr)
1438 break;
1439 for (j = job_list; j != NULL; j = j->next)
1440 if (j->job == job)
1441 return j;
1442 break;
1444 case '?': /* %?string */
1445 last_match = NULL;
1446 for (j = job_list; j != NULL; j = j->next)
1447 for (p = j->proc_list; p != NULL; p = p->next)
1448 if (strstr(p->command, cp+1) != NULL) {
1449 if (last_match) {
1450 if (ecodep)
1451 *ecodep = JL_AMBIG;
1452 return NULL;
1454 last_match = j;
1456 if (last_match)
1457 return last_match;
1458 break;
1460 default: /* %string */
1461 len = strlen(cp);
1462 last_match = NULL;
1463 for (j = job_list; j != NULL; j = j->next)
1464 if (strncmp(cp, j->proc_list->command, len) == 0) {
1465 if (last_match) {
1466 if (ecodep)
1467 *ecodep = JL_AMBIG;
1468 return NULL;
1470 last_match = j;
1472 if (last_match)
1473 return last_match;
1474 break;
1476 if (ecodep)
1477 *ecodep = JL_NOSUCH;
1478 return NULL;
1481 static Job *free_jobs;
1482 static Proc *free_procs;
1484 /* allocate a new job and fill in the job number.
1486 * Expects sigchld to be blocked.
1488 static Job *
1489 new_job(void)
1491 int i;
1492 Job *newj, *j;
1494 if (free_jobs != NULL) {
1495 newj = free_jobs;
1496 free_jobs = free_jobs->next;
1497 } else
1498 newj = alloc(sizeof(Job), APERM);
1500 /* brute force method */
1501 for (i = 1; ; i++) {
1502 for (j = job_list; j && j->job != i; j = j->next)
1504 if (j == NULL)
1505 break;
1507 newj->job = i;
1509 return newj;
1512 /* Allocate new process struct
1514 * Expects sigchld to be blocked.
1516 static Proc *
1517 new_proc(void)
1519 Proc *p;
1521 if (free_procs != NULL) {
1522 p = free_procs;
1523 free_procs = free_procs->next;
1524 } else
1525 p = alloc(sizeof(Proc), APERM);
1527 return p;
1530 /* Take job out of job_list and put old structures into free list.
1531 * Keeps nzombies, last_job and async_job up to date.
1533 * Expects sigchld to be blocked.
1535 static void
1536 remove_job(Job *j, const char *where)
1538 Proc *p, *tmp;
1539 Job **prev, *curr;
1541 prev = &job_list;
1542 curr = *prev;
1543 for (; curr != NULL && curr != j; prev = &curr->next, curr = *prev)
1545 if (curr != j) {
1546 internal_warningf("%s: job not found (%s)", __func__, where);
1547 return;
1549 *prev = curr->next;
1551 /* free up proc structures */
1552 for (p = j->proc_list; p != NULL; ) {
1553 tmp = p;
1554 p = p->next;
1555 tmp->next = free_procs;
1556 free_procs = tmp;
1559 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1560 --nzombie;
1561 j->next = free_jobs;
1562 free_jobs = j;
1564 if (j == last_job)
1565 last_job = NULL;
1566 if (j == async_job)
1567 async_job = NULL;
1570 /* Put j in a particular location (taking it out of job_list if it is
1571 * there already)
1573 * Expects sigchld to be blocked.
1575 static void
1576 put_job(Job *j, int where)
1578 Job **prev, *curr;
1580 /* Remove job from list (if there) */
1581 prev = &job_list;
1582 curr = job_list;
1583 for (; curr && curr != j; prev = &curr->next, curr = *prev)
1585 if (curr == j)
1586 *prev = curr->next;
1588 switch (where) {
1589 case PJ_ON_FRONT:
1590 j->next = job_list;
1591 job_list = j;
1592 break;
1594 case PJ_PAST_STOPPED:
1595 prev = &job_list;
1596 curr = job_list;
1597 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1598 curr = *prev)
1600 j->next = curr;
1601 *prev = j;
1602 break;
1606 /* nuke a job (called when unable to start full job).
1608 * Expects sigchld to be blocked.
1610 static int
1611 kill_job(Job *j, int sig)
1613 Proc *p;
1614 int rval = 0;
1616 for (p = j->proc_list; p != NULL; p = p->next)
1617 if (p->pid != 0)
1618 if (kill(p->pid, sig) < 0)
1619 rval = -1;
1620 return rval;