1 /* $OpenBSD: jobs.c,v 1.43 2015/09/10 22:48:58 nicm Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
5 * 2012, 2013, 2014, 2015, 2016
6 * mirabilos <m@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
26 __RCSID("$MirOS: src/bin/mksh/jobs.c,v 1.121 2016/07/25 00:04:44 tg Exp $");
29 #define mksh_killpg killpg
31 /* cross fingers and hope kill is killpg-endowed */
32 #define mksh_killpg(p,s) kill(-(p), (s))
35 /* Order important! */
41 typedef struct proc Proc;
43 Proc *next; /* next process in pipeline (if any) */
44 pid_t pid; /* process id */
46 int status; /* wait status */
47 /* process command string from vistree */
48 char command[256 - (ALLOC_OVERHEAD + sizeof(Proc *) +
49 sizeof(pid_t) + 2 * sizeof(int))];
52 /* Notify/print flag - j_print() argument */
53 #define JP_SHORT 1 /* print signals processes were killed by */
54 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
55 #define JP_LONG 3 /* print [job-num] -/+ pid command */
56 #define JP_PGRP 4 /* print pgrp */
59 #define PJ_ON_FRONT 0 /* at very front */
60 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
62 /* Job.flags values */
63 #define JF_STARTED 0x001 /* set when all processes in job are started */
64 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
65 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
66 #define JF_XXCOM 0x008 /* set for $(command) jobs */
67 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
68 #define JF_SAVEDTTY 0x020 /* j->ttystat is valid */
69 #define JF_CHANGED 0x040 /* process has changed state */
70 #define JF_KNOWN 0x080 /* $! referenced */
71 #define JF_ZOMBIE 0x100 /* known, unwaited process */
72 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_noityf()) */
73 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
74 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
76 typedef struct job Job;
78 Job *next; /* next job in list */
79 Proc *proc_list; /* process list */
80 Proc *last_proc; /* last process in list */
81 struct timeval systime; /* system time used by job */
82 struct timeval usrtime; /* user time used by job */
83 pid_t pgrp; /* process group of job */
84 pid_t ppid; /* pid of process that forked job */
85 int job; /* job number: %n */
86 int flags; /* see JF_* */
87 volatile int state; /* job state */
88 int status; /* exit status of last process */
89 int age; /* number of jobs started */
90 Coproc_id coproc_id; /* 0 or id of coprocess output pipe */
91 #ifndef MKSH_UNEMPLOYED
92 mksh_ttyst ttystat; /* saved tty state for stopped jobs */
93 pid_t saved_ttypgrp; /* saved tty process group for stopped jobs */
97 /* Flags for j_waitj() */
99 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
100 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
101 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
102 #define JW_PIPEST 0x08 /* want PIPESTATUS */
104 /* Error codes for j_lookup() */
105 #define JL_NOSUCH 0 /* no such job */
106 #define JL_AMBIG 1 /* %foo or %?foo is ambiguous */
107 #define JL_INVALID 2 /* non-pid, non-% job id */
109 static const char * const lookup_msgs[] = {
112 "argument must be %job or process id"
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 static int njobs; /* # of jobs started */
127 #ifndef MKSH_NOPROSPECTOFWORK
128 /* held_sigchld is set if sigchld occurs before a job is completely started */
129 static volatile sig_atomic_t held_sigchld;
132 #ifndef MKSH_UNEMPLOYED
133 static struct shf *shl_j;
134 static bool ttypgrp_ok; /* set if can use tty pgrps */
135 static pid_t restore_ttypgrp = -1;
136 static int const tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
139 static void j_set_async(Job *);
140 static void j_startjob(Job *);
141 static int j_waitj(Job *, int, const char *);
142 static void j_sigchld(int);
143 static void j_print(Job *, int, struct shf *);
144 static Job *j_lookup(const char *, int *);
145 static Job *new_job(void);
146 static Proc *new_proc(void);
147 static void check_job(Job *);
148 static void put_job(Job *, int);
149 static void remove_job(Job *, const char *);
150 static int kill_job(Job *, int);
152 static void tty_init_talking(void);
153 static void tty_init_state(void);
155 /* initialise job control */
159 #ifndef MKSH_UNEMPLOYED
160 bool mflagset = Flag(FMONITOR) != 127;
165 #ifndef MKSH_NOPROSPECTOFWORK
166 (void)sigemptyset(&sm_default);
167 sigprocmask(SIG_SETMASK, &sm_default, NULL);
169 (void)sigemptyset(&sm_sigchld);
170 (void)sigaddset(&sm_sigchld, SIGCHLD);
172 setsig(&sigtraps[SIGCHLD], j_sigchld,
173 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
175 /* Make sure SIGCHLD isn't ignored - can do odd things under SYSV */
176 setsig(&sigtraps[SIGCHLD], SIG_DFL, SS_RESTORE_ORIG|SS_FORCE);
179 #ifndef MKSH_UNEMPLOYED
180 if (!mflagset && Flag(FTALKING))
184 * shl_j is used to do asynchronous notification (used in
185 * an interrupt handler, so need a distinct shf)
187 shl_j = shf_fdopen(2, SHF_WR, NULL);
189 if (Flag(FMONITOR) || Flag(FTALKING)) {
193 * the TF_SHELL_USES test is a kludge that lets us know if
194 * if the signals have been changed by the shell.
196 for (i = NELEM(tt_sigs); --i >= 0; ) {
197 sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
198 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
199 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
200 SS_RESTORE_IGN|SS_FORCE);
204 /* j_change() calls tty_init_talking() and tty_init_state() */
209 if (Flag(FTALKING)) {
216 proc_errorlevel(Proc *p)
220 return ((WEXITSTATUS(p->status)) & 255);
222 return (ksh_sigmask(WTERMSIG(p->status)));
228 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
229 /* suspend the shell */
233 struct sigaction sa, osa;
235 /* Restore tty and pgrp. */
238 mksh_tcset(tty_fd, &tty_state);
239 if (restore_ttypgrp >= 0) {
240 if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
241 warningf(false, Tf_ssfaileds,
242 Tj_suspend, "tcsetpgrp", cstrerror(errno));
243 } else if (setpgid(0, restore_ttypgrp) < 0) {
244 warningf(false, Tf_ssfaileds,
245 Tj_suspend, "setpgid", cstrerror(errno));
250 /* Suspend the shell. */
251 memset(&sa, 0, sizeof(sa));
252 sigemptyset(&sa.sa_mask);
253 sa.sa_handler = SIG_DFL;
254 sigaction(SIGTSTP, &sa, &osa);
257 /* Back from suspend, reset signals, pgrp and tty. */
258 sigaction(SIGTSTP, &osa, NULL);
260 if (restore_ttypgrp >= 0) {
261 if (setpgid(0, kshpid) < 0) {
262 warningf(false, Tf_ssfaileds,
263 Tj_suspend, "setpgid", cstrerror(errno));
265 } else if (tcsetpgrp(tty_fd, kshpid) < 0) {
266 warningf(false, Tf_ssfaileds,
267 Tj_suspend, "tcsetpgrp", cstrerror(errno));
276 /* job cleanup before shell exit */
280 /* kill stopped, and possibly running, jobs */
284 for (j = job_list; j != NULL; j = j->next) {
285 if (j->ppid == procpid &&
286 (j->state == PSTOPPED ||
287 (j->state == PRUNNING &&
288 ((j->flags & JF_FG) ||
289 (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
294 mksh_killpg(j->pgrp, SIGHUP);
295 #ifndef MKSH_UNEMPLOYED
296 if (j->state == PSTOPPED) {
298 kill_job(j, SIGCONT);
300 mksh_killpg(j->pgrp, SIGCONT);
309 #ifndef MKSH_UNEMPLOYED
310 if (kshpid == procpid && restore_ttypgrp >= 0) {
312 * Need to restore the tty pgrp to what it was when the
313 * shell started up, so that the process that started us
314 * will be able to access the tty when we are done.
315 * Also need to restore our process group in case we are
316 * about to do an exec so that both our parent and the
317 * process we are to become will be able to access the tty.
319 tcsetpgrp(tty_fd, restore_ttypgrp);
320 setpgid(0, restore_ttypgrp);
322 if (Flag(FMONITOR)) {
329 #ifndef MKSH_UNEMPLOYED
330 /* turn job control on or off according to Flag(FMONITOR) */
336 if (Flag(FMONITOR)) {
337 bool use_tty = Flag(FTALKING);
339 /* don't call mksh_tcget until we own the tty process group */
343 /* no controlling tty, no SIGT* */
344 if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
345 setsig(&sigtraps[SIGTTIN], SIG_DFL,
346 SS_RESTORE_ORIG|SS_FORCE);
347 /* wait to be given tty (POSIX.1, B.2, job control) */
348 while (/* CONSTCOND */ 1) {
351 if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
352 warningf(false, Tf_ssfaileds,
353 "j_init", "tcgetpgrp",
358 if (ttypgrp == kshpgrp)
363 for (i = NELEM(tt_sigs); --i >= 0; )
364 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
365 SS_RESTORE_DFL|SS_FORCE);
366 if (ttypgrp_ok && kshpgrp != kshpid) {
367 if (setpgid(0, kshpid) < 0) {
368 warningf(false, Tf_ssfaileds,
369 "j_init", "setpgid", cstrerror(errno));
372 if (tcsetpgrp(tty_fd, kshpid) < 0) {
373 warningf(false, Tf_ssfaileds,
374 "j_init", "tcsetpgrp",
378 restore_ttypgrp = kshpgrp;
382 #ifndef MKSH_DISABLE_TTY_WARNING
383 if (use_tty && !ttypgrp_ok)
384 warningf(false, Tf_sD_s, "warning",
385 "won't have full job control");
390 for (i = NELEM(tt_sigs); --i >= 0; )
391 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
392 SS_RESTORE_IGN|SS_FORCE);
394 for (i = NELEM(tt_sigs); --i >= 0; ) {
395 if (sigtraps[tt_sigs[i]].flags &
396 (TF_ORIG_IGN | TF_ORIG_DFL))
397 setsig(&sigtraps[tt_sigs[i]],
398 (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
400 SS_RESTORE_ORIG|SS_FORCE);
408 /* run nice(3) and ignore the result */
412 #if defined(__USE_FORTIFY_LEVEL) && (__USE_FORTIFY_LEVEL > 0)
416 /* this is gonna annoy users; complain to your distro, people! */
417 if (nice(ness) == -1 && (eno = errno) != 0)
418 warningf(false, Tf_sD_s, "bgnice", cstrerror(eno));
425 /* execute tree in child subprocess */
427 exchild(struct op *t, int flags,
428 volatile int *xerrok,
429 /* used if XPCLOSE or XCCLOSE */
433 static Proc *last_proc;
435 int rv = 0, forksleep, jwflags = JW_NONE;
436 #ifndef MKSH_NOPROSPECTOFWORK
443 if (flags & XPIPEST) {
445 jwflags |= JW_PIPEST;
450 * Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
451 * (also done in another execute() below)
453 return (execute(t, flags & (XEXEC | XERROK), xerrok));
455 #ifndef MKSH_NOPROSPECTOFWORK
456 /* no SIGCHLDs while messing with job and process lists */
457 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
466 /* link process into jobs list */
467 if (flags & XPIPEI) {
468 /* continuing with a pipe */
470 internal_errorf("exchild: XPIPEI and no last_job - pid %d",
477 /* fills in j->job */
480 * we don't consider XXCOMs foreground since they don't get
481 * tty process group and we don't save or restore tty modes.
483 j->flags = (flags & XXCOM) ? JF_XXCOM :
484 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
485 timerclear(&j->usrtime);
486 timerclear(&j->systime);
495 put_job(j, PJ_PAST_STOPPED);
498 vistree(p->command, sizeof(p->command), t);
500 /* create child process */
502 while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
504 /* allow user to ^C out... */
509 /* ensure $RANDOM changes between parent and child */
510 rndset((unsigned long)cldpid);
513 kill_job(j, SIGKILL);
514 remove_job(j, "fork failed");
515 #ifndef MKSH_NOPROSPECTOFWORK
516 sigprocmask(SIG_SETMASK, &omask, NULL);
518 errorf("can't fork - try again");
520 p->pid = cldpid ? cldpid : (procpid = getpid());
522 #ifndef MKSH_UNEMPLOYED
523 /* job control set up */
524 if (Flag(FMONITOR) && !(flags&XXCOM)) {
534 * set pgrp in both parent and child to deal with race
537 setpgid(p->pid, j->pgrp);
538 if (ttypgrp_ok && dotty && !(flags & XBGND))
539 tcsetpgrp(tty_fd, j->pgrp);
543 /* used to close pipe input fd */
544 if (close_fd >= 0 && (((flags & XPCLOSE) && cldpid) ||
545 ((flags & XCCLOSE) && !cldpid)))
550 /* Do this before restoring signal */
552 coproc_cleanup(false);
553 cleanup_parents_env();
554 #ifndef MKSH_UNEMPLOYED
556 * If FMONITOR or FTALKING is set, these signals are ignored,
557 * if neither FMONITOR nor FTALKING are set, the signals have
558 * their inherited values.
560 if (Flag(FMONITOR) && !(flags & XXCOM)) {
561 for (forksleep = NELEM(tt_sigs); --forksleep >= 0; )
562 setsig(&sigtraps[tt_sigs[forksleep]], SIG_DFL,
563 SS_RESTORE_DFL|SS_FORCE);
567 if (Flag(FBGNICE) && (flags & XBGND))
571 #ifndef MKSH_UNEMPLOYED
575 setsig(&sigtraps[SIGINT], SIG_IGN,
576 SS_RESTORE_IGN|SS_FORCE);
577 setsig(&sigtraps[SIGQUIT], SIG_IGN,
578 SS_RESTORE_IGN|SS_FORCE);
579 if ((!(flags & (XPIPEI | XCOPROC))) &&
580 ((forksleep = open("/dev/null", 0)) > 0)) {
581 (void)ksh_dup2(forksleep, 0, true);
585 /* in case of $(jobs) command */
586 remove_job(j, "child");
587 #ifndef MKSH_NOPROSPECTOFWORK
588 /* remove_job needs SIGCHLD blocked still */
589 sigprocmask(SIG_SETMASK, &omask, NULL);
592 #ifndef MKSH_UNEMPLOYED
599 execute(t, (flags & XERROK) | XEXEC, NULL);
601 if (t->type == TPIPE)
603 internal_warningf("%s: execute() returned", "exchild");
604 fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
612 /* shell (parent) stuff */
613 if (!(flags & XPIPEO)) {
614 /* last process in a job */
616 if (flags & XCOPROC) {
617 j->coproc_id = coproc.id;
618 /* n jobs using co-process output */
620 /* j using co-process input */
621 coproc.job = (void *)j;
625 if (Flag(FTALKING)) {
626 shf_fprintf(shl_out, "[%d]", j->job);
627 for (p = j->proc_list; p; p = p->next)
628 shf_fprintf(shl_out, Tf__d,
630 shf_putchar('\n', shl_out);
634 rv = j_waitj(j, jwflags, "jw:last proc");
637 #ifndef MKSH_NOPROSPECTOFWORK
638 sigprocmask(SIG_SETMASK, &omask, NULL);
644 /* start the last job: only used for $(command) jobs */
648 #ifndef MKSH_NOPROSPECTOFWORK
651 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
654 /* no need to report error - waitlast() will do it */
656 /* ensure it isn't removed by check_job() */
657 last_job->flags |= JF_WAITING;
658 j_startjob(last_job);
660 #ifndef MKSH_NOPROSPECTOFWORK
661 sigprocmask(SIG_SETMASK, &omask, NULL);
665 /* wait for last job: only used for $(command) jobs */
671 #ifndef MKSH_NOPROSPECTOFWORK
674 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
678 if (!j || !(j->flags & JF_STARTED)) {
680 warningf(true, Tf_sD_s, "waitlast", "no last job");
682 internal_warningf(Tf_sD_s, "waitlast", Tnot_started);
683 #ifndef MKSH_NOPROSPECTOFWORK
684 sigprocmask(SIG_SETMASK, &omask, NULL);
686 /* not so arbitrary, non-zero value */
690 rv = j_waitj(j, JW_NONE, "waitlast");
692 #ifndef MKSH_NOPROSPECTOFWORK
693 sigprocmask(SIG_SETMASK, &omask, NULL);
699 /* wait for child, interruptable. */
701 waitfor(const char *cp, int *sigp)
703 int rv, ecode, flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
705 #ifndef MKSH_NOPROSPECTOFWORK
708 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
715 * wait for an unspecified job - always returns 0, so
716 * don't have to worry about exited/signaled jobs
718 for (j = job_list; j; j = j->next)
719 /* AT&T ksh will wait for stopped jobs - we don't */
720 if (j->ppid == procpid && j->state == PRUNNING)
723 #ifndef MKSH_NOPROSPECTOFWORK
724 sigprocmask(SIG_SETMASK, &omask, NULL);
728 } else if ((j = j_lookup(cp, &ecode))) {
729 /* don't report normal job completion */
730 flags &= ~JW_ASYNCNOTIFY;
731 if (j->ppid != procpid) {
732 #ifndef MKSH_NOPROSPECTOFWORK
733 sigprocmask(SIG_SETMASK, &omask, NULL);
738 #ifndef MKSH_NOPROSPECTOFWORK
739 sigprocmask(SIG_SETMASK, &omask, NULL);
741 if (ecode != JL_NOSUCH)
742 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
746 /* AT&T ksh will wait for stopped jobs - we don't */
747 rv = j_waitj(j, flags, "jw:waitfor");
749 #ifndef MKSH_NOPROSPECTOFWORK
750 sigprocmask(SIG_SETMASK, &omask, NULL);
754 /* we were interrupted */
755 *sigp = ksh_sigmask(-rv);
760 /* kill (built-in) a job */
762 j_kill(const char *cp, int sig)
766 #ifndef MKSH_NOPROSPECTOFWORK
769 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
772 if ((j = j_lookup(cp, &ecode)) == NULL) {
773 #ifndef MKSH_NOPROSPECTOFWORK
774 sigprocmask(SIG_SETMASK, &omask, NULL);
776 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
781 /* started when !Flag(FMONITOR) */
782 if (kill_job(j, sig) < 0) {
783 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
787 #ifndef MKSH_UNEMPLOYED
788 if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
789 mksh_killpg(j->pgrp, SIGCONT);
791 if (mksh_killpg(j->pgrp, sig) < 0) {
792 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
797 #ifndef MKSH_NOPROSPECTOFWORK
798 sigprocmask(SIG_SETMASK, &omask, NULL);
804 #ifndef MKSH_UNEMPLOYED
805 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
807 j_resume(const char *cp, int bg)
815 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
817 if ((j = j_lookup(cp, &ecode)) == NULL) {
818 sigprocmask(SIG_SETMASK, &omask, NULL);
819 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
824 sigprocmask(SIG_SETMASK, &omask, NULL);
825 bi_errorf("job not job-controlled");
830 shprintf("[%d] ", j->job);
833 for (p = j->proc_list; p != NULL; p = p->next) {
834 if (p->state == PSTOPPED) {
839 shf_puts(p->command, shl_stdout);
841 shf_puts("| ", shl_stdout);
843 shf_putc('\n', shl_stdout);
844 shf_flush(shl_stdout);
848 put_job(j, PJ_PAST_STOPPED);
852 /* attach tty to job */
853 if (j->state == PRUNNING) {
854 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
855 mksh_tcset(tty_fd, &j->ttystat);
856 /* See comment in j_waitj regarding saved_ttypgrp. */
858 tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
859 j->saved_ttypgrp : j->pgrp) < 0) {
861 if (j->flags & JF_SAVEDTTY)
862 mksh_tcset(tty_fd, &tty_state);
863 sigprocmask(SIG_SETMASK, &omask, NULL);
864 bi_errorf(Tf_ldfailed,
865 "fg: 1st", "tcsetpgrp", tty_fd,
866 (long)((j->flags & JF_SAVEDTTYPGRP) ?
867 j->saved_ttypgrp : j->pgrp),
873 j->flags &= ~JF_KNOWN;
878 if (j->state == PRUNNING && mksh_killpg(j->pgrp, SIGCONT) < 0) {
883 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
884 mksh_tcset(tty_fd, &tty_state);
885 if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
886 warningf(true, Tf_ldfailed,
887 "fg: 2nd", "tcsetpgrp", tty_fd,
888 (long)kshpgrp, cstrerror(errno));
890 sigprocmask(SIG_SETMASK, &omask, NULL);
891 bi_errorf(Tf_s_sD_s, "can't continue job",
897 j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
899 rv = j_waitj(j, JW_NONE, "jw:resume");
901 sigprocmask(SIG_SETMASK, &omask, NULL);
906 /* are there any running or stopped jobs ? */
908 j_stopped_running(void)
913 for (j = job_list; j != NULL; j = j->next) {
914 #ifndef MKSH_UNEMPLOYED
915 if (j->ppid == procpid && j->state == PSTOPPED)
918 if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
919 j->ppid == procpid && j->state == PRUNNING)
923 shellf("You have %s%s%s jobs\n",
924 which & 1 ? "stopped" : "",
925 which == 3 ? " and " : "",
926 which & 2 ? "running" : "");
934 /* list jobs for jobs built-in */
936 j_jobs(const char *cp, int slp,
937 /* 0: short, 1: long, 2: pgrp */
942 #ifndef MKSH_NOPROSPECTOFWORK
945 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
949 /* kludge: print zombies */
956 if ((j = j_lookup(cp, &ecode)) == NULL) {
957 #ifndef MKSH_NOPROSPECTOFWORK
958 sigprocmask(SIG_SETMASK, &omask, NULL);
960 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
965 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
966 for (; j; j = j->next) {
967 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
968 (!nflag || (j->flags & JF_CHANGED))) {
969 j_print(j, how, shl_stdout);
970 if (j->state == PEXITED || j->state == PSIGNALLED)
971 j->flags |= JF_REMOVE;
976 /* Remove jobs after printing so there won't be multiple + or - jobs */
977 for (j = job_list; j; j = tmp) {
979 if (j->flags & JF_REMOVE)
980 remove_job(j, Tjobs);
982 #ifndef MKSH_NOPROSPECTOFWORK
983 sigprocmask(SIG_SETMASK, &omask, NULL);
988 /* list jobs for top-level notification */
993 #ifndef MKSH_NOPROSPECTOFWORK
996 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
998 for (j = job_list; j; j = j->next) {
999 #ifndef MKSH_UNEMPLOYED
1000 if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
1001 j_print(j, JP_MEDIUM, shl_out);
1004 * Remove job after doing reports so there aren't
1005 * multiple +/- jobs.
1007 if (j->state == PEXITED || j->state == PSIGNALLED)
1008 j->flags |= JF_REMOVE;
1010 for (j = job_list; j; j = tmp) {
1012 if (j->flags & JF_REMOVE)
1013 remove_job(j, "notify");
1016 #ifndef MKSH_NOPROSPECTOFWORK
1017 sigprocmask(SIG_SETMASK, &omask, NULL);
1021 /* Return pid of last process in last asynchronous job */
1025 #ifndef MKSH_NOPROSPECTOFWORK
1028 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1032 async_job->flags |= JF_KNOWN;
1034 #ifndef MKSH_NOPROSPECTOFWORK
1035 sigprocmask(SIG_SETMASK, &omask, NULL);
1042 * Make j the last async process
1044 * If jobs are compiled in then this routine expects sigchld to be blocked.
1051 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
1052 remove_job(async_job, "async");
1053 if (!(j->flags & JF_STARTED)) {
1054 internal_warningf(Tf_sD_s, "j_async", Tjob_not_started);
1058 async_pid = j->last_proc->pid;
1059 while (nzombie > CHILD_MAX) {
1061 for (jl = job_list; jl; jl = jl->next)
1062 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
1063 (!oldest || jl->age < oldest->age))
1067 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
1068 internal_warningf("%s: bad nzombie (%d)",
1069 "j_async", nzombie);
1074 remove_job(oldest, "zombie");
1079 * Start a job: set STARTED, check for held signals and set j->last_proc
1081 * If jobs are compiled in then this routine expects sigchld to be blocked.
1088 j->flags |= JF_STARTED;
1089 for (p = j->proc_list; p->next; p = p->next)
1093 #ifndef MKSH_NOPROSPECTOFWORK
1096 /* Don't call j_sigchld() as it may remove job... */
1097 kill(procpid, SIGCHLD);
1103 * wait for job to complete or change state
1105 * If jobs are compiled in then this routine expects sigchld to be blocked.
1115 #ifdef MKSH_NO_SIGSUSPEND
1120 * No auto-notify on the job we are waiting on.
1122 j->flags |= JF_WAITING;
1123 if (flags & JW_ASYNCNOTIFY)
1124 j->flags |= JF_W_ASYNCNOTIFY;
1126 #ifndef MKSH_UNEMPLOYED
1127 if (!Flag(FMONITOR))
1129 flags |= JW_STOPPEDWAIT;
1131 while (j->state == PRUNNING ||
1132 ((flags & JW_STOPPEDWAIT) && j->state == PSTOPPED)) {
1133 #ifndef MKSH_NOPROSPECTOFWORK
1134 #ifdef MKSH_NO_SIGSUSPEND
1135 sigprocmask(SIG_SETMASK, &sm_default, &omask);
1137 /* note that handlers may run here so they need to know */
1138 sigprocmask(SIG_SETMASK, &omask, NULL);
1140 sigsuspend(&sm_default);
1146 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1147 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1149 /* not reached... */
1152 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1153 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1157 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1159 if (j->flags & JF_FG) {
1161 #ifndef MKSH_UNEMPLOYED
1162 if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1164 * Save the tty's current pgrp so it can be restored
1165 * when the job is foregrounded. This is to
1166 * deal with things like the GNU su which does
1167 * a fork/exec instead of an exec (the fork means
1168 * the execed shell gets a different pid from its
1169 * pgrp, so naturally it sets its pgrp and gets hosed
1170 * when it gets foregrounded by the parent shell which
1171 * has restored the tty's pgrp to that of the su
1174 if (j->state == PSTOPPED &&
1175 (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1176 j->flags |= JF_SAVEDTTYPGRP;
1177 if (tcsetpgrp(tty_fd, kshpgrp) < 0)
1178 warningf(true, Tf_ldfailed,
1179 "j_waitj:", "tcsetpgrp", tty_fd,
1180 (long)kshpgrp, cstrerror(errno));
1181 if (j->state == PSTOPPED) {
1182 j->flags |= JF_SAVEDTTY;
1183 mksh_tcget(tty_fd, &j->ttystat);
1189 * Only restore tty settings if job was originally
1190 * started in the foreground. Problems can be
1191 * caused by things like 'more foobar &' which will
1192 * typically get and save the shell's vi/emacs tty
1193 * settings before setting up the tty for itself;
1194 * when more exits, it restores the 'original'
1195 * settings, and things go down hill from there...
1197 if (j->state == PEXITED && j->status == 0 &&
1198 (j->flags & JF_USETTYMODE)) {
1199 mksh_tcget(tty_fd, &tty_state);
1201 mksh_tcset(tty_fd, &tty_state);
1203 * Don't use tty mode if job is stopped and
1204 * later restarted and exits. Consider
1211 * mode should be that of the stty, not what
1212 * was before the vi started.
1214 if (j->state == PSTOPPED)
1215 j->flags &= ~JF_USETTYMODE;
1218 #ifndef MKSH_UNEMPLOYED
1220 * If it looks like user hit ^C to kill a job, pretend we got
1221 * one too to break out of for loops, etc. (AT&T ksh does this
1222 * even when not monitoring, but this doesn't make sense since
1223 * a tty generated ^C goes to the whole process group)
1225 if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1226 WIFSIGNALED(j->last_proc->status)) {
1229 if ((termsig = WTERMSIG(j->last_proc->status)) > 0 &&
1230 termsig < ksh_NSIG &&
1231 (sigtraps[termsig].flags & TF_TTY_INTR))
1237 j_usrtime = j->usrtime;
1238 j_systime = j->systime;
1241 if (!(p = j->proc_list)) {
1243 } else if (flags & JW_PIPEST) {
1247 unset(vp_pipest, 1);
1249 vp->flag = DEFINED | ISSET | INTEGER | RDONLY | ARRAY | INT_U;
1256 /* strlen(vp_pipest->name) == 10 */
1257 vq = alloc(offsetof(struct tbl, name[0]) + 11,
1259 memset(vq, 0, offsetof(struct tbl, name[0]));
1260 memcpy(vq->name, vp_pipest->name, 11);
1264 vp->areap = vp_pipest->areap;
1265 vp->ua.index = ++num;
1266 vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
1267 ARRAY | INT_U | AINDEX;
1269 vp->val.i = proc_errorlevel(p);
1270 if (Flag(FPIPEFAIL) && vp->val.i)
1274 } else if (Flag(FPIPEFAIL)) {
1276 const int i = proc_errorlevel(p);
1280 } while ((p = p->next));
1283 if (!(flags & JW_ASYNCNOTIFY)
1284 #ifndef MKSH_UNEMPLOYED
1285 && (!Flag(FMONITOR) || j->state != PSTOPPED)
1288 j_print(j, JP_SHORT, shl_out);
1291 if (j->state != PSTOPPED
1292 #ifndef MKSH_UNEMPLOYED
1293 && (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY))
1296 remove_job(j, where);
1302 * SIGCHLD handler to reap children and update job states
1304 * If jobs are compiled in then this routine expects sigchld to be blocked.
1308 j_sigchld(int sig MKSH_A_UNUSED)
1310 int saved_errno = errno;
1315 struct rusage ru0, ru1;
1316 #ifdef MKSH_NO_SIGSUSPEND
1319 /* this handler can run while SIGCHLD is not blocked, so block it now */
1320 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1323 #ifndef MKSH_NOPROSPECTOFWORK
1325 * Don't wait for any processes if a job is partially started.
1326 * This is so we don't do away with the process group leader
1327 * before all the processes in a pipe line are started (so the
1328 * setpgid() won't fail)
1330 for (j = job_list; j; j = j->next)
1331 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1337 getrusage(RUSAGE_CHILDREN, &ru0);
1339 #ifndef MKSH_NOPROSPECTOFWORK
1340 pid = waitpid(-1, &status, (WNOHANG |
1341 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1346 pid = wait(&status);
1350 * return if this would block (0) or no children
1351 * or interrupted (-1)
1356 getrusage(RUSAGE_CHILDREN, &ru1);
1358 /* find job and process structures for this pid */
1359 for (j = job_list; j != NULL; j = j->next)
1360 for (p = j->proc_list; p != NULL; p = p->next)
1365 /* Can occur if process has kids, then execs shell
1366 warningf(true, "bad process waited for (pid = %d)",
1373 timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1374 timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1375 timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1376 timersub(&j->systime, &ru0.ru_stime, &j->systime);
1379 #ifndef MKSH_UNEMPLOYED
1380 if (WIFSTOPPED(status))
1381 p->state = PSTOPPED;
1383 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1384 if (WIFCONTINUED(status)) {
1385 p->state = j->state = PRUNNING;
1386 /* skip check_job(), no-op in this case */
1391 if (WIFSIGNALED(status))
1392 p->state = PSIGNALLED;
1396 /* check to see if entire job is done */
1399 #ifndef MKSH_NOPROSPECTOFWORK
1400 while (/* CONSTCOND */ 1);
1402 while (/* CONSTCOND */ 0);
1406 #ifdef MKSH_NO_SIGSUSPEND
1407 sigprocmask(SIG_SETMASK, &omask, NULL);
1409 errno = saved_errno;
1413 * Called only when a process in j has exited/stopped (ie, called only
1414 * from j_sigchld()). If no processes are running, the job status
1415 * and state are updated, asynchronous job notification is done and,
1416 * if unneeded, the job is removed.
1418 * If jobs are compiled in then this routine expects sigchld to be blocked.
1426 /* XXX debugging (nasty - interrupt routine using shl_out) */
1427 if (!(j->flags & JF_STARTED)) {
1428 internal_warningf("check_job: job started (flags 0x%X)",
1429 (unsigned int)j->flags);
1434 for (p=j->proc_list; p != NULL; p = p->next) {
1435 if (p->state == PRUNNING)
1436 /* some processes still running */
1438 if (p->state > jstate)
1442 j->status = proc_errorlevel(j->last_proc);
1445 * Note when co-process dies: can't be done in j_wait() nor
1446 * remove_job() since neither may be called for non-interactive
1449 if (j->state == PEXITED || j->state == PSIGNALLED) {
1451 * No need to keep co-process input any more
1452 * (at least, this is what ksh93d thinks)
1454 if (coproc.job == j) {
1457 * XXX would be nice to get the closes out of here
1458 * so they aren't done in the signal handler.
1459 * Would mean a check in coproc_getfd() to
1460 * do "if job == 0 && write >= 0, close write".
1462 coproc_write_close(coproc.write);
1464 /* Do we need to keep the output? */
1465 if (j->coproc_id && j->coproc_id == coproc.id &&
1466 --coproc.njobs == 0)
1467 coproc_readw_close(coproc.read);
1470 j->flags |= JF_CHANGED;
1471 #ifndef MKSH_UNEMPLOYED
1472 if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1474 * Only put stopped jobs at the front to avoid confusing
1475 * the user (don't want finished jobs effecting %+ or %-)
1477 if (j->state == PSTOPPED)
1478 put_job(j, PJ_ON_FRONT);
1479 if (Flag(FNOTIFY) &&
1480 (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1481 /* Look for the real file descriptor 2 */
1486 for (ep = e; ep; ep = ep->oenv)
1487 if (ep->savefd && ep->savefd[2])
1489 shf_reopen(fd, SHF_WR, shl_j);
1492 * Can't call j_notify() as it removes jobs. The job
1493 * must stay in the job list as j_waitj() may be
1494 * running with this job.
1496 j_print(j, JP_MEDIUM, shl_j);
1498 if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1499 remove_job(j, "notify");
1504 #ifndef MKSH_UNEMPLOYED
1507 !(j->flags & (JF_WAITING|JF_FG)) &&
1508 j->state != PSTOPPED) {
1509 if (j == async_job || (j->flags & JF_KNOWN)) {
1510 j->flags |= JF_ZOMBIE;
1514 remove_job(j, "checkjob");
1519 * Print job status in either short, medium or long format.
1521 * If jobs are compiled in then this routine expects sigchld to be blocked.
1524 j_print(Job *j, int how, struct shf *shf)
1535 if (how == JP_PGRP) {
1537 * POSIX doesn't say what to do it there is no process
1538 * group leader (ie, !FMONITOR). We arbitrarily return
1539 * last pid (which is what $! returns).
1541 shf_fprintf(shf, Tf_dN, (int)(j->pgrp ? j->pgrp :
1542 (j->last_proc ? j->last_proc->pid : 0)));
1545 j->flags &= ~JF_CHANGED;
1546 filler = j->job > 10 ? "\n " : "\n ";
1549 else if (j == job_list->next)
1552 for (p = j->proc_list; p != NULL;) {
1556 memcpy(buf, "Running", 8);
1559 int stopsig = WSTOPSIG(p->status);
1561 strlcpy(buf, stopsig > 0 && stopsig < ksh_NSIG ?
1562 sigtraps[stopsig].mess : "Stopped", sizeof(buf));
1566 int exitstatus = (WEXITSTATUS(p->status)) & 255;
1568 if (how == JP_SHORT)
1570 else if (exitstatus == 0)
1571 memcpy(buf, "Done", 5);
1573 shf_snprintf(buf, sizeof(buf), "Done (%d)",
1578 int termsig = WTERMSIG(p->status);
1580 if (WCOREDUMP(p->status))
1584 * kludge for not reporting 'normal termination
1585 * signals' (i.e. SIGINT, SIGPIPE)
1587 if (how == JP_SHORT && !coredumped &&
1588 (termsig == SIGINT || termsig == SIGPIPE)) {
1591 strlcpy(buf, termsig > 0 && termsig < ksh_NSIG ?
1592 sigtraps[termsig].mess : "Signalled",
1600 if (how != JP_SHORT) {
1601 if (p == j->proc_list)
1602 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1604 shf_puts(filler, shf);
1608 shf_fprintf(shf, "%5d ", (int)p->pid);
1610 if (how == JP_SHORT) {
1613 shf_fprintf(shf, "%s%s ",
1614 buf, coredumped ? " (core dumped)" : null);
1618 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1619 p->next ? "|" : null,
1620 coredumped ? " (core dumped)" : null);
1626 while (p && p->state == state && p->status == status) {
1628 shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
1629 (int)p->pid, T1space, p->command,
1630 p->next ? "|" : null);
1631 else if (how == JP_MEDIUM)
1632 shf_fprintf(shf, Tf__ss, p->command,
1633 p->next ? "|" : null);
1638 shf_putc('\n', shf);
1642 * Convert % sequence to job
1644 * If jobs are compiled in then this routine expects sigchld to be blocked.
1647 j_lookup(const char *cp, int *ecodep)
1649 Job *j, *last_match;
1654 if (ksh_isdigit(*cp) && getn(cp, &job)) {
1655 /* Look for last_proc->pid (what $! returns) first... */
1656 for (j = job_list; j != NULL; j = j->next)
1657 if (j->last_proc && j->last_proc->pid == job)
1660 * ...then look for process group (this is non-POSIX,
1661 * but should not break anything
1663 for (j = job_list; j != NULL; j = j->next)
1664 if (j->pgrp && j->pgrp == job)
1666 goto j_lookup_nosuch;
1671 *ecodep = JL_INVALID;
1675 case '\0': /* non-standard */
1678 if (job_list != NULL)
1683 if (job_list != NULL && job_list->next)
1684 return (job_list->next);
1687 case '0': case '1': case '2': case '3': case '4':
1688 case '5': case '6': case '7': case '8': case '9':
1689 if (!getn(cp, &job))
1690 goto j_lookup_invalid;
1691 for (j = job_list; j != NULL; j = j->next)
1699 for (j = job_list; j != NULL; j = j->next)
1700 for (p = j->proc_list; p != NULL; p = p->next)
1701 if (strstr(p->command, cp+1) != NULL) {
1710 return (last_match);
1717 for (j = job_list; j != NULL; j = j->next)
1718 if (strncmp(cp, j->proc_list->command, len) == 0) {
1727 return (last_match);
1732 *ecodep = JL_NOSUCH;
1736 static Job *free_jobs;
1737 static Proc *free_procs;
1740 * allocate a new job and fill in the job number.
1742 * If jobs are compiled in then this routine expects sigchld to be blocked.
1750 if (free_jobs != NULL) {
1752 free_jobs = free_jobs->next;
1754 newj = alloc(sizeof(Job), APERM);
1756 /* brute force method */
1757 for (i = 1; ; i++) {
1758 for (j = job_list; j && j->job != i; j = j->next)
1769 * Allocate new process struct
1771 * If jobs are compiled in then this routine expects sigchld to be blocked.
1778 if (free_procs != NULL) {
1780 free_procs = free_procs->next;
1782 p = alloc(sizeof(Proc), APERM);
1788 * Take job out of job_list and put old structures into free list.
1789 * Keeps nzombies, last_job and async_job up to date.
1791 * If jobs are compiled in then this routine expects sigchld to be blocked.
1794 remove_job(Job *j, const char *where)
1801 while (curr && curr != j) {
1806 internal_warningf("remove_job: job %s (%s)", Tnot_found, where);
1811 /* free up proc structures */
1812 for (p = j->proc_list; p != NULL; ) {
1815 tmp->next = free_procs;
1819 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1821 j->next = free_jobs;
1831 * put j in a particular location (taking it out job_list if it is there
1834 * If jobs are compiled in then this routine expects sigchld to be blocked.
1837 put_job(Job *j, int where)
1841 /* Remove job from list (if there) */
1844 while (curr && curr != j) {
1857 case PJ_PAST_STOPPED:
1860 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1870 * nuke a job (called when unable to start full job).
1872 * If jobs are compiled in then this routine expects sigchld to be blocked.
1875 kill_job(Job *j, int sig)
1880 for (p = j->proc_list; p != NULL; p = p->next)
1882 if (kill(p->pid, sig) < 0)
1888 tty_init_talking(void)
1890 switch (tty_init_fd()) {
1894 #ifndef MKSH_DISABLE_TTY_WARNING
1895 warningf(false, Tf_sD_s_sD_s,
1896 "No controlling tty", Topen, T_devtty, cstrerror(errno));
1900 #ifndef MKSH_DISABLE_TTY_WARNING
1901 warningf(false, Tf_sD_s_s, Tcant_find, Ttty_fd,
1906 warningf(false, Tf_ssfaileds, "j_ttyinit",
1907 Ttty_fd_dupof, cstrerror(errno));
1910 warningf(false, Tf_sD_sD_s, "j_ttyinit",
1911 "can't set close-on-exec flag", cstrerror(errno));
1917 tty_init_state(void)
1920 mksh_tcget(tty_fd, &tty_state);
1921 tty_hasstate = true;