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
42 #include <sys/types.h>
43 #include <sys/param.h>
47 #include <sys/resource.h>
49 #include <sys/ioctl.h>
54 #undef CEOF /* syntax.h redefines this */
75 /* mode flags for set_curjob */
80 /* mode flags for dowait */
81 #define DOWAIT_NONBLOCK 0
82 #define DOWAIT_BLOCK 1
83 #define DOWAIT_WAITCMD 2
84 #define DOWAIT_WAITCMD_ALL 4
87 static struct job
*jobtab
;
89 static unsigned njobs
;
90 /* pid of last background process */
94 /* pgrp of shell on invocation */
95 static int initialpgrp
;
96 /* control terminal */
97 static int ttyfd
= -1;
101 static struct job
*curjob
;
103 /* Set if we are in the vforked child */
106 STATIC
void set_curjob(struct job
*, unsigned);
107 STATIC
int jobno(const struct job
*);
108 STATIC
int sprint_status(char *, int, int);
109 STATIC
void freejob(struct job
*);
110 STATIC
struct job
*getjob(const char *, int);
111 STATIC
struct job
*growjobtab(void);
112 STATIC
void forkchild(struct job
*, union node
*, int);
113 STATIC
void forkparent(struct job
*, union node
*, int, pid_t
);
114 STATIC
int dowait(int, struct job
*);
116 STATIC
int onsigchild(void);
118 STATIC
int waitproc(int, int *);
119 STATIC
char *commandtext(union node
*);
120 STATIC
void cmdtxt(union node
*);
121 STATIC
void cmdlist(union node
*, int);
122 STATIC
void cmdputs(const char *);
123 STATIC
void showpipe(struct job
*, struct output
*);
124 STATIC
int getstatus(struct job
*);
127 static int restartjob(struct job
*, int);
128 static void xtcsetpgrp(int, pid_t
);
132 set_curjob(struct job
*jp
, unsigned mode
)
135 struct job
**jpp
, **curp
;
137 /* first remove from list */
138 jpp
= curp
= &curjob
;
143 jpp
= &jp1
->prev_job
;
145 *jpp
= jp1
->prev_job
;
147 /* Then re-insert in correct position */
155 /* job being deleted */
158 /* newly created job or backgrounded job,
159 put after all stopped jobs. */
162 if (!JOBS
|| !jp1
|| jp1
->state
!= JOBSTOPPED
)
164 jpp
= &jp1
->prev_job
;
170 /* newly stopped job - becomes curjob */
179 * Turn job control on and off.
181 * Note: This code assumes that the third arg to ioctl is a character
182 * pointer, which is true on Berkeley systems but not System V. Since
183 * System V doesn't have job control yet, this isn't a problem now.
185 * Called with interrupts off.
196 if (on
== jobctl
|| rootshell
== 0)
200 ofd
= fd
= sh_open(_PATH_TTY
, O_RDWR
, 1);
207 fd
= savefd(fd
, ofd
);
208 do { /* while we are in the background */
209 if ((pgrp
= tcgetpgrp(fd
)) < 0) {
211 sh_warnx("can't access tty; job control turned off");
215 if (pgrp
== getpgrp())
226 xtcsetpgrp(fd
, pgrp
);
228 /* turning job control off */
231 xtcsetpgrp(fd
, pgrp
);
251 extern char *signal_names
[];
261 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
262 "kill -l [exitstatus]"
266 if (**++argv
== '-') {
267 signo
= decode_signal(*argv
+ 1, 1);
271 while ((c
= nextopt("ls:")) != '\0')
281 signo
= decode_signal(optionarg
, 1);
284 "invalid signal number or name: %s",
295 if (!list
&& signo
< 0)
298 if ((signo
< 0 || !*argv
) ^ list
) {
308 for (i
= 1; i
< NSIG
; i
++) {
309 outfmt(out
, snlfmt
, signal_names
[i
]);
313 signo
= number(*argv
);
316 if (0 < signo
&& signo
< NSIG
)
317 outfmt(out
, snlfmt
, signal_names
[signo
]);
319 sh_error("invalid signal number or exit status: %s",
327 jp
= getjob(*argv
, 0);
328 pid
= -jp
->ps
[0].pid
;
330 pid
= **argv
== '-' ?
331 -number(*argv
+ 1) : number(*argv
);
332 if (kill(pid
, signo
) != 0) {
333 sh_warnx("%s\n", strerror(errno
));
342 jobno(const struct job
*jp
)
344 return jp
- jobtab
+ 1;
349 fgcmd(int argc
, char **argv
)
356 mode
= (**argv
== 'f') ? FORK_FG
: FORK_BG
;
361 jp
= getjob(*argv
, 1);
362 if (mode
== FORK_BG
) {
363 set_curjob(jp
, CUR_RUNNING
);
364 outfmt(out
, "[%d] ", jobno(jp
));
366 outstr(jp
->ps
->cmd
, out
);
368 retval
= restartjob(jp
, mode
);
369 } while (*argv
&& *++argv
);
373 int bgcmd(int argc
, char **argv
)
374 #ifdef HAVE_ALIAS_ATTRIBUTE
375 __attribute__((__alias__("fgcmd")));
378 return fgcmd(argc
, argv
);
384 restartjob(struct job
*jp
, int mode
)
392 if (jp
->state
== JOBDONE
)
394 jp
->state
= JOBRUNNING
;
397 xtcsetpgrp(ttyfd
, pgid
);
398 killpg(pgid
, SIGCONT
);
402 if (WIFSTOPPED(ps
->status
)) {
407 status
= (mode
== FORK_FG
) ? waitforjob(jp
) : 0;
414 sprint_status(char *os
, int status
, int sigonly
)
419 st
= WEXITSTATUS(status
);
420 if (!WIFEXITED(status
)) {
422 st
= WSTOPSIG(status
);
423 if (!WIFSTOPPED(status
))
425 st
= WTERMSIG(status
);
427 if (st
== SIGINT
|| st
== SIGPIPE
)
430 if (WIFSTOPPED(status
))
434 s
= stpncpy(s
, strsignal(st
), 32);
436 if (WCOREDUMP(status
)) {
437 s
= stpcpy(s
, " (core dumped)");
440 } else if (!sigonly
) {
442 s
+= fmtstr(s
, 16, "Done(%d)", st
);
444 s
= stpcpy(s
, "Done");
452 showjob(struct output
*out
, struct job
*jp
, int mode
)
455 struct procstat
*psend
;
462 if (mode
& SHOW_PGID
) {
463 /* just output process (group) id of pipeline */
464 outfmt(out
, "%d\n", ps
->pid
);
468 col
= fmtstr(s
, 16, "[%d] ", jobno(jp
));
473 else if (curjob
&& jp
== curjob
->prev_job
)
477 col
+= fmtstr(s
+ col
, 16, "%d ", ps
->pid
);
479 psend
= ps
+ jp
->nprocs
;
481 if (jp
->state
== JOBRUNNING
) {
482 scopy("Running", s
+ col
);
483 col
+= strlen("Running");
485 int status
= psend
[-1].status
;
487 if (jp
->state
== JOBSTOPPED
)
488 status
= jp
->stopstatus
;
490 col
+= sprint_status(s
+ col
, status
, 0);
496 /* for each process */
497 col
= fmtstr(s
, 48, " |\n%*c%d ", indent
, ' ', ps
->pid
) - 3;
502 s
, 33 - col
>= 0 ? 33 - col
: 0, ' ', ps
->cmd
504 if (!(mode
& SHOW_PID
)) {
516 if (jp
->state
== JOBDONE
) {
517 TRACE(("showjob: freeing job %d\n", jobno(jp
)));
524 jobscmd(int argc
, char **argv
)
530 while ((m
= nextopt("lp")))
540 showjob(out
, getjob(*argv
,0), mode
);
550 * Print a list of jobs. If "change" is nonzero, only print jobs whose
551 * statuses have changed since the last call to showjobs.
555 showjobs(struct output
*out
, int mode
)
559 TRACE(("showjobs(%x) called\n", mode
));
561 /* If not even one job changed, there is nothing to do */
562 dowait(DOWAIT_NONBLOCK
, NULL
);
564 for (jp
= curjob
; jp
; jp
= jp
->prev_job
) {
565 if (!(mode
& SHOW_CHANGED
) || jp
->changed
)
566 showjob(out
, jp
, mode
);
571 * Mark a job structure as unused.
575 freejob(struct job
*jp
)
581 for (i
= jp
->nprocs
, ps
= jp
->ps
; --i
>= 0 ; ps
++) {
582 if (ps
->cmd
!= nullstr
)
585 if (jp
->ps
!= &jp
->ps0
)
588 set_curjob(jp
, CUR_DELETE
);
595 waitcmd(int argc
, char **argv
)
606 /* wait for all jobs */
611 /* no running procs */
614 if (jp
->state
== JOBRUNNING
)
619 if (!dowait(DOWAIT_WAITCMD_ALL
, 0))
627 pid_t pid
= number(*argv
);
631 if (job
->ps
[job
->nprocs
- 1].pid
== pid
)
639 job
= getjob(*argv
, 0);
640 /* loop until process terminated or stopped */
641 if (!dowait(DOWAIT_WAITCMD
, job
))
644 retval
= getstatus(job
);
653 retval
= 128 + pending_sig
;
660 * Convert a job name to a job structure.
664 getjob(const char *name
, int getctl
)
668 const char *err_msg
= "No such job: %s";
672 char *(*match
)(const char *, const char *);
687 if (c
== '+' || c
== '%') {
689 err_msg
= "No current job";
691 } else if (c
== '-') {
694 err_msg
= "No previous job";
704 if (num
> 0 && num
<= njobs
) {
705 jp
= jobtab
+ num
- 1;
720 if (match(jp
->ps
[0].cmd
, p
)) {
724 err_msg
= "%s: ambiguous";
735 err_msg
= "job %s not created under job control";
736 if (getctl
&& jp
->jobctl
== 0)
741 sh_error(err_msg
, name
);
747 * Return a new job structure.
748 * Called with interrupts off.
752 makejob(union node
*node
, int nprocs
)
757 for (i
= njobs
, jp
= jobtab
; ; jp
++) {
764 if (jp
->state
!= JOBDONE
|| !jp
->waited
)
771 memset(jp
, 0, sizeof(*jp
));
776 jp
->prev_job
= curjob
;
781 jp
->ps
= ckmalloc(nprocs
* sizeof (struct procstat
));
783 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node
, nprocs
,
795 len
= njobs
* sizeof(*jp
);
797 jp
= ckrealloc(jq
, len
+ 4 * sizeof(*jp
));
799 offset
= (char *)jp
- (char *)jq
;
801 /* Relocate pointers */
804 jq
= (struct job
*)((char *)jq
+ l
);
808 #define joff(p) ((struct job *)((char *)(p) + l))
809 #define jmove(p) (p) = (void *)((char *)(p) + offset)
810 if (likely(joff(jp
)->ps
== &jq
->ps0
))
812 if (joff(jp
)->prev_job
)
813 jmove(joff(jp
)->prev_job
);
823 jp
= (struct job
*)((char *)jp
+ len
);
827 } while (--jq
>= jp
);
833 * Fork off a subshell. If we are doing job control, give the subshell its
834 * own process group. Jp is a job structure that the job is to be added to.
835 * N is the command that will be evaluated by the child. Both jp and n may
836 * be NULL. The mode parameter can be one of the following:
837 * FORK_FG - Fork off a foreground process.
838 * FORK_BG - Fork off a background process.
839 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
840 * process group even if job control is on.
842 * When job control is turned off, background processes have their standard
843 * input redirected to /dev/null (except for the second and later processes
846 * Called with interrupts off.
849 static void forkchild(struct job
*jp
, union node
*n
, int mode
)
854 TRACE(("Child shell %d\n", getpid()));
865 /* do job control only in root shell */
871 if (mode
!= FORK_NOJOB
&& jp
->jobctl
&& !oldlvl
) {
877 pgrp
= jp
->ps
[0].pid
;
878 /* This can fail because we are doing it in the parent also */
879 (void)setpgid(0, pgrp
);
881 xtcsetpgrp(ttyfd
, pgrp
);
886 if (mode
== FORK_BG
) {
889 if (jp
->nprocs
== 0) {
891 sh_open(_PATH_DEVNULL
, O_RDONLY
, 0);
894 if (!oldlvl
&& iflag
) {
903 for (jp
= curjob
; jp
; jp
= jp
->prev_job
)
907 static void forkparent(struct job
*jp
, union node
*n
, int mode
, pid_t pid
)
910 TRACE(("Fork failed, errno=%d", errno
));
913 sh_error("Cannot fork");
917 TRACE(("In parent shell: child = %d\n", pid
));
921 if (mode
!= FORK_NOJOB
&& jp
->jobctl
) {
927 pgrp
= jp
->ps
[0].pid
;
928 /* This can fail because we are doing it in the child also */
929 (void)setpgid(pid
, pgrp
);
932 if (mode
== FORK_BG
) {
933 backgndpid
= pid
; /* set $! */
934 set_curjob(jp
, CUR_RUNNING
);
937 struct procstat
*ps
= &jp
->ps
[jp
->nprocs
++];
942 ps
->cmd
= commandtext(n
);
947 forkshell(struct job
*jp
, union node
*n
, int mode
)
951 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp
), n
, mode
));
954 forkchild(jp
, n
, mode
);
956 forkparent(jp
, n
, mode
, pid
);
961 struct job
*vforkexec(union node
*n
, char **argv
, const char *path
, int idx
)
974 forkchild(jp
, n
, FORK_FG
);
976 shellexec(argv
, path
, idx
);
982 forkparent(jp
, n
, FORK_FG
, pid
);
988 * Wait for job to finish.
990 * Under job control we have the problem that while a child process is
991 * running interrupts generated by the user are sent to the child but not
992 * to the shell. This means that an infinite loop started by an inter-
993 * active user may be hard to kill. With job control turned off, an
994 * interactive user may place an interactive program inside a loop. If
995 * the interactive program catches interrupts, the user doesn't want
996 * these interrupts to also abort the loop. The approach we take here
997 * is to have the shell ignore interrupt signals while waiting for a
998 * forground process to terminate, and then send itself an interrupt
999 * signal if the child process was terminated by an interrupt signal.
1000 * Unfortunately, some programs want to do a bit of cleanup and then
1001 * exit on interrupt; unless these processes terminate themselves by
1002 * sending a signal to themselves (instead of calling exit) they will
1003 * confuse this approach.
1005 * Called with interrupts off.
1009 waitforjob(struct job
*jp
)
1013 TRACE(("waitforjob(%%%d) called\n", jp
? jobno(jp
) : 0));
1014 dowait(jp
? DOWAIT_BLOCK
: DOWAIT_NONBLOCK
, jp
);
1021 xtcsetpgrp(ttyfd
, rootpid
);
1023 * This is truly gross.
1024 * If we're doing job control, then we did a TIOCSPGRP which
1025 * caused us (the shell) to no longer be in the controlling
1026 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
1027 * intuit from the subprocess exit status whether a SIGINT
1028 * occurred, and if so interrupt ourselves. Yuck. - mycroft
1034 if (! JOBS
|| jp
->state
== JOBDONE
)
1042 * Wait for a process to terminate.
1045 static int waitone(int block
, struct job
*job
)
1050 struct job
*thisjob
= NULL
;
1054 TRACE(("dowait(%d) called\n", block
));
1055 pid
= waitproc(block
, &status
);
1056 TRACE(("wait returns pid %d, status=%d\n", pid
, status
));
1060 for (jp
= curjob
; jp
; jp
= jp
->prev_job
) {
1061 struct procstat
*sp
;
1062 struct procstat
*spend
;
1063 if (jp
->state
== JOBDONE
)
1066 spend
= jp
->ps
+ jp
->nprocs
;
1069 if (sp
->pid
== pid
) {
1070 TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jobno(jp
), pid
, sp
->status
, status
));
1071 sp
->status
= status
;
1074 if (sp
->status
== -1)
1077 if (state
== JOBRUNNING
)
1079 if (WIFSTOPPED(sp
->status
)) {
1080 jp
->stopstatus
= sp
->status
;
1084 } while (++sp
< spend
);
1091 if (state
!= JOBRUNNING
) {
1092 thisjob
->changed
= 1;
1094 if (thisjob
->state
!= state
) {
1095 TRACE(("Job %d: changing state from %d to %d\n", jobno(thisjob
), thisjob
->state
, state
));
1096 thisjob
->state
= state
;
1098 if (state
== JOBSTOPPED
) {
1099 set_curjob(thisjob
, CUR_STOPPED
);
1108 if (thisjob
&& thisjob
== job
) {
1112 len
= sprint_status(s
, status
, 1);
1122 static int dowait(int block
, struct job
*jp
)
1124 int gotchld
= *(volatile int *)&gotsigchld
;
1128 if (jp
&& jp
->state
!= JOBRUNNING
)
1129 block
= DOWAIT_NONBLOCK
;
1131 if (block
== DOWAIT_NONBLOCK
&& !gotchld
)
1137 pid
= waitone(block
, jp
);
1140 block
&= ~DOWAIT_WAITCMD_ALL
;
1141 if (!pid
|| (jp
&& jp
->state
!= JOBRUNNING
))
1142 block
= DOWAIT_NONBLOCK
;
1149 * Do a wait system call. If block is zero, we return -1 rather than
1150 * blocking. If block is DOWAIT_WAITCMD, we return 0 when a signal
1151 * other than SIGCHLD interrupted the wait.
1153 * We use sigsuspend in conjunction with a non-blocking wait3 in
1154 * order to ensure that waitcmd exits promptly upon the reception
1157 * For code paths other than waitcmd we either use a blocking wait3
1158 * or a non-blocking wait3. For the latter case the caller of dowait
1159 * must ensure that it is called over and over again until all dead
1160 * children have been reaped. Otherwise zombies may linger.
1165 waitproc(int block
, int *status
)
1168 int flags
= block
== DOWAIT_BLOCK
? 0 : WNOHANG
;
1179 err
= wait3(status
, flags
, NULL
);
1180 while (err
< 0 && errno
== EINTR
);
1182 if (err
|| (err
= -!block
))
1185 sigblockall(&oldmask
);
1187 while (!gotsigchld
&& !pending_sig
)
1188 sigsuspend(&oldmask
);
1191 } while (gotsigchld
);
1197 * return 1 if there are stopped jobs, otherwise 0
1210 if (jp
&& jp
->state
== JOBSTOPPED
) {
1211 out2str("You have stopped jobs.\n");
1221 * Return a string identifying a command (to be printed by the
1225 STATIC
char *cmdnextc
;
1228 commandtext(union node
*n
)
1232 STARTSTACKSTR(cmdnextc
);
1234 name
= stackblock();
1235 TRACE(("commandtext: name %p, end %p\n", name
, cmdnextc
));
1236 return savestr(name
);
1241 cmdtxt(union node
*n
)
1244 struct nodelist
*lp
;
1256 lp
= n
->npipe
.cmdlist
;
1274 cmdtxt(n
->nbinary
.ch1
);
1290 cmdtxt(n
->nif
.test
);
1292 if (n
->nif
.elsepart
) {
1293 cmdtxt(n
->nif
.ifpart
);
1295 n
= n
->nif
.elsepart
;
1313 cmdtxt(n
->nbinary
.ch1
);
1323 cmdputs(n
->nfor
.var
);
1325 cmdlist(n
->nfor
.args
, 1);
1330 cmdputs(n
->ndefun
.text
);
1334 cmdlist(n
->ncmd
.args
, 1);
1335 cmdlist(n
->ncmd
.redirect
, 0);
1348 cmdputs(n
->ncase
.expr
->narg
.text
);
1350 for (np
= n
->ncase
.cases
; np
; np
= np
->nclist
.next
) {
1351 cmdtxt(np
->nclist
.pattern
);
1353 cmdtxt(np
->nclist
.body
);
1379 s
[0] = n
->nfile
.fd
+ '0';
1383 if (n
->type
== NTOFD
|| n
->type
== NFROMFD
) {
1384 s
[0] = n
->ndup
.dupfd
+ '0';
1395 cmdlist(union node
*np
, int sep
)
1397 for (; np
; np
= np
->narg
.next
) {
1401 if (sep
&& np
->narg
.next
)
1408 cmdputs(const char *s
)
1410 const char *p
, *str
;
1416 static const char vstype
[VSTYPE
+ 1][4] = {
1417 "", "}", "-", "+", "?", "=",
1418 "%", "%%", "#", "##",
1421 nextc
= makestrspace((strlen(s
) + 1) * 8, cmdnextc
);
1423 while ((c
= *p
++) != 0) {
1431 if ((subtype
& VSTYPE
) == VSLENGTH
)
1438 str
+= !(quoted
& 1);
1458 if ((subtype
& VSTYPE
) != VSNORMAL
)
1460 str
= vstype
[subtype
& VSTYPE
];
1461 if (subtype
& VSNUL
)
1470 /* These can only happen inside quotes */
1483 while ((c
= *str
++)) {
1488 USTPUTC('"', nextc
);
1496 showpipe(struct job
*jp
, struct output
*out
)
1498 struct procstat
*sp
;
1499 struct procstat
*spend
;
1501 spend
= jp
->ps
+ jp
->nprocs
;
1502 for (sp
= jp
->ps
+ 1; sp
< spend
; sp
++)
1503 outfmt(out
, " | %s", sp
->cmd
);
1504 outcslow('\n', out
);
1511 xtcsetpgrp(int fd
, pid_t pgrp
)
1516 err
= tcsetpgrp(fd
, pgrp
);
1520 sh_error("Cannot set tty process group (%s)", strerror(errno
));
1526 getstatus(struct job
*job
) {
1530 status
= job
->ps
[job
->nprocs
- 1].status
;
1531 retval
= WEXITSTATUS(status
);
1532 if (!WIFEXITED(status
)) {
1534 retval
= WSTOPSIG(status
);
1535 if (!WIFSTOPPED(status
))
1538 /* XXX: limits number of signals */
1539 retval
= WTERMSIG(status
);
1541 if (retval
== SIGINT
)
1547 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
1548 jobno(job
), job
->nprocs
, status
, retval
));