1 /* $OpenBSD: jobs.c,v 1.60 2018/03/15 16:51:29 anton 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
18 #include <sys/resource.h>
34 /* Order important! */
40 typedef struct proc Proc
;
42 Proc
*next
; /* next process in pipeline (if any) */
44 int status
; /* wait status */
45 pid_t pid
; /* process id */
46 char command
[48]; /* process command string */
49 /* Notify/print flag - j_print() argument */
50 #define JP_NONE 0 /* don't print anything */
51 #define JP_SHORT 1 /* print signals processes were killed by */
52 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
53 #define JP_LONG 3 /* print [job-num] -/+ pid command */
54 #define JP_PGRP 4 /* print pgrp */
57 #define PJ_ON_FRONT 0 /* at very front */
58 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
60 /* Job.flags values */
61 #define JF_STARTED 0x001 /* set when all processes in job are started */
62 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
63 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
64 #define JF_XXCOM 0x008 /* set for `command` jobs */
65 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
66 #define JF_SAVEDTTY 0x020 /* j->ttystate is valid */
67 #define JF_CHANGED 0x040 /* process has changed state */
68 #define JF_KNOWN 0x080 /* $! referenced */
69 #define JF_ZOMBIE 0x100 /* known, unwaited process */
70 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_notify()) */
71 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
72 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
74 typedef struct job Job
;
76 Job
*next
; /* next job in list */
77 int job
; /* job number: %n */
78 int flags
; /* see JF_* */
79 int state
; /* job state */
80 int status
; /* exit status of last process */
81 pid_t pgrp
; /* process group of job */
82 pid_t ppid
; /* pid of process that forked job */
83 int age
; /* number of jobs started */
84 struct timeval systime
; /* system time used by job */
85 struct timeval usrtime
; /* user time used by job */
86 Proc
*proc_list
; /* process list */
87 Proc
*last_proc
; /* last process in list */
88 Coproc_id coproc_id
; /* 0 or id of coprocess output pipe */
89 struct termios ttystate
;/* saved tty state for stopped jobs */
90 pid_t saved_ttypgrp
; /* saved tty process group for stopped jobs */
93 /* Flags for j_waitj() */
95 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
96 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
97 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
99 /* Error codes for j_lookup() */
101 #define JL_NOSUCH 1 /* no such job */
102 #define JL_AMBIG 2 /* %foo or %?foo is ambiguous */
103 #define JL_INVALID 3 /* non-pid, non-% job id */
105 static const char *const lookup_msgs
[] = {
109 "argument must be %job or process id",
113 struct timeval j_systime
, j_usrtime
; /* user and system time of last j_waitjed job */
115 static Job
*job_list
; /* job list */
116 static Job
*last_job
;
117 static Job
*async_job
;
118 static pid_t async_pid
;
120 static int nzombie
; /* # of zombies owned by this process */
121 int njobs
; /* # of jobs started */
122 static int child_max
; /* CHILD_MAX */
125 /* held_sigchld is set if sigchld occurs before a job is completely started */
126 static volatile sig_atomic_t held_sigchld
;
128 static struct shf
*shl_j
;
129 static int ttypgrp_ok
; /* set if can use tty pgrps */
130 static pid_t restore_ttypgrp
= -1;
131 static pid_t our_pgrp
;
132 static int const tt_sigs
[] = { SIGTSTP
, SIGTTIN
, SIGTTOU
};
134 static void j_set_async(Job
*);
135 static void j_startjob(Job
*);
136 static int j_waitj(Job
*, int, const char *);
137 static void j_sigchld(int);
138 static void j_print(Job
*, int, struct shf
*);
139 static Job
*j_lookup(const char *, int *);
140 static Job
*new_job(void);
141 static Proc
*new_proc(void);
142 static void check_job(Job
*);
143 static void put_job(Job
*, int);
144 static void remove_job(Job
*, const char *);
145 static int kill_job(Job
*, int);
147 /* initialize job control */
151 child_max
= CHILD_MAX
; /* so syscon() isn't always being called */
153 sigemptyset(&sm_default
);
154 sigprocmask(SIG_SETMASK
, &sm_default
, NULL
);
156 sigemptyset(&sm_sigchld
);
157 sigaddset(&sm_sigchld
, SIGCHLD
);
159 setsig(&sigtraps
[SIGCHLD
], j_sigchld
,
160 SS_RESTORE_ORIG
|SS_FORCE
|SS_SHTRAP
);
162 if (!mflagset
&& Flag(FTALKING
))
165 /* shl_j is used to do asynchronous notification (used in
166 * an interrupt handler, so need a distinct shf)
168 shl_j
= shf_fdopen(2, SHF_WR
, NULL
);
170 if (Flag(FMONITOR
) || Flag(FTALKING
)) {
173 /* the TF_SHELL_USES test is a kludge that lets us know if
174 * if the signals have been changed by the shell.
176 for (i
= NELEM(tt_sigs
); --i
>= 0; ) {
177 sigtraps
[tt_sigs
[i
]].flags
|= TF_SHELL_USES
;
178 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
179 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
180 SS_RESTORE_IGN
|SS_FORCE
);
184 /* j_change() calls tty_init() */
187 else if (Flag(FTALKING
))
191 /* suspend the shell */
195 struct sigaction sa
, osa
;
197 /* Restore tty and pgrp. */
199 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
200 if (restore_ttypgrp
>= 0) {
201 if (tcsetpgrp(tty_fd
, restore_ttypgrp
) < 0) {
202 warningf(false, "%s: tcsetpgrp() failed: %s",
203 __func__
, strerror(errno
));
205 if (setpgid(0, restore_ttypgrp
) < 0) {
207 "%s: setpgid() failed: %s",
208 __func__
, strerror(errno
));
214 /* Suspend the shell. */
215 memset(&sa
, 0, sizeof(sa
));
216 sigemptyset(&sa
.sa_mask
);
217 sa
.sa_handler
= SIG_DFL
;
218 sigaction(SIGTSTP
, &sa
, &osa
);
221 /* Back from suspend, reset signals, pgrp and tty. */
222 sigaction(SIGTSTP
, &osa
, NULL
);
224 if (restore_ttypgrp
>= 0) {
225 if (setpgid(0, kshpid
) < 0) {
226 warningf(false, "%s: setpgid() failed: %s",
227 __func__
, strerror(errno
));
230 if (tcsetpgrp(tty_fd
, kshpid
) < 0) {
232 "%s: tcsetpgrp() failed: %s",
233 __func__
, strerror(errno
));
242 /* job cleanup before shell exit */
246 /* kill stopped, and possibly running, jobs */
250 for (j
= job_list
; j
!= NULL
; j
= j
->next
) {
251 if (j
->ppid
== procpid
&&
252 (j
->state
== PSTOPPED
||
253 (j
->state
== PRUNNING
&&
254 ((j
->flags
& JF_FG
) ||
255 (Flag(FLOGIN
) && !Flag(FNOHUP
) && procpid
== kshpid
))))) {
260 killpg(j
->pgrp
, SIGHUP
);
261 if (j
->state
== PSTOPPED
) {
263 kill_job(j
, SIGCONT
);
265 killpg(j
->pgrp
, SIGCONT
);
273 if (kshpid
== procpid
&& restore_ttypgrp
>= 0) {
274 /* Need to restore the tty pgrp to what it was when the
275 * shell started up, so that the process that started us
276 * will be able to access the tty when we are done.
277 * Also need to restore our process group in case we are
278 * about to do an exec so that both our parent and the
279 * process we are to become will be able to access the tty.
281 tcsetpgrp(tty_fd
, restore_ttypgrp
);
282 setpgid(0, restore_ttypgrp
);
284 if (Flag(FMONITOR
)) {
290 /* turn job control on or off according to Flag(FMONITOR) */
296 if (Flag(FMONITOR
)) {
299 if (Flag(FTALKING
)) {
300 /* Don't call tcgetattr() 'til we own the tty process group */
306 /* no controlling tty, no SIGT* */
307 ttypgrp_ok
= use_tty
&& tty_fd
>= 0 && tty_devtty
;
309 if (ttypgrp_ok
&& (our_pgrp
= getpgrp()) < 0) {
310 warningf(false, "%s: getpgrp() failed: %s",
311 __func__
, strerror(errno
));
315 setsig(&sigtraps
[SIGTTIN
], SIG_DFL
,
316 SS_RESTORE_ORIG
|SS_FORCE
);
317 /* wait to be given tty (POSIX.1, B.2, job control) */
321 if ((ttypgrp
= tcgetpgrp(tty_fd
)) < 0) {
323 "%s: tcgetpgrp() failed: %s",
324 __func__
, strerror(errno
));
328 if (ttypgrp
== our_pgrp
)
333 for (i
= NELEM(tt_sigs
); --i
>= 0; )
334 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
335 SS_RESTORE_DFL
|SS_FORCE
);
336 if (ttypgrp_ok
&& our_pgrp
!= kshpid
) {
337 if (setpgid(0, kshpid
) < 0) {
338 warningf(false, "%s: setpgid() failed: %s",
339 __func__
, strerror(errno
));
342 if (tcsetpgrp(tty_fd
, kshpid
) < 0) {
344 "%s: tcsetpgrp() failed: %s",
345 __func__
, strerror(errno
));
348 restore_ttypgrp
= our_pgrp
;
355 "warning: won't have full job control");
358 tcgetattr(tty_fd
, &tty_state
);
362 for (i
= NELEM(tt_sigs
); --i
>= 0; )
363 setsig(&sigtraps
[tt_sigs
[i
]], SIG_IGN
,
364 SS_RESTORE_IGN
|SS_FORCE
);
366 for (i
= NELEM(tt_sigs
); --i
>= 0; ) {
367 if (sigtraps
[tt_sigs
[i
]].flags
&
368 (TF_ORIG_IGN
| TF_ORIG_DFL
))
369 setsig(&sigtraps
[tt_sigs
[i
]],
370 (sigtraps
[tt_sigs
[i
]].flags
& TF_ORIG_IGN
) ?
372 SS_RESTORE_ORIG
|SS_FORCE
);
379 /* execute tree in child subprocess */
381 exchild(struct op
*t
, int flags
, volatile int *xerrok
,
382 int close_fd
) /* used if XPCLOSE or XCCLOSE */
384 static Proc
*last_proc
; /* for pipelines */
395 /* Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
396 * (also done in another execute() below)
398 return execute(t
, flags
& (XEXEC
| XERROK
), xerrok
);
400 /* no SIGCHLD's while messing with job and process lists */
401 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
409 /* link process into jobs list */
410 if (flags
&XPIPEI
) { /* continuing with a pipe */
412 internal_errorf("%s: XPIPEI and no last_job - pid %d",
413 __func__
, (int) procpid
);
418 j
= new_job(); /* fills in j->job */
419 /* we don't consider XXCOM's foreground since they don't get
420 * tty process group and we don't save or restore tty modes.
422 j
->flags
= (flags
& XXCOM
) ? JF_XXCOM
:
423 ((flags
& XBGND
) ? 0 : (JF_FG
|JF_USETTYMODE
));
424 timerclear(&j
->usrtime
);
425 timerclear(&j
->systime
);
434 put_job(j
, PJ_PAST_STOPPED
);
437 snptreef(p
->command
, sizeof(p
->command
), "%T", t
);
439 /* create child process */
441 while ((i
= fork()) < 0 && errno
== EAGAIN
&& forksleep
< 32) {
442 if (intrsig
) /* allow user to ^C out... */
448 kill_job(j
, SIGKILL
);
449 remove_job(j
, "fork failed");
450 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
451 errorf("cannot fork - try again");
455 p
->pid
= procpid
= getpid();
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 /* YYY: should this be
472 if (ttypgrp_ok && ischild && !(flags&XBGND))
473 tcsetpgrp(tty_fd, j->pgrp);
474 instead? (see also YYY below)
476 if (ttypgrp_ok
&& dotty
&& !(flags
& XBGND
))
477 tcsetpgrp(tty_fd
, j
->pgrp
);
480 /* used to close pipe input fd */
481 if (close_fd
>= 0 && (((flags
& XPCLOSE
) && !ischild
) ||
482 ((flags
& XCCLOSE
) && ischild
)))
484 if (ischild
) { /* child */
485 /* Do this before restoring signal */
487 coproc_cleanup(false);
488 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
489 cleanup_parents_env();
490 /* If FMONITOR or FTALKING is set, these signals are ignored,
491 * if neither FMONITOR nor FTALKING are set, the signals have
492 * their inherited values.
494 if (Flag(FMONITOR
) && !(flags
& XXCOM
)) {
495 for (i
= NELEM(tt_sigs
); --i
>= 0; )
496 setsig(&sigtraps
[tt_sigs
[i
]], SIG_DFL
,
497 SS_RESTORE_DFL
|SS_FORCE
);
499 if (Flag(FBGNICE
) && (flags
& XBGND
))
501 if ((flags
& XBGND
) && !Flag(FMONITOR
)) {
502 setsig(&sigtraps
[SIGINT
], SIG_IGN
,
503 SS_RESTORE_IGN
|SS_FORCE
);
504 setsig(&sigtraps
[SIGQUIT
], SIG_IGN
,
505 SS_RESTORE_IGN
|SS_FORCE
);
506 if (!(flags
& (XPIPEI
| XCOPROC
))) {
507 int fd
= open("/dev/null", O_RDONLY
);
509 (void) ksh_dup2(fd
, 0, true);
514 remove_job(j
, "child"); /* in case of `jobs` command */
521 execute(t
, (flags
& XERROK
) | XEXEC
, NULL
); /* no return */
522 internal_warningf("%s: execute() returned", __func__
);
527 /* shell (parent) stuff */
528 /* Ensure next child gets a (slightly) different $RANDOM sequence */
530 if (!(flags
& XPIPEO
)) { /* last process in a job */
531 /* YYY: Is this needed? (see also YYY above)
532 if (Flag(FMONITOR) && !(flags&(XXCOM|XBGND)))
533 tcsetpgrp(tty_fd, j->pgrp);
536 if (flags
& XCOPROC
) {
537 j
->coproc_id
= coproc
.id
;
538 coproc
.njobs
++; /* n jobs using co-process output */
539 coproc
.job
= (void *) j
; /* j using co-process input */
543 if (Flag(FTALKING
)) {
544 shf_fprintf(shl_out
, "[%d]", j
->job
);
545 for (p
= j
->proc_list
; p
; p
= p
->next
)
546 shf_fprintf(shl_out
, " %d", p
->pid
);
547 shf_putchar('\n', shl_out
);
551 rv
= j_waitj(j
, JW_NONE
, "jw:last proc");
554 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
559 /* start the last job: only used for `command` jobs */
565 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
567 if (last_job
) { /* no need to report error - waitlast() will do it */
568 /* ensure it isn't removed by check_job() */
569 last_job
->flags
|= JF_WAITING
;
570 j_startjob(last_job
);
572 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
575 /* wait for last job: only used for `command` jobs */
583 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
586 if (!j
|| !(j
->flags
& JF_STARTED
)) {
588 warningf(true, "%s: no last job", __func__
);
590 internal_warningf("%s: not started", __func__
);
591 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
592 return 125; /* not so arbitrary, non-zero value */
595 rv
= j_waitj(j
, JW_NONE
, "jw:waitlast");
597 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
602 /* wait for child, interruptable. */
604 waitfor(const char *cp
, int *sigp
)
609 int flags
= JW_INTERRUPT
|JW_ASYNCNOTIFY
;
612 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
617 /* wait for an unspecified job - always returns 0, so
618 * don't have to worry about exited/signaled jobs
620 for (j
= job_list
; j
; j
= j
->next
)
621 /* at&t ksh will wait for stopped jobs - we don't */
622 if (j
->ppid
== procpid
&& j
->state
== PRUNNING
)
625 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
628 } else if ((j
= j_lookup(cp
, &ecode
))) {
629 /* don't report normal job completion */
630 flags
&= ~JW_ASYNCNOTIFY
;
631 if (j
->ppid
!= procpid
) {
632 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
636 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
637 if (ecode
!= JL_NOSUCH
)
638 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
642 /* at&t ksh will wait for stopped jobs - we don't */
643 rv
= j_waitj(j
, flags
, "jw:waitfor");
645 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
647 if (rv
< 0) /* we were interrupted */
653 /* kill (built-in) a job */
655 j_kill(const char *cp
, int sig
)
662 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
664 if ((j
= j_lookup(cp
, &ecode
)) == NULL
) {
665 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
666 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
670 if (j
->pgrp
== 0) { /* started when !Flag(FMONITOR) */
671 if (kill_job(j
, sig
) < 0) {
672 bi_errorf("%s: %s", cp
, strerror(errno
));
676 if (j
->state
== PSTOPPED
&& (sig
== SIGTERM
|| sig
== SIGHUP
))
677 (void) killpg(j
->pgrp
, SIGCONT
);
678 if (killpg(j
->pgrp
, sig
) < 0) {
679 bi_errorf("%s: %s", cp
, strerror(errno
));
684 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
689 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
691 j_resume(const char *cp
, int bg
)
700 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
702 if ((j
= j_lookup(cp
, &ecode
)) == NULL
) {
703 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
704 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
709 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
710 bi_errorf("job not job-controlled");
715 shprintf("[%d] ", j
->job
);
718 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
) {
719 if (p
->state
== PSTOPPED
) {
724 shprintf("%s%s", p
->command
, p
->next
? "| " : "");
727 shf_flush(shl_stdout
);
731 put_job(j
, PJ_PAST_STOPPED
);
735 /* attach tty to job */
736 if (j
->state
== PRUNNING
) {
737 if (ttypgrp_ok
&& (j
->flags
& JF_SAVEDTTY
))
738 tcsetattr(tty_fd
, TCSADRAIN
, &j
->ttystate
);
739 /* See comment in j_waitj regarding saved_ttypgrp. */
741 tcsetpgrp(tty_fd
, (j
->flags
& JF_SAVEDTTYPGRP
) ?
742 j
->saved_ttypgrp
: j
->pgrp
) < 0) {
743 if (j
->flags
& JF_SAVEDTTY
)
744 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
745 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
746 bi_errorf("1st tcsetpgrp(%d, %d) failed: %s",
748 (int) ((j
->flags
& JF_SAVEDTTYPGRP
) ?
749 j
->saved_ttypgrp
: j
->pgrp
),
755 j
->flags
&= ~JF_KNOWN
;
760 if (j
->state
== PRUNNING
&& killpg(j
->pgrp
, SIGCONT
) < 0) {
765 if (ttypgrp_ok
&& (j
->flags
& JF_SAVEDTTY
))
766 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
767 if (ttypgrp_ok
&& tcsetpgrp(tty_fd
, our_pgrp
) < 0) {
769 "fg: 2nd tcsetpgrp(%d, %d) failed: %s",
770 tty_fd
, (int) our_pgrp
,
774 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
775 bi_errorf("cannot continue job %s: %s",
781 j
->flags
&= ~(JF_SAVEDTTY
| JF_SAVEDTTYPGRP
);
783 rv
= j_waitj(j
, JW_NONE
, "jw:resume");
785 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
789 /* are there any running or stopped jobs ? */
791 j_stopped_running(void)
796 for (j
= job_list
; j
!= NULL
; j
= j
->next
) {
797 if (j
->ppid
== procpid
&& j
->state
== PSTOPPED
)
799 if (Flag(FLOGIN
) && !Flag(FNOHUP
) && procpid
== kshpid
&&
800 j
->ppid
== procpid
&& j
->state
== PRUNNING
)
804 shellf("You have %s%s%s jobs\n",
805 which
& 1 ? "stopped" : "",
806 which
== 3 ? " and " : "",
807 which
& 2 ? "running" : "");
821 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
822 for (j
= job_list
; j
; j
= j
->next
)
825 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
830 /* list jobs for jobs built-in */
832 j_jobs(const char *cp
, int slp
,
833 int nflag
) /* 0: short, 1: long, 2: pgrp */
840 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
842 if (nflag
< 0) { /* kludge: print zombies */
849 if ((j
= j_lookup(cp
, &ecode
)) == NULL
) {
850 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
851 bi_errorf("%s: %s", cp
, lookup_msgs
[ecode
]);
856 how
= slp
== 0 ? JP_MEDIUM
: (slp
== 1 ? JP_LONG
: JP_PGRP
);
857 for (; j
; j
= j
->next
) {
858 if ((!(j
->flags
& JF_ZOMBIE
) || zflag
) &&
859 (!nflag
|| (j
->flags
& JF_CHANGED
))) {
860 j_print(j
, how
, shl_stdout
);
861 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
)
862 j
->flags
|= JF_REMOVE
;
867 /* Remove jobs after printing so there won't be multiple + or - jobs */
868 for (j
= job_list
; j
; j
= tmp
) {
870 if (j
->flags
& JF_REMOVE
)
871 remove_job(j
, "jobs");
873 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
877 /* list jobs for top-level notification */
884 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
885 for (j
= job_list
; j
; j
= j
->next
) {
886 if (Flag(FMONITOR
) && (j
->flags
& JF_CHANGED
))
887 j_print(j
, JP_MEDIUM
, shl_out
);
888 /* Remove job after doing reports so there aren't
891 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
)
892 j
->flags
|= JF_REMOVE
;
894 for (j
= job_list
; j
; j
= tmp
) {
896 if (j
->flags
& JF_REMOVE
)
897 remove_job(j
, "notify");
900 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
903 /* Return pid of last process in last asynchronous job */
909 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
912 async_job
->flags
|= JF_KNOWN
;
914 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
919 /* Make j the last async process
921 * Expects sigchld to be blocked.
928 if (async_job
&& (async_job
->flags
& (JF_KNOWN
|JF_ZOMBIE
)) == JF_ZOMBIE
)
929 remove_job(async_job
, "async");
930 if (!(j
->flags
& JF_STARTED
)) {
931 internal_warningf("%s: job not started", __func__
);
935 async_pid
= j
->last_proc
->pid
;
936 while (nzombie
> child_max
) {
938 for (jl
= job_list
; jl
; jl
= jl
->next
)
939 if (jl
!= async_job
&& (jl
->flags
& JF_ZOMBIE
) &&
940 (!oldest
|| jl
->age
< oldest
->age
))
944 if (!(async_job
->flags
& JF_ZOMBIE
) || nzombie
!= 1) {
945 internal_warningf("%s: bad nzombie (%d)",
951 remove_job(oldest
, "zombie");
955 /* Start a job: set STARTED, check for held signals and set j->last_proc
957 * Expects sigchld to be blocked.
964 j
->flags
|= JF_STARTED
;
965 for (p
= j
->proc_list
; p
->next
; p
= p
->next
)
971 /* Don't call j_sigchld() as it may remove job... */
972 kill(procpid
, SIGCHLD
);
977 * wait for job to complete or change state
979 * Expects sigchld to be blocked.
983 int flags
, /* see JW_* */
989 * No auto-notify on the job we are waiting on.
991 j
->flags
|= JF_WAITING
;
992 if (flags
& JW_ASYNCNOTIFY
)
993 j
->flags
|= JF_W_ASYNCNOTIFY
;
996 flags
|= JW_STOPPEDWAIT
;
998 while ((volatile int) j
->state
== PRUNNING
||
999 ((flags
& JW_STOPPEDWAIT
) && (volatile int) j
->state
== PSTOPPED
)) {
1000 sigsuspend(&sm_default
);
1002 int oldf
= j
->flags
& (JF_WAITING
|JF_W_ASYNCNOTIFY
);
1003 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
1005 j
->flags
|= oldf
; /* not reached... */
1007 if ((flags
& JW_INTERRUPT
) && (rv
= trap_pending())) {
1008 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
1012 j
->flags
&= ~(JF_WAITING
|JF_W_ASYNCNOTIFY
);
1014 if (j
->flags
& JF_FG
) {
1018 if (Flag(FMONITOR
) && ttypgrp_ok
&& j
->pgrp
) {
1020 * Save the tty's current pgrp so it can be restored
1021 * when the job is foregrounded. This is to
1022 * deal with things like the GNU su which does
1023 * a fork/exec instead of an exec (the fork means
1024 * the execed shell gets a different pid from its
1025 * pgrp, so naturally it sets its pgrp and gets hosed
1026 * when it gets foregrounded by the parent shell, which
1027 * has restored the tty's pgrp to that of the su
1030 if (j
->state
== PSTOPPED
&&
1031 (j
->saved_ttypgrp
= tcgetpgrp(tty_fd
)) >= 0)
1032 j
->flags
|= JF_SAVEDTTYPGRP
;
1033 if (tcsetpgrp(tty_fd
, our_pgrp
) < 0) {
1035 "%s: tcsetpgrp(%d, %d) failed: %s",
1036 __func__
, tty_fd
, (int)our_pgrp
,
1039 if (j
->state
== PSTOPPED
) {
1040 j
->flags
|= JF_SAVEDTTY
;
1041 tcgetattr(tty_fd
, &j
->ttystate
);
1045 /* Only restore tty settings if job was originally
1046 * started in the foreground. Problems can be
1047 * caused by things like `more foobar &' which will
1048 * typically get and save the shell's vi/emacs tty
1049 * settings before setting up the tty for itself;
1050 * when more exits, it restores the `original'
1051 * settings, and things go down hill from there...
1053 if (j
->state
== PEXITED
&& j
->status
== 0 &&
1054 (j
->flags
& JF_USETTYMODE
)) {
1055 tcgetattr(tty_fd
, &tty_state
);
1057 tcsetattr(tty_fd
, TCSADRAIN
, &tty_state
);
1058 /* Don't use tty mode if job is stopped and
1059 * later restarted and exits. Consider
1066 * mode should be that of the stty, not what
1067 * was before the vi started.
1069 if (j
->state
== PSTOPPED
)
1070 j
->flags
&= ~JF_USETTYMODE
;
1073 /* If it looks like user hit ^C to kill a job, pretend we got
1074 * one too to break out of for loops, etc. (at&t ksh does this
1075 * even when not monitoring, but this doesn't make sense since
1076 * a tty generated ^C goes to the whole process group)
1078 status
= j
->last_proc
->status
;
1079 if (Flag(FMONITOR
) && j
->state
== PSIGNALLED
&&
1080 WIFSIGNALED(status
) &&
1081 (sigtraps
[WTERMSIG(status
)].flags
& TF_TTY_INTR
))
1082 trapsig(WTERMSIG(status
));
1085 j_usrtime
= j
->usrtime
;
1086 j_systime
= j
->systime
;
1089 if (!(flags
& JW_ASYNCNOTIFY
) &&
1090 (!Flag(FMONITOR
) || j
->state
!= PSTOPPED
)) {
1091 j_print(j
, JP_SHORT
, shl_out
);
1094 if (j
->state
!= PSTOPPED
&&
1095 (!Flag(FMONITOR
) || !(flags
& JW_ASYNCNOTIFY
)))
1096 remove_job(j
, where
);
1101 /* SIGCHLD handler to reap children and update job states
1103 * Expects sigchld to be blocked.
1113 struct rusage ru0
, ru1
;
1115 /* Don't wait for any processes if a job is partially started.
1116 * This is so we don't do away with the process group leader
1117 * before all the processes in a pipe line are started (so the
1118 * setpgid() won't fail)
1120 for (j
= job_list
; j
; j
= j
->next
)
1121 if (j
->ppid
== procpid
&& !(j
->flags
& JF_STARTED
)) {
1126 getrusage(RUSAGE_CHILDREN
, &ru0
);
1128 pid
= waitpid(-1, &status
, (WNOHANG
|WUNTRACED
));
1130 if (pid
<= 0) /* return if would block (0) ... */
1131 break; /* ... or no children or interrupted (-1) */
1133 getrusage(RUSAGE_CHILDREN
, &ru1
);
1135 /* find job and process structures for this pid */
1136 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1137 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
)
1142 /* Can occur if process has kids, then execs shell
1143 warningf(true, "bad process waited for (pid = %d)",
1150 timeradd(&j
->usrtime
, &ru1
.ru_utime
, &j
->usrtime
);
1151 timersub(&j
->usrtime
, &ru0
.ru_utime
, &j
->usrtime
);
1152 timeradd(&j
->systime
, &ru1
.ru_stime
, &j
->systime
);
1153 timersub(&j
->systime
, &ru0
.ru_stime
, &j
->systime
);
1156 if (WIFSTOPPED(status
))
1157 p
->state
= PSTOPPED
;
1158 else if (WIFSIGNALED(status
))
1159 p
->state
= PSIGNALLED
;
1163 check_job(j
); /* check to see if entire job is done */
1171 * Called only when a process in j has exited/stopped (ie, called only
1172 * from j_sigchld()). If no processes are running, the job status
1173 * and state are updated, asynchronous job notification is done and,
1174 * if unneeded, the job is removed.
1176 * Expects sigchld to be blocked.
1184 /* XXX debugging (nasty - interrupt routine using shl_out) */
1185 if (!(j
->flags
& JF_STARTED
)) {
1186 internal_warningf("%s: job started (flags 0x%x)",
1187 __func__
, j
->flags
);
1192 for (p
=j
->proc_list
; p
!= NULL
; p
= p
->next
) {
1193 if (p
->state
== PRUNNING
)
1194 return; /* some processes still running */
1195 if (p
->state
> jstate
)
1200 switch (j
->last_proc
->state
) {
1202 j
->status
= WEXITSTATUS(j
->last_proc
->status
);
1205 j
->status
= 128 + WTERMSIG(j
->last_proc
->status
);
1212 /* Note when co-process dies: can't be done in j_wait() nor
1213 * remove_job() since neither may be called for non-interactive
1216 if (j
->state
== PEXITED
|| j
->state
== PSIGNALLED
) {
1217 /* No need to keep co-process input any more
1218 * (at least, this is what ksh93d thinks)
1220 if (coproc
.job
== j
) {
1222 /* XXX would be nice to get the closes out of here
1223 * so they aren't done in the signal handler.
1224 * Would mean a check in coproc_getfd() to
1225 * do "if job == 0 && write >= 0, close write".
1227 coproc_write_close(coproc
.write
);
1229 /* Do we need to keep the output? */
1230 if (j
->coproc_id
&& j
->coproc_id
== coproc
.id
&&
1231 --coproc
.njobs
== 0)
1232 coproc_readw_close(coproc
.read
);
1235 j
->flags
|= JF_CHANGED
;
1236 if (Flag(FMONITOR
) && !(j
->flags
& JF_XXCOM
)) {
1237 /* Only put stopped jobs at the front to avoid confusing
1238 * the user (don't want finished jobs effecting %+ or %-)
1240 if (j
->state
== PSTOPPED
)
1241 put_job(j
, PJ_ON_FRONT
);
1242 if (Flag(FNOTIFY
) &&
1243 (j
->flags
& (JF_WAITING
|JF_W_ASYNCNOTIFY
)) != JF_WAITING
) {
1244 /* Look for the real file descriptor 2 */
1249 for (ep
= genv
; ep
; ep
= ep
->oenv
)
1250 if (ep
->savefd
&& ep
->savefd
[2])
1252 shf_reopen(fd
, SHF_WR
, shl_j
);
1254 /* Can't call j_notify() as it removes jobs. The job
1255 * must stay in the job list as j_waitj() may be
1256 * running with this job.
1258 j_print(j
, JP_MEDIUM
, shl_j
);
1260 if (!(j
->flags
& JF_WAITING
) && j
->state
!= PSTOPPED
)
1261 remove_job(j
, "notify");
1264 if (!Flag(FMONITOR
) && !(j
->flags
& (JF_WAITING
|JF_FG
)) &&
1265 j
->state
!= PSTOPPED
) {
1266 if (j
== async_job
|| (j
->flags
& JF_KNOWN
)) {
1267 j
->flags
|= JF_ZOMBIE
;
1271 remove_job(j
, "checkjob");
1276 * Print job status in either short, medium or long format.
1278 * Expects sigchld to be blocked.
1281 j_print(Job
*j
, int how
, struct shf
*shf
)
1292 if (how
== JP_PGRP
) {
1293 /* POSIX doesn't say what to do if there is no process
1294 * group leader (ie, !FMONITOR). We arbitrarily return
1295 * last pid (which is what $! returns).
1297 shf_fprintf(shf
, "%d\n", j
->pgrp
? j
->pgrp
:
1298 (j
->last_proc
? j
->last_proc
->pid
: 0));
1301 j
->flags
&= ~JF_CHANGED
;
1302 filler
= j
->job
> 10 ? "\n " : "\n ";
1305 else if (j
== job_list
->next
)
1308 for (p
= j
->proc_list
; p
!= NULL
;) {
1312 strlcpy(buf
, "Running", sizeof buf
);
1315 strlcpy(buf
, sigtraps
[WSTOPSIG(p
->status
)].mess
,
1319 if (how
== JP_SHORT
)
1321 else if (WEXITSTATUS(p
->status
) == 0)
1322 strlcpy(buf
, "Done", sizeof buf
);
1324 shf_snprintf(buf
, sizeof(buf
), "Done (%d)",
1325 WEXITSTATUS(p
->status
));
1328 if (WCOREDUMP(p
->status
))
1330 /* kludge for not reporting `normal termination signals'
1331 * (ie, SIGINT, SIGPIPE)
1333 if (how
== JP_SHORT
&& !coredumped
&&
1334 (WTERMSIG(p
->status
) == SIGINT
||
1335 WTERMSIG(p
->status
) == SIGPIPE
)) {
1338 strlcpy(buf
, sigtraps
[WTERMSIG(p
->status
)].mess
,
1343 if (how
!= JP_SHORT
) {
1344 if (p
== j
->proc_list
)
1345 shf_fprintf(shf
, "[%d] %c ", j
->job
, jobchar
);
1347 shf_fprintf(shf
, "%s", filler
);
1351 shf_fprintf(shf
, "%5d ", p
->pid
);
1353 if (how
== JP_SHORT
) {
1356 shf_fprintf(shf
, "%s%s ",
1357 buf
, coredumped
? " (core dumped)" : "");
1361 shf_fprintf(shf
, "%-20s %s%s%s", buf
, p
->command
,
1363 coredumped
? " (core dumped)" : "");
1369 while (p
&& p
->state
== state
&& p
->status
== status
) {
1371 shf_fprintf(shf
, "%s%5d %-20s %s%s", filler
, p
->pid
,
1372 " ", p
->command
, p
->next
? "|" : "");
1373 else if (how
== JP_MEDIUM
)
1374 shf_fprintf(shf
, " %s%s", p
->command
,
1375 p
->next
? "|" : "");
1380 shf_fprintf(shf
, "\n");
1383 /* Convert % sequence to job
1385 * Expects sigchld to be blocked.
1388 j_lookup(const char *cp
, int *ecodep
)
1390 Job
*j
, *last_match
;
1396 job
= strtonum(cp
, 1, INT_MAX
, &errstr
);
1399 *ecodep
= JL_NOSUCH
;
1402 /* Look for last_proc->pid (what $! returns) first... */
1403 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1404 if (j
->last_proc
&& j
->last_proc
->pid
== job
)
1406 /* ...then look for process group (this is non-POSIX),
1407 * but should not break anything (so FPOSIX isn't used).
1409 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1410 if (j
->pgrp
&& j
->pgrp
== job
)
1413 *ecodep
= JL_NOSUCH
;
1418 *ecodep
= JL_INVALID
;
1422 case '\0': /* non-standard */
1425 if (job_list
!= NULL
)
1430 if (job_list
!= NULL
&& job_list
->next
)
1431 return job_list
->next
;
1434 case '0': case '1': case '2': case '3': case '4':
1435 case '5': case '6': case '7': case '8': case '9':
1436 job
= strtonum(cp
, 1, INT_MAX
, &errstr
);
1439 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1444 case '?': /* %?string */
1446 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1447 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
)
1448 if (strstr(p
->command
, cp
+1) != NULL
) {
1460 default: /* %string */
1463 for (j
= job_list
; j
!= NULL
; j
= j
->next
)
1464 if (strncmp(cp
, j
->proc_list
->command
, len
) == 0) {
1477 *ecodep
= JL_NOSUCH
;
1481 static Job
*free_jobs
;
1482 static Proc
*free_procs
;
1484 /* allocate a new job and fill in the job number.
1486 * Expects sigchld to be blocked.
1494 if (free_jobs
!= NULL
) {
1496 free_jobs
= free_jobs
->next
;
1498 newj
= alloc(sizeof(Job
), APERM
);
1500 /* brute force method */
1501 for (i
= 1; ; i
++) {
1502 for (j
= job_list
; j
&& j
->job
!= i
; j
= j
->next
)
1512 /* Allocate new process struct
1514 * Expects sigchld to be blocked.
1521 if (free_procs
!= NULL
) {
1523 free_procs
= free_procs
->next
;
1525 p
= alloc(sizeof(Proc
), APERM
);
1530 /* Take job out of job_list and put old structures into free list.
1531 * Keeps nzombies, last_job and async_job up to date.
1533 * Expects sigchld to be blocked.
1536 remove_job(Job
*j
, const char *where
)
1543 for (; curr
!= NULL
&& curr
!= j
; prev
= &curr
->next
, curr
= *prev
)
1546 internal_warningf("%s: job not found (%s)", __func__
, where
);
1551 /* free up proc structures */
1552 for (p
= j
->proc_list
; p
!= NULL
; ) {
1555 tmp
->next
= free_procs
;
1559 if ((j
->flags
& JF_ZOMBIE
) && j
->ppid
== procpid
)
1561 j
->next
= free_jobs
;
1570 /* Put j in a particular location (taking it out of job_list if it is
1573 * Expects sigchld to be blocked.
1576 put_job(Job
*j
, int where
)
1580 /* Remove job from list (if there) */
1583 for (; curr
&& curr
!= j
; prev
= &curr
->next
, curr
= *prev
)
1594 case PJ_PAST_STOPPED
:
1597 for (; curr
&& curr
->state
== PSTOPPED
; prev
= &curr
->next
,
1606 /* nuke a job (called when unable to start full job).
1608 * Expects sigchld to be blocked.
1611 kill_job(Job
*j
, int sig
)
1616 for (p
= j
->proc_list
; p
!= NULL
; p
= p
->next
)
1618 if (kill(p
->pid
, sig
) < 0)