iso9660fs: initialize buffer cache
[minix.git] / commands / ash / jobs.c
blob2f5e7f48d3009283e276ef6081dea53d70dee559
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 * 4. 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>
40 __FBSDID("$FreeBSD: src/bin/sh/jobs.c,v 1.67 2004/04/06 20:06:51 markm Exp $");
43 #include "shell.h"
45 #include <sys/types.h>
46 #include <fcntl.h>
47 #include <signal.h>
48 #include <errno.h>
49 #ifndef NO_PATHS_H
50 #include <paths.h>
51 #endif
52 #include <unistd.h>
53 #include <stdlib.h>
54 #ifdef POSIX
55 #include <signal.h>
56 #include <sys/wait.h>
57 #elif defined(BSD)
58 #include <sys/param.h>
59 #include <sys/wait.h>
60 #include <sys/time.h>
61 #include <sys/resource.h>
62 #endif
63 #include <sys/ioctl.h>
65 #if JOBS
66 #include <termios.h>
67 #undef CEOF /* syntax.h redefines this */
68 #endif
69 #include "redir.h"
70 #include "show.h"
71 #include "main.h"
72 #include "parser.h"
73 #include "nodes.h"
74 #include "jobs.h"
75 #include "options.h"
76 #include "trap.h"
77 #include "syntax.h"
78 #include "input.h"
79 #include "output.h"
80 #include "memalloc.h"
81 #include "error.h"
82 #include "mystring.h"
83 #include "builtins.h"
85 #ifdef __minix
86 /* #define NO_KILLPG */
87 #endif
89 #ifndef _PATH_TTY
90 #define _PATH_TTY "/dev/tty"
91 #endif
92 #ifndef _PATH_DEVNULL
93 #define _PATH_DEVNULL "/dev/null"
94 #endif
96 STATIC struct job *jobtab; /* array of jobs */
97 STATIC int njobs; /* size of array */
98 MKINIT pid_t backgndpid = -1; /* pid of last background process */
99 #if JOBS
100 STATIC struct job *jobmru; /* most recently used job list */
101 STATIC pid_t initialpgrp; /* pgrp of shell on invocation */
102 #endif
103 int in_waitcmd = 0; /* are we in waitcmd()? */
104 int in_dowait = 0; /* are we in dowait()? */
105 volatile sig_atomic_t breakwaitcmd = 0; /* should wait be terminated? */
106 static int ttyfd = -1;
108 #ifndef WCOREDUMP
109 #define WCOREDUMP(s) ((s) & 0x80)
110 #endif
112 #if JOBS
113 STATIC void restartjob(struct job *);
114 #endif
115 STATIC void freejob(struct job *);
116 STATIC struct job *getjob(char *);
117 STATIC pid_t dowait(int, struct job *);
118 STATIC pid_t waitproc(int, int *);
119 STATIC void cmdtxt(union node *);
120 STATIC void cmdputs(char *);
121 #if JOBS
122 STATIC void setcurjob(struct job *);
123 STATIC void deljob(struct job *);
124 STATIC struct job *getcurjob(struct job *);
125 #endif
126 STATIC void showjob(struct job *, pid_t, int, int);
128 #ifdef NO_KILLPG
129 static int killpg(pid_t,int);
130 #endif
133 * Turn job control on and off.
136 MKINIT int jobctl;
138 #if JOBS
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)) < 0) {
150 i = 0;
151 while (i <= 2 && !isatty(i))
152 i++;
153 if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
154 goto out;
156 if (ttyfd < 10) {
158 * Keep our TTY file descriptor out of the way of
159 * the user's redirections.
161 if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
162 close(ttyfd);
163 ttyfd = -1;
164 goto out;
166 close(ttyfd);
167 ttyfd = i;
169 if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
170 close(ttyfd);
171 ttyfd = -1;
172 goto out;
174 do { /* while we are in the background */
175 initialpgrp = tcgetpgrp(ttyfd);
176 if (initialpgrp < 0) {
177 out: out2str("sh: can't access tty; job control turned off\n");
178 mflag = 0;
179 return;
181 if (initialpgrp == -1)
182 initialpgrp = getpgrp();
183 else if (initialpgrp != getpgrp()) {
184 killpg(0, SIGTTIN);
185 continue;
187 } while (0);
188 setsignal(SIGTSTP);
189 setsignal(SIGTTOU);
190 setsignal(SIGTTIN);
191 setpgid(0, rootpid);
192 tcsetpgrp(ttyfd, rootpid);
193 } else { /* turning job control off */
194 setpgid(0, initialpgrp);
195 tcsetpgrp(ttyfd, initialpgrp);
196 close(ttyfd);
197 ttyfd = -1;
198 setsignal(SIGTSTP);
199 setsignal(SIGTTOU);
200 setsignal(SIGTTIN);
202 jobctl = on;
204 #endif
207 #ifdef mkinit
208 INCLUDE <sys/types.h>
209 INCLUDE <stdlib.h>
211 SHELLPROC {
212 backgndpid = -1;
213 #if JOBS
214 jobctl = 0;
215 #endif
218 #endif
222 #if JOBS
224 fgcmd(int argc __unused, char **argv)
226 struct job *jp;
227 pid_t pgrp;
228 int status;
230 jp = getjob(argv[1]);
231 if (jp->jobctl == 0)
232 error("job not created under job control");
233 out1str(jp->ps[0].cmd);
234 out1c('\n');
235 flushout(&output);
236 pgrp = jp->ps[0].pid;
237 tcsetpgrp(ttyfd, pgrp);
238 restartjob(jp);
239 jp->foreground = 1;
240 INTOFF;
241 status = waitforjob(jp, (int *)NULL);
242 INTON;
243 return status;
248 bgcmd(int argc, char **argv)
250 char s[64];
251 struct job *jp;
253 do {
254 jp = getjob(*++argv);
255 if (jp->jobctl == 0)
256 error("job not created under job control");
257 if (jp->state == JOBDONE)
258 continue;
259 restartjob(jp);
260 jp->foreground = 0;
261 fmtstr(s, 64, "[%td] ", jp - jobtab + 1);
262 out1str(s);
263 out1str(jp->ps[0].cmd);
264 out1c('\n');
265 } while (--argc > 1);
266 return 0;
270 STATIC void
271 restartjob(struct job *jp)
273 struct procstat *ps;
274 int i;
276 if (jp->state == JOBDONE)
277 return;
278 setcurjob(jp);
279 INTOFF;
280 killpg(jp->ps[0].pid, SIGCONT);
281 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
282 if (WIFSTOPPED(ps->status)) {
283 ps->status = -1;
284 jp->state = 0;
287 INTON;
289 #endif
293 jobscmd(int argc, char *argv[])
295 char *id;
296 int ch, sformat, lformat;
298 optind = optreset = 1;
299 opterr = 0;
300 sformat = lformat = 0;
301 while ((ch = getopt(argc, argv, "ls")) != -1) {
302 switch (ch) {
303 case 'l':
304 lformat = 1;
305 break;
306 case 's':
307 sformat = 1;
308 break;
309 case '?':
310 default:
311 error("unknown option: -%c", optopt);
314 argc -= optind;
315 argv += optind;
317 if (argc == 0)
318 showjobs(0, sformat, lformat);
319 else
320 while ((id = *argv++) != NULL)
321 showjob(getjob(id), 0, sformat, lformat);
323 return (0);
326 STATIC void
327 showjob(struct job *jp, pid_t pid, int sformat, int lformat)
329 char s[64];
330 struct procstat *ps;
331 struct job *j;
332 int col, curr, i, jobno, prev, procno;
333 char c;
335 procno = jp->nprocs;
336 jobno = jp - jobtab + 1;
337 curr = prev = 0;
338 #if JOBS
339 if ((j = getcurjob(NULL)) != NULL) {
340 curr = j - jobtab + 1;
341 if ((j = getcurjob(j)) != NULL)
342 prev = j - jobtab + 1;
344 #endif
345 for (ps = jp->ps ; ; ps++) { /* for each process */
346 if (sformat) {
347 out1fmt("%d\n", (int)ps->pid);
348 goto skip;
350 if (!lformat && ps != jp->ps && pid == 0)
351 goto skip;
352 if (pid != 0 && pid != ps->pid)
353 goto skip;
354 if (jobno == curr && ps == jp->ps)
355 c = '+';
356 else if (jobno == prev && ps == jp->ps)
357 c = '-';
358 else
359 c = ' ';
360 if (ps == jp->ps)
361 fmtstr(s, 64, "[%d] %c ", jobno, c);
362 else
363 fmtstr(s, 64, " %c ", c);
364 out1str(s);
365 col = strlen(s);
366 if (lformat) {
367 fmtstr(s, 64, "%d ", (int)ps->pid);
368 out1str(s);
369 col += strlen(s);
371 s[0] = '\0';
372 if (ps != jp->ps) {
373 *s = '\0';
374 } else if (ps->status == -1) {
375 strcpy(s, "Running");
376 } else if (WIFEXITED(ps->status)) {
377 if (WEXITSTATUS(ps->status) == 0)
378 strcpy(s, "Done");
379 else
380 fmtstr(s, 64, "Done (%d)",
381 WEXITSTATUS(ps->status));
382 } else {
383 #if JOBS
384 if (WIFSTOPPED(ps->status))
385 i = WSTOPSIG(ps->status);
386 else
387 #endif
388 i = WTERMSIG(ps->status);
389 if ((i & 0x7F) < _NSIG && strsiglist(i & 0x7F))
390 scopy(strsiglist(i & 0x7F), s);
391 else
392 fmtstr(s, 64, "Signal %d", i & 0x7F);
393 if (WCOREDUMP(ps->status))
394 strcat(s, " (core dumped)");
396 out1str(s);
397 col += strlen(s);
398 do {
399 out1c(' ');
400 col++;
401 } while (col < 30);
402 out1str(ps->cmd);
403 out1c('\n');
404 skip: if (--procno <= 0)
405 break;
410 * Print a list of jobs. If "change" is nonzero, only print jobs whose
411 * statuses have changed since the last call to showjobs.
413 * If the shell is interrupted in the process of creating a job, the
414 * result may be a job structure containing zero processes. Such structures
415 * will be freed here.
418 void
419 showjobs(int change, int sformat, int lformat)
421 int jobno;
422 struct job *jp;
424 TRACE(("showjobs(%d) called\n", change));
425 while (dowait(0, (struct job *)NULL) > 0);
426 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
427 if (! jp->used)
428 continue;
429 if (jp->nprocs == 0) {
430 freejob(jp);
431 continue;
433 if (change && ! jp->changed)
434 continue;
435 showjob(jp, 0, sformat, lformat);
436 jp->changed = 0;
437 if (jp->state == JOBDONE) {
438 freejob(jp);
445 * Mark a job structure as unused.
448 STATIC void
449 freejob(struct job *jp)
451 struct procstat *ps;
452 int i;
454 INTOFF;
455 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
456 if (ps->cmd != nullstr)
457 ckfree(ps->cmd);
459 if (jp->ps != &jp->ps0)
460 ckfree(jp->ps);
461 jp->used = 0;
462 #if JOBS
463 deljob(jp);
464 #endif
465 INTON;
471 waitcmd(int argc, char **argv)
473 struct job *job;
474 int status, retval;
475 struct job *jp;
477 if (argc > 1) {
478 job = getjob(argv[1]);
479 } else {
480 job = NULL;
484 * Loop until a process is terminated or stopped, or a SIGINT is
485 * received.
488 in_waitcmd++;
489 do {
490 if (job != NULL) {
491 if (job->state) {
492 status = job->ps[job->nprocs - 1].status;
493 if (WIFEXITED(status))
494 retval = WEXITSTATUS(status);
495 #if JOBS
496 else if (WIFSTOPPED(status))
497 retval = WSTOPSIG(status) + 128;
498 #endif
499 else
500 retval = WTERMSIG(status) + 128;
501 if (! iflag)
502 freejob(job);
503 in_waitcmd--;
504 return retval;
506 } else {
507 for (jp = jobtab ; ; jp++) {
508 if (jp >= jobtab + njobs) { /* no running procs */
509 in_waitcmd--;
510 return 0;
512 if (jp->used && jp->state == 0)
513 break;
516 } while (dowait(1, (struct job *)NULL) != -1);
517 in_waitcmd--;
519 return 0;
525 jobidcmd(int argc __unused, char **argv)
527 struct job *jp;
528 int i;
530 jp = getjob(argv[1]);
531 for (i = 0 ; i < jp->nprocs ; ) {
532 out1fmt("%d", (int)jp->ps[i].pid);
533 out1c(++i < jp->nprocs? ' ' : '\n');
535 return 0;
541 * Convert a job name to a job structure.
544 STATIC struct job *
545 getjob(char *name)
547 int jobno;
548 struct job *found, *jp;
549 pid_t pid;
550 int i;
552 if (name == NULL) {
553 #if JOBS
554 currentjob: if ((jp = getcurjob(NULL)) == NULL)
555 error("No current job");
556 return (jp);
557 #else
558 error("No current job");
559 #endif
560 } else if (name[0] == '%') {
561 if (is_digit(name[1])) {
562 jobno = number(name + 1);
563 if (jobno > 0 && jobno <= njobs
564 && jobtab[jobno - 1].used != 0)
565 return &jobtab[jobno - 1];
566 #if JOBS
567 } else if (name[1] == '%' && name[2] == '\0') {
568 goto currentjob;
569 } else if (name[1] == '+' && name[2] == '\0') {
570 goto currentjob;
571 } else if (name[1] == '-' && name[2] == '\0') {
572 if ((jp = getcurjob(NULL)) == NULL ||
573 (jp = getcurjob(jp)) == NULL)
574 error("No previous job");
575 return (jp);
576 #endif
577 } else if (name[1] == '?') {
578 found = NULL;
579 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
580 if (jp->used && jp->nprocs > 0
581 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
582 if (found)
583 error("%s: ambiguous", name);
584 found = jp;
587 if (found != NULL)
588 return (found);
589 } else {
590 found = NULL;
591 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
592 if (jp->used && jp->nprocs > 0
593 && prefix(name + 1, jp->ps[0].cmd)) {
594 if (found)
595 error("%s: ambiguous", name);
596 found = jp;
599 if (found)
600 return found;
602 } else if (is_number(name)) {
603 pid = (pid_t)number(name);
604 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
605 if (jp->used && jp->nprocs > 0
606 && jp->ps[jp->nprocs - 1].pid == pid)
607 return jp;
610 error("No such job: %s", name);
611 /*NOTREACHED*/
612 return NULL;
618 * Return a new job structure,
621 struct job *
622 makejob(union node *node __unused, int nprocs)
624 int i;
625 struct job *jp;
627 for (i = njobs, jp = jobtab ; ; jp++) {
628 if (--i < 0) {
629 INTOFF;
630 if (njobs == 0) {
631 jobtab = ckmalloc(4 * sizeof jobtab[0]);
632 #if JOBS
633 jobmru = NULL;
634 #endif
635 } else {
636 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
637 memcpy(jp, jobtab, njobs * sizeof jp[0]);
638 #if JOBS
639 /* Relocate `next' pointers and list head */
640 if (jobmru != NULL)
641 jobmru = &jp[jobmru - jobtab];
642 for (i = 0; i < njobs; i++)
643 if (jp[i].next != NULL)
644 jp[i].next = &jp[jp[i].next -
645 jobtab];
646 #endif
647 /* Relocate `ps' pointers */
648 for (i = 0; i < njobs; i++)
649 if (jp[i].ps == &jobtab[i].ps0)
650 jp[i].ps = &jp[i].ps0;
651 ckfree(jobtab);
652 jobtab = jp;
654 jp = jobtab + njobs;
655 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
656 INTON;
657 break;
659 if (jp->used == 0)
660 break;
662 INTOFF;
663 jp->state = 0;
664 jp->used = 1;
665 jp->changed = 0;
666 jp->nprocs = 0;
667 jp->foreground = 0;
668 #if JOBS
669 jp->jobctl = jobctl;
670 jp->next = NULL;
671 #endif
672 if (nprocs > 1) {
673 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
674 } else {
675 jp->ps = &jp->ps0;
677 INTON;
678 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
679 jp - jobtab + 1));
680 return jp;
683 #if JOBS
684 STATIC void
685 setcurjob(struct job *cj)
687 struct job *jp, *prev;
689 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
690 if (jp == cj) {
691 if (prev != NULL)
692 prev->next = jp->next;
693 else
694 jobmru = jp->next;
695 jp->next = jobmru;
696 jobmru = cj;
697 return;
700 cj->next = jobmru;
701 jobmru = cj;
704 STATIC void
705 deljob(struct job *j)
707 struct job *jp, *prev;
709 for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
710 if (jp == j) {
711 if (prev != NULL)
712 prev->next = jp->next;
713 else
714 jobmru = jp->next;
715 return;
721 * Return the most recently used job that isn't `nj', and preferably one
722 * that is stopped.
724 STATIC struct job *
725 getcurjob(struct job *nj)
727 struct job *jp;
729 /* Try to find a stopped one.. */
730 for (jp = jobmru; jp != NULL; jp = jp->next)
731 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
732 return (jp);
733 /* Otherwise the most recently used job that isn't `nj' */
734 for (jp = jobmru; jp != NULL; jp = jp->next)
735 if (jp->used && jp != nj)
736 return (jp);
738 return (NULL);
741 #endif
744 * Fork of a subshell. If we are doing job control, give the subshell its
745 * own process group. Jp is a job structure that the job is to be added to.
746 * N is the command that will be evaluated by the child. Both jp and n may
747 * be NULL. The mode parameter can be one of the following:
748 * FORK_FG - Fork off a foreground process.
749 * FORK_BG - Fork off a background process.
750 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
751 * process group even if job control is on.
753 * When job control is turned off, background processes have their standard
754 * input redirected to /dev/null (except for the second and later processes
755 * in a pipeline).
758 pid_t
759 forkshell(struct job *jp, union node *n, int mode)
761 pid_t pid;
762 pid_t pgrp;
764 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
765 mode));
766 INTOFF;
767 flushall();
768 pid = fork();
769 if (pid == -1) {
770 TRACE(("Fork failed, errno=%d\n", errno));
771 INTON;
772 error("Cannot fork: %s", strerror(errno));
774 if (pid == 0) {
775 struct job *p;
776 int wasroot;
777 int i;
779 TRACE(("Child shell %d\n", (int)getpid()));
780 wasroot = rootshell;
781 rootshell = 0;
782 closescript();
783 INTON;
784 clear_traps();
785 #if JOBS
786 jobctl = 0; /* do job control only in root shell */
787 if (wasroot && mode != FORK_NOJOB && mflag) {
788 if (jp == NULL || jp->nprocs == 0)
789 pgrp = getpid();
790 else
791 pgrp = jp->ps[0].pid;
792 if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
793 /*** this causes superfluous TIOCSPGRPS ***/
794 if (tcsetpgrp(ttyfd, pgrp) < 0)
795 error("tcsetpgrp failed, errno=%d", errno);
797 setsignal(SIGTSTP);
798 setsignal(SIGTTOU);
799 } else if (mode == FORK_BG) {
800 ignoresig(SIGINT);
801 ignoresig(SIGQUIT);
802 if ((jp == NULL || jp->nprocs == 0) &&
803 ! fd0_redirected_p ()) {
804 close(0);
805 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
806 error("Can't open %s: %s",
807 _PATH_DEVNULL, strerror(errno));
810 #else
811 if (mode == FORK_BG) {
812 ignoresig(SIGINT);
813 ignoresig(SIGQUIT);
814 if ((jp == NULL || jp->nprocs == 0) &&
815 ! fd0_redirected_p ()) {
816 close(0);
817 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
818 error("Can't open %s: %s",
819 _PATH_DEVNULL, strerror(errno));
822 #endif
823 INTOFF;
824 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
825 if (p->used)
826 freejob(p);
827 INTON;
828 if (wasroot && iflag) {
829 setsignal(SIGINT);
830 setsignal(SIGQUIT);
831 setsignal(SIGTERM);
833 return pid;
835 if (rootshell && mode != FORK_NOJOB && mflag) {
836 if (jp == NULL || jp->nprocs == 0)
837 pgrp = pid;
838 else
839 pgrp = jp->ps[0].pid;
840 #if JOBS
841 setpgid(pid, pgrp);
842 #endif
844 if (mode == FORK_BG)
845 backgndpid = pid; /* set $! */
846 if (jp) {
847 struct procstat *ps = &jp->ps[jp->nprocs++];
848 ps->pid = pid;
849 ps->status = -1;
850 ps->cmd = nullstr;
851 if (iflag && rootshell && n)
852 ps->cmd = commandtext(n);
853 jp->foreground = mode == FORK_FG;
854 #if JOBS
855 setcurjob(jp);
856 #endif
858 INTON;
859 TRACE(("In parent shell: child = %d\n", (int)pid));
860 return pid;
866 * Wait for job to finish.
868 * Under job control we have the problem that while a child process is
869 * running interrupts generated by the user are sent to the child but not
870 * to the shell. This means that an infinite loop started by an inter-
871 * active user may be hard to kill. With job control turned off, an
872 * interactive user may place an interactive program inside a loop. If
873 * the interactive program catches interrupts, the user doesn't want
874 * these interrupts to also abort the loop. The approach we take here
875 * is to have the shell ignore interrupt signals while waiting for a
876 * foreground process to terminate, and then send itself an interrupt
877 * signal if the child process was terminated by an interrupt signal.
878 * Unfortunately, some programs want to do a bit of cleanup and then
879 * exit on interrupt; unless these processes terminate themselves by
880 * sending a signal to themselves (instead of calling exit) they will
881 * confuse this approach.
885 waitforjob(struct job *jp, int *origstatus)
887 #if JOBS
888 pid_t mypgrp = getpgrp();
889 #endif
890 int status;
891 int st;
893 INTOFF;
894 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
895 while (jp->state == 0)
896 if (dowait(1, jp) == -1)
897 dotrap();
898 #if JOBS
899 if (jp->jobctl) {
900 if (tcsetpgrp(ttyfd, mypgrp) < 0)
901 error("tcsetpgrp failed, errno=%d\n", errno);
903 if (jp->state == JOBSTOPPED)
904 setcurjob(jp);
905 #endif
906 status = jp->ps[jp->nprocs - 1].status;
907 if (origstatus != NULL)
908 *origstatus = status;
909 /* convert to 8 bits */
910 if (WIFEXITED(status))
911 st = WEXITSTATUS(status);
912 #if JOBS
913 else if (WIFSTOPPED(status))
914 st = WSTOPSIG(status) + 128;
915 #endif
916 else
917 st = WTERMSIG(status) + 128;
918 if (! JOBS || jp->state == JOBDONE)
919 freejob(jp);
920 if (int_pending()) {
921 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
922 kill(getpid(), SIGINT);
923 else
924 CLEAR_PENDING_INT;
926 INTON;
927 return st;
933 * Wait for a process to terminate.
936 STATIC pid_t
937 dowait(int block, struct job *job)
939 pid_t pid;
940 int status, core;
941 struct procstat *sp;
942 struct job *jp;
943 struct job *thisjob;
944 int done;
945 int stopped;
946 int sig;
947 int i;
949 in_dowait++;
950 TRACE(("dowait(%d) called\n", block));
951 do {
952 pid = waitproc(block, &status);
953 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
954 } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
955 (pid > 0 && WIFSTOPPED(status) && !iflag));
956 in_dowait--;
957 if (breakwaitcmd != 0) {
958 breakwaitcmd = 0;
959 return -1;
961 if (pid <= 0)
962 return pid;
963 INTOFF;
964 thisjob = NULL;
965 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
966 if (jp->used) {
967 done = 1;
968 stopped = 1;
969 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
970 if (sp->pid == -1)
971 continue;
972 if (sp->pid == pid) {
973 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
974 (int)pid, sp->status,
975 status));
976 sp->status = status;
977 thisjob = jp;
979 if (sp->status == -1)
980 stopped = 0;
981 else if (WIFSTOPPED(sp->status))
982 done = 0;
984 if (stopped) { /* stopped or done */
985 int state = done? JOBDONE : JOBSTOPPED;
986 if (jp->state != state) {
987 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
988 jp->state = state;
989 #if JOBS
990 if (done)
991 deljob(jp);
992 #endif
997 INTON;
998 if (! rootshell || ! iflag || (job && thisjob == job)) {
999 core = WCOREDUMP(status);
1000 #if JOBS
1001 if (WIFSTOPPED(status))
1002 sig = WSTOPSIG(status);
1003 else
1004 #endif
1006 if (WIFEXITED(status))
1007 sig = 0;
1008 else
1009 sig = WTERMSIG(status);
1011 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
1012 if (!mflag ||
1013 (thisjob->foreground && !WIFSTOPPED(status))) {
1014 i = WTERMSIG(status);
1015 if ((i & 0x7F) < _NSIG && strsiglist(i & 0x7F))
1016 out1str(strsiglist(i & 0x7F));
1017 else
1018 out1fmt("Signal %d", i & 0x7F);
1019 if (core)
1020 out1str(" (core dumped)");
1021 out1c('\n');
1022 } else
1023 showjob(thisjob, pid, 0, 0);
1025 } else {
1026 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1027 if (thisjob)
1028 thisjob->changed = 1;
1030 return pid;
1036 * Do a wait system call. If job control is compiled in, we accept
1037 * stopped processes. If block is zero, we return a value of zero
1038 * rather than blocking.
1040 STATIC pid_t
1041 waitproc(int block, int *status)
1043 #if POSIX
1044 int flags;
1046 #if JOBS
1047 flags = ((rootshell && is_interactive) ? WUNTRACED : 0);
1048 #else
1049 flags = 0;
1050 #endif /* JOBS */
1051 return waitpid(-1, status, (block == 0 ? WNOHANG : 0) | flags);
1052 #else /* !POSIX */
1053 /* Assume BSD */
1054 int flags;
1056 #if JOBS
1057 flags = WUNTRACED;
1058 #else
1059 flags = 0;
1060 #endif /* JOBS */
1061 if (block == 0)
1062 flags |= WNOHANG;
1063 return wait3(status, flags, (struct rusage *)NULL);
1064 #endif /* POSIX */
1068 * return 1 if there are stopped jobs, otherwise 0
1070 int job_warning = 0;
1072 stoppedjobs(void)
1074 int jobno;
1075 struct job *jp;
1077 if (job_warning)
1078 return (0);
1079 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1080 if (jp->used == 0)
1081 continue;
1082 if (jp->state == JOBSTOPPED) {
1083 out2str("You have stopped jobs.\n");
1084 job_warning = 2;
1085 return (1);
1089 return (0);
1093 * Return a string identifying a command (to be printed by the
1094 * jobs command.
1097 STATIC char *cmdnextc;
1098 STATIC int cmdnleft;
1099 #define MAXCMDTEXT 200
1101 char *
1102 commandtext(union node *n)
1104 char *name;
1106 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1107 cmdnleft = MAXCMDTEXT - 4;
1108 cmdtxt(n);
1109 *cmdnextc = '\0';
1110 return name;
1114 STATIC void
1115 cmdtxt(union node *n)
1117 union node *np;
1118 struct nodelist *lp;
1119 char *p;
1120 int i;
1121 char s[2];
1123 if (n == NULL)
1124 return;
1125 switch (n->type) {
1126 case NSEMI:
1127 cmdtxt(n->nbinary.ch1);
1128 cmdputs("; ");
1129 cmdtxt(n->nbinary.ch2);
1130 break;
1131 case NAND:
1132 cmdtxt(n->nbinary.ch1);
1133 cmdputs(" && ");
1134 cmdtxt(n->nbinary.ch2);
1135 break;
1136 case NOR:
1137 cmdtxt(n->nbinary.ch1);
1138 cmdputs(" || ");
1139 cmdtxt(n->nbinary.ch2);
1140 break;
1141 case NPIPE:
1142 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1143 cmdtxt(lp->n);
1144 if (lp->next)
1145 cmdputs(" | ");
1147 break;
1148 case NSUBSHELL:
1149 cmdputs("(");
1150 cmdtxt(n->nredir.n);
1151 cmdputs(")");
1152 break;
1153 case NREDIR:
1154 case NBACKGND:
1155 cmdtxt(n->nredir.n);
1156 break;
1157 case NIF:
1158 cmdputs("if ");
1159 cmdtxt(n->nif.test);
1160 cmdputs("; then ");
1161 cmdtxt(n->nif.ifpart);
1162 cmdputs("...");
1163 break;
1164 case NWHILE:
1165 cmdputs("while ");
1166 goto until;
1167 case NUNTIL:
1168 cmdputs("until ");
1169 until:
1170 cmdtxt(n->nbinary.ch1);
1171 cmdputs("; do ");
1172 cmdtxt(n->nbinary.ch2);
1173 cmdputs("; done");
1174 break;
1175 case NFOR:
1176 cmdputs("for ");
1177 cmdputs(n->nfor.var);
1178 cmdputs(" in ...");
1179 break;
1180 case NCASE:
1181 cmdputs("case ");
1182 cmdputs(n->ncase.expr->narg.text);
1183 cmdputs(" in ...");
1184 break;
1185 case NDEFUN:
1186 cmdputs(n->narg.text);
1187 cmdputs("() ...");
1188 break;
1189 case NCMD:
1190 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1191 cmdtxt(np);
1192 if (np->narg.next)
1193 cmdputs(" ");
1195 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1196 cmdputs(" ");
1197 cmdtxt(np);
1199 break;
1200 case NARG:
1201 cmdputs(n->narg.text);
1202 break;
1203 case NTO:
1204 p = ">"; i = 1; goto redir;
1205 case NAPPEND:
1206 p = ">>"; i = 1; goto redir;
1207 case NTOFD:
1208 p = ">&"; i = 1; goto redir;
1209 case NCLOBBER:
1210 p = ">|"; i = 1; goto redir;
1211 case NFROM:
1212 p = "<"; i = 0; goto redir;
1213 case NFROMTO:
1214 p = "<>"; i = 0; goto redir;
1215 case NFROMFD:
1216 p = "<&"; i = 0; goto redir;
1217 redir:
1218 if (n->nfile.fd != i) {
1219 s[0] = n->nfile.fd + '0';
1220 s[1] = '\0';
1221 cmdputs(s);
1223 cmdputs(p);
1224 if (n->type == NTOFD || n->type == NFROMFD) {
1225 if (n->ndup.dupfd >= 0)
1226 s[0] = n->ndup.dupfd + '0';
1227 else
1228 s[0] = '-';
1229 s[1] = '\0';
1230 cmdputs(s);
1231 } else {
1232 cmdtxt(n->nfile.fname);
1234 break;
1235 case NHERE:
1236 case NXHERE:
1237 cmdputs("<<...");
1238 break;
1239 default:
1240 cmdputs("???");
1241 break;
1247 STATIC void
1248 cmdputs(char *s)
1250 char *p, *q;
1251 char c;
1252 int subtype = 0;
1254 if (cmdnleft <= 0)
1255 return;
1256 p = s;
1257 q = cmdnextc;
1258 while ((c = *p++) != '\0') {
1259 if (c == CTLESC)
1260 *q++ = *p++;
1261 else if (c == CTLVAR) {
1262 *q++ = '$';
1263 if (--cmdnleft > 0)
1264 *q++ = '{';
1265 subtype = *p++;
1266 } else if (c == '=' && subtype != 0) {
1267 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1268 subtype = 0;
1269 } else if (c == CTLENDVAR) {
1270 *q++ = '}';
1271 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1272 cmdnleft++; /* ignore it */
1273 else
1274 *q++ = c;
1275 if (--cmdnleft <= 0) {
1276 *q++ = '.';
1277 *q++ = '.';
1278 *q++ = '.';
1279 break;
1282 cmdnextc = q;
1285 #ifdef NO_KILLPG
1286 static int killpg(grp, sig)
1287 pid_t grp;
1288 int sig;
1290 return kill(-grp, sig);
1292 #endif
1295 * $PchId: jobs.c,v 1.7 2006/05/22 12:02:13 philip Exp $