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, 2018
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.127 2018/07/15 16:23:10 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;
42 /* to take alignment into consideration */
52 /* next process in pipeline (if any) */
54 /* process id of this Unix process in the job */
56 /* one of the four P… above */
60 /* process command string from vistree */
61 char command[256 - (ALLOC_OVERHEAD +
62 offsetof(struct proc_dummy, command[0]))];
65 /* Notify/print flag - j_print() argument */
66 #define JP_SHORT 1 /* print signals processes were killed by */
67 #define JP_MEDIUM 2 /* print [job-num] -/+ command */
68 #define JP_LONG 3 /* print [job-num] -/+ pid command */
69 #define JP_PGRP 4 /* print pgrp */
72 #define PJ_ON_FRONT 0 /* at very front */
73 #define PJ_PAST_STOPPED 1 /* just past any stopped jobs */
75 /* Job.flags values */
76 #define JF_STARTED 0x001 /* set when all processes in job are started */
77 #define JF_WAITING 0x002 /* set if j_waitj() is waiting on job */
78 #define JF_W_ASYNCNOTIFY 0x004 /* set if waiting and async notification ok */
79 #define JF_XXCOM 0x008 /* set for $(command) jobs */
80 #define JF_FG 0x010 /* running in foreground (also has tty pgrp) */
81 #define JF_SAVEDTTY 0x020 /* j->ttystat is valid */
82 #define JF_CHANGED 0x040 /* process has changed state */
83 #define JF_KNOWN 0x080 /* $! referenced */
84 #define JF_ZOMBIE 0x100 /* known, unwaited process */
85 #define JF_REMOVE 0x200 /* flagged for removal (j_jobs()/j_noityf()) */
86 #define JF_USETTYMODE 0x400 /* tty mode saved if process exits normally */
87 #define JF_SAVEDTTYPGRP 0x800 /* j->saved_ttypgrp is valid */
89 typedef struct job Job;
91 Job *next; /* next job in list */
92 Proc *proc_list; /* process list */
93 Proc *last_proc; /* last process in list */
94 struct timeval systime; /* system time used by job */
95 struct timeval usrtime; /* user time used by job */
96 pid_t pgrp; /* process group of job */
97 pid_t ppid; /* pid of process that forked job */
98 int job; /* job number: %n */
99 int flags; /* see JF_* */
100 volatile int state; /* job state */
101 int status; /* exit status of last process */
102 int age; /* number of jobs started */
103 Coproc_id coproc_id; /* 0 or id of coprocess output pipe */
104 #ifndef MKSH_UNEMPLOYED
105 mksh_ttyst ttystat; /* saved tty state for stopped jobs */
106 pid_t saved_ttypgrp; /* saved tty process group for stopped jobs */
110 /* Flags for j_waitj() */
112 #define JW_INTERRUPT 0x01 /* ^C will stop the wait */
113 #define JW_ASYNCNOTIFY 0x02 /* asynchronous notification during wait ok */
114 #define JW_STOPPEDWAIT 0x04 /* wait even if job stopped */
115 #define JW_PIPEST 0x08 /* want PIPESTATUS */
117 /* Error codes for j_lookup() */
118 #define JL_NOSUCH 0 /* no such job */
119 #define JL_AMBIG 1 /* %foo or %?foo is ambiguous */
120 #define JL_INVALID 2 /* non-pid, non-% job id */
122 static const char * const lookup_msgs[] = {
125 "argument must be %job or process id"
128 static Job *job_list; /* job list */
129 static Job *last_job;
130 static Job *async_job;
131 static pid_t async_pid;
133 static int nzombie; /* # of zombies owned by this process */
134 static int njobs; /* # of jobs started */
140 #ifndef MKSH_NOPROSPECTOFWORK
141 /* held_sigchld is set if sigchld occurs before a job is completely started */
142 static volatile sig_atomic_t held_sigchld;
145 #ifndef MKSH_UNEMPLOYED
146 static struct shf *shl_j;
147 static bool ttypgrp_ok; /* set if can use tty pgrps */
148 static pid_t restore_ttypgrp = -1;
149 static int const tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
152 static void j_set_async(Job *);
153 static void j_startjob(Job *);
154 static int j_waitj(Job *, int, const char *);
155 static void j_sigchld(int);
156 static void j_print(Job *, int, struct shf *);
157 static Job *j_lookup(const char *, int *);
158 static Job *new_job(void);
159 static Proc *new_proc(void);
160 static void check_job(Job *);
161 static void put_job(Job *, int);
162 static void remove_job(Job *, const char *);
163 static int kill_job(Job *, int);
165 static void tty_init_talking(void);
166 static void tty_init_state(void);
168 /* initialise job control */
172 #ifndef MKSH_NOPROSPECTOFWORK
173 (void)sigemptyset(&sm_default);
174 sigprocmask(SIG_SETMASK, &sm_default, NULL);
176 (void)sigemptyset(&sm_sigchld);
177 (void)sigaddset(&sm_sigchld, SIGCHLD);
179 setsig(&sigtraps[SIGCHLD], j_sigchld,
180 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
182 /* Make sure SIGCHLD isn't ignored - can do odd things under SYSV */
183 setsig(&sigtraps[SIGCHLD], SIG_DFL, SS_RESTORE_ORIG|SS_FORCE);
186 #ifndef MKSH_UNEMPLOYED
187 if (Flag(FMONITOR) == 127)
188 Flag(FMONITOR) = Flag(FTALKING);
191 * shl_j is used to do asynchronous notification (used in
192 * an interrupt handler, so need a distinct shf)
194 shl_j = shf_fdopen(2, SHF_WR, NULL);
196 if (Flag(FMONITOR) || Flag(FTALKING)) {
200 * the TF_SHELL_USES test is a kludge that lets us know if
201 * if the signals have been changed by the shell.
203 for (i = NELEM(tt_sigs); --i >= 0; ) {
204 sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
205 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
206 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
207 SS_RESTORE_IGN|SS_FORCE);
211 /* j_change() calls tty_init_talking() and tty_init_state() */
216 if (Flag(FTALKING)) {
223 proc_errorlevel(Proc *p)
227 return ((WEXITSTATUS(p->status)) & 255);
229 return (ksh_sigmask(WTERMSIG(p->status)));
235 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
236 /* suspend the shell */
240 struct sigaction sa, osa;
242 /* Restore tty and pgrp. */
245 mksh_tcset(tty_fd, &tty_state);
246 if (restore_ttypgrp >= 0) {
247 if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
248 warningf(false, Tf_ssfaileds,
249 Tj_suspend, "tcsetpgrp", cstrerror(errno));
250 } else if (setpgid(0, restore_ttypgrp) < 0) {
251 warningf(false, Tf_ssfaileds,
252 Tj_suspend, "setpgid", cstrerror(errno));
257 /* Suspend the shell. */
258 memset(&sa, 0, sizeof(sa));
259 sigemptyset(&sa.sa_mask);
260 sa.sa_handler = SIG_DFL;
261 sigaction(SIGTSTP, &sa, &osa);
264 /* Back from suspend, reset signals, pgrp and tty. */
265 sigaction(SIGTSTP, &osa, NULL);
267 if (restore_ttypgrp >= 0) {
268 if (setpgid(0, kshpid) < 0) {
269 warningf(false, Tf_ssfaileds,
270 Tj_suspend, "setpgid", cstrerror(errno));
272 } else if (tcsetpgrp(tty_fd, kshpid) < 0) {
273 warningf(false, Tf_ssfaileds,
274 Tj_suspend, "tcsetpgrp", cstrerror(errno));
283 /* job cleanup before shell exit */
287 /* kill stopped, and possibly running, jobs */
291 for (j = job_list; j != NULL; j = j->next) {
292 if (j->ppid == procpid &&
293 (j->state == PSTOPPED ||
294 (j->state == PRUNNING &&
295 ((j->flags & JF_FG) ||
296 (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
301 mksh_killpg(j->pgrp, SIGHUP);
302 #ifndef MKSH_UNEMPLOYED
303 if (j->state == PSTOPPED) {
305 kill_job(j, SIGCONT);
307 mksh_killpg(j->pgrp, SIGCONT);
316 #ifndef MKSH_UNEMPLOYED
317 if (kshpid == procpid && restore_ttypgrp >= 0) {
319 * Need to restore the tty pgrp to what it was when the
320 * shell started up, so that the process that started us
321 * will be able to access the tty when we are done.
322 * Also need to restore our process group in case we are
323 * about to do an exec so that both our parent and the
324 * process we are to become will be able to access the tty.
326 tcsetpgrp(tty_fd, restore_ttypgrp);
327 setpgid(0, restore_ttypgrp);
329 if (Flag(FMONITOR)) {
336 #ifndef MKSH_UNEMPLOYED
337 /* turn job control on or off according to Flag(FMONITOR) */
343 if (Flag(FMONITOR)) {
344 bool use_tty = Flag(FTALKING);
346 /* don't call mksh_tcget until we own the tty process group */
350 /* no controlling tty, no SIGT* */
351 if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
352 setsig(&sigtraps[SIGTTIN], SIG_DFL,
353 SS_RESTORE_ORIG|SS_FORCE);
354 /* wait to be given tty (POSIX.1, B.2, job control) */
355 while (/* CONSTCOND */ 1) {
358 if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
359 warningf(false, Tf_ssfaileds,
360 "j_init", "tcgetpgrp",
365 if (ttypgrp == kshpgrp)
370 for (i = NELEM(tt_sigs); --i >= 0; )
371 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
372 SS_RESTORE_DFL|SS_FORCE);
373 if (ttypgrp_ok && kshpgrp != kshpid) {
374 if (setpgid(0, kshpid) < 0) {
375 warningf(false, Tf_ssfaileds,
376 "j_init", "setpgid", cstrerror(errno));
379 if (tcsetpgrp(tty_fd, kshpid) < 0) {
380 warningf(false, Tf_ssfaileds,
381 "j_init", "tcsetpgrp",
385 restore_ttypgrp = kshpgrp;
389 #ifndef MKSH_DISABLE_TTY_WARNING
390 if (use_tty && !ttypgrp_ok)
391 warningf(false, Tf_sD_s, "warning",
392 "won't have full job control");
397 for (i = NELEM(tt_sigs); --i >= 0; )
398 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
399 SS_RESTORE_IGN|SS_FORCE);
401 for (i = NELEM(tt_sigs); --i >= 0; ) {
402 if (sigtraps[tt_sigs[i]].flags &
403 (TF_ORIG_IGN | TF_ORIG_DFL))
404 setsig(&sigtraps[tt_sigs[i]],
405 (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
407 SS_RESTORE_ORIG|SS_FORCE);
415 /* run nice(3) and ignore the result */
419 #if defined(__USE_FORTIFY_LEVEL) && (__USE_FORTIFY_LEVEL > 0)
423 /* this is gonna annoy users; complain to your distro, people! */
424 if (nice(ness) == -1 && (eno = errno) != 0)
425 warningf(false, Tf_sD_s, "bgnice", cstrerror(eno));
432 /* execute tree in child subprocess */
434 exchild(struct op *t, int flags,
435 volatile int *xerrok,
436 /* used if XPCLOSE or XCCLOSE */
440 static Proc *last_proc;
442 int rv = 0, forksleep, jwflags = JW_NONE;
443 #ifndef MKSH_NOPROSPECTOFWORK
450 if (flags & XPIPEST) {
452 jwflags |= JW_PIPEST;
457 * Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
458 * (also done in another execute() below)
460 return (execute(t, flags & (XEXEC | XERROK), xerrok));
462 #ifndef MKSH_NOPROSPECTOFWORK
463 /* no SIGCHLDs while messing with job and process lists */
464 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
473 /* link process into jobs list */
474 if (flags & XPIPEI) {
475 /* continuing with a pipe */
477 internal_errorf("exchild: XPIPEI and no last_job - pid %d",
484 /* fills in j->job */
487 * we don't consider XXCOMs foreground since they don't get
488 * tty process group and we don't save or restore tty modes.
490 j->flags = (flags & XXCOM) ? JF_XXCOM :
491 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
492 timerclear(&j->usrtime);
493 timerclear(&j->systime);
502 put_job(j, PJ_PAST_STOPPED);
505 vistree(p->command, sizeof(p->command), t);
507 /* create child process */
509 while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
511 /* allow user to ^C out... */
516 /* ensure $RANDOM changes between parent and child */
517 rndset((unsigned long)cldpid);
520 kill_job(j, SIGKILL);
521 remove_job(j, "fork failed");
522 #ifndef MKSH_NOPROSPECTOFWORK
523 sigprocmask(SIG_SETMASK, &omask, NULL);
525 errorf("can't fork - try again");
527 p->pid = cldpid ? cldpid : (procpid = getpid());
529 #ifndef MKSH_UNEMPLOYED
530 /* job control set up */
531 if (Flag(FMONITOR) && !(flags&XXCOM)) {
541 * set pgrp in both parent and child to deal with race
544 setpgid(p->pid, j->pgrp);
545 if (ttypgrp_ok && dotty && !(flags & XBGND))
546 tcsetpgrp(tty_fd, j->pgrp);
550 /* used to close pipe input fd */
551 if (close_fd >= 0 && (((flags & XPCLOSE) && cldpid) ||
552 ((flags & XCCLOSE) && !cldpid)))
557 /* Do this before restoring signal */
559 coproc_cleanup(false);
560 cleanup_parents_env();
561 #ifndef MKSH_UNEMPLOYED
563 * If FMONITOR or FTALKING is set, these signals are ignored,
564 * if neither FMONITOR nor FTALKING are set, the signals have
565 * their inherited values.
567 if (Flag(FMONITOR) && !(flags & XXCOM)) {
568 for (forksleep = NELEM(tt_sigs); --forksleep >= 0; )
569 setsig(&sigtraps[tt_sigs[forksleep]], SIG_DFL,
570 SS_RESTORE_DFL|SS_FORCE);
574 if (Flag(FBGNICE) && (flags & XBGND))
578 #ifndef MKSH_UNEMPLOYED
582 setsig(&sigtraps[SIGINT], SIG_IGN,
583 SS_RESTORE_IGN|SS_FORCE);
584 setsig(&sigtraps[SIGQUIT], SIG_IGN,
585 SS_RESTORE_IGN|SS_FORCE);
586 if ((!(flags & (XPIPEI | XCOPROC))) &&
587 ((forksleep = open("/dev/null", 0)) > 0)) {
588 (void)ksh_dup2(forksleep, 0, true);
592 /* in case of $(jobs) command */
593 remove_job(j, "child");
594 #ifndef MKSH_NOPROSPECTOFWORK
595 /* remove_job needs SIGCHLD blocked still */
596 sigprocmask(SIG_SETMASK, &omask, NULL);
599 #ifndef MKSH_UNEMPLOYED
606 execute(t, (flags & XERROK) | XEXEC, NULL);
608 if (t->type == TPIPE)
610 internal_warningf("%s: execute() returned", "exchild");
611 fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
619 /* shell (parent) stuff */
620 if (!(flags & XPIPEO)) {
621 /* last process in a job */
623 if (flags & XCOPROC) {
624 j->coproc_id = coproc.id;
625 /* n jobs using co-process output */
627 /* j using co-process input */
628 coproc.job = (void *)j;
632 if (Flag(FTALKING)) {
633 shf_fprintf(shl_out, "[%d]", j->job);
634 for (p = j->proc_list; p; p = p->next)
635 shf_fprintf(shl_out, Tf__d,
637 shf_putchar('\n', shl_out);
641 rv = j_waitj(j, jwflags, "jw:last proc");
644 #ifndef MKSH_NOPROSPECTOFWORK
645 sigprocmask(SIG_SETMASK, &omask, NULL);
651 /* start the last job: only used for $(command) jobs */
655 #ifndef MKSH_NOPROSPECTOFWORK
658 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
661 /* no need to report error - waitlast() will do it */
663 /* ensure it isn't removed by check_job() */
664 last_job->flags |= JF_WAITING;
665 j_startjob(last_job);
667 #ifndef MKSH_NOPROSPECTOFWORK
668 sigprocmask(SIG_SETMASK, &omask, NULL);
672 /* wait for last job: only used for $(command) jobs */
678 #ifndef MKSH_NOPROSPECTOFWORK
681 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
685 if (!j || !(j->flags & JF_STARTED)) {
687 warningf(true, Tf_sD_s, "waitlast", "no last job");
689 internal_warningf(Tf_sD_s, "waitlast", Tnot_started);
690 #ifndef MKSH_NOPROSPECTOFWORK
691 sigprocmask(SIG_SETMASK, &omask, NULL);
693 /* not so arbitrary, non-zero value */
697 rv = j_waitj(j, JW_NONE, "waitlast");
699 #ifndef MKSH_NOPROSPECTOFWORK
700 sigprocmask(SIG_SETMASK, &omask, NULL);
706 /* wait for child, interruptable. */
708 waitfor(const char *cp, int *sigp)
710 int rv, ecode, flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
712 #ifndef MKSH_NOPROSPECTOFWORK
715 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
722 * wait for an unspecified job - always returns 0, so
723 * don't have to worry about exited/signaled jobs
725 for (j = job_list; j; j = j->next)
726 /* AT&T ksh will wait for stopped jobs - we don't */
727 if (j->ppid == procpid && j->state == PRUNNING)
730 #ifndef MKSH_NOPROSPECTOFWORK
731 sigprocmask(SIG_SETMASK, &omask, NULL);
735 } else if ((j = j_lookup(cp, &ecode))) {
736 /* don't report normal job completion */
737 flags &= ~JW_ASYNCNOTIFY;
738 if (j->ppid != procpid) {
739 #ifndef MKSH_NOPROSPECTOFWORK
740 sigprocmask(SIG_SETMASK, &omask, NULL);
745 #ifndef MKSH_NOPROSPECTOFWORK
746 sigprocmask(SIG_SETMASK, &omask, NULL);
748 if (ecode != JL_NOSUCH)
749 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
753 /* AT&T ksh will wait for stopped jobs - we don't */
754 rv = j_waitj(j, flags, "jw:waitfor");
756 #ifndef MKSH_NOPROSPECTOFWORK
757 sigprocmask(SIG_SETMASK, &omask, NULL);
761 /* we were interrupted */
762 *sigp = ksh_sigmask(-rv);
767 /* kill (built-in) a job */
769 j_kill(const char *cp, int sig)
773 #ifndef MKSH_NOPROSPECTOFWORK
776 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
779 if ((j = j_lookup(cp, &ecode)) == NULL) {
780 #ifndef MKSH_NOPROSPECTOFWORK
781 sigprocmask(SIG_SETMASK, &omask, NULL);
783 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
788 /* started when !Flag(FMONITOR) */
789 if (kill_job(j, sig) < 0) {
790 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
794 #ifndef MKSH_UNEMPLOYED
795 if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
796 mksh_killpg(j->pgrp, SIGCONT);
798 if (mksh_killpg(j->pgrp, sig) < 0) {
799 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
804 #ifndef MKSH_NOPROSPECTOFWORK
805 sigprocmask(SIG_SETMASK, &omask, NULL);
811 #ifndef MKSH_UNEMPLOYED
812 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
814 j_resume(const char *cp, int bg)
822 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
824 if ((j = j_lookup(cp, &ecode)) == NULL) {
825 sigprocmask(SIG_SETMASK, &omask, NULL);
826 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
831 sigprocmask(SIG_SETMASK, &omask, NULL);
832 bi_errorf("job not job-controlled");
837 shprintf("[%d] ", j->job);
840 for (p = j->proc_list; p != NULL; p = p->next) {
841 if (p->state == PSTOPPED) {
846 shf_puts(p->command, shl_stdout);
848 shf_puts("| ", shl_stdout);
850 shf_putc('\n', shl_stdout);
851 shf_flush(shl_stdout);
855 put_job(j, PJ_PAST_STOPPED);
859 /* attach tty to job */
860 if (j->state == PRUNNING) {
861 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
862 mksh_tcset(tty_fd, &j->ttystat);
863 /* See comment in j_waitj regarding saved_ttypgrp. */
865 tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
866 j->saved_ttypgrp : j->pgrp) < 0) {
868 if (j->flags & JF_SAVEDTTY)
869 mksh_tcset(tty_fd, &tty_state);
870 sigprocmask(SIG_SETMASK, &omask, NULL);
871 bi_errorf(Tf_ldfailed,
872 "fg: 1st", "tcsetpgrp", tty_fd,
873 (long)((j->flags & JF_SAVEDTTYPGRP) ?
874 j->saved_ttypgrp : j->pgrp),
880 j->flags &= ~JF_KNOWN;
885 if (j->state == PRUNNING && mksh_killpg(j->pgrp, SIGCONT) < 0) {
890 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
891 mksh_tcset(tty_fd, &tty_state);
892 if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
893 warningf(true, Tf_ldfailed,
894 "fg: 2nd", "tcsetpgrp", tty_fd,
895 (long)kshpgrp, cstrerror(errno));
897 sigprocmask(SIG_SETMASK, &omask, NULL);
898 bi_errorf(Tf_s_sD_s, "can't continue job",
904 j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
906 rv = j_waitj(j, JW_NONE, "jw:resume");
908 sigprocmask(SIG_SETMASK, &omask, NULL);
913 /* are there any running or stopped jobs ? */
915 j_stopped_running(void)
920 for (j = job_list; j != NULL; j = j->next) {
921 #ifndef MKSH_UNEMPLOYED
922 if (j->ppid == procpid && j->state == PSTOPPED)
925 if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
926 j->ppid == procpid && j->state == PRUNNING)
930 shellf("You have %s%s%s jobs\n",
931 which & 1 ? "stopped" : "",
932 which == 3 ? " and " : "",
933 which & 2 ? "running" : "");
941 /* list jobs for jobs built-in */
943 j_jobs(const char *cp, int slp,
944 /* 0: short, 1: long, 2: pgrp */
949 #ifndef MKSH_NOPROSPECTOFWORK
952 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
956 /* kludge: print zombies */
963 if ((j = j_lookup(cp, &ecode)) == NULL) {
964 #ifndef MKSH_NOPROSPECTOFWORK
965 sigprocmask(SIG_SETMASK, &omask, NULL);
967 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
972 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
973 for (; j; j = j->next) {
974 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
975 (!nflag || (j->flags & JF_CHANGED))) {
976 j_print(j, how, shl_stdout);
977 if (j->state == PEXITED || j->state == PSIGNALLED)
978 j->flags |= JF_REMOVE;
983 /* Remove jobs after printing so there won't be multiple + or - jobs */
984 for (j = job_list; j; j = tmp) {
986 if (j->flags & JF_REMOVE)
987 remove_job(j, Tjobs);
989 #ifndef MKSH_NOPROSPECTOFWORK
990 sigprocmask(SIG_SETMASK, &omask, NULL);
995 /* list jobs for top-level notification */
1000 #ifndef MKSH_NOPROSPECTOFWORK
1003 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1005 for (j = job_list; j; j = j->next) {
1006 #ifndef MKSH_UNEMPLOYED
1007 if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
1008 j_print(j, JP_MEDIUM, shl_out);
1011 * Remove job after doing reports so there aren't
1012 * multiple +/- jobs.
1014 if (j->state == PEXITED || j->state == PSIGNALLED)
1015 j->flags |= JF_REMOVE;
1017 for (j = job_list; j; j = tmp) {
1019 if (j->flags & JF_REMOVE) {
1020 if (j == async_job || (j->flags & JF_KNOWN)) {
1021 j->flags = (j->flags & ~JF_REMOVE) | JF_ZOMBIE;
1025 remove_job(j, "notify");
1029 #ifndef MKSH_NOPROSPECTOFWORK
1030 sigprocmask(SIG_SETMASK, &omask, NULL);
1034 /* Return pid of last process in last asynchronous job */
1038 #ifndef MKSH_NOPROSPECTOFWORK
1041 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1045 async_job->flags |= JF_KNOWN;
1047 #ifndef MKSH_NOPROSPECTOFWORK
1048 sigprocmask(SIG_SETMASK, &omask, NULL);
1055 * Make j the last async process
1057 * If jobs are compiled in then this routine expects sigchld to be blocked.
1064 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
1065 remove_job(async_job, "async");
1066 if (!(j->flags & JF_STARTED)) {
1067 internal_warningf(Tf_sD_s, "j_async", Tjob_not_started);
1071 async_pid = j->last_proc->pid;
1072 while (nzombie > CHILD_MAX) {
1074 for (jl = job_list; jl; jl = jl->next)
1075 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
1076 (!oldest || jl->age < oldest->age))
1080 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
1081 internal_warningf("%s: bad nzombie (%d)",
1082 "j_async", nzombie);
1087 remove_job(oldest, "zombie");
1092 * Start a job: set STARTED, check for held signals and set j->last_proc
1094 * If jobs are compiled in then this routine expects sigchld to be blocked.
1101 j->flags |= JF_STARTED;
1102 for (p = j->proc_list; p->next; p = p->next)
1106 #ifndef MKSH_NOPROSPECTOFWORK
1109 /* Don't call j_sigchld() as it may remove job... */
1110 kill(procpid, SIGCHLD);
1116 * wait for job to complete or change state
1118 * If jobs are compiled in then this routine expects sigchld to be blocked.
1128 #ifdef MKSH_NO_SIGSUSPEND
1133 * No auto-notify on the job we are waiting on.
1135 j->flags |= JF_WAITING;
1136 if (flags & JW_ASYNCNOTIFY)
1137 j->flags |= JF_W_ASYNCNOTIFY;
1139 #ifndef MKSH_UNEMPLOYED
1140 if (!Flag(FMONITOR))
1142 flags |= JW_STOPPEDWAIT;
1144 while (j->state == PRUNNING ||
1145 ((flags & JW_STOPPEDWAIT) && j->state == PSTOPPED)) {
1146 #ifndef MKSH_NOPROSPECTOFWORK
1147 #ifdef MKSH_NO_SIGSUSPEND
1148 sigprocmask(SIG_SETMASK, &sm_default, &omask);
1150 /* note that handlers may run here so they need to know */
1151 sigprocmask(SIG_SETMASK, &omask, NULL);
1153 sigsuspend(&sm_default);
1159 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1160 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1162 /* not reached... */
1165 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1166 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1170 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1172 if (j->flags & JF_FG) {
1174 #ifndef MKSH_UNEMPLOYED
1175 if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1177 * Save the tty's current pgrp so it can be restored
1178 * when the job is foregrounded. This is to
1179 * deal with things like the GNU su which does
1180 * a fork/exec instead of an exec (the fork means
1181 * the execed shell gets a different pid from its
1182 * pgrp, so naturally it sets its pgrp and gets hosed
1183 * when it gets foregrounded by the parent shell which
1184 * has restored the tty's pgrp to that of the su
1187 if (j->state == PSTOPPED &&
1188 (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1189 j->flags |= JF_SAVEDTTYPGRP;
1190 if (tcsetpgrp(tty_fd, kshpgrp) < 0)
1191 warningf(true, Tf_ldfailed,
1192 "j_waitj:", "tcsetpgrp", tty_fd,
1193 (long)kshpgrp, cstrerror(errno));
1194 if (j->state == PSTOPPED) {
1195 j->flags |= JF_SAVEDTTY;
1196 mksh_tcget(tty_fd, &j->ttystat);
1202 * Only restore tty settings if job was originally
1203 * started in the foreground. Problems can be
1204 * caused by things like 'more foobar &' which will
1205 * typically get and save the shell's vi/emacs tty
1206 * settings before setting up the tty for itself;
1207 * when more exits, it restores the 'original'
1208 * settings, and things go down hill from there...
1210 if (j->state == PEXITED && j->status == 0 &&
1211 (j->flags & JF_USETTYMODE)) {
1212 mksh_tcget(tty_fd, &tty_state);
1214 mksh_tcset(tty_fd, &tty_state);
1216 * Don't use tty mode if job is stopped and
1217 * later restarted and exits. Consider
1224 * mode should be that of the stty, not what
1225 * was before the vi started.
1227 if (j->state == PSTOPPED)
1228 j->flags &= ~JF_USETTYMODE;
1231 #ifndef MKSH_UNEMPLOYED
1233 * If it looks like user hit ^C to kill a job, pretend we got
1234 * one too to break out of for loops, etc. (AT&T ksh does this
1235 * even when not monitoring, but this doesn't make sense since
1236 * a tty generated ^C goes to the whole process group)
1238 if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1239 WIFSIGNALED(j->last_proc->status)) {
1242 if ((termsig = WTERMSIG(j->last_proc->status)) > 0 &&
1243 termsig < ksh_NSIG &&
1244 (sigtraps[termsig].flags & TF_TTY_INTR))
1250 j_usrtime = j->usrtime;
1251 j_systime = j->systime;
1254 if (!(p = j->proc_list)) {
1256 } else if (flags & JW_PIPEST) {
1260 unset(vp_pipest, 1);
1262 vp->flag = DEFINED | ISSET | INTEGER | RDONLY | ARRAY | INT_U;
1269 /* strlen(vp_pipest->name) == 10 */
1270 vq = alloc(offsetof(struct tbl, name[0]) + 11,
1272 memset(vq, 0, offsetof(struct tbl, name[0]));
1273 memcpy(vq->name, vp_pipest->name, 11);
1277 vp->areap = vp_pipest->areap;
1278 vp->ua.index = ++num;
1279 vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
1280 ARRAY | INT_U | AINDEX;
1282 vp->val.i = proc_errorlevel(p);
1283 if (Flag(FPIPEFAIL) && vp->val.i)
1287 } else if (Flag(FPIPEFAIL)) {
1289 const int i = proc_errorlevel(p);
1293 } while ((p = p->next));
1296 if (!(flags & JW_ASYNCNOTIFY)
1297 #ifndef MKSH_UNEMPLOYED
1298 && (!Flag(FMONITOR) || j->state != PSTOPPED)
1301 j_print(j, JP_SHORT, shl_out);
1304 if (j->state != PSTOPPED
1305 #ifndef MKSH_UNEMPLOYED
1306 && (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY))
1309 remove_job(j, where);
1315 * SIGCHLD handler to reap children and update job states
1317 * If jobs are compiled in then this routine expects sigchld to be blocked.
1321 j_sigchld(int sig MKSH_A_UNUSED)
1323 int saved_errno = errno;
1328 struct rusage ru0, ru1;
1329 #ifdef MKSH_NO_SIGSUSPEND
1332 /* this handler can run while SIGCHLD is not blocked, so block it now */
1333 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1336 #ifndef MKSH_NOPROSPECTOFWORK
1338 * Don't wait for any processes if a job is partially started.
1339 * This is so we don't do away with the process group leader
1340 * before all the processes in a pipe line are started (so the
1341 * setpgid() won't fail)
1343 for (j = job_list; j; j = j->next)
1344 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1350 getrusage(RUSAGE_CHILDREN, &ru0);
1352 #ifndef MKSH_NOPROSPECTOFWORK
1353 pid = waitpid(-1, &status, (WNOHANG |
1354 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1359 pid = wait(&status);
1363 * return if this would block (0) or no children
1364 * or interrupted (-1)
1369 getrusage(RUSAGE_CHILDREN, &ru1);
1371 /* find job and process structures for this pid */
1372 for (j = job_list; j != NULL; j = j->next)
1373 for (p = j->proc_list; p != NULL; p = p->next)
1378 /* Can occur if process has kids, then execs shell
1379 warningf(true, "bad process waited for (pid = %d)",
1386 timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1387 timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1388 timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1389 timersub(&j->systime, &ru0.ru_stime, &j->systime);
1392 #ifndef MKSH_UNEMPLOYED
1393 if (WIFSTOPPED(status))
1394 p->state = PSTOPPED;
1396 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1397 if (WIFCONTINUED(status)) {
1398 p->state = j->state = PRUNNING;
1399 /* skip check_job(), no-op in this case */
1404 if (WIFSIGNALED(status))
1405 p->state = PSIGNALLED;
1409 /* check to see if entire job is done */
1412 #ifndef MKSH_NOPROSPECTOFWORK
1413 while (/* CONSTCOND */ 1);
1415 while (/* CONSTCOND */ 0);
1419 #ifdef MKSH_NO_SIGSUSPEND
1420 sigprocmask(SIG_SETMASK, &omask, NULL);
1422 errno = saved_errno;
1426 * Called only when a process in j has exited/stopped (ie, called only
1427 * from j_sigchld()). If no processes are running, the job status
1428 * and state are updated, asynchronous job notification is done and,
1429 * if unneeded, the job is removed.
1431 * If jobs are compiled in then this routine expects sigchld to be blocked.
1439 /* XXX debugging (nasty - interrupt routine using shl_out) */
1440 if (!(j->flags & JF_STARTED)) {
1441 internal_warningf("check_job: job started (flags 0x%X)",
1442 (unsigned int)j->flags);
1447 for (p=j->proc_list; p != NULL; p = p->next) {
1448 if (p->state == PRUNNING)
1449 /* some processes still running */
1451 if (p->state > jstate)
1455 j->status = proc_errorlevel(j->last_proc);
1458 * Note when co-process dies: can't be done in j_wait() nor
1459 * remove_job() since neither may be called for non-interactive
1462 if (j->state == PEXITED || j->state == PSIGNALLED) {
1464 * No need to keep co-process input any more
1465 * (at least, this is what ksh93d thinks)
1467 if (coproc.job == j) {
1470 * XXX would be nice to get the closes out of here
1471 * so they aren't done in the signal handler.
1472 * Would mean a check in coproc_getfd() to
1473 * do "if job == 0 && write >= 0, close write".
1475 coproc_write_close(coproc.write);
1477 /* Do we need to keep the output? */
1478 if (j->coproc_id && j->coproc_id == coproc.id &&
1479 --coproc.njobs == 0)
1480 coproc_readw_close(coproc.read);
1483 j->flags |= JF_CHANGED;
1484 #ifndef MKSH_UNEMPLOYED
1485 if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1487 * Only put stopped jobs at the front to avoid confusing
1488 * the user (don't want finished jobs effecting %+ or %-)
1490 if (j->state == PSTOPPED)
1491 put_job(j, PJ_ON_FRONT);
1492 if (Flag(FNOTIFY) &&
1493 (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1494 /* Look for the real file descriptor 2 */
1499 for (ep = e; ep; ep = ep->oenv)
1500 if (ep->savefd && ep->savefd[2])
1502 shf_reopen(fd, SHF_WR, shl_j);
1505 * Can't call j_notify() as it removes jobs. The job
1506 * must stay in the job list as j_waitj() may be
1507 * running with this job.
1509 j_print(j, JP_MEDIUM, shl_j);
1511 if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1512 remove_job(j, "notify");
1517 #ifndef MKSH_UNEMPLOYED
1520 !(j->flags & (JF_WAITING|JF_FG)) &&
1521 j->state != PSTOPPED) {
1522 if (j == async_job || (j->flags & JF_KNOWN)) {
1523 j->flags |= JF_ZOMBIE;
1527 remove_job(j, "checkjob");
1532 * Print job status in either short, medium or long format.
1534 * If jobs are compiled in then this routine expects sigchld to be blocked.
1537 j_print(Job *j, int how, struct shf *shf)
1550 if (how == JP_PGRP) {
1552 * POSIX doesn't say what to do it there is no process
1553 * group leader (ie, !FMONITOR). We arbitrarily return
1554 * last pid (which is what $! returns).
1556 shf_fprintf(shf, Tf_dN, (int)(j->pgrp ? j->pgrp :
1557 (j->last_proc ? j->last_proc->pid : 0)));
1560 j->flags &= ~JF_CHANGED;
1561 filler = j->job > 10 ? "\n " : "\n ";
1564 else if (j == job_list->next)
1567 for (p = j->proc_list; p != NULL;) {
1573 memcpy(buf, "Running", 8);
1576 int stopsig = WSTOPSIG(p->status);
1578 strlcpy(buf, stopsig > 0 && stopsig < ksh_NSIG ?
1579 sigtraps[stopsig].mess : "Stopped", sizeof(buf));
1583 int exitstatus = (WEXITSTATUS(p->status)) & 255;
1585 if (how == JP_SHORT)
1587 else if (exitstatus == 0)
1588 memcpy(buf, "Done", 5);
1590 shf_snprintf(buf, sizeof(buf), "Done (%d)",
1595 int termsig = WTERMSIG(p->status);
1597 if (WCOREDUMP(p->status))
1601 * kludge for not reporting 'normal termination
1602 * signals' (i.e. SIGINT, SIGPIPE)
1604 if (how == JP_SHORT &&
1608 (termsig == SIGINT || termsig == SIGPIPE)) {
1611 strlcpy(buf, termsig > 0 && termsig < ksh_NSIG ?
1612 sigtraps[termsig].mess : "Signalled",
1620 if (how != JP_SHORT) {
1621 if (p == j->proc_list)
1622 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1624 shf_puts(filler, shf);
1628 shf_fprintf(shf, "%5d ", (int)p->pid);
1630 if (how == JP_SHORT) {
1634 shf_fprintf(shf, "%s%s ",
1635 buf, coredumped ? " (core dumped)" : null);
1638 shf_putchar(' ', shf);
1643 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1644 p->next ? "|" : null,
1646 coredumped ? " (core dumped)" :
1654 while (p && p->state == state && p->status == status) {
1656 shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
1657 (int)p->pid, T1space, p->command,
1658 p->next ? "|" : null);
1659 else if (how == JP_MEDIUM)
1660 shf_fprintf(shf, Tf__ss, p->command,
1661 p->next ? "|" : null);
1666 shf_putc('\n', shf);
1670 * Convert % sequence to job
1672 * If jobs are compiled in then this routine expects sigchld to be blocked.
1675 j_lookup(const char *cp, int *ecodep)
1677 Job *j, *last_match;
1682 if (ctype(*cp, C_DIGIT) && getn(cp, &job)) {
1683 /* Look for last_proc->pid (what $! returns) first... */
1684 for (j = job_list; j != NULL; j = j->next)
1685 if (j->last_proc && j->last_proc->pid == job)
1688 * ...then look for process group (this is non-POSIX,
1689 * but should not break anything
1691 for (j = job_list; j != NULL; j = j->next)
1692 if (j->pgrp && j->pgrp == job)
1694 goto j_lookup_nosuch;
1699 *ecodep = JL_INVALID;
1703 case '\0': /* non-standard */
1706 if (job_list != NULL)
1711 if (job_list != NULL && job_list->next)
1712 return (job_list->next);
1715 case '0': case '1': case '2': case '3': case '4':
1716 case '5': case '6': case '7': case '8': case '9':
1717 if (!getn(cp, &job))
1718 goto j_lookup_invalid;
1719 for (j = job_list; j != NULL; j = j->next)
1727 for (j = job_list; j != NULL; j = j->next)
1728 for (p = j->proc_list; p != NULL; p = p->next)
1729 if (strstr(p->command, cp+1) != NULL) {
1738 return (last_match);
1745 for (j = job_list; j != NULL; j = j->next)
1746 if (strncmp(cp, j->proc_list->command, len) == 0) {
1755 return (last_match);
1760 *ecodep = JL_NOSUCH;
1764 static Job *free_jobs;
1765 static Proc *free_procs;
1768 * allocate a new job and fill in the job number.
1770 * If jobs are compiled in then this routine expects sigchld to be blocked.
1778 if (free_jobs != NULL) {
1780 free_jobs = free_jobs->next;
1782 newj = alloc(sizeof(Job), APERM);
1784 /* brute force method */
1785 for (i = 1; ; i++) {
1786 for (j = job_list; j && j->job != i; j = j->next)
1797 * Allocate new process struct
1799 * If jobs are compiled in then this routine expects sigchld to be blocked.
1806 if (free_procs != NULL) {
1808 free_procs = free_procs->next;
1810 p = alloc(sizeof(Proc), APERM);
1816 * Take job out of job_list and put old structures into free list.
1817 * Keeps nzombies, last_job and async_job up to date.
1819 * If jobs are compiled in then this routine expects sigchld to be blocked.
1822 remove_job(Job *j, const char *where)
1829 while (curr && curr != j) {
1834 internal_warningf("remove_job: job %s (%s)", Tnot_found, where);
1839 /* free up proc structures */
1840 for (p = j->proc_list; p != NULL; ) {
1843 tmp->next = free_procs;
1847 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1849 j->next = free_jobs;
1859 * put j in a particular location (taking it out job_list if it is there
1862 * If jobs are compiled in then this routine expects sigchld to be blocked.
1865 put_job(Job *j, int where)
1869 /* Remove job from list (if there) */
1872 while (curr && curr != j) {
1885 case PJ_PAST_STOPPED:
1888 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1898 * nuke a job (called when unable to start full job).
1900 * If jobs are compiled in then this routine expects sigchld to be blocked.
1903 kill_job(Job *j, int sig)
1908 for (p = j->proc_list; p != NULL; p = p->next)
1910 if (kill(p->pid, sig) < 0)
1916 tty_init_talking(void)
1918 switch (tty_init_fd()) {
1922 #ifndef MKSH_DISABLE_TTY_WARNING
1923 warningf(false, Tf_sD_s_sD_s,
1924 "No controlling tty", Topen, T_devtty, cstrerror(errno));
1928 #ifndef MKSH_DISABLE_TTY_WARNING
1929 warningf(false, Tf_s_sD_s, Tcant_find, Ttty_fd,
1934 warningf(false, Tf_ssfaileds, "j_ttyinit",
1935 Ttty_fd_dupof, cstrerror(errno));
1938 warningf(false, Tf_sD_sD_s, "j_ttyinit",
1939 "can't set close-on-exec flag", cstrerror(errno));
1945 tty_init_state(void)
1948 mksh_tcget(tty_fd, &tty_state);
1949 tty_hasstate = true;