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$");
50 #include <sys/param.h>
54 #include <sys/resource.h>
57 #include <sys/ioctl.h>
62 #undef CEOF /* syntax.h redefines this */
80 struct job *jobtab; /* array of jobs */
81 int njobs; /* size of array */
82 MKINIT pid_t backgndpid = -1; /* pid of last background process */
84 struct job *jobmru; /* most recently used job list */
85 int initialpgrp; /* pgrp of shell on invocation */
87 int in_waitcmd = 0; /* are we in waitcmd()? */
88 int in_dowait = 0; /* are we in dowait()? */
89 volatile sig_atomic_t breakwaitcmd = 0; /* should wait be terminated? */
92 STATIC void restartjob(struct job *);
94 STATIC void freejob(struct job *);
95 STATIC struct job *getjob(char *);
96 STATIC int dowait(int, struct job *);
98 STATIC int onsigchild(void);
100 STATIC int waitproc(int, int *);
101 STATIC void cmdtxt(union node *);
102 STATIC void cmdputs(char *);
104 STATIC void setcurjob(struct job *);
105 STATIC void deljob(struct job *);
106 STATIC struct job *getcurjob(struct job *);
108 STATIC void showjob(struct job *, pid_t, int, int);
112 * Turn job control on and off.
114 * Note: This code assumes that the third arg to ioctl is a character
115 * pointer, which is true on Berkeley systems but not System V. Since
116 * System V doesn't have job control yet, this isn't a problem now.
126 if (on == jobctl || rootshell == 0)
129 do { /* while we are in the background */
130 initialpgrp = tcgetpgrp(2);
131 if (initialpgrp < 0) {
132 out2str("sh: can't access tty; job control turned off\n");
136 if (initialpgrp == -1)
137 initialpgrp = getpgrp();
138 else if (initialpgrp != getpgrp()) {
139 killpg(initialpgrp, SIGTTIN);
147 tcsetpgrp(2, rootpid);
148 } else { /* turning job control off */
149 setpgid(0, initialpgrp);
150 tcsetpgrp(2, initialpgrp);
161 INCLUDE <sys/types.h>
177 fgcmd(int argc __unused, char **argv)
183 jp = getjob(argv[1]);
185 error("job not created under job control");
186 out1str(jp->ps[0].cmd);
189 pgrp = jp->ps[0].pid;
193 status = waitforjob(jp, (int *)NULL);
200 bgcmd(int argc, char **argv)
206 jp = getjob(*++argv);
208 error("job not created under job control");
209 if (jp->state == JOBDONE)
212 fmtstr(s, 64, "[%d] ", jp - jobtab + 1);
214 out1str(jp->ps[0].cmd);
216 } while (--argc > 1);
222 restartjob(struct job *jp)
227 if (jp->state == JOBDONE)
231 killpg(jp->ps[0].pid, SIGCONT);
232 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
233 if (WIFSTOPPED(ps->status)) {
244 jobscmd(int argc, char *argv[])
247 int ch, sformat, lformat;
249 optind = optreset = 1;
250 sformat = lformat = 0;
251 while ((ch = getopt(argc, argv, "ls")) != -1) {
261 error("unknown option: -%c", optopt);
268 showjobs(0, sformat, lformat);
270 while ((id = *argv++) != NULL)
271 showjob(getjob(id), 0, sformat, lformat);
277 showjob(struct job *jp, pid_t pid, int sformat, int lformat)
282 int col, curr, i, jobno, prev, procno;
286 jobno = jp - jobtab + 1;
289 if ((j = getcurjob(NULL)) != NULL) {
290 curr = j - jobtab + 1;
291 if ((j = getcurjob(j)) != NULL)
292 prev = j - jobtab + 1;
295 for (ps = jp->ps ; ; ps++) { /* for each process */
297 out1fmt("%d\n", ps->pid);
300 if (!lformat && ps != jp->ps && pid == 0)
302 if (pid != 0 && pid != ps->pid)
304 if (jobno == curr && ps == jp->ps)
306 else if (jobno == prev && ps == jp->ps)
311 fmtstr(s, 64, "[%d] %c ", jobno, c);
313 fmtstr(s, 64, " %c ", c);
317 fmtstr(s, 64, "%d ", ps->pid);
324 } else if (ps->status == -1) {
325 strcpy(s, "Running");
326 } else if (WIFEXITED(ps->status)) {
327 if (WEXITSTATUS(ps->status) == 0)
330 fmtstr(s, 64, "Done (%d)",
331 WEXITSTATUS(ps->status));
334 if (WIFSTOPPED(ps->status))
335 i = WSTOPSIG(ps->status);
338 i = WTERMSIG(ps->status);
339 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
340 scopy(sys_siglist[i & 0x7F], s);
342 fmtstr(s, 64, "Signal %d", i & 0x7F);
343 if (WCOREDUMP(ps->status))
344 strcat(s, " (core dumped)");
354 skip: if (--procno <= 0)
360 * Print a list of jobs. If "change" is nonzero, only print jobs whose
361 * statuses have changed since the last call to showjobs.
363 * If the shell is interrupted in the process of creating a job, the
364 * result may be a job structure containing zero processes. Such structures
365 * will be freed here.
369 showjobs(int change, int sformat, int lformat)
374 TRACE(("showjobs(%d) called\n", change));
375 while (dowait(0, (struct job *)NULL) > 0);
376 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
379 if (jp->nprocs == 0) {
383 if (change && ! jp->changed)
385 showjob(jp, 0, sformat, lformat);
387 if (jp->state == JOBDONE) {
395 * Mark a job structure as unused.
399 freejob(struct job *jp)
405 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
406 if (ps->cmd != nullstr)
409 if (jp->ps != &jp->ps0)
421 waitcmd(int argc, char **argv)
428 job = getjob(argv[1]);
434 * Loop until a process is terminated or stopped, or a SIGINT is
442 status = job->ps[job->nprocs - 1].status;
443 if (WIFEXITED(status))
444 retval = WEXITSTATUS(status);
446 else if (WIFSTOPPED(status))
447 retval = WSTOPSIG(status) + 128;
450 retval = WTERMSIG(status) + 128;
457 for (jp = jobtab ; ; jp++) {
458 if (jp >= jobtab + njobs) { /* no running procs */
462 if (jp->used && jp->state == 0)
466 } while (dowait(1, (struct job *)NULL) != -1);
475 jobidcmd(int argc __unused, char **argv)
480 jp = getjob(argv[1]);
481 for (i = 0 ; i < jp->nprocs ; ) {
482 out1fmt("%d", jp->ps[i].pid);
483 out1c(++i < jp->nprocs? ' ' : '\n');
491 * Convert a job name to a job structure.
498 struct job *found, *jp;
504 currentjob: if ((jp = getcurjob(NULL)) == NULL)
505 error("No current job");
508 error("No current job");
510 } else if (name[0] == '%') {
511 if (is_digit(name[1])) {
512 jobno = number(name + 1);
513 if (jobno > 0 && jobno <= njobs
514 && jobtab[jobno - 1].used != 0)
515 return &jobtab[jobno - 1];
517 } else if (name[1] == '%' && name[2] == '\0') {
519 } else if (name[1] == '+' && name[2] == '\0') {
521 } else if (name[1] == '-' && name[2] == '\0') {
522 if ((jp = getcurjob(NULL)) == NULL ||
523 (jp = getcurjob(jp)) == NULL)
524 error("No previous job");
527 } else if (name[1] == '?') {
529 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
530 if (jp->used && jp->nprocs > 0
531 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
533 error("%s: ambiguous", name);
541 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
542 if (jp->used && jp->nprocs > 0
543 && prefix(name + 1, jp->ps[0].cmd)) {
545 error("%s: ambiguous", name);
552 } else if (is_number(name)) {
554 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
555 if (jp->used && jp->nprocs > 0
556 && jp->ps[jp->nprocs - 1].pid == pid)
560 error("No such job: %s", name);
568 * Return a new job structure,
572 makejob(union node *node __unused, int nprocs)
577 for (i = njobs, jp = jobtab ; ; jp++) {
581 jobtab = ckmalloc(4 * sizeof jobtab[0]);
586 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
587 memcpy(jp, jobtab, njobs * sizeof jp[0]);
589 /* Relocate `next' pointers and list head */
591 jobmru = &jp[jobmru - jobtab];
592 for (i = 0; i < njobs; i++)
593 if (jp[i].next != NULL)
594 jp[i].next = &jp[jp[i].next -
597 /* Relocate `ps' pointers */
598 for (i = 0; i < njobs; i++)
599 if (jp[i].ps == &jobtab[i].ps0)
600 jp[i].ps = &jp[i].ps0;
605 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
622 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
627 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
634 setcurjob(struct job *cj)
636 struct job *jp, *prev;
638 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
641 prev->next = jp->next;
654 deljob(struct job *j)
656 struct job *jp, *prev;
658 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
661 prev->next = jp->next;
670 * Return the most recently used job that isn't `nj', and preferably one
674 getcurjob(struct job *nj)
678 /* Try to find a stopped one.. */
679 for (jp = jobmru; jp != NULL; jp = jp->next)
680 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
682 /* Otherwise the most recently used job that isn't `nj' */
683 for (jp = jobmru; jp != NULL; jp = jp->next)
684 if (jp->used && jp != nj)
693 * Fork of a subshell. If we are doing job control, give the subshell its
694 * own process group. Jp is a job structure that the job is to be added to.
695 * N is the command that will be evaluated by the child. Both jp and n may
696 * be NULL. The mode parameter can be one of the following:
697 * FORK_FG - Fork off a foreground process.
698 * FORK_BG - Fork off a background process.
699 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
700 * process group even if job control is on.
702 * When job control is turned off, background processes have their standard
703 * input redirected to /dev/null (except for the second and later processes
708 forkshell(struct job *jp, union node *n, int mode)
713 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
718 TRACE(("Fork failed, errno=%d\n", errno));
720 error("Cannot fork: %s", strerror(errno));
727 TRACE(("Child shell %d\n", getpid()));
730 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
737 jobctl = 0; /* do job control only in root shell */
738 if (wasroot && mode != FORK_NOJOB && mflag) {
739 if (jp == NULL || jp->nprocs == 0)
742 pgrp = jp->ps[0].pid;
743 if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
744 /*** this causes superfluous TIOCSPGRPS ***/
745 if (tcsetpgrp(2, pgrp) < 0)
746 error("tcsetpgrp failed, errno=%d", errno);
750 } else if (mode == FORK_BG) {
753 if ((jp == NULL || jp->nprocs == 0) &&
754 ! fd0_redirected_p ()) {
756 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
757 error("Can't open %s: %s",
758 _PATH_DEVNULL, strerror(errno));
762 if (mode == FORK_BG) {
765 if ((jp == NULL || jp->nprocs == 0) &&
766 ! fd0_redirected_p ()) {
768 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
769 error("Can't open %s: %s",
770 _PATH_DEVNULL, strerror(errno));
774 if (wasroot && iflag) {
781 if (rootshell && mode != FORK_NOJOB && mflag) {
782 if (jp == NULL || jp->nprocs == 0)
785 pgrp = jp->ps[0].pid;
789 backgndpid = pid; /* set $! */
791 struct procstat *ps = &jp->ps[jp->nprocs++];
795 if (iflag && rootshell && n)
796 ps->cmd = commandtext(n);
802 TRACE(("In parent shell: child = %d\n", pid));
809 * Wait for job to finish.
811 * Under job control we have the problem that while a child process is
812 * running interrupts generated by the user are sent to the child but not
813 * to the shell. This means that an infinite loop started by an inter-
814 * active user may be hard to kill. With job control turned off, an
815 * interactive user may place an interactive program inside a loop. If
816 * the interactive program catches interrupts, the user doesn't want
817 * these interrupts to also abort the loop. The approach we take here
818 * is to have the shell ignore interrupt signals while waiting for a
819 * foreground process to terminate, and then send itself an interrupt
820 * signal if the child process was terminated by an interrupt signal.
821 * Unfortunately, some programs want to do a bit of cleanup and then
822 * exit on interrupt; unless these processes terminate themselves by
823 * sending a signal to themselves (instead of calling exit) they will
824 * confuse this approach.
828 waitforjob(struct job *jp, int *origstatus)
831 int mypgrp = getpgrp();
837 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
838 while (jp->state == 0)
839 if (dowait(1, jp) == -1)
843 if (tcsetpgrp(2, mypgrp) < 0)
844 error("tcsetpgrp failed, errno=%d\n", errno);
846 if (jp->state == JOBSTOPPED)
849 status = jp->ps[jp->nprocs - 1].status;
850 if (origstatus != NULL)
851 *origstatus = status;
852 /* convert to 8 bits */
853 if (WIFEXITED(status))
854 st = WEXITSTATUS(status);
856 else if (WIFSTOPPED(status))
857 st = WSTOPSIG(status) + 128;
860 st = WTERMSIG(status) + 128;
861 if (! JOBS || jp->state == JOBDONE)
864 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
865 kill(getpid(), SIGINT);
876 * Wait for a process to terminate.
880 dowait(int block, struct job *job)
892 TRACE(("dowait(%d) called\n", block));
894 pid = waitproc(block, &status);
895 TRACE(("wait returns %d, status=%d\n", pid, status));
896 } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
897 (WIFSTOPPED(status) && !iflag));
899 if (breakwaitcmd != 0) {
907 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
911 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
914 if (sp->pid == pid) {
915 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
916 pid, sp->status, status));
920 if (sp->status == -1)
922 else if (WIFSTOPPED(sp->status))
925 if (stopped) { /* stopped or done */
926 int state = done? JOBDONE : JOBSTOPPED;
927 if (jp->state != state) {
928 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
939 if (! rootshell || ! iflag || (job && thisjob == job)) {
941 if (WIFSTOPPED(status))
942 sig = WSTOPSIG(status);
946 if (WIFEXITED(status))
949 sig = WTERMSIG(status);
951 if (sig != 0 && sig != SIGINT && sig != SIGPIPE)
952 showjob(thisjob, pid, 0, 1);
954 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
956 thisjob->changed = 1;
964 * Do a wait system call. If job control is compiled in, we accept
965 * stopped processes. If block is zero, we return a value of zero
966 * rather than blocking.
968 * System V doesn't have a non-blocking wait system call. It does
969 * have a SIGCLD signal that is sent to a process when one of it's
970 * children dies. The obvious way to use SIGCLD would be to install
971 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
972 * was received, and have waitproc bump another counter when it got
973 * the status of a process. Waitproc would then know that a wait
974 * system call would not block if the two counters were different.
975 * This approach doesn't work because if a process has children that
976 * have not been waited for, System V will send it a SIGCLD when it
977 * installs a signal handler for SIGCLD. What this means is that when
978 * a child exits, the shell will be sent SIGCLD signals continuously
979 * until is runs out of stack space, unless it does a wait call before
980 * restoring the signal handler. The code below takes advantage of
981 * this (mis)feature by installing a signal handler for SIGCLD and
982 * then checking to see whether it was called. If there are any
983 * children to be waited for, it will be.
985 * If neither SYSV nor BSD is defined, we don't implement nonblocking
986 * waits at all. In this case, the user will not be informed when
987 * a background process until the next time she runs a real program
988 * (as opposed to running a builtin command or just typing return),
989 * and the jobs command may give out of date information.
993 STATIC sig_atomic_t gotsigchild;
995 STATIC int onsigchild() {
1002 waitproc(int block, int *status)
1014 return wait3(status, flags, (struct rusage *)NULL);
1021 save = signal(SIGCLD, onsigchild);
1022 signal(SIGCLD, save);
1023 if (gotsigchild == 0)
1026 return wait(status);
1030 return wait(status);
1036 * return 1 if there are stopped jobs, otherwise 0
1038 int job_warning = 0;
1047 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1050 if (jp->state == JOBSTOPPED) {
1051 out2str("You have stopped jobs.\n");
1061 * Return a string identifying a command (to be printed by the
1065 STATIC char *cmdnextc;
1066 STATIC int cmdnleft;
1067 #define MAXCMDTEXT 200
1070 commandtext(union node *n)
1074 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1075 cmdnleft = MAXCMDTEXT - 4;
1083 cmdtxt(union node *n)
1086 struct nodelist *lp;
1095 cmdtxt(n->nbinary.ch1);
1097 cmdtxt(n->nbinary.ch2);
1100 cmdtxt(n->nbinary.ch1);
1102 cmdtxt(n->nbinary.ch2);
1105 cmdtxt(n->nbinary.ch1);
1107 cmdtxt(n->nbinary.ch2);
1110 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1118 cmdtxt(n->nredir.n);
1123 cmdtxt(n->nredir.n);
1127 cmdtxt(n->nif.test);
1129 cmdtxt(n->nif.ifpart);
1138 cmdtxt(n->nbinary.ch1);
1140 cmdtxt(n->nbinary.ch2);
1145 cmdputs(n->nfor.var);
1150 cmdputs(n->ncase.expr->narg.text);
1154 cmdputs(n->narg.text);
1158 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1163 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1169 cmdputs(n->narg.text);
1172 p = ">"; i = 1; goto redir;
1174 p = ">>"; i = 1; goto redir;
1176 p = ">&"; i = 1; goto redir;
1178 p = ">|"; i = 1; goto redir;
1180 p = "<"; i = 0; goto redir;
1182 p = "<>"; i = 0; goto redir;
1184 p = "<&"; i = 0; goto redir;
1186 if (n->nfile.fd != i) {
1187 s[0] = n->nfile.fd + '0';
1192 if (n->type == NTOFD || n->type == NFROMFD) {
1193 if (n->ndup.dupfd >= 0)
1194 s[0] = n->ndup.dupfd + '0';
1200 cmdtxt(n->nfile.fname);
1226 while ((c = *p++) != '\0') {
1229 else if (c == CTLVAR) {
1234 } else if (c == '=' && subtype != 0) {
1235 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1237 } else if (c == CTLENDVAR) {
1239 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1240 cmdnleft++; /* ignore it */
1243 if (--cmdnleft <= 0) {