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
36 * @(#)jobs.c 8.5 (Berkeley) 5/4/95
37 * $FreeBSD: src/bin/sh/jobs.c,v 1.27.2.10 2003/04/04 08:16:26 tjr Exp $
38 * $DragonFly: src/bin/sh/jobs.c,v 1.7 2005/01/13 23:20:07 dillon Exp $
47 #include <sys/param.h>
50 #include <sys/resource.h>
52 #include <sys/ioctl.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 cmdtxt(union node *);
95 STATIC void cmdputs(const char *);
97 STATIC void setcurjob(struct job *);
98 STATIC void deljob(struct job *);
99 STATIC struct job *getcurjob(struct job *);
101 STATIC void showjob(struct job *, pid_t, int, int);
105 * Turn job control on and off.
116 if (on == jobctl || rootshell == 0)
121 if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
123 while (i <= 2 && !isatty(i))
125 if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
130 * Keep our TTY file descriptor out of the way of
131 * the user's redirections.
133 if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
141 if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
146 do { /* while we are in the background */
147 initialpgrp = tcgetpgrp(ttyfd);
148 if (initialpgrp < 0) {
149 out: out2str("sh: can't access tty; job control turned off\n");
153 if (initialpgrp == -1)
154 initialpgrp = getpgrp();
155 else if (initialpgrp != getpgrp()) {
164 tcsetpgrp(ttyfd, rootpid);
165 } else { /* turning job control off */
166 setpgid(0, initialpgrp);
167 tcsetpgrp(ttyfd, initialpgrp);
180 INCLUDE <sys/types.h>
196 fgcmd(int argc __unused, char **argv)
202 jp = getjob(argv[1]);
204 error("job not created under job control");
205 out1str(jp->ps[0].cmd);
208 pgrp = jp->ps[0].pid;
209 tcsetpgrp(ttyfd, pgrp);
213 status = waitforjob(jp, (int *)NULL);
220 bgcmd(int argc, char **argv)
226 jp = getjob(*++argv);
228 error("job not created under job control");
229 if (jp->state == JOBDONE)
233 fmtstr(s, 64, "[%d] ", jp - jobtab + 1);
235 out1str(jp->ps[0].cmd);
237 } while (--argc > 1);
243 restartjob(struct job *jp)
248 if (jp->state == JOBDONE)
252 killpg(jp->ps[0].pid, SIGCONT);
253 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
254 if (WIFSTOPPED(ps->status)) {
265 jobscmd(int argc, char *argv[])
268 int ch, sformat, lformat;
270 optind = optreset = 1;
272 sformat = lformat = 0;
273 while ((ch = getopt(argc, argv, "ls")) != -1) {
283 error("unknown option: -%c", optopt);
290 showjobs(0, sformat, lformat);
292 while ((id = *argv++) != NULL)
293 showjob(getjob(id), 0, sformat, lformat);
299 showjob(struct job *jp, pid_t pid, int sformat, int lformat)
304 int col, curr, i, jobno, prev, procno;
308 jobno = jp - jobtab + 1;
311 if ((j = getcurjob(NULL)) != NULL) {
312 curr = j - jobtab + 1;
313 if ((j = getcurjob(j)) != NULL)
314 prev = j - jobtab + 1;
317 for (ps = jp->ps ; ; ps++) { /* for each process */
319 out1fmt("%d\n", (int)ps->pid);
322 if (!lformat && ps != jp->ps && pid == 0)
324 if (pid != 0 && pid != ps->pid)
326 if (jobno == curr && ps == jp->ps)
328 else if (jobno == prev && ps == jp->ps)
333 fmtstr(s, 64, "[%d] %c ", jobno, c);
335 fmtstr(s, 64, " %c ", c);
339 fmtstr(s, 64, "%d ", (int)ps->pid);
346 } else if (ps->status == -1) {
347 strcpy(s, "Running");
348 } else if (WIFEXITED(ps->status)) {
349 if (WEXITSTATUS(ps->status) == 0)
352 fmtstr(s, 64, "Done (%d)",
353 WEXITSTATUS(ps->status));
356 if (WIFSTOPPED(ps->status))
357 i = WSTOPSIG(ps->status);
360 i = WTERMSIG(ps->status);
361 if ((i & 0x7F) < sys_nsig && sys_siglist[i & 0x7F])
362 scopy(sys_siglist[i & 0x7F], s);
364 fmtstr(s, 64, "Signal %d", i & 0x7F);
365 if (WCOREDUMP(ps->status))
366 strcat(s, " (core dumped)");
376 skip: if (--procno <= 0)
382 * Print a list of jobs. If "change" is nonzero, only print jobs whose
383 * statuses have changed since the last call to showjobs.
385 * If the shell is interrupted in the process of creating a job, the
386 * result may be a job structure containing zero processes. Such structures
387 * will be freed here.
391 showjobs(int change, int sformat, int lformat)
396 TRACE(("showjobs(%d) called\n", change));
397 while (dowait(0, (struct job *)NULL) > 0);
398 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
401 if (jp->nprocs == 0) {
405 if (change && ! jp->changed)
407 showjob(jp, 0, sformat, lformat);
409 if (jp->state == JOBDONE) {
417 * Mark a job structure as unused.
421 freejob(struct job *jp)
427 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
428 if (ps->cmd != nullstr)
431 if (jp->ps != &jp->ps0)
443 waitcmd(int argc, char **argv)
450 job = getjob(argv[1]);
456 * Loop until a process is terminated or stopped, or a SIGINT is
464 status = job->ps[job->nprocs - 1].status;
465 if (WIFEXITED(status))
466 retval = WEXITSTATUS(status);
468 else if (WIFSTOPPED(status))
469 retval = WSTOPSIG(status) + 128;
472 retval = WTERMSIG(status) + 128;
479 for (jp = jobtab ; ; jp++) {
480 if (jp >= jobtab + njobs) { /* no running procs */
484 if (jp->used && jp->state == 0)
488 } while (dowait(1, (struct job *)NULL) != -1);
497 jobidcmd(int argc __unused, char **argv)
502 jp = getjob(argv[1]);
503 for (i = 0 ; i < jp->nprocs ; ) {
504 out1fmt("%d", (int)jp->ps[i].pid);
505 out1c(++i < jp->nprocs? ' ' : '\n');
513 * Convert a job name to a job structure.
520 struct job *found, *jp;
526 currentjob: if ((jp = getcurjob(NULL)) == NULL)
527 error("No current job");
530 error("No current job");
532 } else if (name[0] == '%') {
533 if (is_digit(name[1])) {
534 jobno = number(name + 1);
535 if (jobno > 0 && jobno <= njobs
536 && jobtab[jobno - 1].used != 0)
537 return &jobtab[jobno - 1];
539 } else if (name[1] == '%' && name[2] == '\0') {
541 } else if (name[1] == '+' && name[2] == '\0') {
543 } else if (name[1] == '-' && name[2] == '\0') {
544 if ((jp = getcurjob(NULL)) == NULL ||
545 (jp = getcurjob(jp)) == NULL)
546 error("No previous job");
549 } else if (name[1] == '?') {
551 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
552 if (jp->used && jp->nprocs > 0
553 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
555 error("%s: ambiguous", name);
563 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
564 if (jp->used && jp->nprocs > 0
565 && prefix(name + 1, jp->ps[0].cmd)) {
567 error("%s: ambiguous", name);
574 } else if (is_number(name)) {
575 pid = (pid_t)number(name);
576 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
577 if (jp->used && jp->nprocs > 0
578 && jp->ps[jp->nprocs - 1].pid == pid)
582 error("No such job: %s", name);
590 * Return a new job structure,
594 makejob(union node *node __unused, int nprocs)
599 for (i = njobs, jp = jobtab ; ; jp++) {
603 jobtab = ckmalloc(4 * sizeof jobtab[0]);
608 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
609 memcpy(jp, jobtab, njobs * sizeof jp[0]);
611 /* Relocate `next' pointers and list head */
613 jobmru = &jp[jobmru - jobtab];
614 for (i = 0; i < njobs; i++)
615 if (jp[i].next != NULL)
616 jp[i].next = &jp[jp[i].next -
619 /* Relocate `ps' pointers */
620 for (i = 0; i < njobs; i++)
621 if (jp[i].ps == &jobtab[i].ps0)
622 jp[i].ps = &jp[i].ps0;
627 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
645 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
650 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
657 setcurjob(struct job *cj)
659 struct job *jp, *prev;
661 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
664 prev->next = jp->next;
677 deljob(struct job *j)
679 struct job *jp, *prev;
681 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
684 prev->next = jp->next;
693 * Return the most recently used job that isn't `nj', and preferably one
697 getcurjob(struct job *nj)
701 /* Try to find a stopped one.. */
702 for (jp = jobmru; jp != NULL; jp = jp->next)
703 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
705 /* Otherwise the most recently used job that isn't `nj' */
706 for (jp = jobmru; jp != NULL; jp = jp->next)
707 if (jp->used && jp != nj)
716 * Fork of a subshell. If we are doing job control, give the subshell its
717 * own process group. Jp is a job structure that the job is to be added to.
718 * N is the command that will be evaluated by the child. Both jp and n may
719 * be NULL. The mode parameter can be one of the following:
720 * FORK_FG - Fork off a foreground process.
721 * FORK_BG - Fork off a background process.
722 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
723 * process group even if job control is on.
725 * When job control is turned off, background processes have their standard
726 * input redirected to /dev/null (except for the second and later processes
731 forkshell(struct job *jp, union node *n, int mode)
736 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
742 TRACE(("Fork failed, errno=%d\n", errno));
744 error("Cannot fork: %s", strerror(errno));
751 TRACE(("Child shell %d\n", (int)getpid()));
758 jobctl = 0; /* do job control only in root shell */
759 if (wasroot && mode != FORK_NOJOB && mflag) {
760 if (jp == NULL || jp->nprocs == 0)
763 pgrp = jp->ps[0].pid;
764 if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
765 /*** this causes superfluous TIOCSPGRPS ***/
766 if (tcsetpgrp(ttyfd, pgrp) < 0)
767 error("tcsetpgrp failed, errno=%d", errno);
771 } else if (mode == FORK_BG) {
774 if ((jp == NULL || jp->nprocs == 0) &&
775 ! fd0_redirected_p ()) {
777 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
778 error("Can't open %s: %s",
779 _PATH_DEVNULL, strerror(errno));
783 if (mode == FORK_BG) {
786 if ((jp == NULL || jp->nprocs == 0) &&
787 ! fd0_redirected_p ()) {
789 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
790 error("Can't open %s: %s",
791 _PATH_DEVNULL, strerror(errno));
796 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
800 if (wasroot && iflag) {
807 if (rootshell && mode != FORK_NOJOB && mflag) {
808 if (jp == NULL || jp->nprocs == 0)
811 pgrp = jp->ps[0].pid;
815 backgndpid = pid; /* set $! */
817 struct procstat *ps = &jp->ps[jp->nprocs++];
821 if (iflag && rootshell && n)
822 ps->cmd = commandtext(n);
823 jp->foreground = mode == FORK_FG;
829 TRACE(("In parent shell: child = %d\n", (int)pid));
836 * Wait for job to finish.
838 * Under job control we have the problem that while a child process is
839 * running interrupts generated by the user are sent to the child but not
840 * to the shell. This means that an infinite loop started by an inter-
841 * active user may be hard to kill. With job control turned off, an
842 * interactive user may place an interactive program inside a loop. If
843 * the interactive program catches interrupts, the user doesn't want
844 * these interrupts to also abort the loop. The approach we take here
845 * is to have the shell ignore interrupt signals while waiting for a
846 * foreground process to terminate, and then send itself an interrupt
847 * signal if the child process was terminated by an interrupt signal.
848 * Unfortunately, some programs want to do a bit of cleanup and then
849 * exit on interrupt; unless these processes terminate themselves by
850 * sending a signal to themselves (instead of calling exit) they will
851 * confuse this approach.
855 waitforjob(struct job *jp, int *origstatus)
858 pid_t mypgrp = getpgrp();
864 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
865 while (jp->state == 0)
866 if (dowait(1, jp) == -1)
870 if (tcsetpgrp(ttyfd, mypgrp) < 0)
871 error("tcsetpgrp failed, errno=%d\n", errno);
873 if (jp->state == JOBSTOPPED)
876 status = jp->ps[jp->nprocs - 1].status;
877 if (origstatus != NULL)
878 *origstatus = status;
879 /* convert to 8 bits */
880 if (WIFEXITED(status))
881 st = WEXITSTATUS(status);
883 else if (WIFSTOPPED(status))
884 st = WSTOPSIG(status) + 128;
887 st = WTERMSIG(status) + 128;
888 if (! JOBS || jp->state == JOBDONE)
891 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
892 kill(getpid(), SIGINT);
903 * Wait for a process to terminate.
907 dowait(int block, struct job *job)
920 TRACE(("dowait(%d) called\n", block));
922 pid = waitproc(block, &status);
923 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
924 } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
925 (WIFSTOPPED(status) && !iflag));
927 if (breakwaitcmd != 0) {
930 * Do not early terminate if the pid is positive, else the
931 * job will not be properly recorded.
940 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
944 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
947 if (sp->pid == pid) {
948 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
949 (int)pid, sp->status,
954 if (sp->status == -1)
956 else if (WIFSTOPPED(sp->status))
959 if (stopped) { /* stopped or done */
960 int state = done? JOBDONE : JOBSTOPPED;
961 if (jp->state != state) {
962 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
973 if (! rootshell || ! iflag || (job && thisjob == job)) {
975 if (WIFSTOPPED(status))
976 sig = WSTOPSIG(status);
980 if (WIFEXITED(status))
983 sig = WTERMSIG(status);
985 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
987 (thisjob->foreground && !WIFSTOPPED(status))) {
988 i = WTERMSIG(status);
989 if ((i & 0x7F) < sys_nsig && sys_siglist[i & 0x7F])
990 out1str(sys_siglist[i & 0x7F]);
992 out1fmt("Signal %d", i & 0x7F);
993 if (WCOREDUMP(status))
994 out1str(" (core dumped)");
997 showjob(thisjob, pid, 0, 0);
1000 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
1002 thisjob->changed = 1;
1010 * Do a wait system call. If job control is compiled in, we accept
1011 * stopped processes. If block is zero, we return a value of zero
1012 * rather than blocking.
1015 waitproc(int block, int *status)
1026 return wait3(status, flags, (struct rusage *)NULL);
1030 * return 1 if there are stopped jobs, otherwise 0
1032 int job_warning = 0;
1041 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1044 if (jp->state == JOBSTOPPED) {
1045 out2str("You have stopped jobs.\n");
1055 * Return a string identifying a command (to be printed by the
1059 STATIC char *cmdnextc;
1060 STATIC int cmdnleft;
1061 #define MAXCMDTEXT 200
1064 commandtext(union node *n)
1068 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1069 cmdnleft = MAXCMDTEXT - 4;
1077 cmdtxt(union node *n)
1080 struct nodelist *lp;
1089 cmdtxt(n->nbinary.ch1);
1091 cmdtxt(n->nbinary.ch2);
1094 cmdtxt(n->nbinary.ch1);
1096 cmdtxt(n->nbinary.ch2);
1099 cmdtxt(n->nbinary.ch1);
1101 cmdtxt(n->nbinary.ch2);
1104 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1112 cmdtxt(n->nredir.n);
1117 cmdtxt(n->nredir.n);
1121 cmdtxt(n->nif.test);
1123 cmdtxt(n->nif.ifpart);
1132 cmdtxt(n->nbinary.ch1);
1134 cmdtxt(n->nbinary.ch2);
1139 cmdputs(n->nfor.var);
1144 cmdputs(n->ncase.expr->narg.text);
1148 cmdputs(n->narg.text);
1152 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1157 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1163 cmdputs(n->narg.text);
1166 p = ">"; i = 1; goto redir;
1168 p = ">>"; i = 1; goto redir;
1170 p = ">&"; i = 1; goto redir;
1172 p = ">|"; i = 1; goto redir;
1174 p = "<"; i = 0; goto redir;
1176 p = "<>"; i = 0; goto redir;
1178 p = "<&"; i = 0; goto redir;
1180 if (n->nfile.fd != i) {
1181 s[0] = n->nfile.fd + '0';
1186 if (n->type == NTOFD || n->type == NFROMFD) {
1187 if (n->ndup.dupfd >= 0)
1188 s[0] = n->ndup.dupfd + '0';
1194 cmdtxt(n->nfile.fname);
1210 cmdputs(const char *s)
1221 while ((c = *p++) != '\0') {
1224 else if (c == CTLVAR) {
1229 } else if (c == '=' && subtype != 0) {
1230 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1232 } else if (c == CTLENDVAR) {
1234 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1235 cmdnleft++; /* ignore it */
1238 if (--cmdnleft <= 0) {