2 * Process and job control
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
14 * Notes regarding the copious ifdefs:
15 * - TTY_PGRP defined iff JOBS is defined - defined if there are tty
17 * - NEED_PGRP_SYNC defined iff JOBS is defined - see comment below
25 #include <sys/times.h>
28 /* Start of system configuration stuff */
31 # if defined(HAVE_TCSETPGRP) || defined(TIOCSPGRP)
35 # define setpgid setpgrp
36 # define getpgID() getpgrp(0)
38 # define getpgID() getpgrp()
41 /* These so we can use ifdef xxx instead of if defined(JOBS) && defined(xxx) */
43 # undef NEED_PGRP_SYNC
46 /* End of system configuration stuff */
49 /* Order important! */
55 typedef struct proc Proc
;
57 Proc
*next
; /* next process in pipeline (if any) */
58 pid_t pid
; /* process id */
60 int status
; /* wait status */
61 char command
[48]; /* process command string */
64 /* Notify/print flag - j_print() argument */
65 #define JP_NONE 0 /* don't print anything */
66 #define JP_SHORT 1 /* print signals processes were killed by */
67 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
68 #define JP_LONG 3 /* print [job-num] -/+ pid command */
69 #define JP_PGRP 4 /* print pgrp */
72 #define PJ_ON_FRONT 0 /* at very front */
73 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
75 /* Job.flags values */
76 #define JF_STARTED 0x001 /* set when all processes in job are started */
77 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
78 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
79 #define JF_XXCOM 0x008 /* set for $(command) jobs */
80 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
81 #define JF_SAVEDTTY 0x020 /* j->ttystate is valid */
82 #define JF_CHANGED 0x040 /* process has changed state */
83 #define JF_KNOWN 0x080 /* $! referenced */
84 #define JF_ZOMBIE 0x100 /* known, unwaited process */
85 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_noityf()) */
86 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
87 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
89 typedef struct job Job
;
91 Job
*next
; /* next job in list */
92 Proc
*proc_list
; /* process list */
93 Proc
*last_proc
; /* last process in list */
94 struct timeval systime
; /* system time used by job */
95 struct timeval usrtime
; /* user time used by job */
96 pid_t pgrp
; /* process group of job */
97 pid_t ppid
; /* pid of process that forked job */
98 int job
; /* job number: %n */
99 int flags
; /* see JF_* */
100 volatile int state
; /* job state */
101 int status
; /* exit status of last process */
102 int32_t age
; /* number of jobs started */
103 #ifdef SILLY_FEATURES
104 Coproc_id coproc_id
; /* 0 or id of coprocess output pipe */
105 struct termios ttystate
;/* saved tty state for stopped jobs */
106 pid_t saved_ttypgrp
; /* saved tty process group for stopped jobs */
110 /* Flags for j_waitj() */
112 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
113 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
114 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
116 /* Error codes for j_lookup() */
118 #define JL_NOSUCH 1 /* no such job */
119 #define JL_AMBIG 2 /* %foo or %?foo is ambiguous */
120 #define JL_INVALID 3 /* non-pid, non-% job id */
122 static const char *const lookup_msgs
[] = {
126 "argument must be %job or process id",
130 static Job
*job_list
; /* job list */
131 static Job
*last_job
;
132 static Job
*async_job
;
133 static pid_t async_pid
;
135 static int nzombie
; /* # of zombies owned by this process */
136 static int32_t njobs
; /* # of jobs started */
137 static long child_max
; /* CHILD_MAX */
141 /* held_sigchld is set if sigchld occurs before a job is completely started */
142 static volatile sig_atomic_t held_sigchld
;
143 #endif /* JOB_SIGS */
145 #ifdef SILLY_FEATURES
146 static struct shf
*shl_j
;
147 static bool ttypgrp_ok
; /* set if can use tty pgrps */
148 static pid_t restore_ttypgrp
= -1;
149 static int const tt_sigs
[] = { SIGTSTP
, SIGTTIN
, SIGTTOU
};
152 static void j_set_async(Job
*);
153 static void j_startjob(Job
*);
154 static int j_waitj(Job
*, int, const char *);
155 static void j_sigchld(int);
156 static void j_print(Job
*, int, struct shf
*);
157 static Job
*j_lookup(const char *, int *);
158 static Job
*new_job(void);
159 static Proc
*new_proc(void);
160 static void check_job(Job
*);
161 static void put_job(Job
*, int);
162 static void remove_job(Job
*, const char *);
163 static int kill_job(Job
*, int);
165 /* initialize job control */
169 child_max
= sysconf(_SC_CHILD_MAX
);
175 (void)sigemptyset(&sm_default
);
176 sigprocmask(SIG_SETMASK
, &sm_default
, NULL
);
178 (void)sigemptyset(&sm_sigchld
);
179 (void)sigaddset(&sm_sigchld
, SIGCHLD
);
181 setsig(&sigtraps
[SIGCHLD
], j_sigchld
,
182 SS_RESTORE_ORIG
|SS_FORCE
|SS_SHTRAP
);
184 /* Make sure SIGCHLD isn't ignored - can do odd things under SYSV */
185 setsig(&sigtraps
[SIGCHLD
], SIG_DFL
, SS_RESTORE_ORIG
|SS_FORCE
);
186 #endif /* JOB_SIGS */
188 #ifdef SILLY_FEATURES
189 if (!mflagset
&& Flag(FTALKING
))
192 /* shl_j is used to do asynchronous notification (used in
193 * an interrupt handler, so need a distinct shf)
195 shl_j
= shf_fdopen(2, SHF_WR
, NULL
);
197 if (Flag(FMONITOR
) || Flag(FTALKING
)) {
200 /* the TF_SHELL_USES test is a kludge that lets us know if
201 * if the signals have been changed by the shell.
203 for (i
= NELEM(tt_sigs
); --i
>= 0; ) {
204 sigtraps
[tt_sigs
[i
]].flags
|= TF_SHELL_USES
;
205 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
206 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
207 SS_RESTORE_IGN
|SS_FORCE
);
211 /* j_change() calls tty_init() */
220 /* job cleanup before shell exit */
224 /* kill stopped, and possibly running, jobs */
228 for (j
= job_list
; j
!= NULL
; j
= j
->next
) {
229 if (j
->ppid
== procpid
&&
230 (j
->state
== PSTOPPED
||
231 (j
->state
== PRUNNING
&&
232 ((j
->flags
& JF_FG
) ||
233 (Flag(FLOGIN
) && !Flag(FNOHUP
) && procpid
== kshpid
))))) {
238 killpg(j
->pgrp
, SIGHUP
);
239 #ifdef SILLY_FEATURES
240 if (j
->state
== PSTOPPED
) {
242 kill_job(j
, SIGCONT
);
244 killpg(j
->pgrp
, SIGCONT
);
253 #ifdef SILLY_FEATURES
254 if (kshpid
== procpid
&& restore_ttypgrp
>= 0) {
255 /* Need to restore the tty pgrp to what it was when the
256 * shell started up, so that the process that started us
257 * will be able to access the tty when we are done.
258 * Also need to restore our process group in case we are
259 * about to do an exec so that both our parent and the
260 * process we are to become will be able to access the tty.
262 tcsetpgrp(tty_fd
, restore_ttypgrp
);
263 setpgid(0, restore_ttypgrp
);
265 if (Flag(FMONITOR
)) {
272 #ifdef SILLY_FEATURES
273 /* turn job control on or off according to Flag(FMONITOR) */
279 if (Flag(FMONITOR
)) {
280 /* Don't call get_tty() 'til we own the tty process group */
284 /* no controlling tty, no SIGT* */
285 ttypgrp_ok
= tty_fd
>= 0 && tty_devtty
;
287 if (ttypgrp_ok
&& (our_pgrp
= getpgID()) < 0) {
288 warningf(FALSE
, "j_init: getpgrp() failed: %s",
293 setsig(&sigtraps
[SIGTTIN
], SIG_DFL
,
294 SS_RESTORE_ORIG
|SS_FORCE
);
295 /* wait to be given tty (POSIX.1, B.2, job control) */
299 if ((ttypgrp
= tcgetpgrp(tty_fd
)) < 0) {
301 "j_init: tcgetpgrp() failed: %s",
306 if (ttypgrp
== our_pgrp
)
311 for (i
= NELEM(tt_sigs
); --i
>= 0; )
312 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
313 SS_RESTORE_DFL
|SS_FORCE
);
314 if (ttypgrp_ok
&& our_pgrp
!= kshpid
) {
315 if (setpgid(0, kshpid
) < 0) {
317 "j_init: setpgid() failed: %s",
321 if (tcsetpgrp(tty_fd
, kshpid
) < 0) {
323 "j_init: tcsetpgrp() failed: %s",
327 restore_ttypgrp
= our_pgrp
;
331 # if defined(NTTYDISC) && defined(TIOCSETD) && !defined(HAVE_TERMIOS_H) && !defined(HAVE_TERMIO_H)
333 int ldisc
= NTTYDISC
;
335 if (ioctl(tty_fd
, TIOCSETD
, &ldisc
) < 0)
337 "j_init: can't set new line discipline: %s",
340 # endif /* NTTYDISC && TIOCSETD */
342 warningf(FALSE
, "warning: won't have full job control");
343 # endif /* TTY_PGRP */
345 get_tty(tty_fd
, &tty_state
);
350 for (i
= NELEM(tt_sigs
); --i
>= 0; )
351 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
352 SS_RESTORE_IGN
|SS_FORCE
);
354 for (i
= NELEM(tt_sigs
); --i
>= 0; ) {
355 if (sigtraps
[tt_sigs
[i
]].flags
&
356 (TF_ORIG_IGN
| TF_ORIG_DFL
))
357 setsig(&sigtraps
[tt_sigs
[i
]],
358 (sigtraps
[tt_sigs
[i
]].flags
& TF_ORIG_IGN
) ?
360 SS_RESTORE_ORIG
|SS_FORCE
);
362 # endif /* TTY_PGRP */
369 /* execute tree in child subprocess */
371 exchild(struct op
*t
, int flags
, volatile int *xerrok
, int close_fd
)
373 static Proc
*last_proc
; /* for pipelines */
378 #endif /* JOB_SIGS */
386 /* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
387 * (also done in another execute() below)
389 return (execute(t
, flags
& (XEXEC
| XERROK
), xerrok
));
391 /* no SIGCHLDs while messing with job and process lists */
393 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
399 WSTATUS(p
->status
) = 0;
402 /* link process into jobs list */
403 if (flags
& XPIPEI
) { /* continuing with a pipe */
406 "exchild: XPIPEI and no last_job - pid %d",
413 j
= new_job(); /* fills in j->job */
414 /* we don't consider XXCOMs foreground since they don't get
415 * tty process group and we don't save or restore tty modes.
417 j
->flags
= (flags
& XXCOM
) ? JF_XXCOM
:
418 ((flags
& XBGND
) ? 0 : (JF_FG
|JF_USETTYMODE
));
419 timerclear(&j
->usrtime
);
420 timerclear(&j
->systime
);
426 #ifdef SILLY_FEATURES
431 put_job(j
, PJ_PAST_STOPPED
);
434 snptreef(p
->command
, sizeof(p
->command
), "%T", t
);
436 /* create child process */
438 while ((i
= fork()) < 0 && errno
== EAGAIN
&& forksleep
< 32) {
439 if (intrsig
) /* allow user to ^C out... */
445 kill_job(j
, SIGKILL
);
446 remove_job(j
, "fork failed");
448 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
450 errorf("cannot fork - try again");
454 p
->pid
= procpid
= getpid();
458 #ifdef SILLY_FEATURES
459 /* job control set up */
460 if (Flag(FMONITOR
) && !(flags
&XXCOM
)) {
462 if (j
->pgrp
== 0) { /* First process */
467 /* set pgrp in both parent and child to deal with race
470 setpgid(p
->pid
, j
->pgrp
);
471 if (ttypgrp_ok
&& dotty
&& !(flags
& XBGND
))
472 tcsetpgrp(tty_fd
, j
->pgrp
);
476 /* used to close pipe input fd */
477 if (close_fd
>= 0 && (((flags
& XPCLOSE
) && !ischild
) ||
478 ((flags
& XCCLOSE
) && ischild
)))
480 if (ischild
) { /* child */
481 #ifdef SILLY_FEATURES
482 /* Do this before restoring signal */
484 coproc_cleanup(FALSE
);
487 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
488 #endif /* JOB_SIGS */
489 cleanup_parents_env();
490 #ifdef SILLY_FEATURES
491 /* If FMONITOR or FTALKING is set, these signals are ignored,
492 * if neither FMONITOR nor FTALKING are set, the signals have
493 * their inherited values.
495 if (Flag(FMONITOR
) && !(flags
& XXCOM
)) {
496 for (i
= NELEM(tt_sigs
); --i
>= 0; )
497 setsig(&sigtraps
[tt_sigs
[i
]], SIG_DFL
,
498 SS_RESTORE_DFL
|SS_FORCE
);
500 #endif /* TTY_PGRP */
501 if ((flags
& XBGND
) && !Flag(FMONITOR
)) {
502 setsig(&sigtraps
[SIGINT
], SIG_IGN
,
503 SS_RESTORE_IGN
|SS_FORCE
);
504 setsig(&sigtraps
[SIGQUIT
], SIG_IGN
,
505 SS_RESTORE_IGN
|SS_FORCE
);
506 if (!(flags
& (XPIPEI
| XCOPROC
))) {
507 int fd
= open("/dev/null", 0);
508 (void) ksh_dup2(fd
, 0, TRUE
);
512 remove_job(j
, "child"); /* in case of $(jobs) command */
514 #ifdef SILLY_FEATURES
521 execute(t
, (flags
& XERROK
) | XEXEC
, NULL
); /* no return */
522 internal_errorf(0, "exchild: execute() returned");
527 /* shell (parent) stuff */
528 /* Ensure next child gets a (slightly) different $RANDOM sequence */
530 if (!(flags
& XPIPEO
)) { /* last process in a job */
532 #ifdef SILLY_FEATURES
533 if (flags
& XCOPROC
) {
534 j
->coproc_id
= coproc
.id
;
535 coproc
.njobs
++; /* n jobs using co-process output */
536 coproc
.job
= (void *) j
; /* j using co-process input */
541 if (Flag(FTALKING
)) {
542 shf_fprintf(shl_out
, "[%d]", j
->job
);
543 for (p
= j
->proc_list
; p
; p
= p
->next
)
544 shf_fprintf(shl_out
, " %d",
546 shf_putchar('\n', shl_out
);
550 rv
= j_waitj(j
, JW_NONE
, "jw:last proc");
554 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
555 #endif /* JOB_SIGS */
560 /* start the last job: only used for $(command) jobs */
567 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
568 #endif /* JOB_SIGS */
570 if (last_job
) { /* no need to report error - waitlast() will do it */
571 /* ensure it isn't removed by check_job() */
572 last_job
->flags
|= JF_WAITING
;
573 j_startjob(last_job
);
576 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
580 /* wait for last job: only used for $(command) jobs */
589 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
590 #endif /* JOB_SIGS */
593 if (!j
|| !(j
->flags
& JF_STARTED
)) {
595 warningf(TRUE
, "waitlast: no last job");
597 internal_errorf(0, "waitlast: not started");
599 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
600 #endif /* JOB_SIGS */
601 return (125); /* not so arbitrary, non-zero value */
604 rv
= j_waitj(j
, JW_NONE
, "jw:waitlast");
607 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
613 /* wait for child, interruptable. */
615 waitfor(const char *cp
, int *sigp
)
620 int flags
= JW_INTERRUPT
|JW_ASYNCNOTIFY
;
624 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
625 #endif /* JOB_SIGS */
630 /* wait for an unspecified job - always returns 0, so
631 * don't have to worry about exited/signaled jobs
633 for (j
= job_list
; j
; j
= j
->next
)
634 /* at&t ksh will wait for stopped jobs - we don't */
635 if (j
->ppid
== procpid
&& j
->state
== PRUNNING
)
639 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
640 #endif /* JOB_SIGS */
643 } else if ((j
= j_lookup(cp
, &ecode
))) {
644 /* don't report normal job completion */
645 flags
&= ~JW_ASYNCNOTIFY
;
646 if (j
->ppid
!= procpid
) {
648 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
649 #endif /* JOB_SIGS */
654 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
655 #endif /* JOB_SIGS */
656 if (ecode
!= JL_NOSUCH
)
657 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
661 /* at&t ksh will wait for stopped jobs - we don't */
662 rv
= j_waitj(j
, flags
, "jw:waitfor");
665 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
666 #endif /* JOB_SIGS */
668 if (rv
< 0) /* we were interrupted */
674 /* kill (built-in) a job */
676 j_kill(const char *cp
, int sig
)
684 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
685 #endif /* JOB_SIGS */
687 if ((j
= j_lookup(cp
, &ecode
)) == NULL
) {
689 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
690 #endif /* JOB_SIGS */
691 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
695 if (j
->pgrp
== 0) { /* started when !Flag(FMONITOR) */
696 if (kill_job(j
, sig
) < 0) {
697 bi_errorf("%s: %s", cp
, strerror(errno
));
702 if (j
->state
== PSTOPPED
&& (sig
== SIGTERM
|| sig
== SIGHUP
))
703 (void) killpg(j
->pgrp
, SIGCONT
);
705 if (killpg(j
->pgrp
, sig
) < 0) {
706 bi_errorf("%s: %s", cp
, strerror(errno
));
712 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
713 #endif /* JOB_SIGS */
719 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
721 j_resume(const char *cp
, int bg
)
730 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
732 if ((j
= j_lookup(cp
, &ecode
)) == NULL
) {
733 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
734 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
739 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
740 bi_errorf("job not job-controlled");
745 shprintf("[%d] ", j
->job
);
748 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
) {
749 if (p
->state
== PSTOPPED
) {
751 WSTATUS(p
->status
) = 0;
754 shprintf("%s%s", p
->command
, p
->next
? "| " : null
);
757 shf_flush(shl_stdout
);
761 put_job(j
, PJ_PAST_STOPPED
);
765 /* attach tty to job */
766 if (j
->state
== PRUNNING
) {
767 if (ttypgrp_ok
&& (j
->flags
& JF_SAVEDTTY
))
768 tcsetattr(tty_fd
, TCSADRAIN
, &j
->ttystate
);
769 /* See comment in j_waitj regarding saved_ttypgrp. */
771 tcsetpgrp(tty_fd
, (j
->flags
& JF_SAVEDTTYPGRP
) ?
772 j
->saved_ttypgrp
: j
->pgrp
) < 0) {
774 if (j
->flags
& JF_SAVEDTTY
)
775 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
776 sigprocmask(SIG_SETMASK
, &omask
,
778 bi_errorf("1st tcsetpgrp(%d, %d) failed: %s",
780 (int)((j
->flags
& JF_SAVEDTTYPGRP
) ?
781 j
->saved_ttypgrp
: j
->pgrp
),
787 j
->flags
&= ~JF_KNOWN
;
792 if (j
->state
== PRUNNING
&& killpg(j
->pgrp
, SIGCONT
) < 0) {
797 if (ttypgrp_ok
&& (j
->flags
& JF_SAVEDTTY
))
798 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
799 if (ttypgrp_ok
&& tcsetpgrp(tty_fd
, kshpgrp
) < 0)
801 "fg: 2nd tcsetpgrp(%d, %ld) failed: %s",
802 tty_fd
, (long)kshpgrp
, strerror(errno
));
804 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
805 bi_errorf("cannot continue job %s: %s",
811 j
->flags
&= ~(JF_SAVEDTTY
| JF_SAVEDTTYPGRP
);
813 rv
= j_waitj(j
, JW_NONE
, "jw:resume");
815 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
820 /* are there any running or stopped jobs ? */
822 j_stopped_running(void)
827 for (j
= job_list
; j
!= NULL
; j
= j
->next
) {
828 #ifdef SILLY_FEATURES
829 if (j
->ppid
== procpid
&& j
->state
== PSTOPPED
)
832 if (Flag(FLOGIN
) && !Flag(FNOHUP
) && procpid
== kshpid
&&
833 j
->ppid
== procpid
&& j
->state
== PRUNNING
)
837 shellf("You have %s%s%s jobs\n",
838 which
& 1 ? "stopped" : "",
839 which
== 3 ? " and " : "",
840 which
& 2 ? "running" : "");
847 #ifdef SILLY_FEATURES
856 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
857 for (j
= job_list
; j
; j
= j
->next
)
860 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
865 /* list jobs for jobs built-in */
867 j_jobs(const char *cp
, int slp
,
868 int nflag
) /* 0: short, 1: long, 2: pgrp */
876 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
877 #endif /* JOB_SIGS */
879 if (nflag
< 0) { /* kludge: print zombies */
886 if ((j
= j_lookup(cp
, &ecode
)) == NULL
) {
888 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
889 #endif /* JOB_SIGS */
890 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
895 how
= slp
== 0 ? JP_MEDIUM
: (slp
== 1 ? JP_LONG
: JP_PGRP
);
896 for (; j
; j
= j
->next
) {
897 if ((!(j
->flags
& JF_ZOMBIE
) || zflag
) &&
898 (!nflag
|| (j
->flags
& JF_CHANGED
))) {
899 j_print(j
, how
, shl_stdout
);
900 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
)
901 j
->flags
|= JF_REMOVE
;
906 /* Remove jobs after printing so there won't be multiple + or - jobs */
907 for (j
= job_list
; j
; j
= tmp
) {
909 if (j
->flags
& JF_REMOVE
)
910 remove_job(j
, "jobs");
913 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
914 #endif /* JOB_SIGS */
917 #endif /* SILLY_FEATURES */
919 /* list jobs for top-level notification */
927 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
928 #endif /* JOB_SIGS */
929 for (j
= job_list
; j
; j
= j
->next
) {
930 #ifdef SILLY_FEATURES
931 if (Flag(FMONITOR
) && (j
->flags
& JF_CHANGED
))
932 j_print(j
, JP_MEDIUM
, shl_out
);
934 /* Remove job after doing reports so there aren't
937 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
)
938 j
->flags
|= JF_REMOVE
;
940 for (j
= job_list
; j
; j
= tmp
) {
942 if (j
->flags
& JF_REMOVE
)
943 remove_job(j
, "notify");
947 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
948 #endif /* JOB_SIGS */
951 /* Return pid of last process in last asynchronous job */
958 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
959 #endif /* JOB_SIGS */
962 async_job
->flags
|= JF_KNOWN
;
965 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
966 #endif /* JOB_SIGS */
971 /* Make j the last async process
973 * If jobs are compiled in then this routine expects sigchld to be blocked.
980 if (async_job
&& (async_job
->flags
& (JF_KNOWN
|JF_ZOMBIE
)) == JF_ZOMBIE
)
981 remove_job(async_job
, "async");
982 if (!(j
->flags
& JF_STARTED
)) {
983 internal_errorf(0, "j_async: job not started");
987 async_pid
= j
->last_proc
->pid
;
988 while (nzombie
> child_max
) {
990 for (jl
= job_list
; jl
; jl
= jl
->next
)
991 if (jl
!= async_job
&& (jl
->flags
& JF_ZOMBIE
) &&
992 (!oldest
|| jl
->age
< oldest
->age
))
996 if (!(async_job
->flags
& JF_ZOMBIE
) || nzombie
!= 1) {
997 internal_errorf(0, "j_async: bad nzombie (%d)", nzombie
);
1002 remove_job(oldest
, "zombie");
1006 /* Start a job: set STARTED, check for held signals and set j->last_proc
1008 * If jobs are compiled in then this routine expects sigchld to be blocked.
1015 j
->flags
|= JF_STARTED
;
1016 for (p
= j
->proc_list
; p
->next
; p
= p
->next
)
1023 /* Don't call j_sigchld() as it may remove job... */
1024 kill(procpid
, SIGCHLD
);
1026 #endif /* JOB_SIGS */
1030 * wait for job to complete or change state
1032 * If jobs are compiled in then this routine expects sigchld to be blocked.
1035 j_waitj(j
, flags
, where
)
1037 int flags
; /* see JW_* */
1043 * No auto-notify on the job we are waiting on.
1045 j
->flags
|= JF_WAITING
;
1046 if (flags
& JW_ASYNCNOTIFY
)
1047 j
->flags
|= JF_W_ASYNCNOTIFY
;
1049 if (!Flag(FMONITOR
))
1050 flags
|= JW_STOPPEDWAIT
;
1052 while ((volatile int) j
->state
== PRUNNING
1053 || ((flags
& JW_STOPPEDWAIT
)
1054 && (volatile int) j
->state
== PSTOPPED
))
1057 sigsuspend(&sm_default
);
1058 #else /* JOB_SIGS */
1060 #endif /* JOB_SIGS */
1062 int oldf
= j
->flags
& (JF_WAITING
|JF_W_ASYNCNOTIFY
);
1063 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
1065 j
->flags
|= oldf
; /* not reached... */
1067 if ((flags
& JW_INTERRUPT
) && (rv
= trap_pending())) {
1068 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
1072 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
1074 if (j
->flags
& JF_FG
) {
1078 #ifdef SILLY_FEATURES
1079 if (Flag(FMONITOR
) && ttypgrp_ok
&& j
->pgrp
) {
1081 * Save the tty's current pgrp so it can be restored
1082 * when the job is foregrounded. This is to
1083 * deal with things like the GNU su which does
1084 * a fork/exec instead of an exec (the fork means
1085 * the execed shell gets a different pid from its
1086 * pgrp, so naturally it sets its pgrp and gets hosed
1087 * when it gets foregrounded by the parent shell which
1088 * has restored the tty's pgrp to that of the su
1091 if (j
->state
== PSTOPPED
&&
1092 (j
->saved_ttypgrp
= tcgetpgrp(tty_fd
)) >= 0)
1093 j
->flags
|= JF_SAVEDTTYPGRP
;
1094 if (tcsetpgrp(tty_fd
, our_pgrp
) < 0) {
1096 "j_waitj: tcsetpgrp(%d, %d) failed: %s",
1097 tty_fd
, (int) our_pgrp
,
1100 if (j
->state
== PSTOPPED
) {
1101 j
->flags
|= JF_SAVEDTTY
;
1102 get_tty(tty_fd
, &j
->ttystate
);
1105 #endif /* TTY_PGRP */
1107 /* Only restore tty settings if job was originally
1108 * started in the foreground. Problems can be
1109 * caused by things like 'more foobar &' which will
1110 * typically get and save the shell's vi/emacs tty
1111 * settings before setting up the tty for itself;
1112 * when more exits, it restores the `original'
1113 * settings, and things go down hill from there...
1115 if (j
->state
== PEXITED
&& j
->status
== 0
1116 && (j
->flags
& JF_USETTYMODE
))
1118 get_tty(tty_fd
, &tty_state
);
1120 set_tty(tty_fd
, &tty_state
,
1121 (j
->state
== PEXITED
) ? 0 : TF_MIPSKLUDGE
);
1122 /* Don't use tty mode if job is stopped and
1123 * later restarted and exits. Consider
1130 * mode should be that of the stty, not what
1131 * was before the vi started.
1133 if (j
->state
== PSTOPPED
)
1134 j
->flags
&= ~JF_USETTYMODE
;
1137 #ifdef SILLY_FEATURES
1138 /* If it looks like user hit ^C to kill a job, pretend we got
1139 * one too to break out of for loops, etc. (at&t ksh does this
1140 * even when not monitoring, but this doesn't make sense since
1141 * a tty generated ^C goes to the whole process group)
1143 status
= j
->last_proc
->status
;
1144 if (Flag(FMONITOR
) && j
->state
== PSIGNALLED
1145 && WIFSIGNALED(status
)
1146 && (sigtraps
[WTERMSIG(status
)].flags
& TF_TTY_INTR
))
1147 trapsig(WTERMSIG(status
));
1151 j_usrtime
= j
->usrtime
;
1152 j_systime
= j
->systime
;
1155 if (!(flags
& JW_ASYNCNOTIFY
)
1156 && (!Flag(FMONITOR
) || j
->state
!= PSTOPPED
))
1158 j_print(j
, JP_SHORT
, shl_out
);
1161 if (j
->state
!= PSTOPPED
1162 && (!Flag(FMONITOR
) || !(flags
& JW_ASYNCNOTIFY
)))
1163 remove_job(j
, where
);
1168 /* SIGCHLD handler to reap children and update job states
1170 * If jobs are compiled in then this routine expects sigchld to be blocked.
1174 j_sigchld(int UNUSED(sig
))
1181 struct rusage ru0
, ru1
;
1184 /* Don't wait for any processes if a job is partially started.
1185 * This is so we don't do away with the process group leader
1186 * before all the processes in a pipe line are started (so the
1187 * setpgid() won't fail)
1189 for (j
= job_list
; j
; j
= j
->next
)
1190 if (j
->ppid
== procpid
&& !(j
->flags
& JF_STARTED
)) {
1194 #endif /* JOB_SIGS */
1196 getrusage(RUSAGE_CHILDREN
, &ru0
);
1199 pid
= waitpid(-1, &status
, (WNOHANG
|WUNTRACED
));
1200 #else /* JOB_SIGS */
1201 pid
= wait(&status
);
1202 #endif /* JOB_SIGS */
1204 if (pid
<= 0) /* return if would block (0) ... */
1205 break; /* ... or no children or interrupted (-1) */
1207 getrusage(RUSAGE_CHILDREN
, &ru1
);
1209 /* find job and process structures for this pid */
1210 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1211 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
)
1216 /* Can occur if process has kids, then execs shell
1217 warningf(true, "bad process waited for (pid = %d)",
1224 timeradd(&j
->usrtime
, &ru1
.ru_utime
, &j
->usrtime
);
1225 timersub(&j
->usrtime
, &ru0
.ru_utime
, &j
->usrtime
);
1226 timeradd(&j
->systime
, &ru1
.ru_stime
, &j
->systime
);
1227 timersub(&j
->systime
, &ru0
.ru_stime
, &j
->systime
);
1230 #ifdef SILLY_FEATURES
1231 if (WIFSTOPPED(status
))
1232 p
->state
= PSTOPPED
;
1235 if (WIFSIGNALED(status
))
1236 p
->state
= PSIGNALLED
;
1240 check_job(j
); /* check to see if entire job is done */
1244 #else /* JOB_SIGS */
1246 #endif /* JOB_SIGS */
1252 * Called only when a process in j has exited/stopped (ie, called only
1253 * from j_sigchld()). If no processes are running, the job status
1254 * and state are updated, asynchronous job notification is done and,
1255 * if unneeded, the job is removed.
1257 * If jobs are compiled in then this routine expects sigchld to be blocked.
1265 /* XXX debugging (nasty - interrupt routine using shl_out) */
1266 if (!(j
->flags
& JF_STARTED
)) {
1267 internal_errorf(0, "check_job: job started (flags 0x%x)",
1273 for (p
=j
->proc_list
; p
!= NULL
; p
= p
->next
) {
1274 if (p
->state
== PRUNNING
)
1275 return; /* some processes still running */
1276 if (p
->state
> jstate
)
1281 switch (j
->last_proc
->state
) {
1283 j
->status
= WEXITSTATUS(j
->last_proc
->status
);
1286 j
->status
= 128 + WTERMSIG(j
->last_proc
->status
);
1293 #ifdef SILLY_FEATURES
1294 /* Note when co-process dies: can't be done in j_wait() nor
1295 * remove_job() since neither may be called for non-interactive
1298 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
) {
1299 /* No need to keep co-process input any more
1300 * (at least, this is what ksh93d thinks)
1302 if (coproc
.job
== j
) {
1304 /* XXX would be nice to get the closes out of here
1305 * so they aren't done in the signal handler.
1306 * Would mean a check in coproc_getfd() to
1307 * do "if job == 0 && write >= 0, close write".
1309 coproc_write_close(coproc
.write
);
1311 /* Do we need to keep the output? */
1312 if (j
->coproc_id
&& j
->coproc_id
== coproc
.id
&&
1313 --coproc
.njobs
== 0)
1314 coproc_readw_close(coproc
.read
);
1318 j
->flags
|= JF_CHANGED
;
1319 #ifdef SILLY_FEATURES
1320 if (Flag(FMONITOR
) && !(j
->flags
& JF_XXCOM
)) {
1321 /* Only put stopped jobs at the front to avoid confusing
1322 * the user (don't want finished jobs effecting %+ or %-)
1324 if (j
->state
== PSTOPPED
)
1325 put_job(j
, PJ_ON_FRONT
);
1327 && (j
->flags
& (JF_WAITING
|JF_W_ASYNCNOTIFY
)) != JF_WAITING
)
1329 /* Look for the real file descriptor 2 */
1334 for (ep
= e
; ep
; ep
= ep
->oenv
)
1335 if (ep
->savefd
&& ep
->savefd
[2])
1337 shf_reopen(fd
, SHF_WR
, shl_j
);
1339 /* Can't call j_notify() as it removes jobs. The job
1340 * must stay in the job list as j_waitj() may be
1341 * running with this job.
1343 j_print(j
, JP_MEDIUM
, shl_j
);
1345 if (!(j
->flags
& JF_WAITING
) && j
->state
!= PSTOPPED
)
1346 remove_job(j
, "notify");
1350 if (!Flag(FMONITOR
) && !(j
->flags
& (JF_WAITING
|JF_FG
))
1351 && j
->state
!= PSTOPPED
)
1353 if (j
== async_job
|| (j
->flags
& JF_KNOWN
)) {
1354 j
->flags
|= JF_ZOMBIE
;
1358 remove_job(j
, "checkjob");
1363 * Print job status in either short, medium or long format.
1365 * If jobs are compiled in then this routine expects sigchld to be blocked.
1368 j_print(Job
*j
, int how
, struct shf
*shf
)
1379 if (how
== JP_PGRP
) {
1380 /* POSIX doesn't say what to do it there is no process
1381 * group leader (ie, !FMONITOR). We arbitrarily return
1382 * last pid (which is what $! returns).
1384 shf_fprintf(shf
, "%d\n", (int)(j
->pgrp
? j
->pgrp
:
1385 (j
->last_proc
? j
->last_proc
->pid
: 0)));
1388 j
->flags
&= ~JF_CHANGED
;
1389 filler
= j
->job
> 10 ? "\n " : "\n ";
1392 else if (j
== job_list
->next
)
1395 for (p
= j
->proc_list
; p
!= NULL
;) {
1399 memcpy(buf
, "Running", 8);
1402 strcpy(buf
, sigtraps
[WSTOPSIG(p
->status
)].mess
);
1405 if (how
== JP_SHORT
)
1407 else if (WEXITSTATUS(p
->status
) == 0)
1408 memcpy(buf
, "Done", 5);
1410 snprintf(buf
, sizeof(buf
), "Done (%d)",
1411 WEXITSTATUS(p
->status
));
1414 if (WIFCORED(p
->status
))
1416 /* kludge for not reporting `normal termination signals'
1417 * (ie, SIGINT, SIGPIPE)
1419 if (how
== JP_SHORT
&& !coredumped
1420 && (WTERMSIG(p
->status
) == SIGINT
1421 || WTERMSIG(p
->status
) == SIGPIPE
)) {
1424 strcpy(buf
, sigtraps
[WTERMSIG(p
->status
)].mess
);
1428 if (how
!= JP_SHORT
) {
1429 if (p
== j
->proc_list
)
1430 shf_fprintf(shf
, "[%d] %c ", j
->job
, jobchar
);
1432 shf_fprintf(shf
, "%s", filler
);
1436 shf_fprintf(shf
, "%5d ", (int)p
->pid
);
1438 if (how
== JP_SHORT
) {
1441 shf_fprintf(shf
, "%s%s ",
1442 buf
, coredumped
? " (core dumped)" : null
);
1446 shf_fprintf(shf
, "%-20s %s%s%s", buf
, p
->command
,
1447 p
->next
? "|" : null
,
1448 coredumped
? " (core dumped)" : null
);
1454 while (p
&& p
->state
== state
1455 && WSTATUS(p
->status
) == WSTATUS(status
))
1458 shf_fprintf(shf
, "%s%5d %-20s %s%s", filler
,
1459 (int)p
->pid
, " ", p
->command
,
1460 p
->next
? "|" : null
);
1461 else if (how
== JP_MEDIUM
)
1462 shf_fprintf(shf
, " %s%s", p
->command
,
1463 p
->next
? "|" : null
);
1468 shf_fprintf(shf
, "\n");
1471 /* Convert % sequence to job
1473 * If jobs are compiled in then this routine expects sigchld to be blocked.
1476 j_lookup(const char *cp
, int *ecodep
)
1478 Job
*j
, *last_match
;
1483 job
= strtol(cp
, (char **)NULL
, 10);
1484 /* Look for last_proc->pid (what $! returns) first... */
1485 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1486 if (j
->last_proc
&& j
->last_proc
->pid
== job
)
1488 /* ...then look for process group (this is non-POSIX,
1489 * but should not break anything) */
1490 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1491 if (j
->pgrp
&& j
->pgrp
== job
)
1494 *ecodep
= JL_NOSUCH
;
1499 *ecodep
= JL_INVALID
;
1503 case '\0': /* non-standard */
1506 if (job_list
!= NULL
)
1511 if (job_list
!= NULL
&& job_list
->next
)
1512 return job_list
->next
;
1515 case '0': case '1': case '2': case '3': case '4':
1516 case '5': case '6': case '7': case '8': case '9':
1517 job
= strtol(cp
, (char **)NULL
, 10);
1518 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1523 case '?': /* %?string */
1525 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1526 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
)
1527 if (strstr(p
->command
, cp
+1) != NULL
) {
1536 return (last_match
);
1539 default: /* %string */
1542 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1543 if (strncmp(cp
, j
->proc_list
->command
, len
) == 0) {
1552 return (last_match
);
1556 *ecodep
= JL_NOSUCH
;
1560 static Job
*free_jobs
;
1561 static Proc
*free_procs
;
1563 /* allocate a new job and fill in the job number.
1565 * If jobs are compiled in then this routine expects sigchld to be blocked.
1573 if (free_jobs
!= NULL
) {
1575 free_jobs
= free_jobs
->next
;
1577 newj
= (Job
*) alloc(sizeof(Job
), APERM
);
1579 /* brute force method */
1580 for (i
= 1; ; i
++) {
1581 for (j
= job_list
; j
&& j
->job
!= i
; j
= j
->next
)
1591 /* Allocate new process struct
1593 * If jobs are compiled in then this routine expects sigchld to be blocked.
1600 if (free_procs
!= NULL
) {
1602 free_procs
= free_procs
->next
;
1604 p
= (Proc
*) alloc(sizeof(Proc
), APERM
);
1609 /* Take job out of job_list and put old structures into free list.
1610 * Keeps nzombies, last_job and async_job up to date.
1612 * If jobs are compiled in then this routine expects sigchld to be blocked.
1615 remove_job(Job
*j
, const char *where
)
1622 for (; curr
!= NULL
&& curr
!= j
; prev
= &curr
->next
, curr
= *prev
)
1625 internal_errorf(0, "remove_job: job not found (%s)", where
);
1630 /* free up proc structures */
1631 for (p
= j
->proc_list
; p
!= NULL
; ) {
1634 tmp
->next
= free_procs
;
1638 if ((j
->flags
& JF_ZOMBIE
) && j
->ppid
== procpid
)
1640 j
->next
= free_jobs
;
1649 /* put j in a particular location (taking it out job_list if it is there
1652 * If jobs are compiled in then this routine expects sigchld to be blocked.
1655 put_job(Job
*j
, int where
)
1659 /* Remove job from list (if there) */
1662 for (; curr
&& curr
!= j
; prev
= &curr
->next
, curr
= *prev
)
1673 case PJ_PAST_STOPPED
:
1676 for (; curr
&& curr
->state
== PSTOPPED
; prev
= &curr
->next
,
1685 /* nuke a job (called when unable to start full job).
1687 * If jobs are compiled in then this routine expects sigchld to be blocked.
1690 kill_job(Job
*j
, int sig
)
1695 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
)
1697 if (kill(p
->pid
, sig
) < 0)