bsd-family-tree: Small sync with FreeBSD.
[dragonfly.git] / bin / sh / jobs.c
blob5ee1105b03c611fe68e8778422fe851c04619595
1 /*-
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
6 * Kenneth Almquist.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)jobs.c 8.5 (Berkeley) 5/4/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
41 #include <sys/ioctl.h>
42 #include <sys/param.h>
43 #include <sys/resource.h>
44 #include <sys/time.h>
45 #include <sys/wait.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <paths.h>
49 #include <signal.h>
50 #include <stddef.h>
51 #include <stdlib.h>
52 #include <unistd.h>
54 #include "shell.h"
55 #if JOBS
56 #include <termios.h>
57 #undef CEOF /* syntax.h redefines this */
58 #endif
59 #include "redir.h"
60 #include "exec.h"
61 #include "show.h"
62 #include "main.h"
63 #include "parser.h"
64 #include "nodes.h"
65 #include "jobs.h"
66 #include "options.h"
67 #include "trap.h"
68 #include "syntax.h"
69 #include "input.h"
70 #include "output.h"
71 #include "memalloc.h"
72 #include "error.h"
73 #include "mystring.h"
74 #include "var.h"
75 #include "builtins.h"
78 static struct job *jobtab; /* array of jobs */
79 static int njobs; /* size of array */
80 static pid_t backgndpid = -1; /* pid of last background process */
81 static struct job *bgjob = NULL; /* last background process */
82 #if JOBS
83 static struct job *jobmru; /* most recently used job list */
84 static pid_t initialpgrp; /* pgrp of shell on invocation */
85 #endif
86 static int ttyfd = -1;
88 /* mode flags for dowait */
89 #define DOWAIT_BLOCK 0x1 /* wait until a child exits */
90 #define DOWAIT_SIG 0x2 /* if DOWAIT_BLOCK, abort on signal */
91 #define DOWAIT_SIG_TRAP 0x4 /* if DOWAIT_SIG, abort on trapped signal only */
93 #if JOBS
94 static void restartjob(struct job *);
95 #endif
96 static void freejob(struct job *);
97 static int waitcmdloop(struct job *);
98 static struct job *getjob_nonotfound(const char *);
99 static struct job *getjob(const char *);
100 pid_t killjob(const char *, int);
101 static pid_t dowait(int, struct job *);
102 static void checkzombies(void);
103 static void cmdtxt(union node *);
104 static void cmdputs(const char *);
105 #if JOBS
106 static void setcurjob(struct job *);
107 static void deljob(struct job *);
108 static struct job *getcurjob(struct job *);
109 #endif
110 static void printjobcmd(struct job *);
111 static void showjob(struct job *, int);
115 * Turn job control on and off.
118 static int jobctl;
120 #if JOBS
121 static void
122 jobctl_notty(void)
124 if (ttyfd >= 0) {
125 close(ttyfd);
126 ttyfd = -1;
128 if (!iflag) {
129 setsignal(SIGTSTP);
130 setsignal(SIGTTOU);
131 setsignal(SIGTTIN);
132 jobctl = 1;
133 return;
135 out2fmt_flush("sh: can't access tty; job control turned off\n");
136 mflag = 0;
139 void
140 setjobctl(int on)
142 int i;
144 if (on == jobctl || rootshell == 0)
145 return;
146 if (on) {
147 if (ttyfd != -1)
148 close(ttyfd);
149 if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC_MAYBE)) < 0) {
150 i = 0;
151 while (i <= 2 && !isatty(i))
152 i++;
153 if (i > 2 ||
154 (ttyfd = fcntl(i, F_DUPFD_CLOEXEC_MAYBE, 10)) < 0) {
155 jobctl_notty();
156 return;
159 if (ttyfd < 10) {
161 * Keep our TTY file descriptor out of the way of
162 * the user's redirections.
164 if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC_MAYBE, 10)) < 0) {
165 jobctl_notty();
166 return;
168 close(ttyfd);
169 ttyfd = i;
171 #if !defined(O_CLOEXEC) || !defined(F_DUPFD_CLOEXEC)
172 if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
173 close(ttyfd);
174 ttyfd = -1;
175 goto out;
177 #endif
178 do { /* while we are in the background */
179 initialpgrp = tcgetpgrp(ttyfd);
180 if (initialpgrp < 0) {
181 #if !defined(O_CLOEXEC) || !defined(F_DUPFD_CLOEXEC)
182 out:
183 #endif
184 jobctl_notty();
185 return;
187 if (initialpgrp != getpgrp()) {
188 if (!iflag) {
189 initialpgrp = -1;
190 jobctl_notty();
191 return;
193 kill(0, SIGTTIN);
194 continue;
196 } while (0);
197 setsignal(SIGTSTP);
198 setsignal(SIGTTOU);
199 setsignal(SIGTTIN);
200 setpgid(0, rootpid);
201 tcsetpgrp(ttyfd, rootpid);
202 } else { /* turning job control off */
203 setpgid(0, initialpgrp);
204 if (ttyfd >= 0) {
205 tcsetpgrp(ttyfd, initialpgrp);
206 close(ttyfd);
207 ttyfd = -1;
209 setsignal(SIGTSTP);
210 setsignal(SIGTTOU);
211 setsignal(SIGTTIN);
213 jobctl = on;
215 #endif
218 #if JOBS
220 fgcmd(int argc __unused, char **argv __unused)
222 struct job *jp;
223 pid_t pgrp;
224 int status;
226 nextopt("");
227 jp = getjob(*argptr);
228 if (jp->jobctl == 0)
229 error("job not created under job control");
230 printjobcmd(jp);
231 flushout(&output);
232 pgrp = jp->ps[0].pid;
233 if (ttyfd >= 0)
234 tcsetpgrp(ttyfd, pgrp);
235 restartjob(jp);
236 jp->foreground = 1;
237 INTOFF;
238 status = waitforjob(jp, (int *)NULL);
239 INTON;
240 return status;
245 bgcmd(int argc __unused, char **argv __unused)
247 struct job *jp;
249 nextopt("");
250 do {
251 jp = getjob(*argptr);
252 if (jp->jobctl == 0)
253 error("job not created under job control");
254 if (jp->state == JOBDONE)
255 continue;
256 restartjob(jp);
257 jp->foreground = 0;
258 out1fmt("[%td] ", jp - jobtab + 1);
259 printjobcmd(jp);
260 } while (*argptr != NULL && *++argptr != NULL);
261 return 0;
265 static void
266 restartjob(struct job *jp)
268 struct procstat *ps;
269 int i;
271 if (jp->state == JOBDONE)
272 return;
273 setcurjob(jp);
274 INTOFF;
275 kill(-jp->ps[0].pid, SIGCONT);
276 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
277 if (WIFSTOPPED(ps->status)) {
278 ps->status = -1;
279 jp->state = 0;
282 INTON;
284 #endif
288 jobscmd(int argc __unused, char *argv[] __unused)
290 char *id;
291 int ch, mode;
293 mode = SHOWJOBS_DEFAULT;
294 while ((ch = nextopt("lps")) != '\0') {
295 switch (ch) {
296 case 'l':
297 mode = SHOWJOBS_VERBOSE;
298 break;
299 case 'p':
300 mode = SHOWJOBS_PGIDS;
301 break;
302 case 's':
303 mode = SHOWJOBS_PIDS;
304 break;
308 if (*argptr == NULL)
309 showjobs(0, mode);
310 else
311 while ((id = *argptr++) != NULL)
312 showjob(getjob(id), mode);
314 return (0);
317 static void
318 printjobcmd(struct job *jp)
320 struct procstat *ps;
321 int i;
323 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
324 out1str(ps->cmd);
325 if (i > 0)
326 out1str(" | ");
328 out1c('\n');
331 static void
332 showjob(struct job *jp, int mode)
334 char s[64];
335 char statestr[64];
336 const char *sigstr;
337 struct procstat *ps;
338 struct job *j;
339 int col, curr, i, jobno, prev, procno;
340 char c;
342 procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
343 jobno = jp - jobtab + 1;
344 curr = prev = 0;
345 #if JOBS
346 if ((j = getcurjob(NULL)) != NULL) {
347 curr = j - jobtab + 1;
348 if ((j = getcurjob(j)) != NULL)
349 prev = j - jobtab + 1;
351 #endif
352 ps = jp->ps + jp->nprocs - 1;
353 if (jp->state == 0) {
354 strcpy(statestr, "Running");
355 #if JOBS
356 } else if (jp->state == JOBSTOPPED) {
357 while (!WIFSTOPPED(ps->status) && ps > jp->ps)
358 ps--;
359 if (WIFSTOPPED(ps->status))
360 i = WSTOPSIG(ps->status);
361 else
362 i = -1;
363 sigstr = strsignal(i);
364 if (sigstr != NULL)
365 strcpy(statestr, sigstr);
366 else
367 strcpy(statestr, "Suspended");
368 #endif
369 } else if (WIFEXITED(ps->status)) {
370 if (WEXITSTATUS(ps->status) == 0)
371 strcpy(statestr, "Done");
372 else
373 fmtstr(statestr, 64, "Done(%d)",
374 WEXITSTATUS(ps->status));
375 } else {
376 i = WTERMSIG(ps->status);
377 sigstr = strsignal(i);
378 if (sigstr != NULL)
379 strcpy(statestr, sigstr);
380 else
381 strcpy(statestr, "Unknown signal");
382 if (WCOREDUMP(ps->status))
383 strcat(statestr, " (core dumped)");
386 for (ps = jp->ps ; procno > 0 ; ps++, procno--) { /* for each process */
387 if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
388 out1fmt("%d\n", (int)ps->pid);
389 continue;
391 if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
392 continue;
393 if (jobno == curr && ps == jp->ps)
394 c = '+';
395 else if (jobno == prev && ps == jp->ps)
396 c = '-';
397 else
398 c = ' ';
399 if (ps == jp->ps)
400 fmtstr(s, 64, "[%d] %c ", jobno, c);
401 else
402 fmtstr(s, 64, " %c ", c);
403 out1str(s);
404 col = strlen(s);
405 if (mode == SHOWJOBS_VERBOSE) {
406 fmtstr(s, 64, "%d ", (int)ps->pid);
407 out1str(s);
408 col += strlen(s);
410 if (ps == jp->ps) {
411 out1str(statestr);
412 col += strlen(statestr);
414 do {
415 out1c(' ');
416 col++;
417 } while (col < 30);
418 if (mode == SHOWJOBS_VERBOSE) {
419 out1str(ps->cmd);
420 out1c('\n');
421 } else
422 printjobcmd(jp);
427 * Print a list of jobs. If "change" is nonzero, only print jobs whose
428 * statuses have changed since the last call to showjobs.
430 * If the shell is interrupted in the process of creating a job, the
431 * result may be a job structure containing zero processes. Such structures
432 * will be freed here.
435 void
436 showjobs(int change, int mode)
438 int jobno;
439 struct job *jp;
441 TRACE(("showjobs(%d) called\n", change));
442 checkzombies();
443 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
444 if (! jp->used)
445 continue;
446 if (jp->nprocs == 0) {
447 freejob(jp);
448 continue;
450 if (change && ! jp->changed)
451 continue;
452 showjob(jp, mode);
453 if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
454 jp->changed = 0;
455 /* Hack: discard jobs for which $! has not been
456 * referenced in interactive mode when they terminate.
458 if (jp->state == JOBDONE && !jp->remembered &&
459 (iflag || jp != bgjob)) {
460 freejob(jp);
468 * Mark a job structure as unused.
471 static void
472 freejob(struct job *jp)
474 struct procstat *ps;
475 int i;
477 INTOFF;
478 if (bgjob == jp)
479 bgjob = NULL;
480 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
481 if (ps->cmd != nullstr)
482 ckfree(ps->cmd);
484 if (jp->ps != &jp->ps0)
485 ckfree(jp->ps);
486 jp->used = 0;
487 #if JOBS
488 deljob(jp);
489 #endif
490 INTON;
496 waitcmd(int argc __unused, char **argv __unused)
498 struct job *job;
499 int retval;
501 nextopt("");
502 if (*argptr == NULL)
503 return (waitcmdloop(NULL));
505 do {
506 job = getjob_nonotfound(*argptr);
507 if (job == NULL)
508 retval = 127;
509 else
510 retval = waitcmdloop(job);
511 argptr++;
512 } while (*argptr != NULL);
514 return (retval);
517 static int
518 waitcmdloop(struct job *job)
520 int status, retval, sig;
521 struct job *jp;
524 * Loop until a process is terminated or stopped, or a SIGINT is
525 * received.
528 do {
529 if (job != NULL) {
530 if (job->state == JOBDONE) {
531 status = job->ps[job->nprocs - 1].status;
532 if (WIFEXITED(status))
533 retval = WEXITSTATUS(status);
534 else
535 retval = WTERMSIG(status) + 128;
536 if (! iflag || ! job->changed)
537 freejob(job);
538 else {
539 job->remembered = 0;
540 if (job == bgjob)
541 bgjob = NULL;
543 return retval;
545 } else {
546 for (jp = jobtab ; jp < jobtab + njobs; jp++)
547 if (jp->used && jp->state == JOBDONE) {
548 if (! iflag || ! jp->changed)
549 freejob(jp);
550 else {
551 jp->remembered = 0;
552 if (jp == bgjob)
553 bgjob = NULL;
556 for (jp = jobtab ; ; jp++) {
557 if (jp >= jobtab + njobs) { /* no running procs */
558 return 0;
560 if (jp->used && jp->state == 0)
561 break;
564 } while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, (struct job *)NULL) != -1);
566 sig = pendingsig_waitcmd;
567 pendingsig_waitcmd = 0;
568 return sig + 128;
574 jobidcmd(int argc __unused, char **argv __unused)
576 struct job *jp;
577 int i;
579 nextopt("");
580 jp = getjob(*argptr);
581 for (i = 0 ; i < jp->nprocs ; ) {
582 out1fmt("%d", (int)jp->ps[i].pid);
583 out1c(++i < jp->nprocs? ' ' : '\n');
585 return 0;
591 * Convert a job name to a job structure.
594 static struct job *
595 getjob_nonotfound(const char *name)
597 int jobno;
598 struct job *found, *jp;
599 size_t namelen;
600 pid_t pid;
601 int i;
603 if (name == NULL) {
604 #if JOBS
605 name = "%+";
606 #else
607 error("No current job");
608 #endif
610 if (name[0] == '%') {
611 if (is_digit(name[1])) {
612 jobno = number(name + 1);
613 if (jobno > 0 && jobno <= njobs
614 && jobtab[jobno - 1].used != 0)
615 return &jobtab[jobno - 1];
616 #if JOBS
617 } else if ((name[1] == '%' || name[1] == '+') &&
618 name[2] == '\0') {
619 if ((jp = getcurjob(NULL)) == NULL)
620 error("No current job");
621 return (jp);
622 } else if (name[1] == '-' && name[2] == '\0') {
623 if ((jp = getcurjob(NULL)) == NULL ||
624 (jp = getcurjob(jp)) == NULL)
625 error("No previous job");
626 return (jp);
627 #endif
628 } else if (name[1] == '?') {
629 found = NULL;
630 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
631 if (jp->used && jp->nprocs > 0
632 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
633 if (found)
634 error("%s: ambiguous", name);
635 found = jp;
638 if (found != NULL)
639 return (found);
640 } else {
641 namelen = strlen(name);
642 found = NULL;
643 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
644 if (jp->used && jp->nprocs > 0
645 && strncmp(jp->ps[0].cmd, name + 1,
646 namelen - 1) == 0) {
647 if (found)
648 error("%s: ambiguous", name);
649 found = jp;
652 if (found)
653 return found;
655 } else if (is_number(name)) {
656 pid = (pid_t)number(name);
657 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
658 if (jp->used && jp->nprocs > 0
659 && jp->ps[jp->nprocs - 1].pid == pid)
660 return jp;
663 return NULL;
667 static struct job *
668 getjob(const char *name)
670 struct job *jp;
672 jp = getjob_nonotfound(name);
673 if (jp == NULL)
674 error("No such job: %s", name);
675 return (jp);
680 killjob(const char *name, int sig)
682 struct job *jp;
683 int i, ret;
685 jp = getjob(name);
686 if (jp->state == JOBDONE)
687 return 0;
688 if (jp->jobctl)
689 return kill(-jp->ps[0].pid, sig);
690 ret = -1;
691 errno = ESRCH;
692 for (i = 0; i < jp->nprocs; i++)
693 if (jp->ps[i].status == -1 || WIFSTOPPED(jp->ps[i].status)) {
694 if (kill(jp->ps[i].pid, sig) == 0)
695 ret = 0;
696 } else
697 ret = 0;
698 return ret;
702 * Return a new job structure,
705 struct job *
706 makejob(union node *node __unused, int nprocs)
708 int i;
709 struct job *jp;
711 for (i = njobs, jp = jobtab ; ; jp++) {
712 if (--i < 0) {
713 INTOFF;
714 if (njobs == 0) {
715 jobtab = ckmalloc(4 * sizeof jobtab[0]);
716 #if JOBS
717 jobmru = NULL;
718 #endif
719 } else {
720 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
721 memcpy(jp, jobtab, njobs * sizeof jp[0]);
722 #if JOBS
723 /* Relocate `next' pointers and list head */
724 if (jobmru != NULL)
725 jobmru = &jp[jobmru - jobtab];
726 for (i = 0; i < njobs; i++)
727 if (jp[i].next != NULL)
728 jp[i].next = &jp[jp[i].next -
729 jobtab];
730 #endif
731 if (bgjob != NULL)
732 bgjob = &jp[bgjob - jobtab];
733 /* Relocate `ps' pointers */
734 for (i = 0; i < njobs; i++)
735 if (jp[i].ps == &jobtab[i].ps0)
736 jp[i].ps = &jp[i].ps0;
737 ckfree(jobtab);
738 jobtab = jp;
740 jp = jobtab + njobs;
741 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
743 INTON;
744 break;
746 if (jp->used == 0)
747 break;
749 INTOFF;
750 jp->state = 0;
751 jp->used = 1;
752 jp->changed = 0;
753 jp->nprocs = 0;
754 jp->foreground = 0;
755 jp->remembered = 0;
756 #if JOBS
757 jp->jobctl = jobctl;
758 jp->next = NULL;
759 #endif
760 if (nprocs > 1) {
761 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
762 } else {
763 jp->ps = &jp->ps0;
765 INTON;
766 TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
767 jp - jobtab + 1));
768 return jp;
771 #if JOBS
772 static void
773 setcurjob(struct job *cj)
775 struct job *jp, *prev;
777 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
778 if (jp == cj) {
779 if (prev != NULL)
780 prev->next = jp->next;
781 else
782 jobmru = jp->next;
783 jp->next = jobmru;
784 jobmru = cj;
785 return;
788 cj->next = jobmru;
789 jobmru = cj;
792 static void
793 deljob(struct job *j)
795 struct job *jp, *prev;
797 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
798 if (jp == j) {
799 if (prev != NULL)
800 prev->next = jp->next;
801 else
802 jobmru = jp->next;
803 return;
809 * Return the most recently used job that isn't `nj', and preferably one
810 * that is stopped.
812 static struct job *
813 getcurjob(struct job *nj)
815 struct job *jp;
817 /* Try to find a stopped one.. */
818 for (jp = jobmru; jp != NULL; jp = jp->next)
819 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
820 return (jp);
821 /* Otherwise the most recently used job that isn't `nj' */
822 for (jp = jobmru; jp != NULL; jp = jp->next)
823 if (jp->used && jp != nj)
824 return (jp);
826 return (NULL);
829 #endif
832 * Fork of a subshell. If we are doing job control, give the subshell its
833 * own process group. Jp is a job structure that the job is to be added to.
834 * N is the command that will be evaluated by the child. Both jp and n may
835 * be NULL. The mode parameter can be one of the following:
836 * FORK_FG - Fork off a foreground process.
837 * FORK_BG - Fork off a background process.
838 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
839 * process group even if job control is on.
841 * When job control is turned off, background processes have their standard
842 * input redirected to /dev/null (except for the second and later processes
843 * in a pipeline).
846 pid_t
847 forkshell(struct job *jp, union node *n, int mode)
849 pid_t pid;
850 pid_t pgrp;
852 TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
853 mode));
854 INTOFF;
855 if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
856 checkzombies();
857 flushall();
858 pid = fork();
859 if (pid == -1) {
860 TRACE(("Fork failed, errno=%d\n", errno));
861 INTON;
862 error("Cannot fork: %s", strerror(errno));
864 if (pid == 0) {
865 struct job *p;
866 int wasroot;
867 int i;
869 TRACE(("Child shell %d\n", (int)getpid()));
870 wasroot = rootshell;
871 rootshell = 0;
872 handler = &main_handler;
873 closescript();
874 INTON;
875 forcelocal = 0;
876 clear_traps();
877 #if JOBS
878 jobctl = 0; /* do job control only in root shell */
879 if (wasroot && mode != FORK_NOJOB && mflag) {
880 if (jp == NULL || jp->nprocs == 0)
881 pgrp = getpid();
882 else
883 pgrp = jp->ps[0].pid;
884 if (setpgid(0, pgrp) == 0 && mode == FORK_FG &&
885 ttyfd >= 0) {
886 /*** this causes superfluous TIOCSPGRPS ***/
887 if (tcsetpgrp(ttyfd, pgrp) < 0)
888 error("tcsetpgrp failed, errno=%d", errno);
890 setsignal(SIGTSTP);
891 setsignal(SIGTTOU);
892 } else if (mode == FORK_BG) {
893 ignoresig(SIGINT);
894 ignoresig(SIGQUIT);
895 if ((jp == NULL || jp->nprocs == 0) &&
896 ! fd0_redirected_p ()) {
897 close(0);
898 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
899 error("cannot open %s: %s",
900 _PATH_DEVNULL, strerror(errno));
903 #else
904 if (mode == FORK_BG) {
905 ignoresig(SIGINT);
906 ignoresig(SIGQUIT);
907 if ((jp == NULL || jp->nprocs == 0) &&
908 ! fd0_redirected_p ()) {
909 close(0);
910 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
911 error("cannot open %s: %s",
912 _PATH_DEVNULL, strerror(errno));
915 #endif
916 INTOFF;
917 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
918 if (p->used)
919 freejob(p);
920 INTON;
921 if (wasroot && iflag) {
922 setsignal(SIGINT);
923 setsignal(SIGQUIT);
924 setsignal(SIGTERM);
926 return pid;
928 if (rootshell && mode != FORK_NOJOB && mflag) {
929 if (jp == NULL || jp->nprocs == 0)
930 pgrp = pid;
931 else
932 pgrp = jp->ps[0].pid;
933 setpgid(pid, pgrp);
935 if (mode == FORK_BG) {
936 if (bgjob != NULL && bgjob->state == JOBDONE &&
937 !bgjob->remembered && !iflag)
938 freejob(bgjob);
939 backgndpid = pid; /* set $! */
940 bgjob = jp;
942 if (jp) {
943 struct procstat *ps = &jp->ps[jp->nprocs++];
944 ps->pid = pid;
945 ps->status = -1;
946 ps->cmd = nullstr;
947 if (iflag && rootshell && n)
948 ps->cmd = commandtext(n);
949 jp->foreground = mode == FORK_FG;
950 #if JOBS
951 setcurjob(jp);
952 #endif
954 INTON;
955 TRACE(("In parent shell: child = %d\n", (int)pid));
956 return pid;
960 pid_t
961 vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
963 pid_t pid;
964 struct jmploc jmploc;
965 struct jmploc *savehandler;
967 TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
968 (void *)pip));
969 INTOFF;
970 flushall();
971 savehandler = handler;
972 pid = vfork();
973 if (pid == -1) {
974 TRACE(("Vfork failed, errno=%d\n", errno));
975 INTON;
976 error("Cannot fork: %s", strerror(errno));
978 if (pid == 0) {
979 TRACE(("Child shell %d\n", (int)getpid()));
980 if (setjmp(jmploc.loc))
981 _exit(exception == EXEXEC ? exerrno : 2);
982 if (pip != NULL) {
983 close(pip[0]);
984 if (pip[1] != 1) {
985 dup2(pip[1], 1);
986 close(pip[1]);
989 handler = &jmploc;
990 shellexec(argv, envp, path, idx);
992 handler = savehandler;
993 if (jp) {
994 struct procstat *ps = &jp->ps[jp->nprocs++];
995 ps->pid = pid;
996 ps->status = -1;
997 ps->cmd = nullstr;
998 jp->foreground = 1;
999 #if JOBS
1000 setcurjob(jp);
1001 #endif
1003 INTON;
1004 TRACE(("In parent shell: child = %d\n", (int)pid));
1005 return pid;
1010 * Wait for job to finish.
1012 * Under job control we have the problem that while a child process is
1013 * running interrupts generated by the user are sent to the child but not
1014 * to the shell. This means that an infinite loop started by an inter-
1015 * active user may be hard to kill. With job control turned off, an
1016 * interactive user may place an interactive program inside a loop. If
1017 * the interactive program catches interrupts, the user doesn't want
1018 * these interrupts to also abort the loop. The approach we take here
1019 * is to have the shell ignore interrupt signals while waiting for a
1020 * foreground process to terminate, and then send itself an interrupt
1021 * signal if the child process was terminated by an interrupt signal.
1022 * Unfortunately, some programs want to do a bit of cleanup and then
1023 * exit on interrupt; unless these processes terminate themselves by
1024 * sending a signal to themselves (instead of calling exit) they will
1025 * confuse this approach.
1029 waitforjob(struct job *jp, int *origstatus)
1031 #if JOBS
1032 int propagate_int = jp->jobctl && jp->foreground;
1033 #endif
1034 int status;
1035 int st;
1037 INTOFF;
1038 TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
1039 while (jp->state == 0)
1040 if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
1041 DOWAIT_SIG_TRAP : 0), jp) == -1)
1042 dotrap();
1043 #if JOBS
1044 if (jp->jobctl) {
1045 if (ttyfd >= 0 && tcsetpgrp(ttyfd, rootpid) < 0)
1046 error("tcsetpgrp failed, errno=%d\n", errno);
1048 if (jp->state == JOBSTOPPED)
1049 setcurjob(jp);
1050 #endif
1051 status = jp->ps[jp->nprocs - 1].status;
1052 if (origstatus != NULL)
1053 *origstatus = status;
1054 /* convert to 8 bits */
1055 if (WIFEXITED(status))
1056 st = WEXITSTATUS(status);
1057 #if JOBS
1058 else if (WIFSTOPPED(status))
1059 st = WSTOPSIG(status) + 128;
1060 #endif
1061 else
1062 st = WTERMSIG(status) + 128;
1063 if (! JOBS || jp->state == JOBDONE)
1064 freejob(jp);
1065 if (int_pending()) {
1066 if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
1067 CLEAR_PENDING_INT;
1069 #if JOBS
1070 else if (rootshell && propagate_int &&
1071 WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1072 kill(getpid(), SIGINT);
1073 #endif
1074 INTON;
1075 return st;
1079 static void
1080 dummy_handler(int sig __unused)
1085 * Wait for a process to terminate.
1088 static pid_t
1089 dowait(int mode, struct job *job)
1091 struct sigaction sa, osa;
1092 sigset_t mask, omask;
1093 pid_t pid;
1094 int status;
1095 struct procstat *sp;
1096 struct job *jp;
1097 struct job *thisjob;
1098 const char *sigstr;
1099 int done;
1100 int stopped;
1101 int sig;
1102 int coredump;
1103 int wflags;
1104 int restore_sigchld;
1106 TRACE(("dowait(%d, %p) called\n", mode, job));
1107 restore_sigchld = 0;
1108 if ((mode & DOWAIT_SIG) != 0) {
1109 sigfillset(&mask);
1110 sigprocmask(SIG_BLOCK, &mask, &omask);
1111 INTOFF;
1112 if (!issigchldtrapped()) {
1113 restore_sigchld = 1;
1114 sa.sa_handler = dummy_handler;
1115 sa.sa_flags = 0;
1116 sigemptyset(&sa.sa_mask);
1117 sigaction(SIGCHLD, &sa, &osa);
1120 do {
1121 #if JOBS
1122 if (iflag)
1123 wflags = WUNTRACED | WCONTINUED;
1124 else
1125 #endif
1126 wflags = 0;
1127 if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1128 wflags |= WNOHANG;
1129 pid = wait3(&status, wflags, (struct rusage *)NULL);
1130 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1131 if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1132 pid = -1;
1133 if (((mode & DOWAIT_SIG_TRAP) != 0 ?
1134 pendingsig : pendingsig_waitcmd) != 0) {
1135 errno = EINTR;
1136 break;
1138 sigsuspend(&omask);
1139 if (int_pending())
1140 break;
1142 } while (pid == -1 && errno == EINTR);
1143 if (pid == -1 && errno == ECHILD && job != NULL)
1144 job->state = JOBDONE;
1145 if ((mode & DOWAIT_SIG) != 0) {
1146 if (restore_sigchld)
1147 sigaction(SIGCHLD, &osa, NULL);
1148 sigprocmask(SIG_SETMASK, &omask, NULL);
1149 INTON;
1151 if (pid <= 0)
1152 return pid;
1153 INTOFF;
1154 thisjob = NULL;
1155 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1156 if (jp->used && jp->nprocs > 0) {
1157 done = 1;
1158 stopped = 1;
1159 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1160 if (sp->pid == -1)
1161 continue;
1162 if (sp->pid == pid && (sp->status == -1 ||
1163 WIFSTOPPED(sp->status))) {
1164 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1165 (int)pid, sp->status,
1166 status));
1167 if (WIFCONTINUED(status)) {
1168 sp->status = -1;
1169 jp->state = 0;
1170 } else
1171 sp->status = status;
1172 thisjob = jp;
1174 if (sp->status == -1)
1175 stopped = 0;
1176 else if (WIFSTOPPED(sp->status))
1177 done = 0;
1179 if (stopped) { /* stopped or done */
1180 int state = done? JOBDONE : JOBSTOPPED;
1181 if (jp->state != state) {
1182 TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1183 jp->state = state;
1184 if (jp != job) {
1185 if (done && !jp->remembered &&
1186 !iflag && jp != bgjob)
1187 freejob(jp);
1188 #if JOBS
1189 else if (done)
1190 deljob(jp);
1191 #endif
1197 INTON;
1198 if (!thisjob || thisjob->state == 0)
1200 else if ((!rootshell || !iflag || thisjob == job) &&
1201 thisjob->foreground && thisjob->state != JOBSTOPPED) {
1202 sig = 0;
1203 coredump = 0;
1204 for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1205 if (WIFSIGNALED(sp->status)) {
1206 sig = WTERMSIG(sp->status);
1207 coredump = WCOREDUMP(sp->status);
1209 if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1210 sigstr = strsignal(sig);
1211 if (sigstr != NULL)
1212 out2str(sigstr);
1213 else
1214 out2str("Unknown signal");
1215 if (coredump)
1216 out2str(" (core dumped)");
1217 out2c('\n');
1218 flushout(out2);
1220 } else {
1221 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1222 thisjob->changed = 1;
1224 return pid;
1230 * return 1 if there are stopped jobs, otherwise 0
1232 int job_warning = 0;
1234 stoppedjobs(void)
1236 int jobno;
1237 struct job *jp;
1239 if (job_warning)
1240 return (0);
1241 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1242 if (jp->used == 0)
1243 continue;
1244 if (jp->state == JOBSTOPPED) {
1245 out2fmt_flush("You have stopped jobs.\n");
1246 job_warning = 2;
1247 return (1);
1251 return (0);
1255 static void
1256 checkzombies(void)
1258 while (njobs > 0 && dowait(0, NULL) > 0)
1264 backgndpidset(void)
1266 return backgndpid != -1;
1270 pid_t
1271 backgndpidval(void)
1273 if (bgjob != NULL && !forcelocal)
1274 bgjob->remembered = 1;
1275 return backgndpid;
1279 * Return a string identifying a command (to be printed by the
1280 * jobs command.
1283 static char *cmdnextc;
1284 static int cmdnleft;
1285 #define MAXCMDTEXT 200
1287 char *
1288 commandtext(union node *n)
1290 char *name;
1292 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1293 cmdnleft = MAXCMDTEXT - 4;
1294 cmdtxt(n);
1295 *cmdnextc = '\0';
1296 return name;
1300 static void
1301 cmdtxtdogroup(union node *n)
1303 cmdputs("; do ");
1304 cmdtxt(n);
1305 cmdputs("; done");
1309 static void
1310 cmdtxtredir(union node *n, const char *op, int deffd)
1312 char s[2];
1314 if (n->nfile.fd != deffd) {
1315 s[0] = n->nfile.fd + '0';
1316 s[1] = '\0';
1317 cmdputs(s);
1319 cmdputs(op);
1320 if (n->type == NTOFD || n->type == NFROMFD) {
1321 if (n->ndup.dupfd >= 0)
1322 s[0] = n->ndup.dupfd + '0';
1323 else
1324 s[0] = '-';
1325 s[1] = '\0';
1326 cmdputs(s);
1327 } else {
1328 cmdtxt(n->nfile.fname);
1333 static void
1334 cmdtxt(union node *n)
1336 union node *np;
1337 struct nodelist *lp;
1339 if (n == NULL)
1340 return;
1341 switch (n->type) {
1342 case NSEMI:
1343 cmdtxt(n->nbinary.ch1);
1344 cmdputs("; ");
1345 cmdtxt(n->nbinary.ch2);
1346 break;
1347 case NAND:
1348 cmdtxt(n->nbinary.ch1);
1349 cmdputs(" && ");
1350 cmdtxt(n->nbinary.ch2);
1351 break;
1352 case NOR:
1353 cmdtxt(n->nbinary.ch1);
1354 cmdputs(" || ");
1355 cmdtxt(n->nbinary.ch2);
1356 break;
1357 case NPIPE:
1358 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1359 cmdtxt(lp->n);
1360 if (lp->next)
1361 cmdputs(" | ");
1363 break;
1364 case NSUBSHELL:
1365 cmdputs("(");
1366 cmdtxt(n->nredir.n);
1367 cmdputs(")");
1368 break;
1369 case NREDIR:
1370 case NBACKGND:
1371 cmdtxt(n->nredir.n);
1372 break;
1373 case NIF:
1374 cmdputs("if ");
1375 cmdtxt(n->nif.test);
1376 cmdputs("; then ");
1377 cmdtxt(n->nif.ifpart);
1378 cmdputs("...");
1379 break;
1380 case NWHILE:
1381 cmdputs("while ");
1382 cmdtxt(n->nbinary.ch1);
1383 cmdtxtdogroup(n->nbinary.ch2);
1384 break;
1385 case NUNTIL:
1386 cmdputs("until ");
1387 cmdtxt(n->nbinary.ch1);
1388 cmdtxtdogroup(n->nbinary.ch2);
1389 break;
1390 case NFOR:
1391 cmdputs("for ");
1392 cmdputs(n->nfor.var);
1393 cmdputs(" in ...");
1394 break;
1395 case NCASE:
1396 cmdputs("case ");
1397 cmdputs(n->ncase.expr->narg.text);
1398 cmdputs(" in ...");
1399 break;
1400 case NDEFUN:
1401 cmdputs(n->narg.text);
1402 cmdputs("() ...");
1403 break;
1404 case NNOT:
1405 cmdputs("! ");
1406 cmdtxt(n->nnot.com);
1407 break;
1408 case NCMD:
1409 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1410 cmdtxt(np);
1411 if (np->narg.next)
1412 cmdputs(" ");
1414 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1415 cmdputs(" ");
1416 cmdtxt(np);
1418 break;
1419 case NARG:
1420 cmdputs(n->narg.text);
1421 break;
1422 case NTO:
1423 cmdtxtredir(n, ">", 1);
1424 break;
1425 case NAPPEND:
1426 cmdtxtredir(n, ">>", 1);
1427 break;
1428 case NTOFD:
1429 cmdtxtredir(n, ">&", 1);
1430 break;
1431 case NCLOBBER:
1432 cmdtxtredir(n, ">|", 1);
1433 break;
1434 case NFROM:
1435 cmdtxtredir(n, "<", 0);
1436 break;
1437 case NFROMTO:
1438 cmdtxtredir(n, "<>", 0);
1439 break;
1440 case NFROMFD:
1441 cmdtxtredir(n, "<&", 0);
1442 break;
1443 case NHERE:
1444 case NXHERE:
1445 cmdputs("<<...");
1446 break;
1447 default:
1448 cmdputs("???");
1449 break;
1455 static void
1456 cmdputs(const char *s)
1458 const char *p;
1459 char *q;
1460 char c;
1461 int subtype = 0;
1463 if (cmdnleft <= 0)
1464 return;
1465 p = s;
1466 q = cmdnextc;
1467 while ((c = *p++) != '\0') {
1468 if (c == CTLESC)
1469 *q++ = *p++;
1470 else if (c == CTLVAR) {
1471 *q++ = '$';
1472 if (--cmdnleft > 0)
1473 *q++ = '{';
1474 subtype = *p++;
1475 if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1476 *q++ = '#';
1477 } else if (c == '=' && subtype != 0) {
1478 *q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1479 if (*q)
1480 q++;
1481 else
1482 cmdnleft++;
1483 if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1484 (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1485 --cmdnleft > 0)
1486 *q = q[-1], q++;
1487 subtype = 0;
1488 } else if (c == CTLENDVAR) {
1489 *q++ = '}';
1490 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1491 cmdnleft -= 5;
1492 if (cmdnleft > 0) {
1493 *q++ = '$';
1494 *q++ = '(';
1495 *q++ = '.';
1496 *q++ = '.';
1497 *q++ = '.';
1498 *q++ = ')';
1500 } else if (c == CTLARI) {
1501 cmdnleft -= 2;
1502 if (cmdnleft > 0) {
1503 *q++ = '$';
1504 *q++ = '(';
1505 *q++ = '(';
1507 p++;
1508 } else if (c == CTLENDARI) {
1509 if (--cmdnleft > 0) {
1510 *q++ = ')';
1511 *q++ = ')';
1513 } else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1514 cmdnleft++; /* ignore */
1515 else
1516 *q++ = c;
1517 if (--cmdnleft <= 0) {
1518 *q++ = '.';
1519 *q++ = '.';
1520 *q++ = '.';
1521 break;
1524 cmdnextc = q;