shell: Call CHECK_DECL on stat64
[dash.git] / src / jobs.c
blobf3b9ffc28535ef3ef4ecd2e3be05d9a834f24a86
1 /*-
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
8 * Kenneth Almquist.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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
32 * SUCH DAMAGE.
35 #include <fcntl.h>
36 #include <signal.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #ifdef HAVE_PATHS_H
40 #include <paths.h>
41 #endif
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #ifdef BSD
45 #include <sys/wait.h>
46 #include <sys/time.h>
47 #include <sys/resource.h>
48 #endif
49 #include <sys/ioctl.h>
51 #include "shell.h"
52 #if JOBS
53 #include <termios.h>
54 #undef CEOF /* syntax.h redefines this */
55 #endif
56 #include "exec.h"
57 #include "eval.h"
58 #include "init.h"
59 #include "redir.h"
60 #include "show.h"
61 #include "main.h"
62 #include "parser.h"
63 #include "nodes.h"
64 #include "jobs.h"
65 #include "options.h"
66 #include "trap.h"
67 #include "syntax.h"
68 #include "input.h"
69 #include "output.h"
70 #include "memalloc.h"
71 #include "error.h"
72 #include "mystring.h"
73 #include "system.h"
75 /* mode flags for set_curjob */
76 #define CUR_DELETE 2
77 #define CUR_RUNNING 1
78 #define CUR_STOPPED 0
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
86 /* array of jobs */
87 static struct job *jobtab;
88 /* size of array */
89 static unsigned njobs;
90 /* pid of last background process */
91 pid_t backgndpid;
93 #if JOBS
94 /* pgrp of shell on invocation */
95 static int initialpgrp;
96 /* control terminal */
97 static int ttyfd = -1;
98 #endif
100 /* current job */
101 static struct job *curjob;
103 /* Set if we are in the vforked child */
104 int vforked;
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 *);
115 #ifdef SYSV
116 STATIC int onsigchild(void);
117 #endif
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 *);
126 #if JOBS
127 static int restartjob(struct job *, int);
128 static void xtcsetpgrp(int, pid_t);
129 #endif
131 STATIC void
132 set_curjob(struct job *jp, unsigned mode)
134 struct job *jp1;
135 struct job **jpp, **curp;
137 /* first remove from list */
138 jpp = curp = &curjob;
139 do {
140 jp1 = *jpp;
141 if (jp1 == jp)
142 break;
143 jpp = &jp1->prev_job;
144 } while (1);
145 *jpp = jp1->prev_job;
147 /* Then re-insert in correct position */
148 jpp = curp;
149 switch (mode) {
150 default:
151 #ifdef DEBUG
152 abort();
153 #endif
154 case CUR_DELETE:
155 /* job being deleted */
156 break;
157 case CUR_RUNNING:
158 /* newly created job or backgrounded job,
159 put after all stopped jobs. */
160 do {
161 jp1 = *jpp;
162 if (!JOBS || !jp1 || jp1->state != JOBSTOPPED)
163 break;
164 jpp = &jp1->prev_job;
165 } while (1);
166 /* FALLTHROUGH */
167 #if JOBS
168 case CUR_STOPPED:
169 #endif
170 /* newly stopped job - becomes curjob */
171 jp->prev_job = *jpp;
172 *jpp = jp;
173 break;
177 #if JOBS
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.
188 int jobctl;
190 void
191 setjobctl(int on)
193 int fd;
194 int pgrp;
196 if (on == jobctl || rootshell == 0)
197 return;
198 if (on) {
199 int ofd;
200 ofd = fd = sh_open(_PATH_TTY, O_RDWR, 1);
201 if (fd < 0) {
202 fd += 3;
203 while (!isatty(fd))
204 if (--fd < 0)
205 goto out;
207 fd = savefd(fd, ofd);
208 do { /* while we are in the background */
209 if ((pgrp = tcgetpgrp(fd)) < 0) {
210 out:
211 sh_warnx("can't access tty; job control turned off");
212 mflag = on = 0;
213 goto close;
215 if (pgrp == getpgrp())
216 break;
217 killpg(0, SIGTTIN);
218 } while (1);
219 initialpgrp = pgrp;
221 setsignal(SIGTSTP);
222 setsignal(SIGTTOU);
223 setsignal(SIGTTIN);
224 pgrp = rootpid;
225 setpgid(0, pgrp);
226 xtcsetpgrp(fd, pgrp);
227 } else {
228 /* turning job control off */
229 fd = ttyfd;
230 pgrp = initialpgrp;
231 xtcsetpgrp(fd, pgrp);
232 setpgid(0, pgrp);
233 setsignal(SIGTSTP);
234 setsignal(SIGTTOU);
235 setsignal(SIGTTIN);
236 close:
237 close(fd);
238 fd = -1;
240 ttyfd = fd;
241 jobctl = on;
243 #endif
247 killcmd(argc, argv)
248 int argc;
249 char **argv;
251 extern char *signal_names[];
252 int signo = -1;
253 int list = 0;
254 int i;
255 pid_t pid;
256 struct job *jp;
258 if (argc <= 1) {
259 usage:
260 sh_error(
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);
268 if (signo < 0) {
269 int c;
271 while ((c = nextopt("ls:")) != '\0')
272 switch (c) {
273 default:
274 #ifdef DEBUG
275 abort();
276 #endif
277 case 'l':
278 list = 1;
279 break;
280 case 's':
281 signo = decode_signal(optionarg, 1);
282 if (signo < 0) {
283 sh_error(
284 "invalid signal number or name: %s",
285 optionarg
288 break;
290 argv = argptr;
291 } else
292 argv++;
295 if (!list && signo < 0)
296 signo = SIGTERM;
298 if ((signo < 0 || !*argv) ^ list) {
299 goto usage;
302 if (list) {
303 struct output *out;
305 out = out1;
306 if (!*argv) {
307 outstr("0\n", out);
308 for (i = 1; i < NSIG; i++) {
309 outfmt(out, snlfmt, signal_names[i]);
311 return 0;
313 signo = number(*argv);
314 if (signo > 128)
315 signo -= 128;
316 if (0 < signo && signo < NSIG)
317 outfmt(out, snlfmt, signal_names[signo]);
318 else
319 sh_error("invalid signal number or exit status: %s",
320 *argv);
321 return 0;
324 i = 0;
325 do {
326 if (**argv == '%') {
327 jp = getjob(*argv, 0);
328 pid = -jp->ps[0].pid;
329 } else
330 pid = **argv == '-' ?
331 -number(*argv + 1) : number(*argv);
332 if (kill(pid, signo) != 0) {
333 sh_warnx("%s\n", strerror(errno));
334 i = 1;
336 } while (*++argv);
338 return i;
341 STATIC int
342 jobno(const struct job *jp)
344 return jp - jobtab + 1;
347 #if JOBS
349 fgcmd(int argc, char **argv)
351 struct job *jp;
352 struct output *out;
353 int mode;
354 int retval;
356 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
357 nextopt(nullstr);
358 argv = argptr;
359 out = out1;
360 do {
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);
367 showpipe(jp, out);
368 retval = restartjob(jp, mode);
369 } while (*argv && *++argv);
370 return retval;
373 int bgcmd(int argc, char **argv)
374 #ifdef HAVE_ALIAS_ATTRIBUTE
375 __attribute__((__alias__("fgcmd")));
376 #else
378 return fgcmd(argc, argv);
380 #endif
383 STATIC int
384 restartjob(struct job *jp, int mode)
386 struct procstat *ps;
387 int i;
388 int status;
389 pid_t pgid;
391 INTOFF;
392 if (jp->state == JOBDONE)
393 goto out;
394 jp->state = JOBRUNNING;
395 pgid = jp->ps->pid;
396 if (mode == FORK_FG)
397 xtcsetpgrp(ttyfd, pgid);
398 killpg(pgid, SIGCONT);
399 ps = jp->ps;
400 i = jp->nprocs;
401 do {
402 if (WIFSTOPPED(ps->status)) {
403 ps->status = -1;
405 } while (ps++, --i);
406 out:
407 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
408 INTON;
409 return status;
411 #endif
413 STATIC int
414 sprint_status(char *os, int status, int sigonly)
416 char *s = os;
417 int st;
419 st = WEXITSTATUS(status);
420 if (!WIFEXITED(status)) {
421 #if JOBS
422 st = WSTOPSIG(status);
423 if (!WIFSTOPPED(status))
424 #endif
425 st = WTERMSIG(status);
426 if (sigonly) {
427 if (st == SIGINT || st == SIGPIPE)
428 goto out;
429 #if JOBS
430 if (WIFSTOPPED(status))
431 goto out;
432 #endif
434 s = stpncpy(s, strsignal(st), 32);
435 #ifdef WCOREDUMP
436 if (WCOREDUMP(status)) {
437 s = stpcpy(s, " (core dumped)");
439 #endif
440 } else if (!sigonly) {
441 if (st)
442 s += fmtstr(s, 16, "Done(%d)", st);
443 else
444 s = stpcpy(s, "Done");
447 out:
448 return s - os;
451 static void
452 showjob(struct output *out, struct job *jp, int mode)
454 struct procstat *ps;
455 struct procstat *psend;
456 int col;
457 int indent;
458 char s[80];
460 ps = jp->ps;
462 if (mode & SHOW_PGID) {
463 /* just output process (group) id of pipeline */
464 outfmt(out, "%d\n", ps->pid);
465 return;
468 col = fmtstr(s, 16, "[%d] ", jobno(jp));
469 indent = col;
471 if (jp == curjob)
472 s[col - 2] = '+';
473 else if (curjob && jp == curjob->prev_job)
474 s[col - 2] = '-';
476 if (mode & SHOW_PID)
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");
484 } else {
485 int status = psend[-1].status;
486 #if JOBS
487 if (jp->state == JOBSTOPPED)
488 status = jp->stopstatus;
489 #endif
490 col += sprint_status(s + col, status, 0);
493 goto start;
495 do {
496 /* for each process */
497 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
499 start:
500 outfmt(
501 out, "%s%*c%s",
502 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
504 if (!(mode & SHOW_PID)) {
505 showpipe(jp, out);
506 break;
508 if (++ps == psend) {
509 outcslow('\n', out);
510 break;
512 } while (1);
514 jp->changed = 0;
516 if (jp->state == JOBDONE) {
517 TRACE(("showjob: freeing job %d\n", jobno(jp)));
518 freejob(jp);
524 jobscmd(int argc, char **argv)
526 int mode, m;
527 struct output *out;
529 mode = 0;
530 while ((m = nextopt("lp")))
531 if (m == 'l')
532 mode = SHOW_PID;
533 else
534 mode = SHOW_PGID;
536 out = out1;
537 argv = argptr;
538 if (*argv)
540 showjob(out, getjob(*argv,0), mode);
541 while (*++argv);
542 else
543 showjobs(out, mode);
545 return 0;
550 * Print a list of jobs. If "change" is nonzero, only print jobs whose
551 * statuses have changed since the last call to showjobs.
554 void
555 showjobs(struct output *out, int mode)
557 struct job *jp;
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.
574 STATIC void
575 freejob(struct job *jp)
577 struct procstat *ps;
578 int i;
580 INTOFF;
581 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
582 if (ps->cmd != nullstr)
583 ckfree(ps->cmd);
585 if (jp->ps != &jp->ps0)
586 ckfree(jp->ps);
587 jp->used = 0;
588 set_curjob(jp, CUR_DELETE);
589 INTON;
595 waitcmd(int argc, char **argv)
597 struct job *job;
598 int retval;
599 struct job *jp;
601 nextopt(nullstr);
602 retval = 0;
604 argv = argptr;
605 if (!*argv) {
606 /* wait for all jobs */
607 for (;;) {
608 jp = curjob;
609 while (1) {
610 if (!jp) {
611 /* no running procs */
612 goto out;
614 if (jp->state == JOBRUNNING)
615 break;
616 jp->waited = 1;
617 jp = jp->prev_job;
619 if (!dowait(DOWAIT_WAITCMD_ALL, 0))
620 goto sigout;
624 retval = 127;
625 do {
626 if (**argv != '%') {
627 pid_t pid = number(*argv);
628 job = curjob;
629 goto start;
630 do {
631 if (job->ps[job->nprocs - 1].pid == pid)
632 break;
633 job = job->prev_job;
634 start:
635 if (!job)
636 goto repeat;
637 } while (1);
638 } else
639 job = getjob(*argv, 0);
640 /* loop until process terminated or stopped */
641 if (!dowait(DOWAIT_WAITCMD, job))
642 goto sigout;
643 job->waited = 1;
644 retval = getstatus(job);
645 repeat:
647 } while (*++argv);
649 out:
650 return retval;
652 sigout:
653 retval = 128 + pending_sig;
654 goto out;
660 * Convert a job name to a job structure.
663 STATIC struct job *
664 getjob(const char *name, int getctl)
666 struct job *jp;
667 struct job *found;
668 const char *err_msg = "No such job: %s";
669 unsigned num;
670 int c;
671 const char *p;
672 char *(*match)(const char *, const char *);
674 jp = curjob;
675 p = name;
676 if (!p)
677 goto currentjob;
679 if (*p != '%')
680 goto err;
682 c = *++p;
683 if (!c)
684 goto currentjob;
686 if (!p[1]) {
687 if (c == '+' || c == '%') {
688 currentjob:
689 err_msg = "No current job";
690 goto check;
691 } else if (c == '-') {
692 if (jp)
693 jp = jp->prev_job;
694 err_msg = "No previous job";
695 check:
696 if (!jp)
697 goto err;
698 goto gotit;
702 if (is_number(p)) {
703 num = atoi(p);
704 if (num > 0 && num <= njobs) {
705 jp = jobtab + num - 1;
706 if (jp->used)
707 goto gotit;
708 goto err;
712 match = prefix;
713 if (*p == '?') {
714 match = strstr;
715 p++;
718 found = 0;
719 while (jp) {
720 if (match(jp->ps[0].cmd, p)) {
721 if (found)
722 goto err;
723 found = jp;
724 err_msg = "%s: ambiguous";
726 jp = jp->prev_job;
729 if (!found)
730 goto err;
731 jp = found;
733 gotit:
734 #if JOBS
735 err_msg = "job %s not created under job control";
736 if (getctl && jp->jobctl == 0)
737 goto err;
738 #endif
739 return jp;
740 err:
741 sh_error(err_msg, name);
747 * Return a new job structure.
748 * Called with interrupts off.
751 struct job *
752 makejob(union node *node, int nprocs)
754 int i;
755 struct job *jp;
757 for (i = njobs, jp = jobtab ; ; jp++) {
758 if (--i < 0) {
759 jp = growjobtab();
760 break;
762 if (jp->used == 0)
763 break;
764 if (jp->state != JOBDONE || !jp->waited)
765 continue;
766 if (jobctl)
767 continue;
768 freejob(jp);
769 break;
771 memset(jp, 0, sizeof(*jp));
772 #if JOBS
773 if (jobctl)
774 jp->jobctl = 1;
775 #endif
776 jp->prev_job = curjob;
777 curjob = jp;
778 jp->used = 1;
779 jp->ps = &jp->ps0;
780 if (nprocs > 1) {
781 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
783 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
784 jobno(jp)));
785 return jp;
788 STATIC struct job *
789 growjobtab(void)
791 size_t len;
792 ptrdiff_t offset;
793 struct job *jp, *jq;
795 len = njobs * sizeof(*jp);
796 jq = jobtab;
797 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
799 offset = (char *)jp - (char *)jq;
800 if (offset) {
801 /* Relocate pointers */
802 size_t l = len;
804 jq = (struct job *)((char *)jq + l);
805 while (l) {
806 l -= sizeof(*jp);
807 jq--;
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))
811 jmove(joff(jp)->ps);
812 if (joff(jp)->prev_job)
813 jmove(joff(jp)->prev_job);
815 if (curjob)
816 jmove(curjob);
817 #undef joff
818 #undef jmove
821 njobs += 4;
822 jobtab = jp;
823 jp = (struct job *)((char *)jp + len);
824 jq = jp + 3;
825 do {
826 jq->used = 0;
827 } while (--jq >= jp);
828 return 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
844 * in a pipeline).
846 * Called with interrupts off.
849 static void forkchild(struct job *jp, union node *n, int mode)
851 int lvforked;
852 int oldlvl;
854 TRACE(("Child shell %d\n", getpid()));
856 oldlvl = shlvl;
857 lvforked = vforked;
859 if (!lvforked) {
860 shlvl++;
862 forkreset();
864 #if JOBS
865 /* do job control only in root shell */
866 jobctl = 0;
867 #endif
870 #if JOBS
871 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
872 pid_t pgrp;
874 if (jp->nprocs == 0)
875 pgrp = getpid();
876 else
877 pgrp = jp->ps[0].pid;
878 /* This can fail because we are doing it in the parent also */
879 (void)setpgid(0, pgrp);
880 if (mode == FORK_FG)
881 xtcsetpgrp(ttyfd, pgrp);
882 setsignal(SIGTSTP);
883 setsignal(SIGTTOU);
884 } else
885 #endif
886 if (mode == FORK_BG) {
887 ignoresig(SIGINT);
888 ignoresig(SIGQUIT);
889 if (jp->nprocs == 0) {
890 close(0);
891 sh_open(_PATH_DEVNULL, O_RDONLY, 0);
894 if (!oldlvl && iflag) {
895 setsignal(SIGINT);
896 setsignal(SIGQUIT);
897 setsignal(SIGTERM);
900 if (lvforked)
901 return;
903 for (jp = curjob; jp; jp = jp->prev_job)
904 freejob(jp);
907 static void forkparent(struct job *jp, union node *n, int mode, pid_t pid)
909 if (pid < 0) {
910 TRACE(("Fork failed, errno=%d", errno));
911 if (jp)
912 freejob(jp);
913 sh_error("Cannot fork");
914 /* NOTREACHED */
917 TRACE(("In parent shell: child = %d\n", pid));
918 if (!jp)
919 return;
920 #if JOBS
921 if (mode != FORK_NOJOB && jp->jobctl) {
922 int pgrp;
924 if (jp->nprocs == 0)
925 pgrp = pid;
926 else
927 pgrp = jp->ps[0].pid;
928 /* This can fail because we are doing it in the child also */
929 (void)setpgid(pid, pgrp);
931 #endif
932 if (mode == FORK_BG) {
933 backgndpid = pid; /* set $! */
934 set_curjob(jp, CUR_RUNNING);
936 if (jp) {
937 struct procstat *ps = &jp->ps[jp->nprocs++];
938 ps->pid = pid;
939 ps->status = -1;
940 ps->cmd = nullstr;
941 if (jobctl && n)
942 ps->cmd = commandtext(n);
947 forkshell(struct job *jp, union node *n, int mode)
949 int pid;
951 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
952 pid = fork();
953 if (pid == 0)
954 forkchild(jp, n, mode);
955 else
956 forkparent(jp, n, mode, pid);
958 return pid;
961 struct job *vforkexec(union node *n, char **argv, const char *path, int idx)
963 struct job *jp;
964 int pid;
966 jp = makejob(n, 1);
968 sigblockall(NULL);
969 vforked++;
971 pid = vfork();
973 if (!pid) {
974 forkchild(jp, n, FORK_FG);
975 sigclearmask();
976 shellexec(argv, path, idx);
977 /* NOTREACHED */
980 vforked = 0;
981 sigclearmask();
982 forkparent(jp, n, FORK_FG, pid);
984 return jp;
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)
1011 int st;
1013 TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
1014 dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
1015 if (!jp)
1016 return exitstatus;
1018 st = getstatus(jp);
1019 #if JOBS
1020 if (jp->jobctl) {
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
1030 if (jp->sigint)
1031 raise(SIGINT);
1033 #endif
1034 if (! JOBS || jp->state == JOBDONE)
1035 freejob(jp);
1036 return st;
1042 * Wait for a process to terminate.
1045 static int waitone(int block, struct job *job)
1047 int pid;
1048 int status;
1049 struct job *jp;
1050 struct job *thisjob = NULL;
1051 int state;
1053 INTOFF;
1054 TRACE(("dowait(%d) called\n", block));
1055 pid = waitproc(block, &status);
1056 TRACE(("wait returns pid %d, status=%d\n", pid, status));
1057 if (pid <= 0)
1058 goto out;
1060 for (jp = curjob; jp; jp = jp->prev_job) {
1061 struct procstat *sp;
1062 struct procstat *spend;
1063 if (jp->state == JOBDONE)
1064 continue;
1065 state = JOBDONE;
1066 spend = jp->ps + jp->nprocs;
1067 sp = jp->ps;
1068 do {
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;
1072 thisjob = jp;
1074 if (sp->status == -1)
1075 state = JOBRUNNING;
1076 #if JOBS
1077 if (state == JOBRUNNING)
1078 continue;
1079 if (WIFSTOPPED(sp->status)) {
1080 jp->stopstatus = sp->status;
1081 state = JOBSTOPPED;
1083 #endif
1084 } while (++sp < spend);
1085 if (thisjob)
1086 goto gotjob;
1088 goto out;
1090 gotjob:
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;
1097 #if JOBS
1098 if (state == JOBSTOPPED) {
1099 set_curjob(thisjob, CUR_STOPPED);
1101 #endif
1105 out:
1106 INTON;
1108 if (thisjob && thisjob == job) {
1109 char s[48 + 1];
1110 int len;
1112 len = sprint_status(s, status, 1);
1113 if (len) {
1114 s[len] = '\n';
1115 s[len + 1] = 0;
1116 outstr(s, out2);
1119 return pid;
1122 static int dowait(int block, struct job *jp)
1124 int gotchld = *(volatile int *)&gotsigchld;
1125 int rpid;
1126 int pid;
1128 if (jp && jp->state != JOBRUNNING)
1129 block = DOWAIT_NONBLOCK;
1131 if (block == DOWAIT_NONBLOCK && !gotchld)
1132 return 1;
1134 rpid = 1;
1136 do {
1137 pid = waitone(block, jp);
1138 rpid &= !!pid;
1140 block &= ~DOWAIT_WAITCMD_ALL;
1141 if (!pid || (jp && jp->state != JOBRUNNING))
1142 block = DOWAIT_NONBLOCK;
1143 } while (pid >= 0);
1145 return rpid;
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
1155 * of a signal.
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.
1164 STATIC int
1165 waitproc(int block, int *status)
1167 sigset_t oldmask;
1168 int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
1169 int err;
1171 #if JOBS
1172 if (jobctl)
1173 flags |= WUNTRACED;
1174 #endif
1176 do {
1177 gotsigchld = 0;
1179 err = wait3(status, flags, NULL);
1180 while (err < 0 && errno == EINTR);
1182 if (err || (err = -!block))
1183 break;
1185 sigblockall(&oldmask);
1187 while (!gotsigchld && !pending_sig)
1188 sigsuspend(&oldmask);
1190 sigclearmask();
1191 } while (gotsigchld);
1193 return err;
1197 * return 1 if there are stopped jobs, otherwise 0
1199 int job_warning;
1201 stoppedjobs(void)
1203 struct job *jp;
1204 int retval;
1206 retval = 0;
1207 if (job_warning)
1208 goto out;
1209 jp = curjob;
1210 if (jp && jp->state == JOBSTOPPED) {
1211 out2str("You have stopped jobs.\n");
1212 job_warning = 2;
1213 retval++;
1216 out:
1217 return retval;
1221 * Return a string identifying a command (to be printed by the
1222 * jobs command).
1225 STATIC char *cmdnextc;
1227 STATIC char *
1228 commandtext(union node *n)
1230 char *name;
1232 STARTSTACKSTR(cmdnextc);
1233 cmdtxt(n);
1234 name = stackblock();
1235 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
1236 return savestr(name);
1240 STATIC void
1241 cmdtxt(union node *n)
1243 union node *np;
1244 struct nodelist *lp;
1245 const char *p;
1246 char s[2];
1248 if (!n)
1249 return;
1250 switch (n->type) {
1251 default:
1252 #if DEBUG
1253 abort();
1254 #endif
1255 case NPIPE:
1256 lp = n->npipe.cmdlist;
1257 for (;;) {
1258 cmdtxt(lp->n);
1259 lp = lp->next;
1260 if (!lp)
1261 break;
1262 cmdputs(" | ");
1264 break;
1265 case NSEMI:
1266 p = "; ";
1267 goto binop;
1268 case NAND:
1269 p = " && ";
1270 goto binop;
1271 case NOR:
1272 p = " || ";
1273 binop:
1274 cmdtxt(n->nbinary.ch1);
1275 cmdputs(p);
1276 n = n->nbinary.ch2;
1277 goto donode;
1278 case NREDIR:
1279 case NBACKGND:
1280 n = n->nredir.n;
1281 goto donode;
1282 case NNOT:
1283 cmdputs("!");
1284 n = n->nnot.com;
1285 donode:
1286 cmdtxt(n);
1287 break;
1288 case NIF:
1289 cmdputs("if ");
1290 cmdtxt(n->nif.test);
1291 cmdputs("; then ");
1292 if (n->nif.elsepart) {
1293 cmdtxt(n->nif.ifpart);
1294 cmdputs("; else ");
1295 n = n->nif.elsepart;
1296 } else {
1297 n = n->nif.ifpart;
1299 p = "; fi";
1300 goto dotail;
1301 case NSUBSHELL:
1302 cmdputs("(");
1303 n = n->nredir.n;
1304 p = ")";
1305 goto dotail;
1306 case NWHILE:
1307 p = "while ";
1308 goto until;
1309 case NUNTIL:
1310 p = "until ";
1311 until:
1312 cmdputs(p);
1313 cmdtxt(n->nbinary.ch1);
1314 n = n->nbinary.ch2;
1315 p = "; done";
1316 dodo:
1317 cmdputs("; do ");
1318 dotail:
1319 cmdtxt(n);
1320 goto dotail2;
1321 case NFOR:
1322 cmdputs("for ");
1323 cmdputs(n->nfor.var);
1324 cmdputs(" in ");
1325 cmdlist(n->nfor.args, 1);
1326 n = n->nfor.body;
1327 p = "; done";
1328 goto dodo;
1329 case NDEFUN:
1330 cmdputs(n->ndefun.text);
1331 p = "() { ... }";
1332 goto dotail2;
1333 case NCMD:
1334 cmdlist(n->ncmd.args, 1);
1335 cmdlist(n->ncmd.redirect, 0);
1336 break;
1337 case NARG:
1338 p = n->narg.text;
1339 dotail2:
1340 cmdputs(p);
1341 break;
1342 case NHERE:
1343 case NXHERE:
1344 p = "<<...";
1345 goto dotail2;
1346 case NCASE:
1347 cmdputs("case ");
1348 cmdputs(n->ncase.expr->narg.text);
1349 cmdputs(" in ");
1350 for (np = n->ncase.cases; np; np = np->nclist.next) {
1351 cmdtxt(np->nclist.pattern);
1352 cmdputs(") ");
1353 cmdtxt(np->nclist.body);
1354 cmdputs(";; ");
1356 p = "esac";
1357 goto dotail2;
1358 case NTO:
1359 p = ">";
1360 goto redir;
1361 case NCLOBBER:
1362 p = ">|";
1363 goto redir;
1364 case NAPPEND:
1365 p = ">>";
1366 goto redir;
1367 case NTOFD:
1368 p = ">&";
1369 goto redir;
1370 case NFROM:
1371 p = "<";
1372 goto redir;
1373 case NFROMFD:
1374 p = "<&";
1375 goto redir;
1376 case NFROMTO:
1377 p = "<>";
1378 redir:
1379 s[0] = n->nfile.fd + '0';
1380 s[1] = '\0';
1381 cmdputs(s);
1382 cmdputs(p);
1383 if (n->type == NTOFD || n->type == NFROMFD) {
1384 s[0] = n->ndup.dupfd + '0';
1385 p = s;
1386 goto dotail2;
1387 } else {
1388 n = n->nfile.fname;
1389 goto donode;
1394 STATIC void
1395 cmdlist(union node *np, int sep)
1397 for (; np; np = np->narg.next) {
1398 if (!sep)
1399 cmdputs(spcstr);
1400 cmdtxt(np);
1401 if (sep && np->narg.next)
1402 cmdputs(spcstr);
1407 STATIC void
1408 cmdputs(const char *s)
1410 const char *p, *str;
1411 char cc[2] = " ";
1412 char *nextc;
1413 signed char c;
1414 int subtype = 0;
1415 int quoted = 0;
1416 static const char vstype[VSTYPE + 1][4] = {
1417 "", "}", "-", "+", "?", "=",
1418 "%", "%%", "#", "##",
1421 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
1422 p = s;
1423 while ((c = *p++) != 0) {
1424 str = 0;
1425 switch (c) {
1426 case CTLESC:
1427 c = *p++;
1428 break;
1429 case CTLVAR:
1430 subtype = *p++;
1431 if ((subtype & VSTYPE) == VSLENGTH)
1432 str = "${#";
1433 else
1434 str = "${";
1435 goto dostr;
1436 case CTLENDVAR:
1437 str = "\"}";
1438 str += !(quoted & 1);
1439 quoted >>= 1;
1440 subtype = 0;
1441 goto dostr;
1442 case CTLBACKQ:
1443 str = "$(...)";
1444 goto dostr;
1445 case CTLARI:
1446 str = "$((";
1447 goto dostr;
1448 case CTLENDARI:
1449 str = "))";
1450 goto dostr;
1451 case CTLQUOTEMARK:
1452 quoted ^= 1;
1453 c = '"';
1454 break;
1455 case '=':
1456 if (subtype == 0)
1457 break;
1458 if ((subtype & VSTYPE) != VSNORMAL)
1459 quoted <<= 1;
1460 str = vstype[subtype & VSTYPE];
1461 if (subtype & VSNUL)
1462 c = ':';
1463 else
1464 goto checkstr;
1465 break;
1466 case '\'':
1467 case '\\':
1468 case '"':
1469 case '$':
1470 /* These can only happen inside quotes */
1471 cc[0] = c;
1472 str = cc;
1473 c = '\\';
1474 break;
1475 default:
1476 break;
1478 USTPUTC(c, nextc);
1479 checkstr:
1480 if (!str)
1481 continue;
1482 dostr:
1483 while ((c = *str++)) {
1484 USTPUTC(c, nextc);
1487 if (quoted & 1) {
1488 USTPUTC('"', nextc);
1490 *nextc = 0;
1491 cmdnextc = nextc;
1495 STATIC void
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);
1505 flushall();
1509 #if JOBS
1510 STATIC void
1511 xtcsetpgrp(int fd, pid_t pgrp)
1513 int err;
1515 sigblockall(NULL);
1516 err = tcsetpgrp(fd, pgrp);
1517 sigclearmask();
1519 if (err)
1520 sh_error("Cannot set tty process group (%s)", strerror(errno));
1522 #endif
1525 STATIC int
1526 getstatus(struct job *job) {
1527 int status;
1528 int retval;
1530 status = job->ps[job->nprocs - 1].status;
1531 retval = WEXITSTATUS(status);
1532 if (!WIFEXITED(status)) {
1533 #if JOBS
1534 retval = WSTOPSIG(status);
1535 if (!WIFSTOPPED(status))
1536 #endif
1538 /* XXX: limits number of signals */
1539 retval = WTERMSIG(status);
1540 #if JOBS
1541 if (retval == SIGINT)
1542 job->sigint = 1;
1543 #endif
1545 retval += 128;
1547 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
1548 jobno(job), job->nprocs, status, retval));
1549 return retval;