1 /* $OpenBSD: jobs.c,v 1.39 2009/12/13 04:36:48 deraadt Exp $ */
4 * Process and job control
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
22 #include <sys/resource.h>
25 /* Order important! */
31 typedef struct proc Proc
;
33 Proc
*next
; /* next process in pipeline (if any) */
35 int status
; /* wait status */
36 pid_t pid
; /* process id */
37 char command
[48]; /* process command string */
40 /* Notify/print flag - j_print() argument */
41 #define JP_NONE 0 /* don't print anything */
42 #define JP_SHORT 1 /* print signals processes were killed by */
43 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
44 #define JP_LONG 3 /* print [job-num] -/+ pid command */
45 #define JP_PGRP 4 /* print pgrp */
48 #define PJ_ON_FRONT 0 /* at very front */
49 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
51 /* Job.flags values */
52 #define JF_STARTED 0x001 /* set when all processes in job are started */
53 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
54 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
55 #define JF_XXCOM 0x008 /* set for `command` jobs */
56 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
57 #define JF_SAVEDTTY 0x020 /* j->ttystate is valid */
58 #define JF_CHANGED 0x040 /* process has changed state */
59 #define JF_KNOWN 0x080 /* $! referenced */
60 #define JF_ZOMBIE 0x100 /* known, unwaited process */
61 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_noityf()) */
62 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
63 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
65 typedef struct job Job
;
67 Job
*next
; /* next job in list */
68 int job
; /* job number: %n */
69 int flags
; /* see JF_* */
70 int state
; /* job state */
71 int status
; /* exit status of last process */
72 pid_t pgrp
; /* process group of job */
73 pid_t ppid
; /* pid of process that forked job */
74 INT32 age
; /* number of jobs started */
75 struct timeval systime
; /* system time used by job */
76 struct timeval usrtime
; /* user time used by job */
77 Proc
*proc_list
; /* process list */
78 Proc
*last_proc
; /* last process in list */
79 Coproc_id coproc_id
; /* 0 or id of coprocess output pipe */
81 struct termios ttystate
;/* saved tty state for stopped jobs */
82 pid_t saved_ttypgrp
; /* saved tty process group for stopped jobs */
86 /* Flags for j_waitj() */
88 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
89 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
90 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
92 /* Error codes for j_lookup() */
94 #define JL_NOSUCH 1 /* no such job */
95 #define JL_AMBIG 2 /* %foo or %?foo is ambiguous */
96 #define JL_INVALID 3 /* non-pid, non-% job id */
98 static const char *const lookup_msgs
[] = {
102 "argument must be %job or process id",
106 struct timeval j_systime
, j_usrtime
; /* user and system time of last j_waitjed job */
108 static Job
*job_list
; /* job list */
109 static Job
*last_job
;
110 static Job
*async_job
;
111 static pid_t async_pid
;
113 static int nzombie
; /* # of zombies owned by this process */
114 INT32 njobs
; /* # of jobs started */
115 static int child_max
; /* CHILD_MAX */
118 /* held_sigchld is set if sigchld occurs before a job is completely started */
119 static volatile sig_atomic_t held_sigchld
;
122 static struct shf
*shl_j
;
123 static int ttypgrp_ok
; /* set if can use tty pgrps */
124 static pid_t restore_ttypgrp
= -1;
125 static pid_t our_pgrp
;
126 static int const tt_sigs
[] = { SIGTSTP
, SIGTTIN
, SIGTTOU
};
129 static void j_set_async(Job
*);
130 static void j_startjob(Job
*);
131 static int j_waitj(Job
*, int, const char *);
132 static void j_sigchld(int);
133 static void j_print(Job
*, int, struct shf
*);
134 static Job
*j_lookup(const char *, int *);
135 static Job
*new_job(void);
136 static Proc
*new_proc(void);
137 static void check_job(Job
*);
138 static void put_job(Job
*, int);
139 static void remove_job(Job
*, const char *);
140 static int kill_job(Job
*, int);
142 /* initialize job control */
146 child_max
= CHILD_MAX
; /* so syscon() isn't always being called */
148 sigemptyset(&sm_default
);
149 sigprocmask(SIG_SETMASK
, &sm_default
, (sigset_t
*) 0);
151 sigemptyset(&sm_sigchld
);
152 sigaddset(&sm_sigchld
, SIGCHLD
);
154 setsig(&sigtraps
[SIGCHLD
], j_sigchld
,
155 SS_RESTORE_ORIG
|SS_FORCE
|SS_SHTRAP
);
158 if (!mflagset
&& Flag(FTALKING
))
161 /* shl_j is used to do asynchronous notification (used in
162 * an interrupt handler, so need a distinct shf)
164 shl_j
= shf_fdopen(2, SHF_WR
, (struct shf
*) 0);
166 if (Flag(FMONITOR
) || Flag(FTALKING
)) {
169 /* the TF_SHELL_USES test is a kludge that lets us know if
170 * if the signals have been changed by the shell.
172 for (i
= NELEM(tt_sigs
); --i
>= 0; ) {
173 sigtraps
[tt_sigs
[i
]].flags
|= TF_SHELL_USES
;
174 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
175 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
176 SS_RESTORE_IGN
|SS_FORCE
);
180 /* j_change() calls tty_init() */
189 /* job cleanup before shell exit */
193 /* kill stopped, and possibly running, jobs */
197 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
) {
198 if (j
->ppid
== procpid
&&
199 (j
->state
== PSTOPPED
||
200 (j
->state
== PRUNNING
&&
201 ((j
->flags
& JF_FG
) ||
202 (Flag(FLOGIN
) && !Flag(FNOHUP
) && procpid
== kshpid
))))) {
207 killpg(j
->pgrp
, SIGHUP
);
209 if (j
->state
== PSTOPPED
) {
211 kill_job(j
, SIGCONT
);
213 killpg(j
->pgrp
, SIGCONT
);
223 if (kshpid
== procpid
&& restore_ttypgrp
>= 0) {
224 /* Need to restore the tty pgrp to what it was when the
225 * shell started up, so that the process that started us
226 * will be able to access the tty when we are done.
227 * Also need to restore our process group in case we are
228 * about to do an exec so that both our parent and the
229 * process we are to become will be able to access the tty.
231 tcsetpgrp(tty_fd
, restore_ttypgrp
);
232 setpgid(0, restore_ttypgrp
);
234 if (Flag(FMONITOR
)) {
242 /* turn job control on or off according to Flag(FMONITOR) */
248 if (Flag(FMONITOR
)) {
251 if (Flag(FTALKING
)) {
252 /* Don't call tcgetattr() 'til we own the tty process group */
258 /* no controlling tty, no SIGT* */
259 ttypgrp_ok
= use_tty
&& tty_fd
>= 0 && tty_devtty
;
261 if (ttypgrp_ok
&& (our_pgrp
= getpgrp()) < 0) {
262 warningf(false, "j_init: getpgrp() failed: %s",
267 setsig(&sigtraps
[SIGTTIN
], SIG_DFL
,
268 SS_RESTORE_ORIG
|SS_FORCE
);
269 /* wait to be given tty (POSIX.1, B.2, job control) */
273 if ((ttypgrp
= tcgetpgrp(tty_fd
)) < 0) {
275 "j_init: tcgetpgrp() failed: %s",
280 if (ttypgrp
== our_pgrp
)
285 for (i
= NELEM(tt_sigs
); --i
>= 0; )
286 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
287 SS_RESTORE_DFL
|SS_FORCE
);
288 if (ttypgrp_ok
&& our_pgrp
!= kshpid
) {
289 if (setpgid(0, kshpid
) < 0) {
291 "j_init: setpgid() failed: %s",
295 if (tcsetpgrp(tty_fd
, kshpid
) < 0) {
297 "j_init: tcsetpgrp() failed: %s",
301 restore_ttypgrp
= our_pgrp
;
307 warningf(false, "warning: won't have full job control");
310 tcgetattr(tty_fd
, &tty_state
);
314 for (i
= NELEM(tt_sigs
); --i
>= 0; )
315 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
316 SS_RESTORE_IGN
|SS_FORCE
);
318 for (i
= NELEM(tt_sigs
); --i
>= 0; ) {
319 if (sigtraps
[tt_sigs
[i
]].flags
&
320 (TF_ORIG_IGN
| TF_ORIG_DFL
))
321 setsig(&sigtraps
[tt_sigs
[i
]],
322 (sigtraps
[tt_sigs
[i
]].flags
& TF_ORIG_IGN
) ?
324 SS_RESTORE_ORIG
|SS_FORCE
);
332 /* execute tree in child subprocess */
334 exchild(struct op
*t
, int flags
, volatile int *xerrok
,
335 int close_fd
) /* used if XPCLOSE or XCCLOSE */
337 static Proc
*last_proc
; /* for pipelines */
348 /* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
349 * (also done in another execute() below)
351 return execute(t
, flags
& (XEXEC
| XERROK
), xerrok
);
353 /* no SIGCHLD's while messing with job and process lists */
354 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
357 p
->next
= (Proc
*) 0;
362 /* link process into jobs list */
363 if (flags
&XPIPEI
) { /* continuing with a pipe */
366 "exchild: XPIPEI and no last_job - pid %d",
372 j
= new_job(); /* fills in j->job */
373 /* we don't consider XXCOM's foreground since they don't get
374 * tty process group and we don't save or restore tty modes.
376 j
->flags
= (flags
& XXCOM
) ? JF_XXCOM
:
377 ((flags
& XBGND
) ? 0 : (JF_FG
|JF_USETTYMODE
));
378 timerclear(&j
->usrtime
);
379 timerclear(&j
->systime
);
388 put_job(j
, PJ_PAST_STOPPED
);
391 snptreef(p
->command
, sizeof(p
->command
), "%T", t
);
393 /* create child process */
395 while ((i
= fork()) < 0 && errno
== EAGAIN
&& forksleep
< 32) {
396 if (intrsig
) /* allow user to ^C out... */
402 kill_job(j
, SIGKILL
);
403 remove_job(j
, "fork failed");
404 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
405 errorf("cannot fork - try again");
409 p
->pid
= procpid
= getpid();
414 /* job control set up */
415 if (Flag(FMONITOR
) && !(flags
&XXCOM
)) {
417 if (j
->pgrp
== 0) { /* First process */
422 /* set pgrp in both parent and child to deal with race
425 setpgid(p
->pid
, j
->pgrp
);
426 /* YYY: should this be
427 if (ttypgrp_ok && ischild && !(flags&XBGND))
428 tcsetpgrp(tty_fd, j->pgrp);
429 instead? (see also YYY below)
431 if (ttypgrp_ok
&& dotty
&& !(flags
& XBGND
))
432 tcsetpgrp(tty_fd
, j
->pgrp
);
436 /* used to close pipe input fd */
437 if (close_fd
>= 0 && (((flags
& XPCLOSE
) && !ischild
) ||
438 ((flags
& XCCLOSE
) && ischild
)))
440 if (ischild
) { /* child */
441 /* Do this before restoring signal */
443 coproc_cleanup(false);
444 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
445 cleanup_parents_env();
447 /* If FMONITOR or FTALKING is set, these signals are ignored,
448 * if neither FMONITOR nor FTALKING are set, the signals have
449 * their inherited values.
451 if (Flag(FMONITOR
) && !(flags
& XXCOM
)) {
452 for (i
= NELEM(tt_sigs
); --i
>= 0; )
453 setsig(&sigtraps
[tt_sigs
[i
]], SIG_DFL
,
454 SS_RESTORE_DFL
|SS_FORCE
);
457 if (Flag(FBGNICE
) && (flags
& XBGND
))
459 if ((flags
& XBGND
) && !Flag(FMONITOR
)) {
460 setsig(&sigtraps
[SIGINT
], SIG_IGN
,
461 SS_RESTORE_IGN
|SS_FORCE
);
462 setsig(&sigtraps
[SIGQUIT
], SIG_IGN
,
463 SS_RESTORE_IGN
|SS_FORCE
);
464 if (!(flags
& (XPIPEI
| XCOPROC
))) {
465 int fd
= open("/dev/null", 0);
467 (void) ksh_dup2(fd
, 0, true);
472 remove_job(j
, "child"); /* in case of `jobs` command */
481 execute(t
, (flags
& XERROK
) | XEXEC
, NULL
); /* no return */
482 internal_errorf(0, "exchild: execute() returned");
487 /* shell (parent) stuff */
488 /* Ensure next child gets a (slightly) different $RANDOM sequence */
490 if (!(flags
& XPIPEO
)) { /* last process in a job */
492 /* YYY: Is this needed? (see also YYY above)
493 if (Flag(FMONITOR) && !(flags&(XXCOM|XBGND)))
494 tcsetpgrp(tty_fd, j->pgrp);
498 if (flags
& XCOPROC
) {
499 j
->coproc_id
= coproc
.id
;
500 coproc
.njobs
++; /* n jobs using co-process output */
501 coproc
.job
= (void *) j
; /* j using co-process input */
505 if (Flag(FTALKING
)) {
506 shf_fprintf(shl_out
, "[%d]", j
->job
);
507 for (p
= j
->proc_list
; p
; p
= p
->next
)
508 shf_fprintf(shl_out
, " %d", p
->pid
);
509 shf_putchar('\n', shl_out
);
513 rv
= j_waitj(j
, JW_NONE
, "jw:last proc");
516 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
521 /* start the last job: only used for `command` jobs */
527 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
529 if (last_job
) { /* no need to report error - waitlast() will do it */
530 /* ensure it isn't removed by check_job() */
531 last_job
->flags
|= JF_WAITING
;
532 j_startjob(last_job
);
534 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
537 /* wait for last job: only used for `command` jobs */
545 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
548 if (!j
|| !(j
->flags
& JF_STARTED
)) {
550 warningf(true, "waitlast: no last job");
552 internal_errorf(0, "waitlast: not started");
553 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
554 return 125; /* not so arbitrary, non-zero value */
557 rv
= j_waitj(j
, JW_NONE
, "jw:waitlast");
559 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
564 /* wait for child, interruptable. */
566 waitfor(const char *cp
, int *sigp
)
571 int flags
= JW_INTERRUPT
|JW_ASYNCNOTIFY
;
574 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
578 if (cp
== (char *) 0) {
579 /* wait for an unspecified job - always returns 0, so
580 * don't have to worry about exited/signaled jobs
582 for (j
= job_list
; j
; j
= j
->next
)
583 /* at&t ksh will wait for stopped jobs - we don't */
584 if (j
->ppid
== procpid
&& j
->state
== PRUNNING
)
587 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
590 } else if ((j
= j_lookup(cp
, &ecode
))) {
591 /* don't report normal job completion */
592 flags
&= ~JW_ASYNCNOTIFY
;
593 if (j
->ppid
!= procpid
) {
594 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
598 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
599 if (ecode
!= JL_NOSUCH
)
600 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
604 /* at&t ksh will wait for stopped jobs - we don't */
605 rv
= j_waitj(j
, flags
, "jw:waitfor");
607 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
609 if (rv
< 0) /* we were interrupted */
615 /* kill (built-in) a job */
617 j_kill(const char *cp
, int sig
)
624 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
626 if ((j
= j_lookup(cp
, &ecode
)) == (Job
*) 0) {
627 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
628 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
632 if (j
->pgrp
== 0) { /* started when !Flag(FMONITOR) */
633 if (kill_job(j
, sig
) < 0) {
634 bi_errorf("%s: %s", cp
, strerror(errno
));
639 if (j
->state
== PSTOPPED
&& (sig
== SIGTERM
|| sig
== SIGHUP
))
640 (void) killpg(j
->pgrp
, SIGCONT
);
642 if (killpg(j
->pgrp
, sig
) < 0) {
643 bi_errorf("%s: %s", cp
, strerror(errno
));
648 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
654 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
656 j_resume(const char *cp
, int bg
)
665 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
667 if ((j
= j_lookup(cp
, &ecode
)) == (Job
*) 0) {
668 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
669 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
674 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
675 bi_errorf("job not job-controlled");
680 shprintf("[%d] ", j
->job
);
683 for (p
= j
->proc_list
; p
!= (Proc
*) 0; p
= p
->next
) {
684 if (p
->state
== PSTOPPED
) {
689 shprintf("%s%s", p
->command
, p
->next
? "| " : null
);
692 shf_flush(shl_stdout
);
696 put_job(j
, PJ_PAST_STOPPED
);
701 /* attach tty to job */
702 if (j
->state
== PRUNNING
) {
703 if (ttypgrp_ok
&& (j
->flags
& JF_SAVEDTTY
))
704 tcsetattr(tty_fd
, TCSADRAIN
, &j
->ttystate
);
705 /* See comment in j_waitj regarding saved_ttypgrp. */
707 tcsetpgrp(tty_fd
, (j
->flags
& JF_SAVEDTTYPGRP
) ?
708 j
->saved_ttypgrp
: j
->pgrp
) < 0) {
709 if (j
->flags
& JF_SAVEDTTY
)
710 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
711 sigprocmask(SIG_SETMASK
, &omask
,
713 bi_errorf("1st tcsetpgrp(%d, %d) failed: %s",
715 (int) ((j
->flags
& JF_SAVEDTTYPGRP
) ?
716 j
->saved_ttypgrp
: j
->pgrp
),
723 j
->flags
&= ~JF_KNOWN
;
725 async_job
= (Job
*) 0;
728 if (j
->state
== PRUNNING
&& killpg(j
->pgrp
, SIGCONT
) < 0) {
734 if (ttypgrp_ok
&& (j
->flags
& JF_SAVEDTTY
))
735 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
736 if (ttypgrp_ok
&& tcsetpgrp(tty_fd
, our_pgrp
) < 0) {
738 "fg: 2nd tcsetpgrp(%d, %d) failed: %s",
739 tty_fd
, (int) our_pgrp
,
744 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
745 bi_errorf("cannot continue job %s: %s",
752 j
->flags
&= ~(JF_SAVEDTTY
| JF_SAVEDTTYPGRP
);
755 rv
= j_waitj(j
, JW_NONE
, "jw:resume");
757 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
762 /* are there any running or stopped jobs ? */
764 j_stopped_running(void)
769 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
) {
771 if (j
->ppid
== procpid
&& j
->state
== PSTOPPED
)
774 if (Flag(FLOGIN
) && !Flag(FNOHUP
) && procpid
== kshpid
&&
775 j
->ppid
== procpid
&& j
->state
== PRUNNING
)
779 shellf("You have %s%s%s jobs\n",
780 which
& 1 ? "stopped" : "",
781 which
== 3 ? " and " : "",
782 which
& 2 ? "running" : "");
796 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
797 for (j
= job_list
; j
; j
= j
->next
)
800 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
805 /* list jobs for jobs built-in */
807 j_jobs(const char *cp
, int slp
,
808 int nflag
) /* 0: short, 1: long, 2: pgrp */
815 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
817 if (nflag
< 0) { /* kludge: print zombies */
824 if ((j
= j_lookup(cp
, &ecode
)) == (Job
*) 0) {
825 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
826 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
831 how
= slp
== 0 ? JP_MEDIUM
: (slp
== 1 ? JP_LONG
: JP_PGRP
);
832 for (; j
; j
= j
->next
) {
833 if ((!(j
->flags
& JF_ZOMBIE
) || zflag
) &&
834 (!nflag
|| (j
->flags
& JF_CHANGED
))) {
835 j_print(j
, how
, shl_stdout
);
836 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
)
837 j
->flags
|= JF_REMOVE
;
842 /* Remove jobs after printing so there won't be multiple + or - jobs */
843 for (j
= job_list
; j
; j
= tmp
) {
845 if (j
->flags
& JF_REMOVE
)
846 remove_job(j
, "jobs");
848 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
852 /* list jobs for top-level notification */
859 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
860 for (j
= job_list
; j
; j
= j
->next
) {
862 if (Flag(FMONITOR
) && (j
->flags
& JF_CHANGED
))
863 j_print(j
, JP_MEDIUM
, shl_out
);
865 /* Remove job after doing reports so there aren't
868 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
)
869 j
->flags
|= JF_REMOVE
;
871 for (j
= job_list
; j
; j
= tmp
) {
873 if (j
->flags
& JF_REMOVE
)
874 remove_job(j
, "notify");
877 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
880 /* Return pid of last process in last asynchronous job */
886 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
889 async_job
->flags
|= JF_KNOWN
;
891 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
896 /* Make j the last async process
898 * If jobs are compiled in then this routine expects sigchld to be blocked.
905 if (async_job
&& (async_job
->flags
& (JF_KNOWN
|JF_ZOMBIE
)) == JF_ZOMBIE
)
906 remove_job(async_job
, "async");
907 if (!(j
->flags
& JF_STARTED
)) {
908 internal_errorf(0, "j_async: job not started");
912 async_pid
= j
->last_proc
->pid
;
913 while (nzombie
> child_max
) {
915 for (jl
= job_list
; jl
; jl
= jl
->next
)
916 if (jl
!= async_job
&& (jl
->flags
& JF_ZOMBIE
) &&
917 (!oldest
|| jl
->age
< oldest
->age
))
921 if (!(async_job
->flags
& JF_ZOMBIE
) || nzombie
!= 1) {
923 "j_async: bad nzombie (%d)", nzombie
);
928 remove_job(oldest
, "zombie");
932 /* Start a job: set STARTED, check for held signals and set j->last_proc
934 * If jobs are compiled in then this routine expects sigchld to be blocked.
941 j
->flags
|= JF_STARTED
;
942 for (p
= j
->proc_list
; p
->next
; p
= p
->next
)
948 /* Don't call j_sigchld() as it may remove job... */
949 kill(procpid
, SIGCHLD
);
954 * wait for job to complete or change state
956 * If jobs are compiled in then this routine expects sigchld to be blocked.
960 int flags
, /* see JW_* */
966 * No auto-notify on the job we are waiting on.
968 j
->flags
|= JF_WAITING
;
969 if (flags
& JW_ASYNCNOTIFY
)
970 j
->flags
|= JF_W_ASYNCNOTIFY
;
973 flags
|= JW_STOPPEDWAIT
;
975 while ((volatile int) j
->state
== PRUNNING
||
976 ((flags
& JW_STOPPEDWAIT
) && (volatile int) j
->state
== PSTOPPED
)) {
977 sigsuspend(&sm_default
);
979 int oldf
= j
->flags
& (JF_WAITING
|JF_W_ASYNCNOTIFY
);
980 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
982 j
->flags
|= oldf
; /* not reached... */
984 if ((flags
& JW_INTERRUPT
) && (rv
= trap_pending())) {
985 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
989 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
991 if (j
->flags
& JF_FG
) {
996 if (Flag(FMONITOR
) && ttypgrp_ok
&& j
->pgrp
) {
998 * Save the tty's current pgrp so it can be restored
999 * when the job is foregrounded. This is to
1000 * deal with things like the GNU su which does
1001 * a fork/exec instead of an exec (the fork means
1002 * the execed shell gets a different pid from its
1003 * pgrp, so naturally it sets its pgrp and gets hosed
1004 * when it gets foregrounded by the parent shell, which
1005 * has restored the tty's pgrp to that of the su
1008 if (j
->state
== PSTOPPED
&&
1009 (j
->saved_ttypgrp
= tcgetpgrp(tty_fd
)) >= 0)
1010 j
->flags
|= JF_SAVEDTTYPGRP
;
1011 if (tcsetpgrp(tty_fd
, our_pgrp
) < 0) {
1013 "j_waitj: tcsetpgrp(%d, %d) failed: %s",
1014 tty_fd
, (int) our_pgrp
,
1017 if (j
->state
== PSTOPPED
) {
1018 j
->flags
|= JF_SAVEDTTY
;
1019 tcgetattr(tty_fd
, &j
->ttystate
);
1024 /* Only restore tty settings if job was originally
1025 * started in the foreground. Problems can be
1026 * caused by things like `more foobar &' which will
1027 * typically get and save the shell's vi/emacs tty
1028 * settings before setting up the tty for itself;
1029 * when more exits, it restores the `original'
1030 * settings, and things go down hill from there...
1032 if (j
->state
== PEXITED
&& j
->status
== 0 &&
1033 (j
->flags
& JF_USETTYMODE
)) {
1034 tcgetattr(tty_fd
, &tty_state
);
1036 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
1037 /* Don't use tty mode if job is stopped and
1038 * later restarted and exits. Consider
1045 * mode should be that of the stty, not what
1046 * was before the vi started.
1048 if (j
->state
== PSTOPPED
)
1049 j
->flags
&= ~JF_USETTYMODE
;
1053 /* If it looks like user hit ^C to kill a job, pretend we got
1054 * one too to break out of for loops, etc. (at&t ksh does this
1055 * even when not monitoring, but this doesn't make sense since
1056 * a tty generated ^C goes to the whole process group)
1058 status
= j
->last_proc
->status
;
1059 if (Flag(FMONITOR
) && j
->state
== PSIGNALLED
&&
1060 WIFSIGNALED(status
) &&
1061 (sigtraps
[WTERMSIG(status
)].flags
& TF_TTY_INTR
))
1062 trapsig(WTERMSIG(status
));
1066 j_usrtime
= j
->usrtime
;
1067 j_systime
= j
->systime
;
1070 if (!(flags
& JW_ASYNCNOTIFY
) &&
1071 (!Flag(FMONITOR
) || j
->state
!= PSTOPPED
)) {
1072 j_print(j
, JP_SHORT
, shl_out
);
1075 if (j
->state
!= PSTOPPED
&&
1076 (!Flag(FMONITOR
) || !(flags
& JW_ASYNCNOTIFY
)))
1077 remove_job(j
, where
);
1082 /* SIGCHLD handler to reap children and update job states
1084 * If jobs are compiled in then this routine expects sigchld to be blocked.
1095 struct rusage ru0
, ru1
;
1097 /* Don't wait for any processes if a job is partially started.
1098 * This is so we don't do away with the process group leader
1099 * before all the processes in a pipe line are started (so the
1100 * setpgid() won't fail)
1102 for (j
= job_list
; j
; j
= j
->next
)
1103 if (j
->ppid
== procpid
&& !(j
->flags
& JF_STARTED
)) {
1108 getrusage(RUSAGE_CHILDREN
, &ru0
);
1110 pid
= waitpid(-1, &status
, (WNOHANG
|WUNTRACED
));
1112 if (pid
<= 0) /* return if would block (0) ... */
1113 break; /* ... or no children or interrupted (-1) */
1115 getrusage(RUSAGE_CHILDREN
, &ru1
);
1117 /* find job and process structures for this pid */
1118 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
)
1119 for (p
= j
->proc_list
; p
!= (Proc
*) 0; p
= p
->next
)
1123 if (j
== (Job
*) 0) {
1124 /* Can occur if process has kids, then execs shell
1125 warningf(true, "bad process waited for (pid = %d)",
1132 timeradd(&j
->usrtime
, &ru1
.ru_utime
, &j
->usrtime
);
1133 timersub(&j
->usrtime
, &ru0
.ru_utime
, &j
->usrtime
);
1134 timeradd(&j
->systime
, &ru1
.ru_stime
, &j
->systime
);
1135 timersub(&j
->systime
, &ru0
.ru_stime
, &j
->systime
);
1139 if (WIFSTOPPED(status
))
1140 p
->state
= PSTOPPED
;
1143 if (WIFSIGNALED(status
))
1144 p
->state
= PSIGNALLED
;
1148 check_job(j
); /* check to see if entire job is done */
1156 * Called only when a process in j has exited/stopped (ie, called only
1157 * from j_sigchld()). If no processes are running, the job status
1158 * and state are updated, asynchronous job notification is done and,
1159 * if unneeded, the job is removed.
1161 * If jobs are compiled in then this routine expects sigchld to be blocked.
1169 /* XXX debugging (nasty - interrupt routine using shl_out) */
1170 if (!(j
->flags
& JF_STARTED
)) {
1171 internal_errorf(0, "check_job: job started (flags 0x%x)",
1177 for (p
=j
->proc_list
; p
!= (Proc
*) 0; p
= p
->next
) {
1178 if (p
->state
== PRUNNING
)
1179 return; /* some processes still running */
1180 if (p
->state
> jstate
)
1185 switch (j
->last_proc
->state
) {
1187 j
->status
= WEXITSTATUS(j
->last_proc
->status
);
1190 j
->status
= 128 + WTERMSIG(j
->last_proc
->status
);
1197 /* Note when co-process dies: can't be done in j_wait() nor
1198 * remove_job() since neither may be called for non-interactive
1201 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
) {
1202 /* No need to keep co-process input any more
1203 * (at least, this is what ksh93d thinks)
1205 if (coproc
.job
== j
) {
1206 coproc
.job
= (void *) 0;
1207 /* XXX would be nice to get the closes out of here
1208 * so they aren't done in the signal handler.
1209 * Would mean a check in coproc_getfd() to
1210 * do "if job == 0 && write >= 0, close write".
1212 coproc_write_close(coproc
.write
);
1214 /* Do we need to keep the output? */
1215 if (j
->coproc_id
&& j
->coproc_id
== coproc
.id
&&
1216 --coproc
.njobs
== 0)
1217 coproc_readw_close(coproc
.read
);
1220 j
->flags
|= JF_CHANGED
;
1222 if (Flag(FMONITOR
) && !(j
->flags
& JF_XXCOM
)) {
1223 /* Only put stopped jobs at the front to avoid confusing
1224 * the user (don't want finished jobs effecting %+ or %-)
1226 if (j
->state
== PSTOPPED
)
1227 put_job(j
, PJ_ON_FRONT
);
1228 if (Flag(FNOTIFY
) &&
1229 (j
->flags
& (JF_WAITING
|JF_W_ASYNCNOTIFY
)) != JF_WAITING
) {
1230 /* Look for the real file descriptor 2 */
1235 for (ep
= e
; ep
; ep
= ep
->oenv
)
1236 if (ep
->savefd
&& ep
->savefd
[2])
1238 shf_reopen(fd
, SHF_WR
, shl_j
);
1240 /* Can't call j_notify() as it removes jobs. The job
1241 * must stay in the job list as j_waitj() may be
1242 * running with this job.
1244 j_print(j
, JP_MEDIUM
, shl_j
);
1246 if (!(j
->flags
& JF_WAITING
) && j
->state
!= PSTOPPED
)
1247 remove_job(j
, "notify");
1251 if (!Flag(FMONITOR
) && !(j
->flags
& (JF_WAITING
|JF_FG
)) &&
1252 j
->state
!= PSTOPPED
) {
1253 if (j
== async_job
|| (j
->flags
& JF_KNOWN
)) {
1254 j
->flags
|= JF_ZOMBIE
;
1258 remove_job(j
, "checkjob");
1263 * Print job status in either short, medium or long format.
1265 * If jobs are compiled in then this routine expects sigchld to be blocked.
1268 j_print(Job
*j
, int how
, struct shf
*shf
)
1279 if (how
== JP_PGRP
) {
1280 /* POSIX doesn't say what to do it there is no process
1281 * group leader (ie, !FMONITOR). We arbitrarily return
1282 * last pid (which is what $! returns).
1284 shf_fprintf(shf
, "%d\n", j
->pgrp
? j
->pgrp
:
1285 (j
->last_proc
? j
->last_proc
->pid
: 0));
1288 j
->flags
&= ~JF_CHANGED
;
1289 filler
= j
->job
> 10 ? "\n " : "\n ";
1292 else if (j
== job_list
->next
)
1295 for (p
= j
->proc_list
; p
!= (Proc
*) 0;) {
1299 strlcpy(buf
, "Running", sizeof buf
);
1302 strlcpy(buf
, sigtraps
[WSTOPSIG(p
->status
)].mess
,
1306 if (how
== JP_SHORT
)
1308 else if (WEXITSTATUS(p
->status
) == 0)
1309 strlcpy(buf
, "Done", sizeof buf
);
1311 shf_snprintf(buf
, sizeof(buf
), "Done (%d)",
1312 WEXITSTATUS(p
->status
));
1315 if (WCOREDUMP(p
->status
))
1317 /* kludge for not reporting `normal termination signals'
1318 * (ie, SIGINT, SIGPIPE)
1320 if (how
== JP_SHORT
&& !coredumped
&&
1321 (WTERMSIG(p
->status
) == SIGINT
||
1322 WTERMSIG(p
->status
) == SIGPIPE
)) {
1325 strlcpy(buf
, sigtraps
[WTERMSIG(p
->status
)].mess
,
1330 if (how
!= JP_SHORT
) {
1331 if (p
== j
->proc_list
)
1332 shf_fprintf(shf
, "[%d] %c ", j
->job
, jobchar
);
1334 shf_fprintf(shf
, "%s", filler
);
1338 shf_fprintf(shf
, "%5d ", p
->pid
);
1340 if (how
== JP_SHORT
) {
1343 shf_fprintf(shf
, "%s%s ",
1344 buf
, coredumped
? " (core dumped)" : null
);
1348 shf_fprintf(shf
, "%-20s %s%s%s", buf
, p
->command
,
1349 p
->next
? "|" : null
,
1350 coredumped
? " (core dumped)" : null
);
1356 while (p
&& p
->state
== state
&& p
->status
== status
) {
1358 shf_fprintf(shf
, "%s%5d %-20s %s%s", filler
, p
->pid
,
1359 space
, p
->command
, p
->next
? "|" : null
);
1360 else if (how
== JP_MEDIUM
)
1361 shf_fprintf(shf
, " %s%s", p
->command
,
1362 p
->next
? "|" : null
);
1367 shf_fprintf(shf
, newline
);
1370 /* Convert % sequence to job
1372 * If jobs are compiled in then this routine expects sigchld to be blocked.
1375 j_lookup(const char *cp
, int *ecodep
)
1377 Job
*j
, *last_match
;
1383 /* Look for last_proc->pid (what $! returns) first... */
1384 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
)
1385 if (j
->last_proc
&& j
->last_proc
->pid
== job
)
1387 /* ...then look for process group (this is non-POSIX),
1388 * but should not break anything (so FPOSIX isn't used).
1390 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
)
1391 if (j
->pgrp
&& j
->pgrp
== job
)
1394 *ecodep
= JL_NOSUCH
;
1399 *ecodep
= JL_INVALID
;
1403 case '\0': /* non-standard */
1406 if (job_list
!= (Job
*) 0)
1411 if (job_list
!= (Job
*) 0 && job_list
->next
)
1412 return job_list
->next
;
1415 case '0': case '1': case '2': case '3': case '4':
1416 case '5': case '6': case '7': case '8': case '9':
1418 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
)
1423 case '?': /* %?string */
1424 last_match
= (Job
*) 0;
1425 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
)
1426 for (p
= j
->proc_list
; p
!= (Proc
*) 0; p
= p
->next
)
1427 if (strstr(p
->command
, cp
+1) != (char *) 0) {
1439 default: /* %string */
1441 last_match
= (Job
*) 0;
1442 for (j
= job_list
; j
!= (Job
*) 0; j
= j
->next
)
1443 if (strncmp(cp
, j
->proc_list
->command
, len
) == 0) {
1456 *ecodep
= JL_NOSUCH
;
1460 static Job
*free_jobs
;
1461 static Proc
*free_procs
;
1463 /* allocate a new job and fill in the job number.
1465 * If jobs are compiled in then this routine expects sigchld to be blocked.
1473 if (free_jobs
!= (Job
*) 0) {
1475 free_jobs
= free_jobs
->next
;
1477 newj
= (Job
*) alloc(sizeof(Job
), APERM
);
1479 /* brute force method */
1480 for (i
= 1; ; i
++) {
1481 for (j
= job_list
; j
&& j
->job
!= i
; j
= j
->next
)
1491 /* Allocate new process struct
1493 * If jobs are compiled in then this routine expects sigchld to be blocked.
1500 if (free_procs
!= (Proc
*) 0) {
1502 free_procs
= free_procs
->next
;
1504 p
= (Proc
*) alloc(sizeof(Proc
), APERM
);
1509 /* Take job out of job_list and put old structures into free list.
1510 * Keeps nzombies, last_job and async_job up to date.
1512 * If jobs are compiled in then this routine expects sigchld to be blocked.
1515 remove_job(Job
*j
, const char *where
)
1522 for (; curr
!= (Job
*) 0 && curr
!= j
; prev
= &curr
->next
, curr
= *prev
)
1525 internal_errorf(0, "remove_job: job not found (%s)", where
);
1530 /* free up proc structures */
1531 for (p
= j
->proc_list
; p
!= (Proc
*) 0; ) {
1534 tmp
->next
= free_procs
;
1538 if ((j
->flags
& JF_ZOMBIE
) && j
->ppid
== procpid
)
1540 j
->next
= free_jobs
;
1544 last_job
= (Job
*) 0;
1546 async_job
= (Job
*) 0;
1549 /* put j in a particular location (taking it out job_list if it is there
1552 * If jobs are compiled in then this routine expects sigchld to be blocked.
1555 put_job(Job
*j
, int where
)
1559 /* Remove job from list (if there) */
1562 for (; curr
&& curr
!= j
; prev
= &curr
->next
, curr
= *prev
)
1573 case PJ_PAST_STOPPED
:
1576 for (; curr
&& curr
->state
== PSTOPPED
; prev
= &curr
->next
,
1585 /* nuke a job (called when unable to start full job).
1587 * If jobs are compiled in then this routine expects sigchld to be blocked.
1590 kill_job(Job
*j
, int sig
)
1595 for (p
= j
->proc_list
; p
!= (Proc
*) 0; p
= p
->next
)
1597 if (kill(p
->pid
, sig
) < 0)