reenabled swaptest. quake should now load data and start on big endian architectures...
[AROS-Contrib.git] / gnu / abc-shell / jobs.c
blobfc9fbfa237b6c0eca2ddcc5e3f89aca6668de445
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 :)
16 #include <sys/stat.h>
17 #include "sh.h"
18 #include "ksh_wait.h"
19 #include "ksh_times.h"
20 #include "tty.h"
22 #include <limits.h>
24 /* Start of system configuration stuff */
26 /* We keep CHILD_MAX zombie processes around (exact value isn't critical) */
27 #ifndef CHILD_MAX
28 # ifdef _POSIX_CHILD_MAX
29 # define CHILD_MAX ((_POSIX_CHILD_MAX) * 2)
30 # else /* _POSIX_CHILD_MAX */
31 # define CHILD_MAX 20
32 # endif /* _POSIX_CHILD_MAX */
33 #endif /* !CHILD_MAX */
35 /* Order important! */
36 #define PRUNNING 0
37 #define PEXITED 1
38 #define PSIGNALLED 2
39 #define PSTOPPED 3
41 typedef struct proc Proc;
42 struct proc {
43 Proc *next; /* next process in pipeline (if any) */
44 int state;
45 int status; /* wait status */
46 pid_t pid; /* process id */
47 char command[48]; /* process command string */
50 /* Notify/print flag - j_print() argument */
51 #define JP_NONE 0 /* don't print anything */
52 #define JP_SHORT 1 /* print signals processes were killed by */
53 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
54 #define JP_LONG 3 /* print [job-num] -/+ pid command */
55 #define JP_PGRP 4 /* print pgrp */
57 /* put_job() flags */
58 #define PJ_ON_FRONT 0 /* at very front */
59 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
61 /* Job.flags values */
62 #define JF_STARTED 0x001 /* set when all processes in job are started */
63 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
64 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
65 #define JF_XXCOM 0x008 /* set for `command` jobs */
66 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
67 #define JF_SAVEDTTY 0x020 /* j->ttystate is valid */
68 #define JF_CHANGED 0x040 /* process has changed state */
69 #define JF_KNOWN 0x080 /* $! referenced */
70 #define JF_ZOMBIE 0x100 /* known, unwaited process */
71 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_noityf()) */
72 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
73 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
75 typedef struct job Job;
76 struct job {
77 Job *next; /* next job in list */
78 int job; /* job number: %n */
79 int flags; /* see JF_* */
80 int state; /* job state */
81 int status; /* exit status of last process */
82 pid_t pgrp; /* process group of job */
83 pid_t ppid; /* pid of process that forked job */
84 INT32 age; /* number of jobs started */
85 INT32 systime; /* system time used by job */
86 INT32 usrtime; /* user time used by job */
87 Proc *proc_list; /* process list */
88 Proc *last_proc; /* last process in list */
89 Coproc_id coproc_id; /* 0 or id of coprocess output pipe */
92 /* Flags for j_waitj() */
93 #define JW_NONE 0x00
94 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
95 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
96 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
98 /* Error codes for j_lookup() */
99 #define JL_OK 0
100 #define JL_NOSUCH 1 /* no such job */
101 #define JL_AMBIG 2 /* %foo or %?foo is ambiguous */
102 #define JL_INVALID 3 /* non-pid, non-% job id */
104 static const char *const lookup_msgs[] = {
105 null,
106 "no such job",
107 "ambiguous",
108 "argument must be %job or process id",
109 (char *) 0
112 INT32 j_systime, j_usrtime; /* user and system time of last j_waitjed job */
114 static Job *job_list; /* job list */
115 static Job *last_job;
116 static Job *async_job;
117 static pid_t async_pid;
119 static int nzombie; /* # of zombies owned by this process */
120 INT32 njobs; /* # of jobs started */
121 static int child_max; /* CHILD_MAX */
123 /* held_sigchld is set if sigchld occurs before a job is completely started */
124 static volatile sig_atomic_t held_sigchld;
126 #ifndef AMIGA
127 static void j_set_async(Job *);
128 #endif
129 static void j_startjob(Job *);
130 static int j_waitj(Job *, int, const char *);
131 static void j_sigchld(int);
132 static void j_print(Job *, int, struct shf *);
133 static Job *j_lookup(const char *, int *);
134 #ifndef AMIGA
135 static Job *new_job(void);
136 static Proc *new_proc(void);
137 #endif
138 static void check_job(Job *);
139 #ifndef AMIGA
140 static void put_job(Job *, int);
141 #endif
142 static void remove_job(Job *, const char *);
143 static int kill_job(Job *, int);
145 /* initialize job control */
146 void
147 j_init(int mflagset)
149 child_max = CHILD_MAX; /* so syscon() isn't always being called */
151 sigemptyset(&sm_default);
152 sigprocmask(SIG_SETMASK, &sm_default, (sigset_t *) 0);
154 sigemptyset(&sm_sigchld);
155 sigaddset(&sm_sigchld, SIGCHLD);
157 setsig(&sigtraps[SIGCHLD], j_sigchld,
158 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
160 // if (Flag(FTALKING))
161 // tty_init(true);
164 /* job cleanup before shell exit */
165 void
166 j_exit(void)
168 /* kill stopped, and possibly running, jobs */
169 Job *j;
170 int killed = 0;
172 for (j = job_list; j != (Job *) 0; j = j->next) {
173 if (j->ppid == procpid && (j->state == PSTOPPED ||
174 (j->state == PRUNNING && (j->flags & JF_FG)))) {
175 killed = 1;
176 if (j->pgrp == 0)
177 kill_job(j, SIGHUP);
178 else
179 killpg(j->pgrp, SIGHUP);
182 if (killed)
183 sleep(1);
184 j_notify();
187 /* execute tree in child subprocess */
189 #ifndef AMIGA
191 exchild(struct op *t, int flags,
192 int close_fd) /* used if XPCLOSE or XCCLOSE */
194 static Proc *last_proc; /* for pipelines */
196 int i;
197 sigset_t omask;
198 Proc *p;
199 Job *j;
200 int rv = 0;
201 int forksleep;
202 int ischild;
204 if (flags & XEXEC)
205 /* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
206 * (also done in another execute() below)
208 return execute(t, flags & (XEXEC | XERROK));
210 p = new_proc();
211 p->next = (Proc *) 0;
212 p->state = PRUNNING;
213 p->status = 0;
214 p->pid = 0;
216 /* link process into jobs list */
217 if (flags&XPIPEI) { /* continuing with a pipe */
218 if (!last_job)
219 internal_errorf(1,
220 "exchild: XPIPEI and no last_job - pid %d",
221 (int) procpid);
222 j = last_job;
223 last_proc->next = p;
224 last_proc = p;
225 } else {
226 j = new_job(); /* fills in j->job */
227 /* we don't consider XXCOM's foreground since they don't get
228 * tty process group and we don't save or restore tty modes.
230 j->flags = (flags & XXCOM) ? JF_XXCOM :
231 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
232 j->usrtime = j->systime = 0;
233 j->state = PRUNNING;
234 j->pgrp = 0;
235 j->ppid = procpid;
236 j->age = ++njobs;
237 j->proc_list = p;
238 j->coproc_id = 0;
239 last_job = j;
240 last_proc = p;
241 put_job(j, PJ_PAST_STOPPED);
244 snptreef(p->command, sizeof(p->command), "%T", t);
246 /* create child process */
247 forksleep = 1;
248 while ((i = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
249 if (intrsig) /* allow user to ^C out... */
250 break;
251 sleep(forksleep);
252 forksleep <<= 1;
254 if (i < 0) {
255 kill_job(j, SIGKILL);
256 remove_job(j, "fork failed");
257 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
258 errorf("cannot fork - try again");
260 ischild = i == 0;
261 if (ischild)
262 p->pid = procpid = getpid();
263 else
264 p->pid = i;
266 /* used to close pipe input fd */
267 if (close_fd >= 0 && (((flags & XPCLOSE) && !ischild) ||
268 ((flags & XCCLOSE) && ischild)))
269 close(close_fd);
270 if (ischild) { /* child */
271 /* Do this before restoring signal */
272 if (flags & XCOPROC)
273 coproc_cleanup(false);
274 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
275 cleanup_parents_env();
276 if ((flags & XBGND)) {
277 setsig(&sigtraps[SIGINT], SIG_IGN,
278 SS_RESTORE_IGN|SS_FORCE);
279 setsig(&sigtraps[SIGQUIT], SIG_IGN,
280 SS_RESTORE_IGN|SS_FORCE);
281 if (!(flags & (XPIPEI | XCOPROC))) {
282 int fd = open("/dev/null", 0);
283 if (fd != 0) {
284 (void) ksh_dup2(fd, 0, true);
285 close(fd);
290 remove_job(j, "child"); /* in case of `jobs` command */
291 nzombie = 0;
292 Flag(FTALKING) = 0;
293 tty_close();
294 cleartraps();
295 execute(t, (flags & XERROK) | XEXEC); /* no return */
296 internal_errorf(0, "exchild: execute() returned");
297 unwind(LLEAVE);
298 /* NOTREACHED */
301 /* shell (parent) stuff */
302 /* Ensure next child gets a (slightly) different $RANDOM sequence */
303 change_random();
304 if (!(flags & XPIPEO)) { /* last process in a job */
305 j_startjob(j);
306 if (flags & XCOPROC) {
307 j->coproc_id = coproc.id;
308 coproc.njobs++; /* n jobs using co-process output */
309 coproc.job = (void *) j; /* j using co-process input */
311 if (flags & XBGND) {
312 j_set_async(j);
313 if (Flag(FTALKING)) {
314 shf_fprintf(shl_out, "[%d]", j->job);
315 for (p = j->proc_list; p; p = p->next)
316 shf_fprintf(shl_out, " %d", p->pid);
317 shf_putchar('\n', shl_out);
318 shf_flush(shl_out);
320 } else
321 rv = j_waitj(j, JW_NONE, "jw:last proc");
324 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
326 return rv;
328 #endif
330 /* start the last job: only used for `command` jobs */
331 void
332 startlast(void)
334 sigset_t omask;
336 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
338 if (last_job) { /* no need to report error - waitlast() will do it */
339 /* ensure it isn't removed by check_job() */
340 last_job->flags |= JF_WAITING;
341 j_startjob(last_job);
343 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
346 /* wait for last job: only used for `command` jobs */
348 int lastresult = 125;
351 waitlast(void)
353 int rv;
354 Job *j;
355 sigset_t omask;
357 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
359 j = last_job;
360 if (!j || !(j->flags & JF_STARTED)) {
361 if (!j)
363 // warningf(true, "waitlast: no last job");
365 else
366 internal_errorf(0, "waitlast: not started");
367 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
369 // work arround for no job control
370 // place the result of the last command
371 // subshell or whatever in lastresult
372 // and return it here.
373 return lastresult;
374 //return 125; /* not so arbitrary, non-zero value */
377 rv = j_waitj(j, JW_NONE, "jw:waitlast");
379 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
381 return rv;
384 /* wait for child, interruptable. */
386 waitfor(const char *cp, int *sigp)
388 int rv;
389 Job *j;
390 int ecode;
391 int flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
392 sigset_t omask;
394 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
396 *sigp = 0;
398 if (cp == (char *) 0) {
399 /* wait for an unspecified job - always returns 0, so
400 * don't have to worry about exited/signaled jobs
402 for (j = job_list; j; j = j->next)
403 /* at&t ksh will wait for stopped jobs - we don't */
404 if (j->ppid == procpid && j->state == PRUNNING)
405 break;
406 if (!j) {
407 return -1;
409 } else if ((j = j_lookup(cp, &ecode))) {
410 /* don't report normal job completion */
411 flags &= ~JW_ASYNCNOTIFY;
412 if (j->ppid != procpid) {
413 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
414 return -1;
416 } else {
417 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
418 if (ecode != JL_NOSUCH)
419 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
420 return -1;
423 /* at&t ksh will wait for stopped jobs - we don't */
424 rv = j_waitj(j, flags, "jw:waitfor");
426 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
428 if (rv < 0) /* we were interrupted */
429 *sigp = 128 + -rv;
431 return rv;
434 /* kill (built-in) a job */
436 j_kill(const char *cp, int sig)
438 Job *j;
439 int rv = 0;
440 int ecode;
441 sigset_t omask;
443 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
445 if ((j = j_lookup(cp, &ecode)) == (Job *) 0) {
446 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
447 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
448 return 1;
451 if (j->pgrp == 0) {
452 if (kill_job(j, sig) < 0) {
453 bi_errorf("%s: %s", cp, strerror(errno));
454 rv = 1;
456 } else {
457 if (killpg(j->pgrp, sig) < 0) {
458 bi_errorf("%s: %s", cp, strerror(errno));
459 rv = 1;
463 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
465 return rv;
468 /* are there any running or stopped jobs ? */
470 j_stopped_running(void)
472 Job *j;
473 int which = 0;
475 for (j = job_list; j != (Job *) 0; j = j->next) {
477 if (which) {
478 shellf("You have %s%s%s jobs\n",
479 which & 1 ? "stopped" : "",
480 which == 3 ? " and " : "",
481 which & 2 ? "running" : "");
482 return 1;
485 return 0;
489 j_njobs(void)
491 Job *j;
492 int nj = 0;
493 sigset_t omask;
495 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
496 for (j = job_list; j; j = j->next)
497 nj++;
499 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
500 return nj;
503 /* list jobs for jobs built-in */
505 j_jobs(const char *cp, int slp,
506 int nflag) /* 0: short, 1: long, 2: pgrp */
508 Job *j, *tmp;
509 int how;
510 int zflag = 0;
511 sigset_t omask;
513 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
515 if (nflag < 0) { /* kludge: print zombies */
516 nflag = 0;
517 zflag = 1;
519 if (cp) {
520 int ecode;
522 if ((j = j_lookup(cp, &ecode)) == (Job *) 0) {
523 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
524 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
525 return 1;
527 } else
528 j = job_list;
529 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
530 for (; j; j = j->next) {
531 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
532 (!nflag || (j->flags & JF_CHANGED)))
534 j_print(j, how, shl_stdout);
535 if (j->state == PEXITED || j->state == PSIGNALLED)
536 j->flags |= JF_REMOVE;
538 if (cp)
539 break;
541 /* Remove jobs after printing so there won't be multiple + or - jobs */
542 for (j = job_list; j; j = tmp) {
543 tmp = j->next;
544 if (j->flags & JF_REMOVE)
545 remove_job(j, "jobs");
547 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
548 return 0;
551 /* list jobs for top-level notification */
552 void
553 j_notify(void)
555 Job *j, *tmp;
556 sigset_t omask;
558 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
559 for (j = job_list; j; j = j->next) {
560 /* Remove job after doing reports so there aren't
561 * multiple +/- jobs.
563 if (j->state == PEXITED || j->state == PSIGNALLED)
564 j->flags |= JF_REMOVE;
566 for (j = job_list; j; j = tmp) {
567 tmp = j->next;
568 if (j->flags & JF_REMOVE)
569 remove_job(j, "notify");
571 shf_flush(shl_out);
572 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
575 /* Return pid of last process in last asynchronous job */
576 pid_t
577 j_async(void)
579 sigset_t omask;
581 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
583 if (async_job)
584 async_job->flags |= JF_KNOWN;
586 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
588 return async_pid;
591 #ifndef AMIGA
592 /* Make j the last async process
594 * If jobs are compiled in then this routine expects sigchld to be blocked.
596 static void
597 j_set_async(Job *j)
599 Job *jl, *oldest;
601 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
602 remove_job(async_job, "async");
603 if (!(j->flags & JF_STARTED)) {
604 internal_errorf(0, "j_async: job not started");
605 return;
607 async_job = j;
608 async_pid = j->last_proc->pid;
609 while (nzombie > child_max) {
610 oldest = (Job *) 0;
611 for (jl = job_list; jl; jl = jl->next)
612 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
613 (!oldest || jl->age < oldest->age))
614 oldest = jl;
615 if (!oldest) {
616 /* XXX debugging */
617 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
618 internal_errorf(0,
619 "j_async: bad nzombie (%d)", nzombie);
620 nzombie = 0;
622 break;
624 remove_job(oldest, "zombie");
627 #endif
629 /* Start a job: set STARTED, check for held signals and set j->last_proc
631 * If jobs are compiled in then this routine expects sigchld to be blocked.
633 static void
634 j_startjob(Job *j)
636 Proc *p;
638 j->flags |= JF_STARTED;
639 for (p = j->proc_list; p->next; p = p->next)
641 j->last_proc = p;
643 if (held_sigchld) {
644 held_sigchld = 0;
645 /* Don't call j_sigchld() as it may remove job... */
646 kill(procpid, SIGCHLD);
651 * wait for job to complete or change state
653 * If jobs are compiled in then this routine expects sigchld to be blocked.
655 static int
656 j_waitj(Job *j,
657 int flags, /* see JW_* */
658 const char *where)
660 int rv;
663 * No auto-notify on the job we are waiting on.
665 j->flags |= JF_WAITING;
666 if (flags & JW_ASYNCNOTIFY)
667 j->flags |= JF_W_ASYNCNOTIFY;
669 flags |= JW_STOPPEDWAIT;
671 while ((volatile int) j->state == PRUNNING ||
672 ((flags & JW_STOPPEDWAIT) && (volatile int) j->state == PSTOPPED))
674 if (fatal_trap) {
675 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
676 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
677 runtraps(TF_FATAL);
678 j->flags |= oldf; /* not reached... */
680 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
681 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
682 return -rv;
685 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
687 if (j->flags & JF_FG) {
688 j->flags &= ~JF_FG;
689 if (tty_fd >= 0) {
690 /* Only restore tty settings if job was originally
691 * started in the foreground. Problems can be
692 * caused by things like `more foobar &' which will
693 * typically get and save the shell's vi/emacs tty
694 * settings before setting up the tty for itself;
695 * when more exits, it restores the `original'
696 * settings, and things go down hill from there...
698 if (j->state == PEXITED && j->status == 0 &&
699 (j->flags & JF_USETTYMODE))
701 //tcgetattr(tty_fd, &tty_state);
702 } else {
703 //tcsetattr(tty_fd, TCSADRAIN, &tty_state);
704 /* Don't use tty mode if job is stopped and
705 * later restarted and exits. Consider
706 * the sequence:
707 * vi foo (stopped)
708 * ...
709 * stty something
710 * ...
711 * fg (vi; ZZ)
712 * mode should be that of the stty, not what
713 * was before the vi started.
715 if (j->state == PSTOPPED)
716 j->flags &= ~JF_USETTYMODE;
721 j_usrtime = j->usrtime;
722 j_systime = j->systime;
723 rv = j->status;
725 if (!(flags & JW_ASYNCNOTIFY) &&
726 (j->state != PSTOPPED))
728 j_print(j, JP_SHORT, shl_out);
729 shf_flush(shl_out);
731 if (j->state != PSTOPPED &&
732 (!(flags & JW_ASYNCNOTIFY)))
733 remove_job(j, where);
735 return rv;
738 /* SIGCHLD handler to reap children and update job states
740 * If jobs are compiled in then this routine expects sigchld to be blocked.
742 static void
743 j_sigchld(int sig)
745 int errno_ = errno;
746 Job *j;
747 Proc *p = 0;
748 int pid;
749 WAIT_T status;
750 struct tms t0, t1;
752 /* Don't wait for any processes if a job is partially started.
753 * This is so we don't do away with the process group leader
754 * before all the processes in a pipe line are started (so the
755 * setpgid() won't fail)
757 for (j = job_list; j; j = j->next)
758 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
759 held_sigchld = 1;
760 return;
764 ksh_times(&t0);
765 do {
766 pid = wait(&status);
768 if (pid <= 0) /* return if would block (0) ... */
769 break; /* ... or no children or interrupted (-1) */
771 ksh_times(&t1);
773 /* find job and process structures for this pid */
774 for (j = job_list; j != (Job *) 0; j = j->next)
775 for (p = j->proc_list; p != (Proc *) 0; p = p->next)
776 if (p->pid == pid)
777 goto found;
778 found:
779 if (j == (Job *) 0) {
780 /* Can occur if process has kids, then execs shell
781 warningf(true, "bad process waited for (pid = %d)",
782 pid);
784 t0 = t1;
785 continue;
788 j->usrtime += t1.tms_cutime - t0.tms_cutime;
789 j->systime += t1.tms_cstime - t0.tms_cstime;
790 t0 = t1;
791 p->status = status;
792 if (WIFSIGNALED(status))
793 p->state = PSIGNALLED;
794 else
795 p->state = PEXITED;
797 check_job(j); /* check to see if entire job is done */
799 while (0);
801 errno = errno_;
805 * Called only when a process in j has exited/stopped (ie, called only
806 * from j_sigchld()). If no processes are running, the job status
807 * and state are updated, asynchronous job notification is done and,
808 * if unneeded, the job is removed.
810 * If jobs are compiled in then this routine expects sigchld to be blocked.
812 static void
813 check_job(Job *j)
815 int jstate;
816 Proc *p;
818 /* XXX debugging (nasty - interrupt routine using shl_out) */
819 if (!(j->flags & JF_STARTED)) {
820 internal_errorf(0, "check_job: job started (flags 0x%x)",
821 j->flags);
822 return;
825 jstate = PRUNNING;
826 for (p=j->proc_list; p != (Proc *) 0; p = p->next) {
827 if (p->state == PRUNNING)
828 return; /* some processes still running */
829 if (p->state > jstate)
830 jstate = p->state;
832 j->state = jstate;
834 switch (j->last_proc->state) {
835 case PEXITED:
836 j->status = WEXITSTATUS(j->last_proc->status);
837 break;
838 case PSIGNALLED:
839 j->status = 128 + WTERMSIG(j->last_proc->status);
840 break;
841 default:
842 j->status = 0;
843 break;
846 /* Note when co-process dies: can't be done in j_wait() nor
847 * remove_job() since neither may be called for non-interactive
848 * shells.
850 if (j->state == PEXITED || j->state == PSIGNALLED) {
851 /* No need to keep co-process input any more
852 * (at leasst, this is what ksh93d thinks)
854 if (coproc.job == j) {
855 coproc.job = (void *) 0;
856 /* XXX would be nice to get the closes out of here
857 * so they aren't done in the signal handler.
858 * Would mean a check in coproc_getfd() to
859 * do "if job == 0 && write >= 0, close write".
861 coproc_write_close(coproc.write);
863 /* Do we need to keep the output? */
864 if (j->coproc_id && j->coproc_id == coproc.id &&
865 --coproc.njobs == 0)
866 coproc_readw_close(coproc.read);
869 j->flags |= JF_CHANGED;
870 if (!(j->flags & (JF_WAITING|JF_FG))
871 && j->state != PSTOPPED)
873 if (j == async_job || (j->flags & JF_KNOWN)) {
874 j->flags |= JF_ZOMBIE;
875 j->job = -1;
876 nzombie++;
877 } else
878 remove_job(j, "checkjob");
883 * Print job status in either short, medium or long format.
885 * If jobs are compiled in then this routine expects sigchld to be blocked.
887 static void
888 j_print(Job *j, int how, struct shf *shf)
890 Proc *p;
891 int state;
892 int status;
893 int coredumped;
894 char jobchar = ' ';
895 char buf[64];
896 const char *filler;
897 int output = 0;
899 if (how == JP_PGRP) {
900 /* POSIX doesn't say what to do it there is no process
901 * group leader. We arbitrarily return
902 * last pid (which is what $! returns).
904 shf_fprintf(shf, "%d\n", j->pgrp ? j->pgrp :
905 (j->last_proc ? j->last_proc->pid : 0));
906 return;
908 j->flags &= ~JF_CHANGED;
909 filler = j->job > 10 ? "\n " : "\n ";
910 if (j == job_list)
911 jobchar = '+';
912 else if (j == job_list->next)
913 jobchar = '-';
915 for (p = j->proc_list; p != (Proc *) 0;) {
916 coredumped = 0;
917 switch (p->state) {
918 case PRUNNING:
919 strlcpy(buf, "Running", sizeof buf);
920 break;
921 case PSTOPPED:
922 strlcpy(buf, sigtraps[WSTOPSIG(p->status)].mess,
923 sizeof buf);
924 break;
925 case PEXITED:
926 if (how == JP_SHORT)
927 buf[0] = '\0';
928 else if (WEXITSTATUS(p->status) == 0)
929 strlcpy(buf, "Done", sizeof buf);
930 else
931 shf_snprintf(buf, sizeof(buf), "Done (%d)",
932 WEXITSTATUS(p->status));
933 break;
934 case PSIGNALLED:
935 if (WIFCORED(p->status))
936 coredumped = 1;
937 /* kludge for not reporting `normal termination signals'
938 * (ie, SIGINT, SIGPIPE)
940 if (how == JP_SHORT && !coredumped &&
941 (WTERMSIG(p->status) == SIGINT ||
942 WTERMSIG(p->status) == SIGPIPE)) {
943 buf[0] = '\0';
944 } else
945 strlcpy(buf, sigtraps[WTERMSIG(p->status)].mess,
946 sizeof buf);
947 break;
950 if (how != JP_SHORT) {
951 if (p == j->proc_list)
952 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
953 else
954 shf_fprintf(shf, "%s", filler);
957 if (how == JP_LONG)
958 shf_fprintf(shf, "%5d ", p->pid);
960 if (how == JP_SHORT) {
961 if (buf[0]) {
962 output = 1;
963 shf_fprintf(shf, "%s%s ",
964 buf, coredumped ? " (core dumped)" : null);
966 } else {
967 output = 1;
968 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
969 p->next ? "|" : null,
970 coredumped ? " (core dumped)" : null);
973 state = p->state;
974 status = p->status;
975 p = p->next;
976 while (p && p->state == state && p->status == status)
978 if (how == JP_LONG)
979 shf_fprintf(shf, "%s%5d %-20s %s%s", filler, p->pid,
980 space, p->command, p->next ? "|" : null);
981 else if (how == JP_MEDIUM)
982 shf_fprintf(shf, " %s%s", p->command,
983 p->next ? "|" : null);
984 p = p->next;
987 if (output)
988 shf_fprintf(shf, newline);
991 /* Convert % sequence to job
993 * If jobs are compiled in then this routine expects sigchld to be blocked.
995 static Job *
996 j_lookup(const char *cp, int *ecodep)
998 Job *j, *last_match;
999 Proc *p;
1000 int len, job = 0;
1002 if (digit(*cp)) {
1003 job = atoi(cp);
1004 /* Look for last_proc->pid (what $! returns) first... */
1005 for (j = job_list; j != (Job *) 0; j = j->next)
1006 if (j->last_proc && j->last_proc->pid == job)
1007 return j;
1008 /* ...then look for process group (this is non-POSIX),
1009 * but should not break anything (so FPOSIX isn't used).
1011 for (j = job_list; j != (Job *) 0; j = j->next)
1012 if (j->pgrp && j->pgrp == job)
1013 return j;
1014 if (ecodep)
1015 *ecodep = JL_NOSUCH;
1016 return (Job *) 0;
1018 if (*cp != '%') {
1019 if (ecodep)
1020 *ecodep = JL_INVALID;
1021 return (Job *) 0;
1023 switch (*++cp) {
1024 case '\0': /* non-standard */
1025 case '+':
1026 case '%':
1027 if (job_list != (Job *) 0)
1028 return job_list;
1029 break;
1031 case '-':
1032 if (job_list != (Job *) 0 && job_list->next)
1033 return job_list->next;
1034 break;
1036 case '0': case '1': case '2': case '3': case '4':
1037 case '5': case '6': case '7': case '8': case '9':
1038 job = atoi(cp);
1039 for (j = job_list; j != (Job *) 0; j = j->next)
1040 if (j->job == job)
1041 return j;
1042 break;
1044 case '?': /* %?string */
1045 last_match = (Job *) 0;
1046 for (j = job_list; j != (Job *) 0; j = j->next)
1047 for (p = j->proc_list; p != (Proc *) 0; p = p->next)
1048 if (strstr(p->command, cp+1) != (char *) 0) {
1049 if (last_match) {
1050 if (ecodep)
1051 *ecodep = JL_AMBIG;
1052 return (Job *) 0;
1054 last_match = j;
1056 if (last_match)
1057 return last_match;
1058 break;
1060 default: /* %string */
1061 len = strlen(cp);
1062 last_match = (Job *) 0;
1063 for (j = job_list; j != (Job *) 0; j = j->next)
1064 if (strncmp(cp, j->proc_list->command, len) == 0) {
1065 if (last_match) {
1066 if (ecodep)
1067 *ecodep = JL_AMBIG;
1068 return (Job *) 0;
1070 last_match = j;
1072 if (last_match)
1073 return last_match;
1074 break;
1076 if (ecodep)
1077 *ecodep = JL_NOSUCH;
1078 return (Job *) 0;
1081 static Job *free_jobs;
1082 static Proc *free_procs;
1084 #ifndef AMIGA
1085 /* allocate a new job and fill in the job number.
1087 * If jobs are compiled in then this routine expects sigchld to be blocked.
1089 static Job *
1090 new_job(void)
1092 int i;
1093 Job *newj, *j;
1095 if (free_jobs != (Job *) 0) {
1096 newj = free_jobs;
1097 free_jobs = free_jobs->next;
1098 } else
1099 newj = (Job *) alloc(sizeof(Job), APERM);
1101 /* brute force method */
1102 for (i = 1; ; i++) {
1103 for (j = job_list; j && j->job != i; j = j->next)
1105 if (j == (Job *) 0)
1106 break;
1108 newj->job = i;
1110 return newj;
1113 /* Allocate new process strut
1115 * If jobs are compiled in then this routine expects sigchld to be blocked.
1117 static Proc *
1118 new_proc(void)
1120 Proc *p;
1122 if (free_procs != (Proc *) 0) {
1123 p = free_procs;
1124 free_procs = free_procs->next;
1125 } else
1126 p = (Proc *) alloc(sizeof(Proc), APERM);
1128 return p;
1130 #endif
1132 /* Take job out of job_list and put old structures into free list.
1133 * Keeps nzombies, last_job and async_job up to date.
1135 * If jobs are compiled in then this routine expects sigchld to be blocked.
1137 static void
1138 remove_job(Job *j, const char *where)
1140 Proc *p, *tmp;
1141 Job **prev, *curr;
1143 prev = &job_list;
1144 curr = *prev;
1145 for (; curr != (Job *) 0 && curr != j; prev = &curr->next, curr = *prev)
1147 if (curr != j) {
1148 internal_errorf(0, "remove_job: job not found (%s)", where);
1149 return;
1151 *prev = curr->next;
1153 /* free up proc structures */
1154 for (p = j->proc_list; p != (Proc *) 0; ) {
1155 tmp = p;
1156 p = p->next;
1157 tmp->next = free_procs;
1158 free_procs = tmp;
1161 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1162 --nzombie;
1163 j->next = free_jobs;
1164 free_jobs = j;
1166 if (j == last_job)
1167 last_job = (Job *) 0;
1168 if (j == async_job)
1169 async_job = (Job *) 0;
1172 #ifndef AMIGA
1173 /* put j in a particular location (taking it out job_list if it is there
1174 * already)
1176 * If jobs are compiled in then this routine expects sigchld to be blocked.
1178 static void
1179 put_job(Job *j, int where)
1181 Job **prev, *curr;
1183 /* Remove job from list (if there) */
1184 prev = &job_list;
1185 curr = job_list;
1186 for (; curr && curr != j; prev = &curr->next,
1187 curr = *prev);
1188 if (curr == j)
1189 *prev = curr->next;
1191 switch (where) {
1192 case PJ_ON_FRONT:
1193 j->next = job_list;
1194 job_list = j;
1195 break;
1197 case PJ_PAST_STOPPED:
1198 prev = &job_list;
1199 curr = job_list;
1200 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1201 curr = *prev)
1203 j->next = curr;
1204 *prev = j;
1205 break;
1208 #endif
1210 /* nuke a job (called when unable to start full job).
1212 * If jobs are compiled in then this routine expects sigchld to be blocked.
1214 static int
1215 kill_job(Job *j, int sig)
1217 Proc *p;
1218 int rval = 0;
1220 for (p = j->proc_list; p != (Proc *) 0; p = p->next)
1221 if (p->pid != 0)
1222 if (kill(p->pid, sig) < 0)
1223 rval = -1;
1224 return rval;