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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 static char sccsid[] = "@(#)jobs.c 8.5 (Berkeley) 5/4/95";
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
41 #include <sys/ioctl.h>
42 #include <sys/param.h>
43 #include <sys/resource.h>
57 #undef CEOF /* syntax.h redefines this */
75 static struct job *jobtab; /* array of jobs */
76 static int njobs; /* size of array */
77 MKINIT pid_t backgndpid = -1; /* pid of last background process */
79 static struct job *jobmru; /* most recently used job list */
80 static pid_t initialpgrp; /* pgrp of shell on invocation */
82 int in_waitcmd = 0; /* are we in waitcmd()? */
83 int in_dowait = 0; /* are we in dowait()? */
84 volatile sig_atomic_t breakwaitcmd = 0; /* should wait be terminated? */
85 static int ttyfd = -1;
88 static void restartjob(struct job *);
90 static void freejob(struct job *);
91 static struct job *getjob(char *);
92 static pid_t dowait(int, struct job *);
93 static pid_t waitproc(int, int *);
94 static void checkzombies(void);
95 static void cmdtxt(union node *);
96 static void cmdputs(const char *);
98 static void setcurjob(struct job *);
99 static void deljob(struct job *);
100 static struct job *getcurjob(struct job *);
102 static void showjob(struct job *, pid_t, int);
106 * Turn job control on and off.
117 if (on == jobctl || rootshell == 0)
122 if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
124 while (i <= 2 && !isatty(i))
126 if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
131 * Keep our TTY file descriptor out of the way of
132 * the user's redirections.
134 if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
142 if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
147 do { /* while we are in the background */
148 initialpgrp = tcgetpgrp(ttyfd);
149 if (initialpgrp < 0) {
150 out: out2str("sh: can't access tty; job control turned off\n");
154 if (initialpgrp == -1)
155 initialpgrp = getpgrp();
156 else if (initialpgrp != getpgrp()) {
165 tcsetpgrp(ttyfd, rootpid);
166 } else { /* turning job control off */
167 setpgid(0, initialpgrp);
168 tcsetpgrp(ttyfd, initialpgrp);
181 INCLUDE <sys/types.h>
197 fgcmd(int argc __unused, char **argv)
203 jp = getjob(argv[1]);
205 error("job not created under job control");
206 out1str(jp->ps[0].cmd);
209 pgrp = jp->ps[0].pid;
210 tcsetpgrp(ttyfd, pgrp);
214 status = waitforjob(jp, (int *)NULL);
221 bgcmd(int argc, char **argv)
227 jp = getjob(*++argv);
229 error("job not created under job control");
230 if (jp->state == JOBDONE)
234 fmtstr(s, 64, "[%td] ", jp - jobtab + 1);
236 out1str(jp->ps[0].cmd);
238 } while (--argc > 1);
244 restartjob(struct job *jp)
249 if (jp->state == JOBDONE)
253 killpg(jp->ps[0].pid, SIGCONT);
254 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
255 if (WIFSTOPPED(ps->status)) {
266 jobscmd(int argc, char *argv[])
271 optind = optreset = 1;
273 mode = SHOWJOBS_DEFAULT;
274 while ((ch = getopt(argc, argv, "lps")) != -1) {
277 mode = SHOWJOBS_VERBOSE;
280 mode = SHOWJOBS_PGIDS;
283 mode = SHOWJOBS_PIDS;
287 error("unknown option: -%c", optopt);
296 while ((id = *argv++) != NULL)
297 showjob(getjob(id), 0, mode);
303 showjob(struct job *jp, pid_t pid, int mode)
308 int col, curr, i, jobno, prev, procno;
312 procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
313 jobno = jp - jobtab + 1;
316 if ((j = getcurjob(NULL)) != NULL) {
317 curr = j - jobtab + 1;
318 if ((j = getcurjob(j)) != NULL)
319 prev = j - jobtab + 1;
322 for (ps = jp->ps ; ; ps++) { /* for each process */
323 if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
324 ppid = (mode == SHOWJOBS_PIDS) ? ps->pid :
326 out1fmt("%d\n", (int)ppid);
329 if (mode != SHOWJOBS_VERBOSE && ps != jp->ps && pid == 0)
331 if (pid != 0 && pid != ps->pid)
333 if (jobno == curr && ps == jp->ps)
335 else if (jobno == prev && ps == jp->ps)
340 fmtstr(s, 64, "[%d] %c ", jobno, c);
342 fmtstr(s, 64, " %c ", c);
345 if (mode == SHOWJOBS_VERBOSE) {
346 fmtstr(s, 64, "%d ", (int)ps->pid);
353 } else if (ps->status == -1) {
354 strcpy(s, "Running");
355 } else if (WIFEXITED(ps->status)) {
356 if (WEXITSTATUS(ps->status) == 0)
359 fmtstr(s, 64, "Done (%d)",
360 WEXITSTATUS(ps->status));
363 if (WIFSTOPPED(ps->status))
364 i = WSTOPSIG(ps->status);
367 i = WTERMSIG(ps->status);
368 if ((i & 0x7F) < sys_nsig && sys_siglist[i & 0x7F])
369 scopy(sys_siglist[i & 0x7F], s);
371 fmtstr(s, 64, "Signal %d", i & 0x7F);
372 if (WCOREDUMP(ps->status))
373 strcat(s, " (core dumped)");
383 skip: if (--procno <= 0)
389 * Print a list of jobs. If "change" is nonzero, only print jobs whose
390 * statuses have changed since the last call to showjobs.
392 * If the shell is interrupted in the process of creating a job, the
393 * result may be a job structure containing zero processes. Such structures
394 * will be freed here.
398 showjobs(int change, int mode)
403 TRACE(("showjobs(%d) called\n", change));
405 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
408 if (jp->nprocs == 0) {
412 if (change && ! jp->changed)
414 showjob(jp, 0, mode);
416 if (jp->state == JOBDONE) {
424 * Mark a job structure as unused.
428 freejob(struct job *jp)
434 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
435 if (ps->cmd != nullstr)
438 if (jp->ps != &jp->ps0)
450 waitcmd(int argc, char **argv)
457 job = getjob(argv[1]);
463 * Loop until a process is terminated or stopped, or a SIGINT is
471 status = job->ps[job->nprocs - 1].status;
472 if (WIFEXITED(status))
473 retval = WEXITSTATUS(status);
475 else if (WIFSTOPPED(status))
476 retval = WSTOPSIG(status) + 128;
479 retval = WTERMSIG(status) + 128;
486 for (jp = jobtab ; ; jp++) {
487 if (jp >= jobtab + njobs) { /* no running procs */
491 if (jp->used && jp->state == 0)
495 } while (dowait(1, (struct job *)NULL) != -1);
504 jobidcmd(int argc __unused, char **argv)
509 jp = getjob(argv[1]);
510 for (i = 0 ; i < jp->nprocs ; ) {
511 out1fmt("%d", (int)jp->ps[i].pid);
512 out1c(++i < jp->nprocs? ' ' : '\n');
520 * Convert a job name to a job structure.
527 struct job *found, *jp;
533 currentjob: if ((jp = getcurjob(NULL)) == NULL)
534 error("No current job");
537 error("No current job");
539 } else if (name[0] == '%') {
540 if (is_digit(name[1])) {
541 jobno = number(name + 1);
542 if (jobno > 0 && jobno <= njobs
543 && jobtab[jobno - 1].used != 0)
544 return &jobtab[jobno - 1];
546 } else if (name[1] == '%' && name[2] == '\0') {
548 } else if (name[1] == '+' && name[2] == '\0') {
550 } else if (name[1] == '-' && name[2] == '\0') {
551 if ((jp = getcurjob(NULL)) == NULL ||
552 (jp = getcurjob(jp)) == NULL)
553 error("No previous job");
556 } else if (name[1] == '?') {
558 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
559 if (jp->used && jp->nprocs > 0
560 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
562 error("%s: ambiguous", name);
570 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
571 if (jp->used && jp->nprocs > 0
572 && prefix(name + 1, jp->ps[0].cmd)) {
574 error("%s: ambiguous", name);
581 } else if (is_number(name)) {
582 pid = (pid_t)number(name);
583 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
584 if (jp->used && jp->nprocs > 0
585 && jp->ps[jp->nprocs - 1].pid == pid)
589 error("No such job: %s", name);
597 * Return a new job structure,
601 makejob(union node *node __unused, int nprocs)
606 for (i = njobs, jp = jobtab ; ; jp++) {
610 jobtab = ckmalloc(4 * sizeof jobtab[0]);
615 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
616 memcpy(jp, jobtab, njobs * sizeof jp[0]);
618 /* Relocate `next' pointers and list head */
620 jobmru = &jp[jobmru - jobtab];
621 for (i = 0; i < njobs; i++)
622 if (jp[i].next != NULL)
623 jp[i].next = &jp[jp[i].next -
626 /* Relocate `ps' pointers */
627 for (i = 0; i < njobs; i++)
628 if (jp[i].ps == &jobtab[i].ps0)
629 jp[i].ps = &jp[i].ps0;
634 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
652 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
657 TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
664 setcurjob(struct job *cj)
666 struct job *jp, *prev;
668 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
671 prev->next = jp->next;
684 deljob(struct job *j)
686 struct job *jp, *prev;
688 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
691 prev->next = jp->next;
700 * Return the most recently used job that isn't `nj', and preferably one
704 getcurjob(struct job *nj)
708 /* Try to find a stopped one.. */
709 for (jp = jobmru; jp != NULL; jp = jp->next)
710 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
712 /* Otherwise the most recently used job that isn't `nj' */
713 for (jp = jobmru; jp != NULL; jp = jp->next)
714 if (jp->used && jp != nj)
723 * Fork of a subshell. If we are doing job control, give the subshell its
724 * own process group. Jp is a job structure that the job is to be added to.
725 * N is the command that will be evaluated by the child. Both jp and n may
726 * be NULL. The mode parameter can be one of the following:
727 * FORK_FG - Fork off a foreground process.
728 * FORK_BG - Fork off a background process.
729 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
730 * process group even if job control is on.
732 * When job control is turned off, background processes have their standard
733 * input redirected to /dev/null (except for the second and later processes
738 forkshell(struct job *jp, union node *n, int mode)
743 TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
746 if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
751 TRACE(("Fork failed, errno=%d\n", errno));
753 error("Cannot fork: %s", strerror(errno));
760 TRACE(("Child shell %d\n", (int)getpid()));
767 jobctl = 0; /* do job control only in root shell */
768 if (wasroot && mode != FORK_NOJOB && mflag) {
769 if (jp == NULL || jp->nprocs == 0)
772 pgrp = jp->ps[0].pid;
773 if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
774 /*** this causes superfluous TIOCSPGRPS ***/
775 if (tcsetpgrp(ttyfd, pgrp) < 0)
776 error("tcsetpgrp failed, errno=%d", errno);
780 } else if (mode == FORK_BG) {
783 if ((jp == NULL || jp->nprocs == 0) &&
784 ! fd0_redirected_p ()) {
786 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
787 error("Can't open %s: %s",
788 _PATH_DEVNULL, strerror(errno));
792 if (mode == FORK_BG) {
795 if ((jp == NULL || jp->nprocs == 0) &&
796 ! fd0_redirected_p ()) {
798 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
799 error("Can't open %s: %s",
800 _PATH_DEVNULL, strerror(errno));
805 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
809 if (wasroot && iflag) {
816 if (rootshell && mode != FORK_NOJOB && mflag) {
817 if (jp == NULL || jp->nprocs == 0)
820 pgrp = jp->ps[0].pid;
824 backgndpid = pid; /* set $! */
826 struct procstat *ps = &jp->ps[jp->nprocs++];
830 if (iflag && rootshell && n)
831 ps->cmd = commandtext(n);
832 jp->foreground = mode == FORK_FG;
838 TRACE(("In parent shell: child = %d\n", (int)pid));
845 * Wait for job to finish.
847 * Under job control we have the problem that while a child process is
848 * running interrupts generated by the user are sent to the child but not
849 * to the shell. This means that an infinite loop started by an inter-
850 * active user may be hard to kill. With job control turned off, an
851 * interactive user may place an interactive program inside a loop. If
852 * the interactive program catches interrupts, the user doesn't want
853 * these interrupts to also abort the loop. The approach we take here
854 * is to have the shell ignore interrupt signals while waiting for a
855 * foreground process to terminate, and then send itself an interrupt
856 * signal if the child process was terminated by an interrupt signal.
857 * Unfortunately, some programs want to do a bit of cleanup and then
858 * exit on interrupt; unless these processes terminate themselves by
859 * sending a signal to themselves (instead of calling exit) they will
860 * confuse this approach.
864 waitforjob(struct job *jp, int *origstatus)
867 pid_t mypgrp = getpgrp();
868 int propagate_int = jp->jobctl && jp->foreground;
874 TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
875 while (jp->state == 0)
876 if (dowait(1, jp) == -1)
880 if (tcsetpgrp(ttyfd, mypgrp) < 0)
881 error("tcsetpgrp failed, errno=%d\n", errno);
883 if (jp->state == JOBSTOPPED)
886 status = jp->ps[jp->nprocs - 1].status;
887 if (origstatus != NULL)
888 *origstatus = status;
889 /* convert to 8 bits */
890 if (WIFEXITED(status))
891 st = WEXITSTATUS(status);
893 else if (WIFSTOPPED(status))
894 st = WSTOPSIG(status) + 128;
897 st = WTERMSIG(status) + 128;
898 if (! JOBS || jp->state == JOBDONE)
901 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
902 kill(getpid(), SIGINT);
907 else if (rootshell && iflag && propagate_int &&
908 WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
909 kill(getpid(), SIGINT);
918 * Wait for a process to terminate.
922 dowait(int block, struct job *job)
935 TRACE(("dowait(%d) called\n", block));
937 pid = waitproc(block, &status);
938 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
939 } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
940 (pid > 0 && WIFSTOPPED(status) && !iflag));
942 if (pid == -1 && errno == ECHILD && job != NULL)
943 job->state = JOBDONE;
944 if (breakwaitcmd != 0) {
953 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
954 if (jp->used && jp->nprocs > 0) {
957 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
960 if (sp->pid == pid) {
961 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
962 (int)pid, sp->status,
967 if (sp->status == -1)
969 else if (WIFSTOPPED(sp->status))
972 if (stopped) { /* stopped or done */
973 int state = done? JOBDONE : JOBSTOPPED;
974 if (jp->state != state) {
975 TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
986 if (! rootshell || ! iflag || (job && thisjob == job)) {
988 if (WIFSTOPPED(status))
989 sig = WSTOPSIG(status);
993 if (WIFEXITED(status))
996 sig = WTERMSIG(status);
998 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
1000 (thisjob->foreground && !WIFSTOPPED(status))) {
1001 i = WTERMSIG(status);
1002 if ((i & 0x7F) < sys_nsig && sys_siglist[i & 0x7F])
1003 out1str(sys_siglist[i & 0x7F]);
1005 out1fmt("Signal %d", i & 0x7F);
1006 if (WCOREDUMP(status))
1007 out1str(" (core dumped)");
1010 showjob(thisjob, pid, SHOWJOBS_DEFAULT);
1014 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1016 thisjob->changed = 1;
1024 * Do a wait system call. If job control is compiled in, we accept
1025 * stopped processes. If block is zero, we return a value of zero
1026 * rather than blocking.
1029 waitproc(int block, int *status)
1040 return wait3(status, flags, (struct rusage *)NULL);
1044 * return 1 if there are stopped jobs, otherwise 0
1046 int job_warning = 0;
1055 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1058 if (jp->state == JOBSTOPPED) {
1059 out2str("You have stopped jobs.\n");
1072 while (njobs > 0 && dowait(0, NULL) > 0)
1078 * Return a string identifying a command (to be printed by the
1082 static char *cmdnextc;
1083 static int cmdnleft;
1084 #define MAXCMDTEXT 200
1087 commandtext(union node *n)
1091 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1092 cmdnleft = MAXCMDTEXT - 4;
1100 cmdtxt(union node *n)
1103 struct nodelist *lp;
1112 cmdtxt(n->nbinary.ch1);
1114 cmdtxt(n->nbinary.ch2);
1117 cmdtxt(n->nbinary.ch1);
1119 cmdtxt(n->nbinary.ch2);
1122 cmdtxt(n->nbinary.ch1);
1124 cmdtxt(n->nbinary.ch2);
1127 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1135 cmdtxt(n->nredir.n);
1140 cmdtxt(n->nredir.n);
1144 cmdtxt(n->nif.test);
1146 cmdtxt(n->nif.ifpart);
1155 cmdtxt(n->nbinary.ch1);
1157 cmdtxt(n->nbinary.ch2);
1162 cmdputs(n->nfor.var);
1167 cmdputs(n->ncase.expr->narg.text);
1171 cmdputs(n->narg.text);
1175 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1180 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1186 cmdputs(n->narg.text);
1189 p = ">"; i = 1; goto redir;
1191 p = ">>"; i = 1; goto redir;
1193 p = ">&"; i = 1; goto redir;
1195 p = ">|"; i = 1; goto redir;
1197 p = "<"; i = 0; goto redir;
1199 p = "<>"; i = 0; goto redir;
1201 p = "<&"; i = 0; goto redir;
1203 if (n->nfile.fd != i) {
1204 s[0] = n->nfile.fd + '0';
1209 if (n->type == NTOFD || n->type == NFROMFD) {
1210 if (n->ndup.dupfd >= 0)
1211 s[0] = n->ndup.dupfd + '0';
1217 cmdtxt(n->nfile.fname);
1233 cmdputs(const char *s)
1244 while ((c = *p++) != '\0') {
1247 else if (c == CTLVAR) {
1252 } else if (c == '=' && subtype != 0) {
1253 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1255 } else if (c == CTLENDVAR) {
1257 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1258 cmdnleft++; /* ignore it */
1261 if (--cmdnleft <= 0) {