1 /* $OpenBSD: jobs.c,v 1.39 2009/12/13 04:36:48 deraadt Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
6 * Thorsten Glaser <tg@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.100 2013/07/26 20:33:23 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_SIZE + sizeof(Proc *) + sizeof(pid_t) +
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 int32_t 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 int32_t 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));
222 return (128 + WTERMSIG(p->status));
228 /* job cleanup before shell exit */
232 /* kill stopped, and possibly running, jobs */
236 for (j = job_list; j != NULL; j = j->next) {
237 if (j->ppid == procpid &&
238 (j->state == PSTOPPED ||
239 (j->state == PRUNNING &&
240 ((j->flags & JF_FG) ||
241 (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
246 mksh_killpg(j->pgrp, SIGHUP);
247 #ifndef MKSH_UNEMPLOYED
248 if (j->state == PSTOPPED) {
250 kill_job(j, SIGCONT);
252 mksh_killpg(j->pgrp, SIGCONT);
261 #ifndef MKSH_UNEMPLOYED
262 if (kshpid == procpid && restore_ttypgrp >= 0) {
264 * Need to restore the tty pgrp to what it was when the
265 * shell started up, so that the process that started us
266 * will be able to access the tty when we are done.
267 * Also need to restore our process group in case we are
268 * about to do an exec so that both our parent and the
269 * process we are to become will be able to access the tty.
271 tcsetpgrp(tty_fd, restore_ttypgrp);
272 setpgid(0, restore_ttypgrp);
274 if (Flag(FMONITOR)) {
281 #ifndef MKSH_UNEMPLOYED
282 /* turn job control on or off according to Flag(FMONITOR) */
288 if (Flag(FMONITOR)) {
289 bool use_tty = Flag(FTALKING);
291 /* don't call mksh_tcget until we own the tty process group */
295 /* no controlling tty, no SIGT* */
296 if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
297 setsig(&sigtraps[SIGTTIN], SIG_DFL,
298 SS_RESTORE_ORIG|SS_FORCE);
299 /* wait to be given tty (POSIX.1, B.2, job control) */
300 while (/* CONSTCOND */ 1) {
303 if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
304 warningf(false, "%s: %s %s: %s",
305 "j_init", "tcgetpgrp", "failed",
310 if (ttypgrp == kshpgrp)
315 for (i = NELEM(tt_sigs); --i >= 0; )
316 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
317 SS_RESTORE_DFL|SS_FORCE);
318 if (ttypgrp_ok && kshpgrp != kshpid) {
319 if (setpgid(0, kshpid) < 0) {
320 warningf(false, "%s: %s %s: %s", "j_init",
321 "setpgid", "failed", cstrerror(errno));
324 if (tcsetpgrp(tty_fd, kshpid) < 0) {
325 warningf(false, "%s: %s %s: %s",
326 "j_init", "tcsetpgrp", "failed",
330 restore_ttypgrp = kshpgrp;
334 #ifndef MKSH_DISABLE_TTY_WARNING
335 if (use_tty && !ttypgrp_ok)
336 warningf(false, "%s: %s", "warning",
337 "won't have full job control");
342 for (i = NELEM(tt_sigs); --i >= 0; )
343 setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
344 SS_RESTORE_IGN|SS_FORCE);
346 for (i = NELEM(tt_sigs); --i >= 0; ) {
347 if (sigtraps[tt_sigs[i]].flags &
348 (TF_ORIG_IGN | TF_ORIG_DFL))
349 setsig(&sigtraps[tt_sigs[i]],
350 (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
352 SS_RESTORE_ORIG|SS_FORCE);
360 /* run nice(3) and ignore the result */
364 #if defined(__USE_FORTIFY_LEVEL) && (__USE_FORTIFY_LEVEL > 0)
368 /* this is gonna annoy users; complain to your distro, people! */
369 if (nice(ness) == -1 && (eno = errno) != 0)
370 warningf(false, "%s: %s", "bgnice", cstrerror(eno));
377 /* execute tree in child subprocess */
379 exchild(struct op *t, int flags,
380 volatile int *xerrok,
381 /* used if XPCLOSE or XCCLOSE */
385 static Proc *last_proc;
387 int rv = 0, forksleep, jwflags = JW_NONE;
388 #ifndef MKSH_NOPROSPECTOFWORK
395 if (flags & XPIPEST) {
397 jwflags |= JW_PIPEST;
402 * Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
403 * (also done in another execute() below)
405 return (execute(t, flags & (XEXEC | XERROK), xerrok));
407 #ifndef MKSH_NOPROSPECTOFWORK
408 /* no SIGCHLDs while messing with job and process lists */
409 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
418 /* link process into jobs list */
419 if (flags & XPIPEI) {
420 /* continuing with a pipe */
422 internal_errorf("%s %d",
423 "exchild: XPIPEI and no last_job - pid",
430 /* fills in j->job */
433 * we don't consider XXCOMs foreground since they don't get
434 * tty process group and we don't save or restore tty modes.
436 j->flags = (flags & XXCOM) ? JF_XXCOM :
437 ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
438 timerclear(&j->usrtime);
439 timerclear(&j->systime);
448 put_job(j, PJ_PAST_STOPPED);
451 vistree(p->command, sizeof(p->command), t);
453 /* create child process */
455 while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
457 /* allow user to ^C out... */
462 /* ensure $RANDOM changes between parent and child */
463 rndset((unsigned long)cldpid);
466 kill_job(j, SIGKILL);
467 remove_job(j, "fork failed");
468 #ifndef MKSH_NOPROSPECTOFWORK
469 sigprocmask(SIG_SETMASK, &omask, NULL);
471 errorf("can't fork - try again");
473 p->pid = cldpid ? cldpid : (procpid = getpid());
475 #ifndef MKSH_UNEMPLOYED
476 /* job control set up */
477 if (Flag(FMONITOR) && !(flags&XXCOM)) {
487 * set pgrp in both parent and child to deal with race
490 setpgid(p->pid, j->pgrp);
491 if (ttypgrp_ok && dotty && !(flags & XBGND))
492 tcsetpgrp(tty_fd, j->pgrp);
496 /* used to close pipe input fd */
497 if (close_fd >= 0 && (((flags & XPCLOSE) && cldpid) ||
498 ((flags & XCCLOSE) && !cldpid)))
503 /* Do this before restoring signal */
505 coproc_cleanup(false);
506 cleanup_parents_env();
507 #ifndef MKSH_UNEMPLOYED
509 * If FMONITOR or FTALKING is set, these signals are ignored,
510 * if neither FMONITOR nor FTALKING are set, the signals have
511 * their inherited values.
513 if (Flag(FMONITOR) && !(flags & XXCOM)) {
514 for (forksleep = NELEM(tt_sigs); --forksleep >= 0; )
515 setsig(&sigtraps[tt_sigs[forksleep]], SIG_DFL,
516 SS_RESTORE_DFL|SS_FORCE);
520 if (Flag(FBGNICE) && (flags & XBGND))
524 #ifndef MKSH_UNEMPLOYED
528 setsig(&sigtraps[SIGINT], SIG_IGN,
529 SS_RESTORE_IGN|SS_FORCE);
530 setsig(&sigtraps[SIGQUIT], SIG_IGN,
531 SS_RESTORE_IGN|SS_FORCE);
532 if ((!(flags & (XPIPEI | XCOPROC))) &&
533 ((forksleep = open("/dev/null", 0)) > 0)) {
534 (void)ksh_dup2(forksleep, 0, true);
538 /* in case of $(jobs) command */
539 remove_job(j, "child");
540 #ifndef MKSH_NOPROSPECTOFWORK
541 /* remove_job needs SIGCHLD blocked still */
542 sigprocmask(SIG_SETMASK, &omask, NULL);
545 #ifndef MKSH_UNEMPLOYED
552 execute(t, (flags & XERROK) | XEXEC, NULL);
554 if (t->type == TPIPE)
556 internal_warningf("%s: %s", "exchild", "execute() returned");
557 fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
565 /* shell (parent) stuff */
566 if (!(flags & XPIPEO)) {
567 /* last process in a job */
569 if (flags & XCOPROC) {
570 j->coproc_id = coproc.id;
571 /* n jobs using co-process output */
573 /* j using co-process input */
574 coproc.job = (void *)j;
578 if (Flag(FTALKING)) {
579 shf_fprintf(shl_out, "[%d]", j->job);
580 for (p = j->proc_list; p; p = p->next)
581 shf_fprintf(shl_out, " %d",
583 shf_putchar('\n', shl_out);
587 rv = j_waitj(j, jwflags, "jw:last proc");
590 #ifndef MKSH_NOPROSPECTOFWORK
591 sigprocmask(SIG_SETMASK, &omask, NULL);
597 /* start the last job: only used for $(command) jobs */
601 #ifndef MKSH_NOPROSPECTOFWORK
604 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
607 /* no need to report error - waitlast() will do it */
609 /* ensure it isn't removed by check_job() */
610 last_job->flags |= JF_WAITING;
611 j_startjob(last_job);
613 #ifndef MKSH_NOPROSPECTOFWORK
614 sigprocmask(SIG_SETMASK, &omask, NULL);
618 /* wait for last job: only used for $(command) jobs */
624 #ifndef MKSH_NOPROSPECTOFWORK
627 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
631 if (!j || !(j->flags & JF_STARTED)) {
633 warningf(true, "%s: %s", "waitlast", "no last job");
635 internal_warningf("%s: %s", "waitlast", "not started");
636 #ifndef MKSH_NOPROSPECTOFWORK
637 sigprocmask(SIG_SETMASK, &omask, NULL);
639 /* not so arbitrary, non-zero value */
643 rv = j_waitj(j, JW_NONE, "waitlast");
645 #ifndef MKSH_NOPROSPECTOFWORK
646 sigprocmask(SIG_SETMASK, &omask, NULL);
652 /* wait for child, interruptable. */
654 waitfor(const char *cp, int *sigp)
656 int rv, ecode, flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
658 #ifndef MKSH_NOPROSPECTOFWORK
661 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
668 * wait for an unspecified job - always returns 0, so
669 * don't have to worry about exited/signaled jobs
671 for (j = job_list; j; j = j->next)
672 /* AT&T ksh will wait for stopped jobs - we don't */
673 if (j->ppid == procpid && j->state == PRUNNING)
676 #ifndef MKSH_NOPROSPECTOFWORK
677 sigprocmask(SIG_SETMASK, &omask, NULL);
681 } else if ((j = j_lookup(cp, &ecode))) {
682 /* don't report normal job completion */
683 flags &= ~JW_ASYNCNOTIFY;
684 if (j->ppid != procpid) {
685 #ifndef MKSH_NOPROSPECTOFWORK
686 sigprocmask(SIG_SETMASK, &omask, NULL);
691 #ifndef MKSH_NOPROSPECTOFWORK
692 sigprocmask(SIG_SETMASK, &omask, NULL);
694 if (ecode != JL_NOSUCH)
695 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
699 /* AT&T ksh will wait for stopped jobs - we don't */
700 rv = j_waitj(j, flags, "jw:waitfor");
702 #ifndef MKSH_NOPROSPECTOFWORK
703 sigprocmask(SIG_SETMASK, &omask, NULL);
707 /* we were interrupted */
713 /* kill (built-in) a job */
715 j_kill(const char *cp, int sig)
719 #ifndef MKSH_NOPROSPECTOFWORK
722 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
725 if ((j = j_lookup(cp, &ecode)) == NULL) {
726 #ifndef MKSH_NOPROSPECTOFWORK
727 sigprocmask(SIG_SETMASK, &omask, NULL);
729 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
734 /* started when !Flag(FMONITOR) */
735 if (kill_job(j, sig) < 0) {
736 bi_errorf("%s: %s", cp, cstrerror(errno));
740 #ifndef MKSH_UNEMPLOYED
741 if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
742 mksh_killpg(j->pgrp, SIGCONT);
744 if (mksh_killpg(j->pgrp, sig) < 0) {
745 bi_errorf("%s: %s", cp, cstrerror(errno));
750 #ifndef MKSH_NOPROSPECTOFWORK
751 sigprocmask(SIG_SETMASK, &omask, NULL);
757 #ifndef MKSH_UNEMPLOYED
758 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
760 j_resume(const char *cp, int bg)
768 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
770 if ((j = j_lookup(cp, &ecode)) == NULL) {
771 sigprocmask(SIG_SETMASK, &omask, NULL);
772 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
777 sigprocmask(SIG_SETMASK, &omask, NULL);
778 bi_errorf("job not job-controlled");
783 shprintf("[%d] ", j->job);
786 for (p = j->proc_list; p != NULL; p = p->next) {
787 if (p->state == PSTOPPED) {
792 shf_puts(p->command, shl_stdout);
794 shf_puts("| ", shl_stdout);
796 shf_putc('\n', shl_stdout);
797 shf_flush(shl_stdout);
801 put_job(j, PJ_PAST_STOPPED);
805 /* attach tty to job */
806 if (j->state == PRUNNING) {
807 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
808 mksh_tcset(tty_fd, &j->ttystat);
809 /* See comment in j_waitj regarding saved_ttypgrp. */
811 tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
812 j->saved_ttypgrp : j->pgrp) < 0) {
814 if (j->flags & JF_SAVEDTTY)
815 mksh_tcset(tty_fd, &tty_state);
816 sigprocmask(SIG_SETMASK, &omask, NULL);
817 bi_errorf("%s %s(%d, %ld) %s: %s",
818 "1st", "tcsetpgrp", tty_fd,
819 (long)((j->flags & JF_SAVEDTTYPGRP) ?
820 j->saved_ttypgrp : j->pgrp), "failed",
826 j->flags &= ~JF_KNOWN;
831 if (j->state == PRUNNING && mksh_killpg(j->pgrp, SIGCONT) < 0) {
836 if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
837 mksh_tcset(tty_fd, &tty_state);
838 if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
839 warningf(true, "%s %s(%d, %ld) %s: %s",
840 "fg: 2nd", "tcsetpgrp", tty_fd,
841 (long)kshpgrp, "failed", cstrerror(errno));
843 sigprocmask(SIG_SETMASK, &omask, NULL);
844 bi_errorf("%s %s %s", "can't continue job",
850 j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
852 rv = j_waitj(j, JW_NONE, "jw:resume");
854 sigprocmask(SIG_SETMASK, &omask, NULL);
859 /* are there any running or stopped jobs ? */
861 j_stopped_running(void)
866 for (j = job_list; j != NULL; j = j->next) {
867 #ifndef MKSH_UNEMPLOYED
868 if (j->ppid == procpid && j->state == PSTOPPED)
871 if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
872 j->ppid == procpid && j->state == PRUNNING)
876 shellf("You have %s%s%s jobs\n",
877 which & 1 ? "stopped" : "",
878 which == 3 ? " and " : "",
879 which & 2 ? "running" : "");
887 /* list jobs for jobs built-in */
889 j_jobs(const char *cp, int slp,
890 /* 0: short, 1: long, 2: pgrp */
895 #ifndef MKSH_NOPROSPECTOFWORK
898 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
902 /* kludge: print zombies */
909 if ((j = j_lookup(cp, &ecode)) == NULL) {
910 #ifndef MKSH_NOPROSPECTOFWORK
911 sigprocmask(SIG_SETMASK, &omask, NULL);
913 bi_errorf("%s: %s", cp, lookup_msgs[ecode]);
918 how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
919 for (; j; j = j->next) {
920 if ((!(j->flags & JF_ZOMBIE) || zflag) &&
921 (!nflag || (j->flags & JF_CHANGED))) {
922 j_print(j, how, shl_stdout);
923 if (j->state == PEXITED || j->state == PSIGNALLED)
924 j->flags |= JF_REMOVE;
929 /* Remove jobs after printing so there won't be multiple + or - jobs */
930 for (j = job_list; j; j = tmp) {
932 if (j->flags & JF_REMOVE)
933 remove_job(j, "jobs");
935 #ifndef MKSH_NOPROSPECTOFWORK
936 sigprocmask(SIG_SETMASK, &omask, NULL);
941 /* list jobs for top-level notification */
946 #ifndef MKSH_NOPROSPECTOFWORK
949 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
951 for (j = job_list; j; j = j->next) {
952 #ifndef MKSH_UNEMPLOYED
953 if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
954 j_print(j, JP_MEDIUM, shl_out);
957 * Remove job after doing reports so there aren't
960 if (j->state == PEXITED || j->state == PSIGNALLED)
961 j->flags |= JF_REMOVE;
963 for (j = job_list; j; j = tmp) {
965 if (j->flags & JF_REMOVE)
966 remove_job(j, "notify");
969 #ifndef MKSH_NOPROSPECTOFWORK
970 sigprocmask(SIG_SETMASK, &omask, NULL);
974 /* Return pid of last process in last asynchronous job */
978 #ifndef MKSH_NOPROSPECTOFWORK
981 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
985 async_job->flags |= JF_KNOWN;
987 #ifndef MKSH_NOPROSPECTOFWORK
988 sigprocmask(SIG_SETMASK, &omask, NULL);
995 * Make j the last async process
997 * If jobs are compiled in then this routine expects sigchld to be blocked.
1004 if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
1005 remove_job(async_job, "async");
1006 if (!(j->flags & JF_STARTED)) {
1007 internal_warningf("%s: %s", "j_async", "job not started");
1011 async_pid = j->last_proc->pid;
1012 while (nzombie > CHILD_MAX) {
1014 for (jl = job_list; jl; jl = jl->next)
1015 if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
1016 (!oldest || jl->age < oldest->age))
1020 if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
1021 internal_warningf("%s: bad nzombie (%d)",
1022 "j_async", nzombie);
1027 remove_job(oldest, "zombie");
1032 * Start a job: set STARTED, check for held signals and set j->last_proc
1034 * If jobs are compiled in then this routine expects sigchld to be blocked.
1041 j->flags |= JF_STARTED;
1042 for (p = j->proc_list; p->next; p = p->next)
1046 #ifndef MKSH_NOPROSPECTOFWORK
1049 /* Don't call j_sigchld() as it may remove job... */
1050 kill(procpid, SIGCHLD);
1056 * wait for job to complete or change state
1058 * If jobs are compiled in then this routine expects sigchld to be blocked.
1067 #ifdef MKSH_NO_SIGSUSPEND
1072 * No auto-notify on the job we are waiting on.
1074 j->flags |= JF_WAITING;
1075 if (flags & JW_ASYNCNOTIFY)
1076 j->flags |= JF_W_ASYNCNOTIFY;
1078 #ifndef MKSH_UNEMPLOYED
1079 if (!Flag(FMONITOR))
1081 flags |= JW_STOPPEDWAIT;
1083 while (j->state == PRUNNING ||
1084 ((flags & JW_STOPPEDWAIT) && j->state == PSTOPPED)) {
1085 #ifndef MKSH_NOPROSPECTOFWORK
1086 #ifdef MKSH_NO_SIGSUSPEND
1087 sigprocmask(SIG_SETMASK, &sm_default, &omask);
1089 /* note that handlers may run here so they need to know */
1090 sigprocmask(SIG_SETMASK, &omask, NULL);
1092 sigsuspend(&sm_default);
1098 int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1099 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1101 /* not reached... */
1104 if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1105 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1109 j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1111 if (j->flags & JF_FG) {
1113 #ifndef MKSH_UNEMPLOYED
1114 if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1116 * Save the tty's current pgrp so it can be restored
1117 * when the job is foregrounded. This is to
1118 * deal with things like the GNU su which does
1119 * a fork/exec instead of an exec (the fork means
1120 * the execed shell gets a different pid from its
1121 * pgrp, so naturally it sets its pgrp and gets hosed
1122 * when it gets foregrounded by the parent shell which
1123 * has restored the tty's pgrp to that of the su
1126 if (j->state == PSTOPPED &&
1127 (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1128 j->flags |= JF_SAVEDTTYPGRP;
1129 if (tcsetpgrp(tty_fd, kshpgrp) < 0)
1130 warningf(true, "%s %s(%d, %ld) %s: %s",
1131 "j_waitj:", "tcsetpgrp", tty_fd,
1132 (long)kshpgrp, "failed", cstrerror(errno));
1133 if (j->state == PSTOPPED) {
1134 j->flags |= JF_SAVEDTTY;
1135 mksh_tcget(tty_fd, &j->ttystat);
1141 * Only restore tty settings if job was originally
1142 * started in the foreground. Problems can be
1143 * caused by things like 'more foobar &' which will
1144 * typically get and save the shell's vi/emacs tty
1145 * settings before setting up the tty for itself;
1146 * when more exits, it restores the 'original'
1147 * settings, and things go down hill from there...
1149 if (j->state == PEXITED && j->status == 0 &&
1150 (j->flags & JF_USETTYMODE)) {
1151 mksh_tcget(tty_fd, &tty_state);
1153 mksh_tcset(tty_fd, &tty_state);
1155 * Don't use tty mode if job is stopped and
1156 * later restarted and exits. Consider
1163 * mode should be that of the stty, not what
1164 * was before the vi started.
1166 if (j->state == PSTOPPED)
1167 j->flags &= ~JF_USETTYMODE;
1170 #ifndef MKSH_UNEMPLOYED
1172 * If it looks like user hit ^C to kill a job, pretend we got
1173 * one too to break out of for loops, etc. (AT&T ksh does this
1174 * even when not monitoring, but this doesn't make sense since
1175 * a tty generated ^C goes to the whole process group)
1180 status = j->last_proc->status;
1181 if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1182 WIFSIGNALED(status) &&
1183 (sigtraps[WTERMSIG(status)].flags & TF_TTY_INTR))
1184 trapsig(WTERMSIG(status));
1189 j_usrtime = j->usrtime;
1190 j_systime = j->systime;
1193 if ((flags & JW_PIPEST) && (j->proc_list != NULL)) {
1195 Proc *p = j->proc_list;
1198 unset(vp_pipest, 1);
1200 vp->flag = DEFINED | ISSET | INTEGER | RDONLY | ARRAY | INT_U;
1207 /* strlen(vp_pipest->name) == 10 */
1208 vq = alloc(offsetof(struct tbl, name[0]) + 11,
1210 memset(vq, 0, offsetof(struct tbl, name[0]));
1211 memcpy(vq->name, vp_pipest->name, 11);
1215 vp->areap = vp_pipest->areap;
1216 vp->ua.index = ++num;
1217 vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
1218 ARRAY | INT_U | AINDEX;
1220 vp->val.i = proc_errorlevel(p);
1221 if (Flag(FPIPEFAIL) && vp->val.i)
1227 if (!(flags & JW_ASYNCNOTIFY)
1228 #ifndef MKSH_UNEMPLOYED
1229 && (!Flag(FMONITOR) || j->state != PSTOPPED)
1232 j_print(j, JP_SHORT, shl_out);
1235 if (j->state != PSTOPPED
1236 #ifndef MKSH_UNEMPLOYED
1237 && (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY))
1240 remove_job(j, where);
1246 * SIGCHLD handler to reap children and update job states
1248 * If jobs are compiled in then this routine expects sigchld to be blocked.
1252 j_sigchld(int sig MKSH_A_UNUSED)
1254 int saved_errno = errno;
1259 struct rusage ru0, ru1;
1260 #ifdef MKSH_NO_SIGSUSPEND
1263 /* this handler can run while SIGCHLD is not blocked, so block it now */
1264 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1267 #ifndef MKSH_NOPROSPECTOFWORK
1269 * Don't wait for any processes if a job is partially started.
1270 * This is so we don't do away with the process group leader
1271 * before all the processes in a pipe line are started (so the
1272 * setpgid() won't fail)
1274 for (j = job_list; j; j = j->next)
1275 if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1281 getrusage(RUSAGE_CHILDREN, &ru0);
1283 #ifndef MKSH_NOPROSPECTOFWORK
1284 pid = waitpid(-1, &status, (WNOHANG|WUNTRACED));
1286 pid = wait(&status);
1290 * return if this would block (0) or no children
1291 * or interrupted (-1)
1296 getrusage(RUSAGE_CHILDREN, &ru1);
1298 /* find job and process structures for this pid */
1299 for (j = job_list; j != NULL; j = j->next)
1300 for (p = j->proc_list; p != NULL; p = p->next)
1305 /* Can occur if process has kids, then execs shell
1306 warningf(true, "bad process waited for (pid = %d)",
1313 timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1314 timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1315 timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1316 timersub(&j->systime, &ru0.ru_stime, &j->systime);
1319 #ifndef MKSH_UNEMPLOYED
1320 if (WIFSTOPPED(status))
1321 p->state = PSTOPPED;
1324 if (WIFSIGNALED(status))
1325 p->state = PSIGNALLED;
1329 /* check to see if entire job is done */
1332 #ifndef MKSH_NOPROSPECTOFWORK
1333 while (/* CONSTCOND */ 1);
1335 while (/* CONSTCOND */ 0);
1339 #ifdef MKSH_NO_SIGSUSPEND
1340 sigprocmask(SIG_SETMASK, &omask, NULL);
1342 errno = saved_errno;
1346 * Called only when a process in j has exited/stopped (ie, called only
1347 * from j_sigchld()). If no processes are running, the job status
1348 * and state are updated, asynchronous job notification is done and,
1349 * if unneeded, the job is removed.
1351 * If jobs are compiled in then this routine expects sigchld to be blocked.
1359 /* XXX debugging (nasty - interrupt routine using shl_out) */
1360 if (!(j->flags & JF_STARTED)) {
1361 internal_warningf("check_job: job started (flags 0x%x)",
1367 for (p=j->proc_list; p != NULL; p = p->next) {
1368 if (p->state == PRUNNING)
1369 /* some processes still running */
1371 if (p->state > jstate)
1375 j->status = proc_errorlevel(j->last_proc);
1378 * Note when co-process dies: can't be done in j_wait() nor
1379 * remove_job() since neither may be called for non-interactive
1382 if (j->state == PEXITED || j->state == PSIGNALLED) {
1384 * No need to keep co-process input any more
1385 * (at least, this is what ksh93d thinks)
1387 if (coproc.job == j) {
1390 * XXX would be nice to get the closes out of here
1391 * so they aren't done in the signal handler.
1392 * Would mean a check in coproc_getfd() to
1393 * do "if job == 0 && write >= 0, close write".
1395 coproc_write_close(coproc.write);
1397 /* Do we need to keep the output? */
1398 if (j->coproc_id && j->coproc_id == coproc.id &&
1399 --coproc.njobs == 0)
1400 coproc_readw_close(coproc.read);
1403 j->flags |= JF_CHANGED;
1404 #ifndef MKSH_UNEMPLOYED
1405 if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1407 * Only put stopped jobs at the front to avoid confusing
1408 * the user (don't want finished jobs effecting %+ or %-)
1410 if (j->state == PSTOPPED)
1411 put_job(j, PJ_ON_FRONT);
1412 if (Flag(FNOTIFY) &&
1413 (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1414 /* Look for the real file descriptor 2 */
1419 for (ep = e; ep; ep = ep->oenv)
1420 if (ep->savefd && ep->savefd[2])
1422 shf_reopen(fd, SHF_WR, shl_j);
1425 * Can't call j_notify() as it removes jobs. The job
1426 * must stay in the job list as j_waitj() may be
1427 * running with this job.
1429 j_print(j, JP_MEDIUM, shl_j);
1431 if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1432 remove_job(j, "notify");
1437 #ifndef MKSH_UNEMPLOYED
1440 !(j->flags & (JF_WAITING|JF_FG)) &&
1441 j->state != PSTOPPED) {
1442 if (j == async_job || (j->flags & JF_KNOWN)) {
1443 j->flags |= JF_ZOMBIE;
1447 remove_job(j, "checkjob");
1452 * Print job status in either short, medium or long format.
1454 * If jobs are compiled in then this routine expects sigchld to be blocked.
1457 j_print(Job *j, int how, struct shf *shf)
1468 if (how == JP_PGRP) {
1470 * POSIX doesn't say what to do it there is no process
1471 * group leader (ie, !FMONITOR). We arbitrarily return
1472 * last pid (which is what $! returns).
1474 shf_fprintf(shf, "%d\n", (int)(j->pgrp ? j->pgrp :
1475 (j->last_proc ? j->last_proc->pid : 0)));
1478 j->flags &= ~JF_CHANGED;
1479 filler = j->job > 10 ? "\n " : "\n ";
1482 else if (j == job_list->next)
1485 for (p = j->proc_list; p != NULL;) {
1489 memcpy(buf, "Running", 8);
1492 strlcpy(buf, sigtraps[WSTOPSIG(p->status)].mess,
1496 if (how == JP_SHORT)
1498 else if (WEXITSTATUS(p->status) == 0)
1499 memcpy(buf, "Done", 5);
1501 shf_snprintf(buf, sizeof(buf), "Done (%d)",
1502 WEXITSTATUS(p->status));
1506 if (WCOREDUMP(p->status))
1510 * kludge for not reporting 'normal termination
1511 * signals' (i.e. SIGINT, SIGPIPE)
1513 if (how == JP_SHORT && !coredumped &&
1514 (WTERMSIG(p->status) == SIGINT ||
1515 WTERMSIG(p->status) == SIGPIPE)) {
1518 strlcpy(buf, sigtraps[WTERMSIG(p->status)].mess,
1525 if (how != JP_SHORT) {
1526 if (p == j->proc_list)
1527 shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1529 shf_puts(filler, shf);
1533 shf_fprintf(shf, "%5d ", (int)p->pid);
1535 if (how == JP_SHORT) {
1538 shf_fprintf(shf, "%s%s ",
1539 buf, coredumped ? " (core dumped)" : null);
1543 shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1544 p->next ? "|" : null,
1545 coredumped ? " (core dumped)" : null);
1551 while (p && p->state == state && p->status == status) {
1553 shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
1554 (int)p->pid, " ", p->command,
1555 p->next ? "|" : null);
1556 else if (how == JP_MEDIUM)
1557 shf_fprintf(shf, " %s%s", p->command,
1558 p->next ? "|" : null);
1563 shf_putc('\n', shf);
1567 * Convert % sequence to job
1569 * If jobs are compiled in then this routine expects sigchld to be blocked.
1572 j_lookup(const char *cp, int *ecodep)
1574 Job *j, *last_match;
1579 if (ksh_isdigit(*cp)) {
1581 /* Look for last_proc->pid (what $! returns) first... */
1582 for (j = job_list; j != NULL; j = j->next)
1583 if (j->last_proc && j->last_proc->pid == job)
1586 * ...then look for process group (this is non-POSIX,
1587 * but should not break anything
1589 for (j = job_list; j != NULL; j = j->next)
1590 if (j->pgrp && j->pgrp == job)
1593 *ecodep = JL_NOSUCH;
1598 *ecodep = JL_INVALID;
1602 case '\0': /* non-standard */
1605 if (job_list != NULL)
1610 if (job_list != NULL && job_list->next)
1611 return (job_list->next);
1614 case '0': case '1': case '2': case '3': case '4':
1615 case '5': case '6': case '7': case '8': case '9':
1617 for (j = job_list; j != NULL; j = j->next)
1625 for (j = job_list; j != NULL; j = j->next)
1626 for (p = j->proc_list; p != NULL; p = p->next)
1627 if (strstr(p->command, cp+1) != NULL) {
1636 return (last_match);
1643 for (j = job_list; j != NULL; j = j->next)
1644 if (strncmp(cp, j->proc_list->command, len) == 0) {
1653 return (last_match);
1657 *ecodep = JL_NOSUCH;
1661 static Job *free_jobs;
1662 static Proc *free_procs;
1665 * allocate a new job and fill in the job number.
1667 * If jobs are compiled in then this routine expects sigchld to be blocked.
1675 if (free_jobs != NULL) {
1677 free_jobs = free_jobs->next;
1679 newj = alloc(sizeof(Job), APERM);
1681 /* brute force method */
1682 for (i = 1; ; i++) {
1683 for (j = job_list; j && j->job != i; j = j->next)
1694 * Allocate new process struct
1696 * If jobs are compiled in then this routine expects sigchld to be blocked.
1703 if (free_procs != NULL) {
1705 free_procs = free_procs->next;
1707 p = alloc(sizeof(Proc), APERM);
1713 * Take job out of job_list and put old structures into free list.
1714 * Keeps nzombies, last_job and async_job up to date.
1716 * If jobs are compiled in then this routine expects sigchld to be blocked.
1719 remove_job(Job *j, const char *where)
1727 while (curr && curr != j) {
1732 internal_warningf("remove_job: job %s (%s)", "not found", where);
1737 /* free up proc structures */
1738 for (p = j->proc_list; p != NULL; ) {
1741 tmp->next = free_procs;
1745 if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1747 j->next = free_jobs;
1757 * put j in a particular location (taking it out job_list if it is there
1760 * If jobs are compiled in then this routine expects sigchld to be blocked.
1763 put_job(Job *j, int where)
1768 /* Remove job from list (if there) */
1771 while (curr && curr != j) {
1784 case PJ_PAST_STOPPED:
1787 for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1797 * nuke a job (called when unable to start full job).
1799 * If jobs are compiled in then this routine expects sigchld to be blocked.
1802 kill_job(Job *j, int sig)
1807 for (p = j->proc_list; p != NULL; p = p->next)
1809 if (kill(p->pid, sig) < 0)
1815 tty_init_talking(void)
1817 switch (tty_init_fd()) {
1821 #ifndef MKSH_DISABLE_TTY_WARNING
1822 warningf(false, "%s: %s %s: %s",
1823 "No controlling tty", "open", "/dev/tty",
1828 #ifndef MKSH_DISABLE_TTY_WARNING
1829 warningf(false, "%s: %s", "can't find tty fd", cstrerror(errno));
1833 warningf(false, "%s: %s %s: %s", "j_ttyinit",
1834 "dup of tty fd", "failed", cstrerror(errno));
1837 warningf(false, "%s: %s: %s", "j_ttyinit",
1838 "can't set close-on-exec flag", cstrerror(errno));
1844 tty_init_state(void)
1847 mksh_tcget(tty_fd, &tty_state);
1848 tty_hasstate = true;