2
* Copyright (c) 1991, 1993
3
* The Regents of the University of California. All rights reserved.
4
* Copyright (c) 1997-2005
5
* Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved.
7
* This code is derived from software contributed to Berkeley by
10
* Redistribution and use in source and binary forms, with or without
11
* modification, are permitted provided that the following conditions
13
* 1. Redistributions of source code must retain the above copyright
14
* notice, this list of conditions and the following disclaimer.
15
* 2. Redistributions in binary form must reproduce the above copyright
16
* notice, this list of conditions and the following disclaimer in the
17
* documentation and/or other materials provided with the distribution.
18
* 3. Neither the name of the University nor the names of its contributors
19
* may be used to endorse or promote products derived from this software
20
* without specific prior written permission.
22
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40
#include <sys/types.h>
41
#include <sys/param.h>
45
#include <sys/resource.h>
47
#include <sys/ioctl.h>
52
#undef CEOF /* syntax.h redefines this */
70
/* mode flags for set_curjob */
75
/* mode flags for dowait */
76
#define DOWAIT_NORMAL 0
77
#define DOWAIT_BLOCK 1
80
static struct job *jobtab;
82
static unsigned njobs;
83
/* pid of last background process */
87
/* pgrp of shell on invocation */
88
static int initialpgrp;
89
/* control terminal */
90
static int ttyfd = -1;
94
static struct job *curjob;
95
/* number of presumed living untracked jobs */
98
STATIC void set_curjob(struct job *, unsigned);
99
STATIC int jobno(const struct job *);
100
STATIC int sprint_status(char *, int, int);
101
STATIC void freejob(struct job *);
102
STATIC struct job *getjob(const char *, int);
103
STATIC struct job *growjobtab(void);
104
STATIC void forkchild(struct job *, union node *, int);
105
STATIC void forkparent(struct job *, union node *, int, pid_t);
106
STATIC int dowait(int, struct job *);
108
STATIC int onsigchild(void);
110
STATIC int waitproc(int, int *);
111
STATIC char *commandtext(union node *);
112
STATIC void cmdtxt(union node *);
113
STATIC void cmdlist(union node *, int);
114
STATIC void cmdputs(const char *);
115
STATIC void showpipe(struct job *, struct output *);
116
STATIC int getstatus(struct job *);
119
static int restartjob(struct job *, int);
120
static void xtcsetpgrp(int, pid_t);
124
set_curjob(struct job *jp, unsigned mode)
127
struct job **jpp, **curp;
129
/* first remove from list */
130
jpp = curp = &curjob;
135
jpp = &jp1->prev_job;
137
*jpp = jp1->prev_job;
139
/* Then re-insert in correct position */
147
/* job being deleted */
150
/* newly created job or backgrounded job,
151
put after all stopped jobs. */
154
if (!JOBS || !jp1 || jp1->state != JOBSTOPPED)
156
jpp = &jp1->prev_job;
162
/* newly stopped job - becomes curjob */
171
* Turn job control on and off.
173
* Note: This code assumes that the third arg to ioctl is a character
174
* pointer, which is true on Berkeley systems but not System V. Since
175
* System V doesn't have job control yet, this isn't a problem now.
177
* Called with interrupts off.
188
if (on == jobctl || rootshell == 0)
192
ofd = fd = open(_PATH_TTY, O_RDWR);
195
while (!isatty(fd) && --fd >= 0)
198
fd = fcntl(fd, F_DUPFD, 10);
202
fcntl(fd, F_SETFD, FD_CLOEXEC);
203
do { /* while we are in the background */
204
if ((pgrp = tcgetpgrp(fd)) < 0) {
206
sh_warnx("can't access tty; job control turned off");
210
if (pgrp == getpgrp())
221
xtcsetpgrp(fd, pgrp);
223
/* turning job control off */
226
xtcsetpgrp(fd, pgrp);
255
"Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
256
"kill -l [exitstatus]"
260
if (**++argv == '-') {
261
signo = decode_signal(*argv + 1, 1);
265
while ((c = nextopt("ls:")) != '\0')
275
signo = decode_signal(optionarg, 1);
278
"invalid signal number or name: %s",
289
if (!list && signo < 0)
292
if ((signo < 0 || !*argv) ^ list) {
302
for (i = 1; i < NSIG; i++) {
303
outfmt(out, snlfmt, signal_name(i));
307
signo = number(*argv);
310
if (0 < signo && signo < NSIG)
311
outfmt(out, snlfmt, signal_name(signo));
313
sh_error("invalid signal number or exit status: %s",
321
jp = getjob(*argv, 0);
322
pid = -jp->ps[0].pid;
324
pid = **argv == '-' ?
325
-number(*argv + 1) : number(*argv);
326
if (kill(pid, signo) != 0) {
327
sh_warnx("%s\n", strerror(errno));
336
jobno(const struct job *jp)
338
return jp - jobtab + 1;
343
fgcmd(int argc, char **argv)
350
mode = (**argv == 'f') ? FORK_FG : FORK_BG;
355
jp = getjob(*argv, 1);
356
if (mode == FORK_BG) {
357
set_curjob(jp, CUR_RUNNING);
358
outfmt(out, "[%d] ", jobno(jp));
360
outstr(jp->ps->cmd, out);
362
retval = restartjob(jp, mode);
363
} while (*argv && *++argv);
367
int bgcmd(int, char **) __attribute__((__alias__("fgcmd")));
371
restartjob(struct job *jp, int mode)
379
if (jp->state == JOBDONE)
381
jp->state = JOBRUNNING;
384
xtcsetpgrp(ttyfd, pgid);
385
killpg(pgid, SIGCONT);
389
if (WIFSTOPPED(ps->status)) {
394
status = (mode == FORK_FG) ? waitforjob(jp) : 0;
401
sprint_status(char *s, int status, int sigonly)
407
st = WEXITSTATUS(status);
408
if (!WIFEXITED(status)) {
410
st = WSTOPSIG(status);
411
if (!WIFSTOPPED(status))
413
st = WTERMSIG(status);
415
if (st == SIGINT || st == SIGPIPE)
418
if (WIFSTOPPED(status))
422
col = fmtstr(s, 32, strsignal(st));
423
if (WCOREDUMP(status)) {
424
col += fmtstr(s + col, 16, " (core dumped)");
426
} else if (!sigonly) {
428
col = fmtstr(s, 16, "Done(%d)", st);
430
col = fmtstr(s, 16, "Done");
438
showjob(struct output *out, struct job *jp, int mode)
441
struct procstat *psend;
448
if (mode & SHOW_PGID) {
449
/* just output process (group) id of pipeline */
450
outfmt(out, "%d\n", ps->pid);
454
col = fmtstr(s, 16, "[%d] ", jobno(jp));
459
else if (curjob && jp == curjob->prev_job)
463
col += fmtstr(s + col, 16, "%d ", ps->pid);
465
psend = ps + jp->nprocs;
467
if (jp->state == JOBRUNNING) {
468
scopy("Running", s + col);
469
col += strlen("Running");
471
int status = psend[-1].status;
473
if (jp->state == JOBSTOPPED)
474
status = jp->stopstatus;
476
col += sprint_status(s + col, status, 0);
482
/* for each process */
483
col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
488
s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
490
if (!(mode & SHOW_PID)) {
502
if (jp->state == JOBDONE) {
503
TRACE(("showjob: freeing job %d\n", jobno(jp)));
510
jobscmd(int argc, char **argv)
516
while ((m = nextopt("lp")))
526
showjob(out, getjob(*argv,0), mode);
536
* Print a list of jobs. If "change" is nonzero, only print jobs whose
537
* statuses have changed since the last call to showjobs.
541
showjobs(struct output *out, int mode)
545
TRACE(("showjobs(%x) called\n", mode));
547
/* If not even one one job changed, there is nothing to do */
548
while (dowait(DOWAIT_NORMAL, NULL) > 0)
551
for (jp = curjob; jp; jp = jp->prev_job) {
552
if (!(mode & SHOW_CHANGED) || jp->changed)
553
showjob(out, jp, mode);
558
* Mark a job structure as unused.
562
freejob(struct job *jp)
568
for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
569
if (ps->cmd != nullstr)
572
if (jp->ps != &jp->ps0)
575
set_curjob(jp, CUR_DELETE);
582
waitcmd(int argc, char **argv)
595
/* wait for all jobs */
600
/* no running procs */
603
if (jp->state == JOBRUNNING)
608
dowait(DOWAIT_BLOCK, 0);
615
pid_t pid = number(*argv);
619
if (job->ps[job->nprocs - 1].pid == pid)
627
job = getjob(*argv, 0);
628
/* loop until process terminated or stopped */
629
while (job->state == JOBRUNNING)
630
dowait(DOWAIT_BLOCK, 0);
632
retval = getstatus(job);
644
* Convert a job name to a job structure.
648
getjob(const char *name, int getctl)
652
const char *err_msg = "No such job: %s";
656
char *(*match)(const char *, const char *);
671
if (c == '+' || c == '%') {
673
err_msg = "No current job";
675
} else if (c == '-') {
678
err_msg = "No previous job";
689
jp = jobtab + num - 1;
706
if (match(jp->ps[0].cmd, p)) {
710
err_msg = "%s: ambiguous";
717
err_msg = "job %s not created under job control";
718
if (getctl && jp->jobctl == 0)
723
sh_error(err_msg, name);
729
* Return a new job structure.
730
* Called with interrupts off.
734
makejob(union node *node, int nprocs)
739
for (i = njobs, jp = jobtab ; ; jp++) {
746
if (jp->state != JOBDONE || !jp->waited)
753
memset(jp, 0, sizeof(*jp));
758
jp->prev_job = curjob;
763
jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
765
TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
777
len = njobs * sizeof(*jp);
779
jp = ckrealloc(jq, len + 4 * sizeof(*jp));
781
offset = (char *)jp - (char *)jq;
783
/* Relocate pointers */
786
jq = (struct job *)((char *)jq + l);
790
#define joff(p) ((struct job *)((char *)(p) + l))
791
#define jmove(p) (p) = (void *)((char *)(p) + offset)
792
if (likely(joff(jp)->ps == &jq->ps0))
794
if (joff(jp)->prev_job)
795
jmove(joff(jp)->prev_job);
805
jp = (struct job *)((char *)jp + len);
809
} while (--jq >= jp);
815
* Fork off a subshell. If we are doing job control, give the subshell its
816
* own process group. Jp is a job structure that the job is to be added to.
817
* N is the command that will be evaluated by the child. Both jp and n may
818
* be NULL. The mode parameter can be one of the following:
819
* FORK_FG - Fork off a foreground process.
820
* FORK_BG - Fork off a background process.
821
* FORK_NOJOB - Like FORK_FG, but don't give the process its own
822
* process group even if job control is on.
824
* When job control is turned off, background processes have their standard
825
* input redirected to /dev/null (except for the second and later processes
828
* Called with interrupts off.
832
forkchild(struct job *jp, union node *n, int mode)
836
TRACE(("Child shell %d\n", getpid()));
843
/* do job control only in root shell */
845
if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
851
pgrp = jp->ps[0].pid;
852
/* This can fail because we are doing it in the parent also */
853
(void)setpgid(0, pgrp);
855
xtcsetpgrp(ttyfd, pgrp);
860
if (mode == FORK_BG) {
863
if (jp->nprocs == 0) {
865
if (open(_PATH_DEVNULL, O_RDONLY) != 0)
866
sh_error("Can't open %s", _PATH_DEVNULL);
869
if (!oldlvl && iflag) {
874
for (jp = curjob; jp; jp = jp->prev_job)
880
forkparent(struct job *jp, union node *n, int mode, pid_t pid)
882
TRACE(("In parent shell: child = %d\n", pid));
884
while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
889
if (mode != FORK_NOJOB && jp->jobctl) {
895
pgrp = jp->ps[0].pid;
896
/* This can fail because we are doing it in the child also */
897
(void)setpgid(pid, pgrp);
900
if (mode == FORK_BG) {
901
backgndpid = pid; /* set $! */
902
set_curjob(jp, CUR_RUNNING);
905
struct procstat *ps = &jp->ps[jp->nprocs++];
910
ps->cmd = commandtext(n);
915
forkshell(struct job *jp, union node *n, int mode)
919
TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
922
TRACE(("Fork failed, errno=%d", errno));
925
sh_error("Cannot fork");
928
forkchild(jp, n, mode);
930
forkparent(jp, n, mode, pid);
935
* Wait for job to finish.
937
* Under job control we have the problem that while a child process is
938
* running interrupts generated by the user are sent to the child but not
939
* to the shell. This means that an infinite loop started by an inter-
940
* active user may be hard to kill. With job control turned off, an
941
* interactive user may place an interactive program inside a loop. If
942
* the interactive program catches interrupts, the user doesn't want
943
* these interrupts to also abort the loop. The approach we take here
944
* is to have the shell ignore interrupt signals while waiting for a
945
* forground process to terminate, and then send itself an interrupt
946
* signal if the child process was terminated by an interrupt signal.
947
* Unfortunately, some programs want to do a bit of cleanup and then
948
* exit on interrupt; unless these processes terminate themselves by
949
* sending a signal to themselves (instead of calling exit) they will
950
* confuse this approach.
952
* Called with interrupts off.
956
waitforjob(struct job *jp)
960
TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
961
while (jp->state == JOBRUNNING) {
962
dowait(DOWAIT_BLOCK, jp);
967
xtcsetpgrp(ttyfd, rootpid);
969
* This is truly gross.
970
* If we're doing job control, then we did a TIOCSPGRP which
971
* caused us (the shell) to no longer be in the controlling
972
* session -- so we wouldn't have seen any ^C/SIGINT. So, we
973
* intuit from the subprocess exit status whether a SIGINT
974
* occurred, and if so interrupt ourselves. Yuck. - mycroft
980
if (! JOBS || jp->state == JOBDONE)
988
* Wait for a process to terminate.
992
dowait(int block, struct job *job)
1000
TRACE(("dowait(%d) called\n", block));
1001
pid = waitproc(block, &status);
1002
TRACE(("wait returns pid %d, status=%d\n", pid, status));
1007
for (jp = curjob; jp; jp = jp->prev_job) {
1008
struct procstat *sp;
1009
struct procstat *spend;
1010
if (jp->state == JOBDONE)
1013
spend = jp->ps + jp->nprocs;
1016
if (sp->pid == pid) {
1017
TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jobno(jp), pid, sp->status, status));
1018
sp->status = status;
1021
if (sp->status == -1)
1024
if (state == JOBRUNNING)
1026
if (WIFSTOPPED(sp->status)) {
1027
jp->stopstatus = sp->status;
1031
} while (++sp < spend);
1035
if (!JOBS || !WIFSTOPPED(status))
1040
if (state != JOBRUNNING) {
1041
thisjob->changed = 1;
1043
if (thisjob->state != state) {
1044
TRACE(("Job %d: changing state from %d to %d\n", jobno(thisjob), thisjob->state, state));
1045
thisjob->state = state;
1047
if (state == JOBSTOPPED) {
1048
set_curjob(thisjob, CUR_STOPPED);
1057
if (thisjob && thisjob == job) {
1061
len = sprint_status(s, status, 1);
1074
* Do a wait system call. If job control is compiled in, we accept
1075
* stopped processes. If block is zero, we return a value of zero
1076
* rather than blocking.
1078
* System V doesn't have a non-blocking wait system call. It does
1079
* have a SIGCLD signal that is sent to a process when one of it's
1080
* children dies. The obvious way to use SIGCLD would be to install
1081
* a handler for SIGCLD which simply bumped a counter when a SIGCLD
1082
* was received, and have waitproc bump another counter when it got
1083
* the status of a process. Waitproc would then know that a wait
1084
* system call would not block if the two counters were different.
1085
* This approach doesn't work because if a process has children that
1086
* have not been waited for, System V will send it a SIGCLD when it
1087
* installs a signal handler for SIGCLD. What this means is that when
1088
* a child exits, the shell will be sent SIGCLD signals continuously
1089
* until is runs out of stack space, unless it does a wait call before
1090
* restoring the signal handler. The code below takes advantage of
1091
* this (mis)feature by installing a signal handler for SIGCLD and
1092
* then checking to see whether it was called. If there are any
1093
* children to be waited for, it will be.
1095
* If neither SYSV nor BSD is defined, we don't implement nonblocking
1096
* waits at all. In this case, the user will not be informed when
1097
* a background process until the next time she runs a real program
1098
* (as opposed to running a builtin command or just typing return),
1099
* and the jobs command may give out of date information.
1103
STATIC int gotsigchild;
1105
STATIC int onsigchild() {
1112
waitproc(int block, int *status)
1123
return wait3(status, flags, (struct rusage *)NULL);
1130
save = signal(SIGCLD, onsigchild);
1131
signal(SIGCLD, save);
1132
if (gotsigchild == 0)
1135
return wait(status);
1139
return wait(status);
1145
* return 1 if there are stopped jobs, otherwise 0
1158
if (jp && jp->state == JOBSTOPPED) {
1159
out2str("You have stopped jobs.\n");
1169
* Return a string identifying a command (to be printed by the
1173
STATIC char *cmdnextc;
1176
commandtext(union node *n)
1180
STARTSTACKSTR(cmdnextc);
1182
name = stackblock();
1183
TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
1184
name, cmdnextc, ps->cmd));
1185
return savestr(name);
1190
cmdtxt(union node *n)
1193
struct nodelist *lp;
1205
lp = n->npipe.cmdlist;
1223
cmdtxt(n->nbinary.ch1);
1239
cmdtxt(n->nif.test);
1242
if (n->nif.elsepart) {
1245
n = n->nif.elsepart;
1261
cmdtxt(n->nbinary.ch1);
1271
cmdputs(n->nfor.var);
1273
cmdlist(n->nfor.args, 1);
1278
cmdputs(n->narg.text);
1282
cmdlist(n->ncmd.args, 1);
1283
cmdlist(n->ncmd.redirect, 0);
1296
cmdputs(n->ncase.expr->narg.text);
1298
for (np = n->ncase.cases; np; np = np->nclist.next) {
1299
cmdtxt(np->nclist.pattern);
1301
cmdtxt(np->nclist.body);
1327
s[0] = n->nfile.fd + '0';
1331
if (n->type == NTOFD || n->type == NFROMFD) {
1332
s[0] = n->ndup.dupfd + '0';
1343
cmdlist(union node *np, int sep)
1345
for (; np; np = np->narg.next) {
1349
if (sep && np->narg.next)
1356
cmdputs(const char *s)
1358
const char *p, *str;
1359
char c, cc[2] = " ";
1363
static const char vstype[VSTYPE + 1][4] = {
1364
"", "}", "-", "+", "?", "=",
1365
"%", "%%", "#", "##",
1368
nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
1370
while ((c = *p++) != 0) {
1378
if ((subtype & VSTYPE) == VSLENGTH)
1382
if (!(subtype & VSQUOTE) != !(quoted & 1)) {
1389
str = "\"}" + !(quoted & 1);
1396
case CTLBACKQ+CTLQUOTE:
1412
if ((subtype & VSTYPE) != VSNORMAL)
1414
str = vstype[subtype & VSTYPE];
1415
if (subtype & VSNUL)
1424
/* These can only happen inside quotes */
1437
while ((c = *str++)) {
1442
USTPUTC('"', nextc);
1450
showpipe(struct job *jp, struct output *out)
1452
struct procstat *sp;
1453
struct procstat *spend;
1455
spend = jp->ps + jp->nprocs;
1456
for (sp = jp->ps + 1; sp < spend; sp++)
1457
outfmt(out, " | %s", sp->cmd);
1458
outcslow('\n', out);
1465
xtcsetpgrp(int fd, pid_t pgrp)
1467
if (tcsetpgrp(fd, pgrp))
1468
sh_error("Cannot set tty process group (%s)", strerror(errno));
1474
getstatus(struct job *job) {
1478
status = job->ps[job->nprocs - 1].status;
1479
retval = WEXITSTATUS(status);
1480
if (!WIFEXITED(status)) {
1482
retval = WSTOPSIG(status);
1483
if (!WIFSTOPPED(status))
1486
/* XXX: limits number of signals */
1487
retval = WTERMSIG(status);
1489
if (retval == SIGINT)
1495
TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
1496
jobno(job), job->nprocs, status, retval));