2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 static char sccsid[] = "@(#)jobs.c 8.5 (Berkeley) 5/4/95";
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD: src/bin/sh/jobs.c,v 1.27.2.10 2003/04/04 08:16:26 tjr Exp $");
51 #include <sys/param.h>
54 #include <sys/resource.h>
56 #include <sys/ioctl.h>
61 #undef CEOF /* syntax.h redefines this */
79 struct job *jobtab; /* array of jobs */
80 int njobs; /* size of array */
81 MKINIT pid_t backgndpid = -1; /* pid of last background process */
83 struct job *jobmru; /* most recently used job list */
84 pid_t initialpgrp; /* pgrp of shell on invocation */
86 int in_waitcmd = 0; /* are we in waitcmd()? */
87 int in_dowait = 0; /* are we in dowait()? */
88 volatile sig_atomic_t breakwaitcmd = 0; /* should wait be terminated? */
89 static int ttyfd = -1;
92 STATIC void restartjob(struct job *);
94 STATIC void freejob(struct job *);
95 STATIC struct job *getjob(char *);
96 STATIC pid_t dowait(int, struct job *);
97 STATIC pid_t waitproc(int, int *);
98 STATIC void cmdtxt(union node *);
99 STATIC void cmdputs(char *);
101 STATIC void setcurjob(struct job *);
102 STATIC void deljob(struct job *);
103 STATIC struct job *getcurjob(struct job *);
105 STATIC void showjob(struct job *, pid_t, int, int);
109 * Turn job control on and off.
120 if (on == jobctl || rootshell == 0)
125 if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
127 while (i <= 2 && !isatty(i))
129 if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
134 * Keep our TTY file descriptor out of the way of
135 * the user's redirections.
137 if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
145 if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
150 do { /* while we are in the background */
151 initialpgrp = tcgetpgrp(ttyfd);
152 if (initialpgrp < 0) {
153 out: out2str("sh: can't access tty; job control turned off\n");
157 if (initialpgrp == -1)
158 initialpgrp = getpgrp();
159 else if (initialpgrp != getpgrp()) {
168 tcsetpgrp(ttyfd, rootpid);
169 } else { /* turning job control off */
170 setpgid(0, initialpgrp);
171 tcsetpgrp(ttyfd, initialpgrp);
184 INCLUDE <sys/types.h>
200 fgcmd(int argc __unused, char **argv)
206 jp = getjob(argv[1]);
208 error("job not created under job control");
209 out1str(jp->ps[0].cmd);
212 pgrp = jp->ps[0].pid;
213 tcsetpgrp(ttyfd, pgrp);
217 status = waitforjob(jp, (int *)NULL);
224 bgcmd(int argc, char **argv)
230 jp = getjob(*++argv);
232 error("job not created under job control");
233 if (jp->state == JOBDONE)
237 fmtstr(s, 64, "[%d] ", jp - jobtab + 1);
239 out1str(jp->ps[0].cmd);
241 } while (--argc > 1);
247 restartjob(struct job *jp)
252 if (jp->state == JOBDONE)
256 killpg(jp->ps[0].pid, SIGCONT);
257 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
258 if (WIFSTOPPED(ps->status)) {
269 jobscmd(int argc, char *argv[])
272 int ch, sformat, lformat;
274 optind = optreset = 1;
276 sformat = lformat = 0;
277 while ((ch = getopt(argc, argv, "ls")) != -1) {
287 error("unknown option: -%c", optopt);
294 showjobs(0, sformat, lformat);
296 while ((id = *argv++) != NULL)
297 showjob(getjob(id), 0, sformat, lformat);
303 showjob(struct job *jp, pid_t pid, int sformat, int lformat)
308 int col, curr, i, jobno, prev, procno;
312 jobno = jp - jobtab + 1;
315 if ((j = getcurjob(NULL)) != NULL) {
316 curr = j - jobtab + 1;
317 if ((j = getcurjob(j)) != NULL)
318 prev = j - jobtab + 1;
321 for (ps = jp->ps ; ; ps++) { /* for each process */
323 out1fmt("%d\n", (int)ps->pid);
326 if (!lformat && ps != jp->ps && pid == 0)
328 if (pid != 0 && pid != ps->pid)
330 if (jobno == curr && ps == jp->ps)
332 else if (jobno == prev && ps == jp->ps)
337 fmtstr(s, 64, "[%d] %c ", jobno, c);
339 fmtstr(s, 64, " %c ", c);
343 fmtstr(s, 64, "%d ", (int)ps->pid);
350 } else if (ps->status == -1) {
351 strcpy(s, "Running");
352 } else if (WIFEXITED(ps->status)) {
353 if (WEXITSTATUS(ps->status) == 0)
356 fmtstr(s, 64, "Done (%d)",
357 WEXITSTATUS(ps->status));
360 if (WIFSTOPPED(ps->status))
361 i = WSTOPSIG(ps->status);
364 i = WTERMSIG(ps->status);
365 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
366 scopy(sys_siglist[i & 0x7F], s);
368 fmtstr(s, 64, "Signal %d", i & 0x7F);
369 if (WCOREDUMP(ps->status))
370 strcat(s, " (core dumped)");
380 skip: if (--procno <= 0)
386 * Print a list of jobs. If "change" is nonzero, only print jobs whose
387 * statuses have changed since the last call to showjobs.
389 * If the shell is interrupted in the process of creating a job, the
390 * result may be a job structure containing zero processes. Such structures
391 * will be freed here.
395 showjobs(int change, int sformat, int lformat)
400 TRACE(("showjobs(%d) called\n", change));
401 while (dowait(0, (struct job *)NULL) > 0);
402 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
405 if (jp->nprocs == 0) {
409 if (change && ! jp->changed)
411 showjob(jp, 0, sformat, lformat);
413 if (jp->state == JOBDONE) {
421 * Mark a job structure as unused.
425 freejob(struct job *jp)
431 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
432 if (ps->cmd != nullstr)
435 if (jp->ps != &jp->ps0)
447 waitcmd(int argc, char **argv)
454 job = getjob(argv[1]);
460 * Loop until a process is terminated or stopped, or a SIGINT is
468 status = job->ps[job->nprocs - 1].status;
469 if (WIFEXITED(status))
470 retval = WEXITSTATUS(status);
472 else if (WIFSTOPPED(status))
473 retval = WSTOPSIG(status) + 128;
476 retval = WTERMSIG(status) + 128;
483 for (jp = jobtab ; ; jp++) {
484 if (jp >= jobtab + njobs) { /* no running procs */
488 if (jp->used && jp->state == 0)
492 } while (dowait(1, (struct job *)NULL) != -1);
501 jobidcmd(int argc __unused, char **argv)
506 jp = getjob(argv[1]);
507 for (i = 0 ; i < jp->nprocs ; ) {
508 out1fmt("%d", (int)jp->ps[i].pid);
509 out1c(++i < jp->nprocs? ' ' : '\n');
517 * Convert a job name to a job structure.
524 struct job *found, *jp;
530 currentjob: if ((jp = getcurjob(NULL)) == NULL)
531 error("No current job");
534 error("No current job");
536 } else if (name[0] == '%') {
537 if (is_digit(name[1])) {
538 jobno = number(name + 1);
539 if (jobno > 0 && jobno <= njobs
540 && jobtab[jobno - 1].used != 0)
541 return &jobtab[jobno - 1];
543 } else if (name[1] == '%' && name[2] == '\0') {
545 } else if (name[1] == '+' && name[2] == '\0') {
547 } else if (name[1] == '-' && name[2] == '\0') {
548 if ((jp = getcurjob(NULL)) == NULL ||
549 (jp = getcurjob(jp)) == NULL)
550 error("No previous job");
553 } else if (name[1] == '?') {
555 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
556 if (jp->used && jp->nprocs > 0
557 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
559 error("%s: ambiguous", name);
567 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
568 if (jp->used && jp->nprocs > 0
569 && prefix(name + 1, jp->ps[0].cmd)) {
571 error("%s: ambiguous", name);
578 } else if (is_number(name)) {
579 pid = (pid_t)number(name);
580 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
581 if (jp->used && jp->nprocs > 0
582 && jp->ps[jp->nprocs - 1].pid == pid)
586 error("No such job: %s", name);
594 * Return a new job structure,
598 makejob(union node *node __unused, int nprocs)
603 for (i = njobs, jp = jobtab ; ; jp++) {
607 jobtab = ckmalloc(4 * sizeof jobtab[0]);
612 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
613 memcpy(jp, jobtab, njobs * sizeof jp[0]);
615 /* Relocate `next' pointers and list head */
617 jobmru = &jp[jobmru - jobtab];
618 for (i = 0; i < njobs; i++)
619 if (jp[i].next != NULL)
620 jp[i].next = &jp[jp[i].next -
623 /* Relocate `ps' pointers */
624 for (i = 0; i < njobs; i++)
625 if (jp[i].ps == &jobtab[i].ps0)
626 jp[i].ps = &jp[i].ps0;
631 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
649 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
654 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
661 setcurjob(struct job *cj)
663 struct job *jp, *prev;
665 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
668 prev->next = jp->next;
681 deljob(struct job *j)
683 struct job *jp, *prev;
685 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
688 prev->next = jp->next;
697 * Return the most recently used job that isn't `nj', and preferably one
701 getcurjob(struct job *nj)
705 /* Try to find a stopped one.. */
706 for (jp = jobmru; jp != NULL; jp = jp->next)
707 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
709 /* Otherwise the most recently used job that isn't `nj' */
710 for (jp = jobmru; jp != NULL; jp = jp->next)
711 if (jp->used && jp != nj)
720 * Fork of a subshell. If we are doing job control, give the subshell its
721 * own process group. Jp is a job structure that the job is to be added to.
722 * N is the command that will be evaluated by the child. Both jp and n may
723 * be NULL. The mode parameter can be one of the following:
724 * FORK_FG - Fork off a foreground process.
725 * FORK_BG - Fork off a background process.
726 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
727 * process group even if job control is on.
729 * When job control is turned off, background processes have their standard
730 * input redirected to /dev/null (except for the second and later processes
735 forkshell(struct job *jp, union node *n, int mode)
740 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
746 TRACE(("Fork failed, errno=%d\n", errno));
748 error("Cannot fork: %s", strerror(errno));
755 TRACE(("Child shell %d\n", (int)getpid()));
762 jobctl = 0; /* do job control only in root shell */
763 if (wasroot && mode != FORK_NOJOB && mflag) {
764 if (jp == NULL || jp->nprocs == 0)
767 pgrp = jp->ps[0].pid;
768 if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
769 /*** this causes superfluous TIOCSPGRPS ***/
770 if (tcsetpgrp(ttyfd, pgrp) < 0)
771 error("tcsetpgrp failed, errno=%d", errno);
775 } else if (mode == FORK_BG) {
778 if ((jp == NULL || jp->nprocs == 0) &&
779 ! fd0_redirected_p ()) {
781 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
782 error("Can't open %s: %s",
783 _PATH_DEVNULL, strerror(errno));
787 if (mode == FORK_BG) {
790 if ((jp == NULL || jp->nprocs == 0) &&
791 ! fd0_redirected_p ()) {
793 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
794 error("Can't open %s: %s",
795 _PATH_DEVNULL, strerror(errno));
800 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
804 if (wasroot && iflag) {
811 if (rootshell && mode != FORK_NOJOB && mflag) {
812 if (jp == NULL || jp->nprocs == 0)
815 pgrp = jp->ps[0].pid;
819 backgndpid = pid; /* set $! */
821 struct procstat *ps = &jp->ps[jp->nprocs++];
825 if (iflag && rootshell && n)
826 ps->cmd = commandtext(n);
827 jp->foreground = mode == FORK_FG;
833 TRACE(("In parent shell: child = %d\n", (int)pid));
840 * Wait for job to finish.
842 * Under job control we have the problem that while a child process is
843 * running interrupts generated by the user are sent to the child but not
844 * to the shell. This means that an infinite loop started by an inter-
845 * active user may be hard to kill. With job control turned off, an
846 * interactive user may place an interactive program inside a loop. If
847 * the interactive program catches interrupts, the user doesn't want
848 * these interrupts to also abort the loop. The approach we take here
849 * is to have the shell ignore interrupt signals while waiting for a
850 * foreground process to terminate, and then send itself an interrupt
851 * signal if the child process was terminated by an interrupt signal.
852 * Unfortunately, some programs want to do a bit of cleanup and then
853 * exit on interrupt; unless these processes terminate themselves by
854 * sending a signal to themselves (instead of calling exit) they will
855 * confuse this approach.
859 waitforjob(struct job *jp, int *origstatus)
862 pid_t mypgrp = getpgrp();
868 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
869 while (jp->state == 0)
870 if (dowait(1, jp) == -1)
874 if (tcsetpgrp(ttyfd, mypgrp) < 0)
875 error("tcsetpgrp failed, errno=%d\n", errno);
877 if (jp->state == JOBSTOPPED)
880 status = jp->ps[jp->nprocs - 1].status;
881 if (origstatus != NULL)
882 *origstatus = status;
883 /* convert to 8 bits */
884 if (WIFEXITED(status))
885 st = WEXITSTATUS(status);
887 else if (WIFSTOPPED(status))
888 st = WSTOPSIG(status) + 128;
891 st = WTERMSIG(status) + 128;
892 if (! JOBS || jp->state == JOBDONE)
895 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
896 kill(getpid(), SIGINT);
907 * Wait for a process to terminate.
911 dowait(int block, struct job *job)
924 TRACE(("dowait(%d) called\n", block));
926 pid = waitproc(block, &status);
927 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
928 } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
929 (WIFSTOPPED(status) && !iflag));
931 if (breakwaitcmd != 0) {
939 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
943 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
946 if (sp->pid == pid) {
947 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
948 (int)pid, sp->status,
953 if (sp->status == -1)
955 else if (WIFSTOPPED(sp->status))
958 if (stopped) { /* stopped or done */
959 int state = done? JOBDONE : JOBSTOPPED;
960 if (jp->state != state) {
961 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
972 if (! rootshell || ! iflag || (job && thisjob == job)) {
974 if (WIFSTOPPED(status))
975 sig = WSTOPSIG(status);
979 if (WIFEXITED(status))
982 sig = WTERMSIG(status);
984 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
986 (thisjob->foreground && !WIFSTOPPED(status))) {
987 i = WTERMSIG(status);
988 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
989 out1str(sys_siglist[i & 0x7F]);
991 out1fmt("Signal %d", i & 0x7F);
992 if (WCOREDUMP(status))
993 out1str(" (core dumped)");
996 showjob(thisjob, pid, 0, 0);
999 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
1001 thisjob->changed = 1;
1009 * Do a wait system call. If job control is compiled in, we accept
1010 * stopped processes. If block is zero, we return a value of zero
1011 * rather than blocking.
1014 waitproc(int block, int *status)
1025 return wait3(status, flags, (struct rusage *)NULL);
1029 * return 1 if there are stopped jobs, otherwise 0
1031 int job_warning = 0;
1040 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1043 if (jp->state == JOBSTOPPED) {
1044 out2str("You have stopped jobs.\n");
1054 * Return a string identifying a command (to be printed by the
1058 STATIC char *cmdnextc;
1059 STATIC int cmdnleft;
1060 #define MAXCMDTEXT 200
1063 commandtext(union node *n)
1067 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1068 cmdnleft = MAXCMDTEXT - 4;
1076 cmdtxt(union node *n)
1079 struct nodelist *lp;
1088 cmdtxt(n->nbinary.ch1);
1090 cmdtxt(n->nbinary.ch2);
1093 cmdtxt(n->nbinary.ch1);
1095 cmdtxt(n->nbinary.ch2);
1098 cmdtxt(n->nbinary.ch1);
1100 cmdtxt(n->nbinary.ch2);
1103 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1111 cmdtxt(n->nredir.n);
1116 cmdtxt(n->nredir.n);
1120 cmdtxt(n->nif.test);
1122 cmdtxt(n->nif.ifpart);
1131 cmdtxt(n->nbinary.ch1);
1133 cmdtxt(n->nbinary.ch2);
1138 cmdputs(n->nfor.var);
1143 cmdputs(n->ncase.expr->narg.text);
1147 cmdputs(n->narg.text);
1151 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1156 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1162 cmdputs(n->narg.text);
1165 p = ">"; i = 1; goto redir;
1167 p = ">>"; i = 1; goto redir;
1169 p = ">&"; i = 1; goto redir;
1171 p = ">|"; i = 1; goto redir;
1173 p = "<"; i = 0; goto redir;
1175 p = "<>"; i = 0; goto redir;
1177 p = "<&"; i = 0; goto redir;
1179 if (n->nfile.fd != i) {
1180 s[0] = n->nfile.fd + '0';
1185 if (n->type == NTOFD || n->type == NFROMFD) {
1186 if (n->ndup.dupfd >= 0)
1187 s[0] = n->ndup.dupfd + '0';
1193 cmdtxt(n->nfile.fname);
1219 while ((c = *p++) != '\0') {
1222 else if (c == CTLVAR) {
1227 } else if (c == '=' && subtype != 0) {
1228 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1230 } else if (c == CTLENDVAR) {
1232 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1233 cmdnleft++; /* ignore it */
1236 if (--cmdnleft <= 0) {