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.125 2018/01/05 20:08:34 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_UNEMPLOYED
173 bool mflagset = Flag(FMONITOR) != 127;
178 #ifndef MKSH_NOPROSPECTOFWORK
179 (void)sigemptyset(&sm_default);
180 sigprocmask(SIG_SETMASK, &sm_default, NULL);
182 (void)sigemptyset(&sm_sigchld);
183 (void)sigaddset(&sm_sigchld, SIGCHLD);
185 setsig(&sigtraps[SIGCHLD], j_sigchld,
186 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
188 /* Make sure SIGCHLD isn't ignored - can do odd things under SYSV */
189 setsig(&sigtraps[SIGCHLD], SIG_DFL, SS_RESTORE_ORIG|SS_FORCE);
192 #ifndef MKSH_UNEMPLOYED
193 if (!mflagset && Flag(FTALKING))
197 * shl_j is used to do asynchronous notification (used in
198 * an interrupt handler, so need a distinct shf)
200 shl_j = shf_fdopen(2, SHF_WR, NULL);
202 if (Flag(FMONITOR) || Flag(FTALKING)) {
206 * the TF_SHELL_USES test is a kludge that lets us know if
207 * if the signals have been changed by the shell.
209 for (i = NELEM(tt_sigs); --i >= 0; ) {
210 sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
211 /* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
212 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
213 SS_RESTORE_IGN|SS_FORCE);
217 /* j_change() calls tty_init_talking() and tty_init_state() */
222 if (Flag(FTALKING)) {
229 proc_errorlevel(Proc *p)
233 return ((WEXITSTATUS(p->status)) & 255);
235 return (ksh_sigmask(WTERMSIG(p->status)));
241 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
242 /* suspend the shell */
246 struct sigaction sa, osa;
248 /* Restore tty and pgrp. */
251 mksh_tcset(tty_fd, &tty_state);
252 if (restore_ttypgrp >= 0) {
253 if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
254 warningf(false, Tf_ssfaileds,
255 Tj_suspend, "tcsetpgrp", cstrerror(errno));
256 } else if (setpgid(0, restore_ttypgrp) < 0) {
257 warningf(false, Tf_ssfaileds,
258 Tj_suspend, "setpgid", cstrerror(errno));
263 /* Suspend the shell. */
264 memset(&sa, 0, sizeof(sa));
265 sigemptyset(&sa.sa_mask);
266 sa.sa_handler = SIG_DFL;
267 sigaction(SIGTSTP, &sa, &osa);
270 /* Back from suspend, reset signals, pgrp and tty. */
271 sigaction(SIGTSTP, &osa, NULL);
273 if (restore_ttypgrp >= 0) {
274 if (setpgid(0, kshpid) < 0) {
275 warningf(false, Tf_ssfaileds,
276 Tj_suspend, "setpgid", cstrerror(errno));
278 } else if (tcsetpgrp(tty_fd, kshpid) < 0) {
279 warningf(false, Tf_ssfaileds,
280 Tj_suspend, "tcsetpgrp", cstrerror(errno));
289 /* job cleanup before shell exit */
293 /* kill stopped, and possibly running, jobs */
297 for (j = job_list; j != NULL; j = j->next) {
298 if (j->ppid == procpid &&
299 (j->state == PSTOPPED ||
300 (j->state == PRUNNING &&
301 ((j->flags & JF_FG) ||
302 (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
307 mksh_killpg(j->pgrp, SIGHUP);
308 #ifndef MKSH_UNEMPLOYED
309 if (j->state == PSTOPPED) {
311 kill_job(j, SIGCONT);
313 mksh_killpg(j->pgrp, SIGCONT);
322 #ifndef MKSH_UNEMPLOYED
323 if (kshpid == procpid && restore_ttypgrp >= 0) {
325 * Need to restore the tty pgrp to what it was when the
326 * shell started up, so that the process that started us
327 * will be able to access the tty when we are done.
328 * Also need to restore our process group in case we are
329 * about to do an exec so that both our parent and the
330 * process we are to become will be able to access the tty.
332 tcsetpgrp(tty_fd, restore_ttypgrp);
333 setpgid(0, restore_ttypgrp);
335 if (Flag(FMONITOR)) {
342 #ifndef MKSH_UNEMPLOYED
343 /* turn job control on or off according to Flag(FMONITOR) */
349 if (Flag(FMONITOR)) {
350 bool use_tty = Flag(FTALKING);
352 /* don't call mksh_tcget until we own the tty process group */
356 /* no controlling tty, no SIGT* */
357 if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
358 setsig(&sigtraps[SIGTTIN], SIG_DFL,
359 SS_RESTORE_ORIG|SS_FORCE);
360 /* wait to be given tty (POSIX.1, B.2, job control) */
361 while (/* CONSTCOND */ 1) {
364 if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
365 warningf(false, Tf_ssfaileds,
366 "j_init", "tcgetpgrp",
371 if (ttypgrp == kshpgrp)
376 for (i = NELEM(tt_sigs); --i >= 0; )
377 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
378 SS_RESTORE_DFL|SS_FORCE);
379 if (ttypgrp_ok && kshpgrp != kshpid) {
380 if (setpgid(0, kshpid) < 0) {
381 warningf(false, Tf_ssfaileds,
382 "j_init", "setpgid", cstrerror(errno));
385 if (tcsetpgrp(tty_fd, kshpid) < 0) {
386 warningf(false, Tf_ssfaileds,
387 "j_init", "tcsetpgrp",
391 restore_ttypgrp = kshpgrp;
395 #ifndef MKSH_DISABLE_TTY_WARNING
396 if (use_tty && !ttypgrp_ok)
397 warningf(false, Tf_sD_s, "warning",
398 "won't have full job control");
403 for (i = NELEM(tt_sigs); --i >= 0; )
404 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
405 SS_RESTORE_IGN|SS_FORCE);
407 for (i = NELEM(tt_sigs); --i >= 0; ) {
408 if (sigtraps[tt_sigs[i]].flags &
409 (TF_ORIG_IGN | TF_ORIG_DFL))
410 setsig(&sigtraps[tt_sigs[i]],
411 (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
413 SS_RESTORE_ORIG|SS_FORCE);
421 /* run nice(3) and ignore the result */
425 #if defined(__USE_FORTIFY_LEVEL) && (__USE_FORTIFY_LEVEL > 0)
429 /* this is gonna annoy users; complain to your distro, people! */
430 if (nice(ness) == -1 && (eno = errno) != 0)
431 warningf(false, Tf_sD_s, "bgnice", cstrerror(eno));
438 /* execute tree in child subprocess */
440 exchild(struct op *t, int flags,
441 volatile int *xerrok,
442 /* used if XPCLOSE or XCCLOSE */
446 static Proc *last_proc;
448 int rv = 0, forksleep, jwflags = JW_NONE;
449 #ifndef MKSH_NOPROSPECTOFWORK
456 if (flags & XPIPEST) {
458 jwflags |= JW_PIPEST;
463 * Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
464 * (also done in another execute() below)
466 return (execute(t, flags & (XEXEC | XERROK), xerrok));
468 #ifndef MKSH_NOPROSPECTOFWORK
469 /* no SIGCHLDs while messing with job and process lists */
470 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
479 /* link process into jobs list */
480 if (flags & XPIPEI) {
481 /* continuing with a pipe */
483 internal_errorf("exchild: XPIPEI and no last_job - pid %d",
490 /* fills in j->job */
493 * we don't consider XXCOMs foreground since they don't get
494 * tty process group and we don't save or restore tty modes.
496 j->flags = (flags & XXCOM) ? JF_XXCOM :
497 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
498 timerclear(&j->usrtime);
499 timerclear(&j->systime);
508 put_job(j, PJ_PAST_STOPPED);
511 vistree(p->command, sizeof(p->command), t);
513 /* create child process */
515 while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
517 /* allow user to ^C out... */
522 /* ensure $RANDOM changes between parent and child */
523 rndset((unsigned long)cldpid);
526 kill_job(j, SIGKILL);
527 remove_job(j, "fork failed");
528 #ifndef MKSH_NOPROSPECTOFWORK
529 sigprocmask(SIG_SETMASK, &omask, NULL);
531 errorf("can't fork - try again");
533 p->pid = cldpid ? cldpid : (procpid = getpid());
535 #ifndef MKSH_UNEMPLOYED
536 /* job control set up */
537 if (Flag(FMONITOR) && !(flags&XXCOM)) {
547 * set pgrp in both parent and child to deal with race
550 setpgid(p->pid, j->pgrp);
551 if (ttypgrp_ok && dotty && !(flags & XBGND))
552 tcsetpgrp(tty_fd, j->pgrp);
556 /* used to close pipe input fd */
557 if (close_fd >= 0 && (((flags & XPCLOSE) && cldpid) ||
558 ((flags & XCCLOSE) && !cldpid)))
563 /* Do this before restoring signal */
565 coproc_cleanup(false);
566 cleanup_parents_env();
567 #ifndef MKSH_UNEMPLOYED
569 * If FMONITOR or FTALKING is set, these signals are ignored,
570 * if neither FMONITOR nor FTALKING are set, the signals have
571 * their inherited values.
573 if (Flag(FMONITOR) && !(flags & XXCOM)) {
574 for (forksleep = NELEM(tt_sigs); --forksleep >= 0; )
575 setsig(&sigtraps[tt_sigs[forksleep]], SIG_DFL,
576 SS_RESTORE_DFL|SS_FORCE);
580 if (Flag(FBGNICE) && (flags & XBGND))
584 #ifndef MKSH_UNEMPLOYED
588 setsig(&sigtraps[SIGINT], SIG_IGN,
589 SS_RESTORE_IGN|SS_FORCE);
590 setsig(&sigtraps[SIGQUIT], SIG_IGN,
591 SS_RESTORE_IGN|SS_FORCE);
592 if ((!(flags & (XPIPEI | XCOPROC))) &&
593 ((forksleep = open("/dev/null", 0)) > 0)) {
594 (void)ksh_dup2(forksleep, 0, true);
598 /* in case of $(jobs) command */
599 remove_job(j, "child");
600 #ifndef MKSH_NOPROSPECTOFWORK
601 /* remove_job needs SIGCHLD blocked still */
602 sigprocmask(SIG_SETMASK, &omask, NULL);
605 #ifndef MKSH_UNEMPLOYED
612 execute(t, (flags & XERROK) | XEXEC, NULL);
614 if (t->type == TPIPE)
616 internal_warningf("%s: execute() returned", "exchild");
617 fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
625 /* shell (parent) stuff */
626 if (!(flags & XPIPEO)) {
627 /* last process in a job */
629 if (flags & XCOPROC) {
630 j->coproc_id = coproc.id;
631 /* n jobs using co-process output */
633 /* j using co-process input */
634 coproc.job = (void *)j;
638 if (Flag(FTALKING)) {
639 shf_fprintf(shl_out, "[%d]", j->job);
640 for (p = j->proc_list; p; p = p->next)
641 shf_fprintf(shl_out, Tf__d,
643 shf_putchar('\n', shl_out);
647 rv = j_waitj(j, jwflags, "jw:last proc");
650 #ifndef MKSH_NOPROSPECTOFWORK
651 sigprocmask(SIG_SETMASK, &omask, NULL);
657 /* start the last job: only used for $(command) jobs */
661 #ifndef MKSH_NOPROSPECTOFWORK
664 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
667 /* no need to report error - waitlast() will do it */
669 /* ensure it isn't removed by check_job() */
670 last_job->flags |= JF_WAITING;
671 j_startjob(last_job);
673 #ifndef MKSH_NOPROSPECTOFWORK
674 sigprocmask(SIG_SETMASK, &omask, NULL);
678 /* wait for last job: only used for $(command) jobs */
684 #ifndef MKSH_NOPROSPECTOFWORK
687 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
691 if (!j || !(j->flags & JF_STARTED)) {
693 warningf(true, Tf_sD_s, "waitlast", "no last job");
695 internal_warningf(Tf_sD_s, "waitlast", Tnot_started);
696 #ifndef MKSH_NOPROSPECTOFWORK
697 sigprocmask(SIG_SETMASK, &omask, NULL);
699 /* not so arbitrary, non-zero value */
703 rv = j_waitj(j, JW_NONE, "waitlast");
705 #ifndef MKSH_NOPROSPECTOFWORK
706 sigprocmask(SIG_SETMASK, &omask, NULL);
712 /* wait for child, interruptable. */
714 waitfor(const char *cp, int *sigp)
716 int rv, ecode, flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
718 #ifndef MKSH_NOPROSPECTOFWORK
721 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
728 * wait for an unspecified job - always returns 0, so
729 * don't have to worry about exited/signaled jobs
731 for (j = job_list; j; j = j->next)
732 /* AT&T ksh will wait for stopped jobs - we don't */
733 if (j->ppid == procpid && j->state == PRUNNING)
736 #ifndef MKSH_NOPROSPECTOFWORK
737 sigprocmask(SIG_SETMASK, &omask, NULL);
741 } else if ((j = j_lookup(cp, &ecode))) {
742 /* don't report normal job completion */
743 flags &= ~JW_ASYNCNOTIFY;
744 if (j->ppid != procpid) {
745 #ifndef MKSH_NOPROSPECTOFWORK
746 sigprocmask(SIG_SETMASK, &omask, NULL);
751 #ifndef MKSH_NOPROSPECTOFWORK
752 sigprocmask(SIG_SETMASK, &omask, NULL);
754 if (ecode != JL_NOSUCH)
755 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
759 /* AT&T ksh will wait for stopped jobs - we don't */
760 rv = j_waitj(j, flags, "jw:waitfor");
762 #ifndef MKSH_NOPROSPECTOFWORK
763 sigprocmask(SIG_SETMASK, &omask, NULL);
767 /* we were interrupted */
768 *sigp = ksh_sigmask(-rv);
773 /* kill (built-in) a job */
775 j_kill(const char *cp, int sig)
779 #ifndef MKSH_NOPROSPECTOFWORK
782 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
785 if ((j = j_lookup(cp, &ecode)) == NULL) {
786 #ifndef MKSH_NOPROSPECTOFWORK
787 sigprocmask(SIG_SETMASK, &omask, NULL);
789 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
794 /* started when !Flag(FMONITOR) */
795 if (kill_job(j, sig) < 0) {
796 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
800 #ifndef MKSH_UNEMPLOYED
801 if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
802 mksh_killpg(j->pgrp, SIGCONT);
804 if (mksh_killpg(j->pgrp, sig) < 0) {
805 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
810 #ifndef MKSH_NOPROSPECTOFWORK
811 sigprocmask(SIG_SETMASK, &omask, NULL);
817 #ifndef MKSH_UNEMPLOYED
818 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
820 j_resume(const char *cp, int bg)
828 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
830 if ((j = j_lookup(cp, &ecode)) == NULL) {
831 sigprocmask(SIG_SETMASK, &omask, NULL);
832 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
837 sigprocmask(SIG_SETMASK, &omask, NULL);
838 bi_errorf("job not job-controlled");
843 shprintf("[%d] ", j->job);
846 for (p = j->proc_list; p != NULL; p = p->next) {
847 if (p->state == PSTOPPED) {
852 shf_puts(p->command, shl_stdout);
854 shf_puts("| ", shl_stdout);
856 shf_putc('\n', shl_stdout);
857 shf_flush(shl_stdout);
861 put_job(j, PJ_PAST_STOPPED);
865 /* attach tty to job */
866 if (j->state == PRUNNING) {
867 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
868 mksh_tcset(tty_fd, &j->ttystat);
869 /* See comment in j_waitj regarding saved_ttypgrp. */
871 tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
872 j->saved_ttypgrp : j->pgrp) < 0) {
874 if (j->flags & JF_SAVEDTTY)
875 mksh_tcset(tty_fd, &tty_state);
876 sigprocmask(SIG_SETMASK, &omask, NULL);
877 bi_errorf(Tf_ldfailed,
878 "fg: 1st", "tcsetpgrp", tty_fd,
879 (long)((j->flags & JF_SAVEDTTYPGRP) ?
880 j->saved_ttypgrp : j->pgrp),
886 j->flags &= ~JF_KNOWN;
891 if (j->state == PRUNNING && mksh_killpg(j->pgrp, SIGCONT) < 0) {
896 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
897 mksh_tcset(tty_fd, &tty_state);
898 if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
899 warningf(true, Tf_ldfailed,
900 "fg: 2nd", "tcsetpgrp", tty_fd,
901 (long)kshpgrp, cstrerror(errno));
903 sigprocmask(SIG_SETMASK, &omask, NULL);
904 bi_errorf(Tf_s_sD_s, "can't continue job",
910 j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
912 rv = j_waitj(j, JW_NONE, "jw:resume");
914 sigprocmask(SIG_SETMASK, &omask, NULL);
919 /* are there any running or stopped jobs ? */
921 j_stopped_running(void)
926 for (j = job_list; j != NULL; j = j->next) {
927 #ifndef MKSH_UNEMPLOYED
928 if (j->ppid == procpid && j->state == PSTOPPED)
931 if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
932 j->ppid == procpid && j->state == PRUNNING)
936 shellf("You have %s%s%s jobs\n",
937 which & 1 ? "stopped" : "",
938 which == 3 ? " and " : "",
939 which & 2 ? "running" : "");
947 /* list jobs for jobs built-in */
949 j_jobs(const char *cp, int slp,
950 /* 0: short, 1: long, 2: pgrp */
955 #ifndef MKSH_NOPROSPECTOFWORK
958 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
962 /* kludge: print zombies */
969 if ((j = j_lookup(cp, &ecode)) == NULL) {
970 #ifndef MKSH_NOPROSPECTOFWORK
971 sigprocmask(SIG_SETMASK, &omask, NULL);
973 bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
978 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
979 for (; j; j = j->next) {
980 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
981 (!nflag || (j->flags & JF_CHANGED))) {
982 j_print(j, how, shl_stdout);
983 if (j->state == PEXITED || j->state == PSIGNALLED)
984 j->flags |= JF_REMOVE;
989 /* Remove jobs after printing so there won't be multiple + or - jobs */
990 for (j = job_list; j; j = tmp) {
992 if (j->flags & JF_REMOVE)
993 remove_job(j, Tjobs);
995 #ifndef MKSH_NOPROSPECTOFWORK
996 sigprocmask(SIG_SETMASK, &omask, NULL);
1001 /* list jobs for top-level notification */
1006 #ifndef MKSH_NOPROSPECTOFWORK
1009 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1011 for (j = job_list; j; j = j->next) {
1012 #ifndef MKSH_UNEMPLOYED
1013 if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
1014 j_print(j, JP_MEDIUM, shl_out);
1017 * Remove job after doing reports so there aren't
1018 * multiple +/- jobs.
1020 if (j->state == PEXITED || j->state == PSIGNALLED)
1021 j->flags |= JF_REMOVE;
1023 for (j = job_list; j; j = tmp) {
1025 if (j->flags & JF_REMOVE) {
1026 if (j == async_job || (j->flags & JF_KNOWN)) {
1027 j->flags = (j->flags & ~JF_REMOVE) | JF_ZOMBIE;
1031 remove_job(j, "notify");
1035 #ifndef MKSH_NOPROSPECTOFWORK
1036 sigprocmask(SIG_SETMASK, &omask, NULL);
1040 /* Return pid of last process in last asynchronous job */
1044 #ifndef MKSH_NOPROSPECTOFWORK
1047 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1051 async_job->flags |= JF_KNOWN;
1053 #ifndef MKSH_NOPROSPECTOFWORK
1054 sigprocmask(SIG_SETMASK, &omask, NULL);
1061 * Make j the last async process
1063 * If jobs are compiled in then this routine expects sigchld to be blocked.
1070 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
1071 remove_job(async_job, "async");
1072 if (!(j->flags & JF_STARTED)) {
1073 internal_warningf(Tf_sD_s, "j_async", Tjob_not_started);
1077 async_pid = j->last_proc->pid;
1078 while (nzombie > CHILD_MAX) {
1080 for (jl = job_list; jl; jl = jl->next)
1081 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
1082 (!oldest || jl->age < oldest->age))
1086 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
1087 internal_warningf("%s: bad nzombie (%d)",
1088 "j_async", nzombie);
1093 remove_job(oldest, "zombie");
1098 * Start a job: set STARTED, check for held signals and set j->last_proc
1100 * If jobs are compiled in then this routine expects sigchld to be blocked.
1107 j->flags |= JF_STARTED;
1108 for (p = j->proc_list; p->next; p = p->next)
1112 #ifndef MKSH_NOPROSPECTOFWORK
1115 /* Don't call j_sigchld() as it may remove job... */
1116 kill(procpid, SIGCHLD);
1122 * wait for job to complete or change state
1124 * If jobs are compiled in then this routine expects sigchld to be blocked.
1134 #ifdef MKSH_NO_SIGSUSPEND
1139 * No auto-notify on the job we are waiting on.
1141 j->flags |= JF_WAITING;
1142 if (flags & JW_ASYNCNOTIFY)
1143 j->flags |= JF_W_ASYNCNOTIFY;
1145 #ifndef MKSH_UNEMPLOYED
1146 if (!Flag(FMONITOR))
1148 flags |= JW_STOPPEDWAIT;
1150 while (j->state == PRUNNING ||
1151 ((flags & JW_STOPPEDWAIT) && j->state == PSTOPPED)) {
1152 #ifndef MKSH_NOPROSPECTOFWORK
1153 #ifdef MKSH_NO_SIGSUSPEND
1154 sigprocmask(SIG_SETMASK, &sm_default, &omask);
1156 /* note that handlers may run here so they need to know */
1157 sigprocmask(SIG_SETMASK, &omask, NULL);
1159 sigsuspend(&sm_default);
1165 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1166 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1168 /* not reached... */
1171 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1172 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1176 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1178 if (j->flags & JF_FG) {
1180 #ifndef MKSH_UNEMPLOYED
1181 if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1183 * Save the tty's current pgrp so it can be restored
1184 * when the job is foregrounded. This is to
1185 * deal with things like the GNU su which does
1186 * a fork/exec instead of an exec (the fork means
1187 * the execed shell gets a different pid from its
1188 * pgrp, so naturally it sets its pgrp and gets hosed
1189 * when it gets foregrounded by the parent shell which
1190 * has restored the tty's pgrp to that of the su
1193 if (j->state == PSTOPPED &&
1194 (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1195 j->flags |= JF_SAVEDTTYPGRP;
1196 if (tcsetpgrp(tty_fd, kshpgrp) < 0)
1197 warningf(true, Tf_ldfailed,
1198 "j_waitj:", "tcsetpgrp", tty_fd,
1199 (long)kshpgrp, cstrerror(errno));
1200 if (j->state == PSTOPPED) {
1201 j->flags |= JF_SAVEDTTY;
1202 mksh_tcget(tty_fd, &j->ttystat);
1208 * Only restore tty settings if job was originally
1209 * started in the foreground. Problems can be
1210 * caused by things like 'more foobar &' which will
1211 * typically get and save the shell's vi/emacs tty
1212 * settings before setting up the tty for itself;
1213 * when more exits, it restores the 'original'
1214 * settings, and things go down hill from there...
1216 if (j->state == PEXITED && j->status == 0 &&
1217 (j->flags & JF_USETTYMODE)) {
1218 mksh_tcget(tty_fd, &tty_state);
1220 mksh_tcset(tty_fd, &tty_state);
1222 * Don't use tty mode if job is stopped and
1223 * later restarted and exits. Consider
1230 * mode should be that of the stty, not what
1231 * was before the vi started.
1233 if (j->state == PSTOPPED)
1234 j->flags &= ~JF_USETTYMODE;
1237 #ifndef MKSH_UNEMPLOYED
1239 * If it looks like user hit ^C to kill a job, pretend we got
1240 * one too to break out of for loops, etc. (AT&T ksh does this
1241 * even when not monitoring, but this doesn't make sense since
1242 * a tty generated ^C goes to the whole process group)
1244 if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1245 WIFSIGNALED(j->last_proc->status)) {
1248 if ((termsig = WTERMSIG(j->last_proc->status)) > 0 &&
1249 termsig < ksh_NSIG &&
1250 (sigtraps[termsig].flags & TF_TTY_INTR))
1256 j_usrtime = j->usrtime;
1257 j_systime = j->systime;
1260 if (!(p = j->proc_list)) {
1262 } else if (flags & JW_PIPEST) {
1266 unset(vp_pipest, 1);
1268 vp->flag = DEFINED | ISSET | INTEGER | RDONLY | ARRAY | INT_U;
1275 /* strlen(vp_pipest->name) == 10 */
1276 vq = alloc(offsetof(struct tbl, name[0]) + 11,
1278 memset(vq, 0, offsetof(struct tbl, name[0]));
1279 memcpy(vq->name, vp_pipest->name, 11);
1283 vp->areap = vp_pipest->areap;
1284 vp->ua.index = ++num;
1285 vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
1286 ARRAY | INT_U | AINDEX;
1288 vp->val.i = proc_errorlevel(p);
1289 if (Flag(FPIPEFAIL) && vp->val.i)
1293 } else if (Flag(FPIPEFAIL)) {
1295 const int i = proc_errorlevel(p);
1299 } while ((p = p->next));
1302 if (!(flags & JW_ASYNCNOTIFY)
1303 #ifndef MKSH_UNEMPLOYED
1304 && (!Flag(FMONITOR) || j->state != PSTOPPED)
1307 j_print(j, JP_SHORT, shl_out);
1310 if (j->state != PSTOPPED
1311 #ifndef MKSH_UNEMPLOYED
1312 && (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY))
1315 remove_job(j, where);
1321 * SIGCHLD handler to reap children and update job states
1323 * If jobs are compiled in then this routine expects sigchld to be blocked.
1327 j_sigchld(int sig MKSH_A_UNUSED)
1329 int saved_errno = errno;
1334 struct rusage ru0, ru1;
1335 #ifdef MKSH_NO_SIGSUSPEND
1338 /* this handler can run while SIGCHLD is not blocked, so block it now */
1339 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1342 #ifndef MKSH_NOPROSPECTOFWORK
1344 * Don't wait for any processes if a job is partially started.
1345 * This is so we don't do away with the process group leader
1346 * before all the processes in a pipe line are started (so the
1347 * setpgid() won't fail)
1349 for (j = job_list; j; j = j->next)
1350 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1356 getrusage(RUSAGE_CHILDREN, &ru0);
1358 #ifndef MKSH_NOPROSPECTOFWORK
1359 pid = waitpid(-1, &status, (WNOHANG |
1360 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1365 pid = wait(&status);
1369 * return if this would block (0) or no children
1370 * or interrupted (-1)
1375 getrusage(RUSAGE_CHILDREN, &ru1);
1377 /* find job and process structures for this pid */
1378 for (j = job_list; j != NULL; j = j->next)
1379 for (p = j->proc_list; p != NULL; p = p->next)
1384 /* Can occur if process has kids, then execs shell
1385 warningf(true, "bad process waited for (pid = %d)",
1392 timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1393 timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1394 timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1395 timersub(&j->systime, &ru0.ru_stime, &j->systime);
1398 #ifndef MKSH_UNEMPLOYED
1399 if (WIFSTOPPED(status))
1400 p->state = PSTOPPED;
1402 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1403 if (WIFCONTINUED(status)) {
1404 p->state = j->state = PRUNNING;
1405 /* skip check_job(), no-op in this case */
1410 if (WIFSIGNALED(status))
1411 p->state = PSIGNALLED;
1415 /* check to see if entire job is done */
1418 #ifndef MKSH_NOPROSPECTOFWORK
1419 while (/* CONSTCOND */ 1);
1421 while (/* CONSTCOND */ 0);
1425 #ifdef MKSH_NO_SIGSUSPEND
1426 sigprocmask(SIG_SETMASK, &omask, NULL);
1428 errno = saved_errno;
1432 * Called only when a process in j has exited/stopped (ie, called only
1433 * from j_sigchld()). If no processes are running, the job status
1434 * and state are updated, asynchronous job notification is done and,
1435 * if unneeded, the job is removed.
1437 * If jobs are compiled in then this routine expects sigchld to be blocked.
1445 /* XXX debugging (nasty - interrupt routine using shl_out) */
1446 if (!(j->flags & JF_STARTED)) {
1447 internal_warningf("check_job: job started (flags 0x%X)",
1448 (unsigned int)j->flags);
1453 for (p=j->proc_list; p != NULL; p = p->next) {
1454 if (p->state == PRUNNING)
1455 /* some processes still running */
1457 if (p->state > jstate)
1461 j->status = proc_errorlevel(j->last_proc);
1464 * Note when co-process dies: can't be done in j_wait() nor
1465 * remove_job() since neither may be called for non-interactive
1468 if (j->state == PEXITED || j->state == PSIGNALLED) {
1470 * No need to keep co-process input any more
1471 * (at least, this is what ksh93d thinks)
1473 if (coproc.job == j) {
1476 * XXX would be nice to get the closes out of here
1477 * so they aren't done in the signal handler.
1478 * Would mean a check in coproc_getfd() to
1479 * do "if job == 0 && write >= 0, close write".
1481 coproc_write_close(coproc.write);
1483 /* Do we need to keep the output? */
1484 if (j->coproc_id && j->coproc_id == coproc.id &&
1485 --coproc.njobs == 0)
1486 coproc_readw_close(coproc.read);
1489 j->flags |= JF_CHANGED;
1490 #ifndef MKSH_UNEMPLOYED
1491 if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1493 * Only put stopped jobs at the front to avoid confusing
1494 * the user (don't want finished jobs effecting %+ or %-)
1496 if (j->state == PSTOPPED)
1497 put_job(j, PJ_ON_FRONT);
1498 if (Flag(FNOTIFY) &&
1499 (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1500 /* Look for the real file descriptor 2 */
1505 for (ep = e; ep; ep = ep->oenv)
1506 if (ep->savefd && ep->savefd[2])
1508 shf_reopen(fd, SHF_WR, shl_j);
1511 * Can't call j_notify() as it removes jobs. The job
1512 * must stay in the job list as j_waitj() may be
1513 * running with this job.
1515 j_print(j, JP_MEDIUM, shl_j);
1517 if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1518 remove_job(j, "notify");
1523 #ifndef MKSH_UNEMPLOYED
1526 !(j->flags & (JF_WAITING|JF_FG)) &&
1527 j->state != PSTOPPED) {
1528 if (j == async_job || (j->flags & JF_KNOWN)) {
1529 j->flags |= JF_ZOMBIE;
1533 remove_job(j, "checkjob");
1538 * Print job status in either short, medium or long format.
1540 * If jobs are compiled in then this routine expects sigchld to be blocked.
1543 j_print(Job *j, int how, struct shf *shf)
1556 if (how == JP_PGRP) {
1558 * POSIX doesn't say what to do it there is no process
1559 * group leader (ie, !FMONITOR). We arbitrarily return
1560 * last pid (which is what $! returns).
1562 shf_fprintf(shf, Tf_dN, (int)(j->pgrp ? j->pgrp :
1563 (j->last_proc ? j->last_proc->pid : 0)));
1566 j->flags &= ~JF_CHANGED;
1567 filler = j->job > 10 ? "\n " : "\n ";
1570 else if (j == job_list->next)
1573 for (p = j->proc_list; p != NULL;) {
1579 memcpy(buf, "Running", 8);
1582 int stopsig = WSTOPSIG(p->status);
1584 strlcpy(buf, stopsig > 0 && stopsig < ksh_NSIG ?
1585 sigtraps[stopsig].mess : "Stopped", sizeof(buf));
1589 int exitstatus = (WEXITSTATUS(p->status)) & 255;
1591 if (how == JP_SHORT)
1593 else if (exitstatus == 0)
1594 memcpy(buf, "Done", 5);
1596 shf_snprintf(buf, sizeof(buf), "Done (%d)",
1601 int termsig = WTERMSIG(p->status);
1603 if (WCOREDUMP(p->status))
1607 * kludge for not reporting 'normal termination
1608 * signals' (i.e. SIGINT, SIGPIPE)
1610 if (how == JP_SHORT &&
1614 (termsig == SIGINT || termsig == SIGPIPE)) {
1617 strlcpy(buf, termsig > 0 && termsig < ksh_NSIG ?
1618 sigtraps[termsig].mess : "Signalled",
1626 if (how != JP_SHORT) {
1627 if (p == j->proc_list)
1628 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1630 shf_puts(filler, shf);
1634 shf_fprintf(shf, "%5d ", (int)p->pid);
1636 if (how == JP_SHORT) {
1640 shf_fprintf(shf, "%s%s ",
1641 buf, coredumped ? " (core dumped)" : null);
1644 shf_putchar(' ', shf);
1649 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1650 p->next ? "|" : null,
1652 coredumped ? " (core dumped)" :
1660 while (p && p->state == state && p->status == status) {
1662 shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
1663 (int)p->pid, T1space, p->command,
1664 p->next ? "|" : null);
1665 else if (how == JP_MEDIUM)
1666 shf_fprintf(shf, Tf__ss, p->command,
1667 p->next ? "|" : null);
1672 shf_putc('\n', shf);
1676 * Convert % sequence to job
1678 * If jobs are compiled in then this routine expects sigchld to be blocked.
1681 j_lookup(const char *cp, int *ecodep)
1683 Job *j, *last_match;
1688 if (ctype(*cp, C_DIGIT) && getn(cp, &job)) {
1689 /* Look for last_proc->pid (what $! returns) first... */
1690 for (j = job_list; j != NULL; j = j->next)
1691 if (j->last_proc && j->last_proc->pid == job)
1694 * ...then look for process group (this is non-POSIX,
1695 * but should not break anything
1697 for (j = job_list; j != NULL; j = j->next)
1698 if (j->pgrp && j->pgrp == job)
1700 goto j_lookup_nosuch;
1705 *ecodep = JL_INVALID;
1709 case '\0': /* non-standard */
1712 if (job_list != NULL)
1717 if (job_list != NULL && job_list->next)
1718 return (job_list->next);
1721 case '0': case '1': case '2': case '3': case '4':
1722 case '5': case '6': case '7': case '8': case '9':
1723 if (!getn(cp, &job))
1724 goto j_lookup_invalid;
1725 for (j = job_list; j != NULL; j = j->next)
1733 for (j = job_list; j != NULL; j = j->next)
1734 for (p = j->proc_list; p != NULL; p = p->next)
1735 if (strstr(p->command, cp+1) != NULL) {
1744 return (last_match);
1751 for (j = job_list; j != NULL; j = j->next)
1752 if (strncmp(cp, j->proc_list->command, len) == 0) {
1761 return (last_match);
1766 *ecodep = JL_NOSUCH;
1770 static Job *free_jobs;
1771 static Proc *free_procs;
1774 * allocate a new job and fill in the job number.
1776 * If jobs are compiled in then this routine expects sigchld to be blocked.
1784 if (free_jobs != NULL) {
1786 free_jobs = free_jobs->next;
1788 newj = alloc(sizeof(Job), APERM);
1790 /* brute force method */
1791 for (i = 1; ; i++) {
1792 for (j = job_list; j && j->job != i; j = j->next)
1803 * Allocate new process struct
1805 * If jobs are compiled in then this routine expects sigchld to be blocked.
1812 if (free_procs != NULL) {
1814 free_procs = free_procs->next;
1816 p = alloc(sizeof(Proc), APERM);
1822 * Take job out of job_list and put old structures into free list.
1823 * Keeps nzombies, last_job and async_job up to date.
1825 * If jobs are compiled in then this routine expects sigchld to be blocked.
1828 remove_job(Job *j, const char *where)
1835 while (curr && curr != j) {
1840 internal_warningf("remove_job: job %s (%s)", Tnot_found, where);
1845 /* free up proc structures */
1846 for (p = j->proc_list; p != NULL; ) {
1849 tmp->next = free_procs;
1853 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1855 j->next = free_jobs;
1865 * put j in a particular location (taking it out job_list if it is there
1868 * If jobs are compiled in then this routine expects sigchld to be blocked.
1871 put_job(Job *j, int where)
1875 /* Remove job from list (if there) */
1878 while (curr && curr != j) {
1891 case PJ_PAST_STOPPED:
1894 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1904 * nuke a job (called when unable to start full job).
1906 * If jobs are compiled in then this routine expects sigchld to be blocked.
1909 kill_job(Job *j, int sig)
1914 for (p = j->proc_list; p != NULL; p = p->next)
1916 if (kill(p->pid, sig) < 0)
1922 tty_init_talking(void)
1924 switch (tty_init_fd()) {
1928 #ifndef MKSH_DISABLE_TTY_WARNING
1929 warningf(false, Tf_sD_s_sD_s,
1930 "No controlling tty", Topen, T_devtty, cstrerror(errno));
1934 #ifndef MKSH_DISABLE_TTY_WARNING
1935 warningf(false, Tf_sD_s_s, Tcant_find, Ttty_fd,
1940 warningf(false, Tf_ssfaileds, "j_ttyinit",
1941 Ttty_fd_dupof, cstrerror(errno));
1944 warningf(false, Tf_sD_sD_s, "j_ttyinit",
1945 "can't set close-on-exec flag", cstrerror(errno));
1951 tty_init_state(void)
1954 mksh_tcget(tty_fd, &tty_state);
1955 tty_hasstate = true;