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.72 2006/10/07 16:51:16 stefanf Exp $
38 * $DragonFly: src/bin/sh/jobs.c,v 1.9 2007/01/13 21:27:45 pavalos 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);
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, 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, "[%td] ", 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[])
270 optind = optreset = 1;
272 mode = SHOWJOBS_DEFAULT;
273 while ((ch = getopt(argc, argv, "lps")) != -1) {
276 mode = SHOWJOBS_VERBOSE;
279 mode = SHOWJOBS_PGIDS;
282 mode = SHOWJOBS_PIDS;
286 error("unknown option: -%c", optopt);
295 while ((id = *argv++) != NULL)
296 showjob(getjob(id), 0, mode);
302 showjob(struct job *jp, pid_t pid, int mode)
307 int col, curr, i, jobno, prev, procno;
311 procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
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 */
322 if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
323 ppid = (mode == SHOWJOBS_PIDS) ? ps->pid :
325 out1fmt("%d\n", (int)ppid);
328 if (mode != SHOWJOBS_VERBOSE && ps != jp->ps && pid == 0)
330 if (pid != 0 && pid != ps->pid)
332 if (jobno == curr && ps == jp->ps)
334 else if (jobno == prev && ps == jp->ps)
339 fmtstr(s, 64, "[%d] %c ", jobno, c);
341 fmtstr(s, 64, " %c ", c);
344 if (mode == SHOWJOBS_VERBOSE) {
345 fmtstr(s, 64, "%d ", (int)ps->pid);
352 } else if (ps->status == -1) {
353 strcpy(s, "Running");
354 } else if (WIFEXITED(ps->status)) {
355 if (WEXITSTATUS(ps->status) == 0)
358 fmtstr(s, 64, "Done (%d)",
359 WEXITSTATUS(ps->status));
362 if (WIFSTOPPED(ps->status))
363 i = WSTOPSIG(ps->status);
366 i = WTERMSIG(ps->status);
367 if ((i & 0x7F) < sys_nsig && sys_siglist[i & 0x7F])
368 scopy(sys_siglist[i & 0x7F], s);
370 fmtstr(s, 64, "Signal %d", i & 0x7F);
371 if (WCOREDUMP(ps->status))
372 strcat(s, " (core dumped)");
382 skip: if (--procno <= 0)
388 * Print a list of jobs. If "change" is nonzero, only print jobs whose
389 * statuses have changed since the last call to showjobs.
391 * If the shell is interrupted in the process of creating a job, the
392 * result may be a job structure containing zero processes. Such structures
393 * will be freed here.
397 showjobs(int change, int mode)
402 TRACE(("showjobs(%d) called\n", change));
403 while (dowait(0, NULL) > 0);
404 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
407 if (jp->nprocs == 0) {
411 if (change && ! jp->changed)
413 showjob(jp, 0, mode);
415 if (jp->state == JOBDONE) {
423 * Mark a job structure as unused.
427 freejob(struct job *jp)
433 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
434 if (ps->cmd != nullstr)
437 if (jp->ps != &jp->ps0)
449 waitcmd(int argc, char **argv)
456 job = getjob(argv[1]);
462 * Loop until a process is terminated or stopped, or a SIGINT is
470 status = job->ps[job->nprocs - 1].status;
471 if (WIFEXITED(status))
472 retval = WEXITSTATUS(status);
474 else if (WIFSTOPPED(status))
475 retval = WSTOPSIG(status) + 128;
478 retval = WTERMSIG(status) + 128;
485 for (jp = jobtab ; ; jp++) {
486 if (jp >= jobtab + njobs) { /* no running procs */
490 if (jp->used && jp->state == 0)
494 } while (dowait(1, NULL) != -1);
503 jobidcmd(int argc __unused, char **argv)
508 jp = getjob(argv[1]);
509 for (i = 0 ; i < jp->nprocs ; ) {
510 out1fmt("%d", (int)jp->ps[i].pid);
511 out1c(++i < jp->nprocs? ' ' : '\n');
519 * Convert a job name to a job structure.
526 struct job *found, *jp;
532 currentjob: if ((jp = getcurjob(NULL)) == NULL)
533 error("No current job");
536 error("No current job");
538 } else if (name[0] == '%') {
539 if (is_digit(name[1])) {
540 jobno = number(name + 1);
541 if (jobno > 0 && jobno <= njobs
542 && jobtab[jobno - 1].used != 0)
543 return &jobtab[jobno - 1];
545 } else if (name[1] == '%' && name[2] == '\0') {
547 } else if (name[1] == '+' && name[2] == '\0') {
549 } else if (name[1] == '-' && name[2] == '\0') {
550 if ((jp = getcurjob(NULL)) == NULL ||
551 (jp = getcurjob(jp)) == NULL)
552 error("No previous job");
555 } else if (name[1] == '?') {
557 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
558 if (jp->used && jp->nprocs > 0
559 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
561 error("%s: ambiguous", name);
569 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
570 if (jp->used && jp->nprocs > 0
571 && prefix(name + 1, jp->ps[0].cmd)) {
573 error("%s: ambiguous", name);
580 } else if (is_number(name)) {
581 pid = (pid_t)number(name);
582 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
583 if (jp->used && jp->nprocs > 0
584 && jp->ps[jp->nprocs - 1].pid == pid)
588 error("No such job: %s", name);
596 * Return a new job structure,
600 makejob(union node *node __unused, int nprocs)
605 for (i = njobs, jp = jobtab ; ; jp++) {
609 jobtab = ckmalloc(4 * sizeof jobtab[0]);
614 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
615 memcpy(jp, jobtab, njobs * sizeof jp[0]);
617 /* Relocate `next' pointers and list head */
619 jobmru = &jp[jobmru - jobtab];
620 for (i = 0; i < njobs; i++)
621 if (jp[i].next != NULL)
622 jp[i].next = &jp[jp[i].next -
625 /* Relocate `ps' pointers */
626 for (i = 0; i < njobs; i++)
627 if (jp[i].ps == &jobtab[i].ps0)
628 jp[i].ps = &jp[i].ps0;
633 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
651 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
656 TRACE(("makejob(%p, %d) returns %%%d\n", (void *)node, nprocs,
663 setcurjob(struct job *cj)
665 struct job *jp, *prev;
667 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
670 prev->next = jp->next;
683 deljob(struct job *j)
685 struct job *jp, *prev;
687 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
690 prev->next = jp->next;
699 * Return the most recently used job that isn't `nj', and preferably one
703 getcurjob(struct job *nj)
707 /* Try to find a stopped one.. */
708 for (jp = jobmru; jp != NULL; jp = jp->next)
709 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
711 /* Otherwise the most recently used job that isn't `nj' */
712 for (jp = jobmru; jp != NULL; jp = jp->next)
713 if (jp->used && jp != nj)
722 * Fork of a subshell. If we are doing job control, give the subshell its
723 * own process group. Jp is a job structure that the job is to be added to.
724 * N is the command that will be evaluated by the child. Both jp and n may
725 * be NULL. The mode parameter can be one of the following:
726 * FORK_FG - Fork off a foreground process.
727 * FORK_BG - Fork off a background process.
728 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
729 * process group even if job control is on.
731 * When job control is turned off, background processes have their standard
732 * input redirected to /dev/null (except for the second and later processes
737 forkshell(struct job *jp, union node *n, int mode)
742 TRACE(("forkshell(%%%d, %p, %d) called\n", jp - jobtab, (void *)n,
748 TRACE(("Fork failed, errno=%d\n", errno));
750 error("Cannot fork: %s", strerror(errno));
757 TRACE(("Child shell %d\n", (int)getpid()));
764 jobctl = 0; /* do job control only in root shell */
765 if (wasroot && mode != FORK_NOJOB && mflag) {
766 if (jp == NULL || jp->nprocs == 0)
769 pgrp = jp->ps[0].pid;
770 if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
771 /*** this causes superfluous TIOCSPGRPS ***/
772 if (tcsetpgrp(ttyfd, pgrp) < 0)
773 error("tcsetpgrp failed, errno=%d", errno);
777 } else if (mode == FORK_BG) {
780 if ((jp == NULL || jp->nprocs == 0) &&
781 ! fd0_redirected_p ()) {
783 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
784 error("Can't open %s: %s",
785 _PATH_DEVNULL, strerror(errno));
789 if (mode == FORK_BG) {
792 if ((jp == NULL || jp->nprocs == 0) &&
793 ! fd0_redirected_p ()) {
795 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
796 error("Can't open %s: %s",
797 _PATH_DEVNULL, strerror(errno));
802 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
806 if (wasroot && iflag) {
813 if (rootshell && mode != FORK_NOJOB && mflag) {
814 if (jp == NULL || jp->nprocs == 0)
817 pgrp = jp->ps[0].pid;
821 backgndpid = pid; /* set $! */
823 struct procstat *ps = &jp->ps[jp->nprocs++];
827 if (iflag && rootshell && n)
828 ps->cmd = commandtext(n);
829 jp->foreground = mode == FORK_FG;
835 TRACE(("In parent shell: child = %d\n", (int)pid));
842 * Wait for job to finish.
844 * Under job control we have the problem that while a child process is
845 * running interrupts generated by the user are sent to the child but not
846 * to the shell. This means that an infinite loop started by an inter-
847 * active user may be hard to kill. With job control turned off, an
848 * interactive user may place an interactive program inside a loop. If
849 * the interactive program catches interrupts, the user doesn't want
850 * these interrupts to also abort the loop. The approach we take here
851 * is to have the shell ignore interrupt signals while waiting for a
852 * foreground process to terminate, and then send itself an interrupt
853 * signal if the child process was terminated by an interrupt signal.
854 * Unfortunately, some programs want to do a bit of cleanup and then
855 * exit on interrupt; unless these processes terminate themselves by
856 * sending a signal to themselves (instead of calling exit) they will
857 * confuse this approach.
861 waitforjob(struct job *jp, int *origstatus)
864 pid_t mypgrp = getpgrp();
870 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
871 while (jp->state == 0)
872 if (dowait(1, jp) == -1)
876 if (tcsetpgrp(ttyfd, mypgrp) < 0)
877 error("tcsetpgrp failed, errno=%d\n", errno);
879 if (jp->state == JOBSTOPPED)
882 status = jp->ps[jp->nprocs - 1].status;
883 if (origstatus != NULL)
884 *origstatus = status;
885 /* convert to 8 bits */
886 if (WIFEXITED(status))
887 st = WEXITSTATUS(status);
889 else if (WIFSTOPPED(status))
890 st = WSTOPSIG(status) + 128;
893 st = WTERMSIG(status) + 128;
894 if (! JOBS || jp->state == JOBDONE)
897 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
898 kill(getpid(), SIGINT);
909 * Wait for a process to terminate.
913 dowait(int block, struct job *job)
926 TRACE(("dowait(%d) called\n", block));
928 pid = waitproc(block, &status);
929 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
930 } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
931 (pid > 0 && WIFSTOPPED(status) && !iflag));
933 if (pid == -1 && errno == ECHILD && job != NULL)
934 job->state = JOBDONE;
935 if (breakwaitcmd != 0) {
938 * Do not early terminate if the pid is positive, else the
939 * job will not be properly recorded.
948 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
952 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
955 if (sp->pid == pid) {
956 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
957 (int)pid, sp->status,
962 if (sp->status == -1)
964 else if (WIFSTOPPED(sp->status))
967 if (stopped) { /* stopped or done */
968 int state = done? JOBDONE : JOBSTOPPED;
969 if (jp->state != state) {
970 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
981 if (! rootshell || ! iflag || (job && thisjob == job)) {
983 if (WIFSTOPPED(status))
984 sig = WSTOPSIG(status);
988 if (WIFEXITED(status))
991 sig = WTERMSIG(status);
993 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
995 (thisjob->foreground && !WIFSTOPPED(status))) {
996 i = WTERMSIG(status);
997 if ((i & 0x7F) < sys_nsig && sys_siglist[i & 0x7F])
998 out1str(sys_siglist[i & 0x7F]);
1000 out1fmt("Signal %d", i & 0x7F);
1001 if (WCOREDUMP(status))
1002 out1str(" (core dumped)");
1005 showjob(thisjob, pid, SHOWJOBS_DEFAULT);
1008 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1010 thisjob->changed = 1;
1018 * Do a wait system call. If job control is compiled in, we accept
1019 * stopped processes. If block is zero, we return a value of zero
1020 * rather than blocking.
1023 waitproc(int block, int *status)
1034 return wait3(status, flags, NULL);
1038 * return 1 if there are stopped jobs, otherwise 0
1040 int job_warning = 0;
1049 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1052 if (jp->state == JOBSTOPPED) {
1053 out2str("You have stopped jobs.\n");
1063 * Return a string identifying a command (to be printed by the
1067 STATIC char *cmdnextc;
1068 STATIC int cmdnleft;
1069 #define MAXCMDTEXT 200
1072 commandtext(union node *n)
1076 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1077 cmdnleft = MAXCMDTEXT - 4;
1085 cmdtxt(union node *n)
1088 struct nodelist *lp;
1097 cmdtxt(n->nbinary.ch1);
1099 cmdtxt(n->nbinary.ch2);
1102 cmdtxt(n->nbinary.ch1);
1104 cmdtxt(n->nbinary.ch2);
1107 cmdtxt(n->nbinary.ch1);
1109 cmdtxt(n->nbinary.ch2);
1112 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1120 cmdtxt(n->nredir.n);
1125 cmdtxt(n->nredir.n);
1129 cmdtxt(n->nif.test);
1131 cmdtxt(n->nif.ifpart);
1140 cmdtxt(n->nbinary.ch1);
1142 cmdtxt(n->nbinary.ch2);
1147 cmdputs(n->nfor.var);
1152 cmdputs(n->ncase.expr->narg.text);
1156 cmdputs(n->narg.text);
1160 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1165 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1171 cmdputs(n->narg.text);
1174 p = ">"; i = 1; goto redir;
1176 p = ">>"; i = 1; goto redir;
1178 p = ">&"; i = 1; goto redir;
1180 p = ">|"; i = 1; goto redir;
1182 p = "<"; i = 0; goto redir;
1184 p = "<>"; i = 0; goto redir;
1186 p = "<&"; i = 0; goto redir;
1188 if (n->nfile.fd != i) {
1189 s[0] = n->nfile.fd + '0';
1194 if (n->type == NTOFD || n->type == NFROMFD) {
1195 if (n->ndup.dupfd >= 0)
1196 s[0] = n->ndup.dupfd + '0';
1202 cmdtxt(n->nfile.fname);
1218 cmdputs(const char *s)
1229 while ((c = *p++) != '\0') {
1232 else if (c == CTLVAR) {
1237 } else if (c == '=' && subtype != 0) {
1238 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1240 } else if (c == CTLENDVAR) {
1242 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1243 cmdnleft++; /* ignore it */
1246 if (--cmdnleft <= 0) {