jobs.c revision 1.49 1 /* $NetBSD: jobs.c,v 1.49 2002/09/27 21:32:25 mycroft Exp $ */
2
3 /*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
9 *
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. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)jobs.c 8.5 (Berkeley) 5/4/95";
43 #else
44 __RCSID("$NetBSD: jobs.c,v 1.49 2002/09/27 21:32:25 mycroft Exp $");
45 #endif
46 #endif /* not lint */
47
48 #include <fcntl.h>
49 #include <signal.h>
50 #include <errno.h>
51 #include <unistd.h>
52 #include <stdlib.h>
53 #include <paths.h>
54 #include <sys/types.h>
55 #include <sys/param.h>
56 #ifdef BSD
57 #include <sys/wait.h>
58 #include <sys/time.h>
59 #include <sys/resource.h>
60 #endif
61 #include <sys/ioctl.h>
62
63 #include "shell.h"
64 #if JOBS
65 #if OLD_TTY_DRIVER
66 #include "sgtty.h"
67 #else
68 #include <termios.h>
69 #endif
70 #undef CEOF /* syntax.h redefines this */
71 #endif
72 #include "redir.h"
73 #include "show.h"
74 #include "main.h"
75 #include "parser.h"
76 #include "nodes.h"
77 #include "jobs.h"
78 #include "options.h"
79 #include "trap.h"
80 #include "syntax.h"
81 #include "input.h"
82 #include "output.h"
83 #include "memalloc.h"
84 #include "error.h"
85 #include "mystring.h"
86
87
88 struct job *jobtab; /* array of jobs */
89 int njobs; /* size of array */
90 MKINIT short backgndpid = -1; /* pid of last background process */
91 #if JOBS
92 int initialpgrp; /* pgrp of shell on invocation */
93 short curjob; /* current job */
94 #endif
95 static int ttyfd = -1;
96
97 STATIC void restartjob __P((struct job *));
98 STATIC void freejob __P((struct job *));
99 STATIC struct job *getjob __P((char *));
100 STATIC int dowait __P((int, struct job *));
101 STATIC int onsigchild __P((void));
102 STATIC int waitproc __P((int, struct job *, int *));
103 STATIC void cmdtxt __P((union node *));
104 STATIC void cmdputs __P((const char *));
105
106 #ifdef OLD_TTY_DRIVER
107 static pid_t tcgetpgrp __P((int fd));
108 static int tcsetpgrp __P((int fd, pid_t pgrp));
109
110 static pid_t
111 tcgetpgrp(fd)
112 int fd;
113 {
114 pid_t pgrp;
115 if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
116 return -1;
117 else
118 return pgrp;
119 }
120
121 static int
122 tcsetpgrp(fd, pgrp)
123 int fd;
124 pid_t pgrp;
125 {
126 return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
127 }
128 #endif
129
130 /*
131 * Turn job control on and off.
132 *
133 * Note: This code assumes that the third arg to ioctl is a character
134 * pointer, which is true on Berkeley systems but not System V. Since
135 * System V doesn't have job control yet, this isn't a problem now.
136 */
137
138 MKINIT int jobctl;
139
140 void
141 setjobctl(on)
142 int on;
143 {
144 #ifdef OLD_TTY_DRIVER
145 int ldisc;
146 #endif
147
148 if (on == jobctl || rootshell == 0)
149 return;
150 if (on) {
151 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
152 int err;
153 if (ttyfd != -1)
154 close(ttyfd);
155 if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
156 int i;
157 for (i = 0; i < 3; i++) {
158 if (isatty(i) && (ttyfd = dup(i)) != -1)
159 break;
160 }
161 if (i == 3)
162 goto out;
163 }
164 #ifdef FIOCLEX
165 err = ioctl(ttyfd, FIOCLEX, 0);
166 #elif FD_CLOEXEC
167 err = fcntl(ttyfd, FD_CLOEXEC, 1);
168 #endif
169 if (err == -1) {
170 close(ttyfd);
171 ttyfd = -1;
172 goto out;
173 }
174 #else
175 out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
176 goto out;
177 #endif
178 do { /* while we are in the background */
179 if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
180 out:
181 out2str("sh: can't access tty; job control turned off\n");
182 mflag = 0;
183 return;
184 }
185 if (initialpgrp == -1)
186 initialpgrp = getpgrp();
187 else if (initialpgrp != getpgrp()) {
188 killpg(0, SIGTTIN);
189 continue;
190 }
191 } while (0);
192
193 #ifdef OLD_TTY_DRIVER
194 if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
195 || ldisc != NTTYDISC) {
196 out2str("sh: need new tty driver to run job control; job control turned off\n");
197 mflag = 0;
198 return;
199 }
200 #endif
201 setsignal(SIGTSTP, 0);
202 setsignal(SIGTTOU, 0);
203 setsignal(SIGTTIN, 0);
204 if (getpgid(0) != rootpid && setpgid(0, rootpid) == -1)
205 error("Cannot set process group (%s) at %d",
206 strerror(errno), __LINE__);
207 if (tcsetpgrp(ttyfd, rootpid) == -1)
208 error("Cannot set tty process group (%s) at %d",
209 strerror(errno), __LINE__);
210 } else { /* turning job control off */
211 if (getpgid(0) != initialpgrp && setpgid(0, initialpgrp) == -1)
212 error("Cannot set process group (%s) at %d",
213 strerror(errno), __LINE__);
214 if (tcsetpgrp(ttyfd, initialpgrp) == -1)
215 error("Cannot set tty process group (%s) at %d",
216 strerror(errno), __LINE__);
217 close(ttyfd);
218 ttyfd = -1;
219 setsignal(SIGTSTP, 0);
220 setsignal(SIGTTOU, 0);
221 setsignal(SIGTTIN, 0);
222 }
223 jobctl = on;
224 }
225
226
227 #ifdef mkinit
228 INCLUDE <stdlib.h>
229
230 SHELLPROC {
231 backgndpid = -1;
232 #if JOBS
233 jobctl = 0;
234 #endif
235 }
236
237 #endif
238
239
240
241 #if JOBS
242 int
243 fgcmd(argc, argv)
244 int argc;
245 char **argv;
246 {
247 struct job *jp;
248 int i;
249 int status;
250
251 jp = getjob(argv[1]);
252 if (jp->jobctl == 0)
253 error("job not created under job control");
254
255 for (i = 0; i < jp->nprocs; i++)
256 if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
257 break;
258
259 if (i >= jp->nprocs) {
260 error("Cannot set tty process group (%s) at %d",
261 strerror(errno), __LINE__);
262 }
263 restartjob(jp);
264 INTOFF;
265 status = waitforjob(jp);
266 INTON;
267 return status;
268 }
269
270
271 int
272 bgcmd(argc, argv)
273 int argc;
274 char **argv;
275 {
276 struct job *jp;
277
278 do {
279 jp = getjob(*++argv);
280 if (jp->jobctl == 0)
281 error("job not created under job control");
282 restartjob(jp);
283 } while (--argc > 1);
284 return 0;
285 }
286
287
288 STATIC void
289 restartjob(jp)
290 struct job *jp;
291 {
292 struct procstat *ps;
293 int i;
294
295 if (jp->state == JOBDONE)
296 return;
297 INTOFF;
298 for (i = 0; i < jp->nprocs; i++)
299 if (killpg(jp->ps[i].pid, SIGCONT) != -1)
300 break;
301 if (i >= jp->nprocs)
302 error("Cannot continue job (%s)", strerror(errno));
303 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
304 if (WIFSTOPPED(ps->status)) {
305 ps->status = -1;
306 jp->state = 0;
307 }
308 }
309 INTON;
310 }
311 #endif
312
313
314 int
315 jobscmd(argc, argv)
316 int argc;
317 char **argv;
318 {
319 showjobs(0);
320 return 0;
321 }
322
323
324 /*
325 * Print a list of jobs. If "change" is nonzero, only print jobs whose
326 * statuses have changed since the last call to showjobs.
327 *
328 * If the shell is interrupted in the process of creating a job, the
329 * result may be a job structure containing zero processes. Such structures
330 * will be freed here.
331 */
332
333 void
334 showjobs(change)
335 int change;
336 {
337 int jobno;
338 int procno;
339 int i;
340 struct job *jp;
341 struct procstat *ps;
342 int col;
343 int silent = 0, gotpid;
344 char s[64];
345
346 TRACE(("showjobs(%d) called\n", change));
347
348 /* If not even one one job changed, there is nothing to do */
349 gotpid = dowait(0, NULL);
350 while (dowait(0, NULL) > 0)
351 continue;
352 #ifdef JOBS
353 /*
354 * Check if we are not in our foreground group, and if not
355 * put us in it.
356 */
357 if (gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
358 if (tcsetpgrp(ttyfd, getpid()) == -1)
359 error("Cannot set tty process group (%s) at %d",
360 strerror(errno), __LINE__);
361 TRACE(("repaired tty process group\n"));
362 silent = 1;
363 }
364 #endif
365 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
366 if (! jp->used)
367 continue;
368 if (jp->nprocs == 0) {
369 freejob(jp);
370 continue;
371 }
372 if (change && ! jp->changed)
373 continue;
374 if (silent && jp->changed) {
375 jp->changed = 0;
376 continue;
377 }
378 procno = jp->nprocs;
379 for (ps = jp->ps ; ; ps++) { /* for each process */
380 if (ps == jp->ps)
381 fmtstr(s, 64, "[%d] %ld ", jobno,
382 (long)ps->pid);
383 else
384 fmtstr(s, 64, " %ld ",
385 (long)ps->pid);
386 out1str(s);
387 col = strlen(s);
388 s[0] = '\0';
389 if (ps->status == -1) {
390 /* don't print anything */
391 } else if (WIFEXITED(ps->status)) {
392 fmtstr(s, 64, "Exit %d",
393 WEXITSTATUS(ps->status));
394 } else {
395 #if JOBS
396 if (WIFSTOPPED(ps->status))
397 i = WSTOPSIG(ps->status);
398 else /* WIFSIGNALED(ps->status) */
399 #endif
400 i = WTERMSIG(ps->status);
401 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
402 scopy(sys_siglist[i & 0x7F], s);
403 else
404 fmtstr(s, 64, "Signal %d", i & 0x7F);
405 if (WCOREDUMP(ps->status))
406 strcat(s, " (core dumped)");
407 }
408 out1str(s);
409 col += strlen(s);
410 do {
411 out1c(' ');
412 col++;
413 } while (col < 30);
414 out1str(ps->cmd);
415 out1c('\n');
416 if (--procno <= 0)
417 break;
418 }
419 jp->changed = 0;
420 if (jp->state == JOBDONE) {
421 freejob(jp);
422 }
423 }
424 }
425
426
427 /*
428 * Mark a job structure as unused.
429 */
430
431 STATIC void
432 freejob(jp)
433 struct job *jp;
434 {
435 struct procstat *ps;
436 int i;
437
438 INTOFF;
439 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
440 if (ps->cmd != nullstr)
441 ckfree(ps->cmd);
442 }
443 if (jp->ps != &jp->ps0) {
444 ckfree(jp->ps);
445 jp->ps = &jp->ps0;
446 }
447 jp->nprocs = 0;
448 jp->used = 0;
449 #if JOBS
450 if (curjob == jp - jobtab + 1)
451 curjob = 0;
452 #endif
453 INTON;
454 }
455
456
457
458 int
459 waitcmd(argc, argv)
460 int argc;
461 char **argv;
462 {
463 struct job *job;
464 int status, retval;
465 struct job *jp;
466
467 if (argc > 1) {
468 job = getjob(argv[1]);
469 } else {
470 job = NULL;
471 }
472 for (;;) { /* loop until process terminated or stopped */
473 if (job != NULL) {
474 if (job->state) {
475 status = job->ps[job->nprocs - 1].status;
476 if (WIFEXITED(status))
477 retval = WEXITSTATUS(status);
478 #if JOBS
479 else if (WIFSTOPPED(status))
480 retval = WSTOPSIG(status) + 128;
481 #endif
482 else {
483 /* XXX: limits number of signals */
484 retval = WTERMSIG(status) + 128;
485 }
486 if (! iflag)
487 freejob(job);
488 return retval;
489 }
490 } else {
491 for (jp = jobtab ; ; jp++) {
492 if (jp >= jobtab + njobs) { /* no running procs */
493 return 0;
494 }
495 if (jp->used && jp->state == 0)
496 break;
497 }
498 }
499 if (dowait(1, (struct job *)NULL) == -1)
500 return 128 + SIGINT;
501 }
502 }
503
504
505
506 int
507 jobidcmd(argc, argv)
508 int argc;
509 char **argv;
510 {
511 struct job *jp;
512 int i;
513
514 jp = getjob(argv[1]);
515 for (i = 0 ; i < jp->nprocs ; ) {
516 out1fmt("%ld", (long)jp->ps[i].pid);
517 out1c(++i < jp->nprocs? ' ' : '\n');
518 }
519 return 0;
520 }
521
522
523
524 /*
525 * Convert a job name to a job structure.
526 */
527
528 STATIC struct job *
529 getjob(name)
530 char *name;
531 {
532 int jobno;
533 struct job *jp;
534 int pid;
535 int i;
536
537 if (name == NULL) {
538 #if JOBS
539 currentjob:
540 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
541 error("No current job");
542 return &jobtab[jobno - 1];
543 #else
544 error("No current job");
545 #endif
546 } else if (name[0] == '%') {
547 if (is_digit(name[1])) {
548 jobno = number(name + 1);
549 if (jobno > 0 && jobno <= njobs
550 && jobtab[jobno - 1].used != 0)
551 return &jobtab[jobno - 1];
552 #if JOBS
553 } else if (name[1] == '%' && name[2] == '\0') {
554 goto currentjob;
555 #endif
556 } else {
557 struct job *found = NULL;
558 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
559 if (jp->used && jp->nprocs > 0
560 && prefix(name + 1, jp->ps[0].cmd)) {
561 if (found)
562 error("%s: ambiguous", name);
563 found = jp;
564 }
565 }
566 if (found)
567 return found;
568 }
569 } else if (is_number(name)) {
570 pid = number(name);
571 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
572 if (jp->used && jp->nprocs > 0
573 && jp->ps[jp->nprocs - 1].pid == pid)
574 return jp;
575 }
576 }
577 error("No such job: %s", name);
578 /* NOTREACHED */
579 }
580
581
582
583 /*
584 * Return a new job structure,
585 */
586
587 struct job *
588 makejob(node, nprocs)
589 union node *node;
590 int nprocs;
591 {
592 int i;
593 struct job *jp;
594
595 for (i = njobs, jp = jobtab ; ; jp++) {
596 if (--i < 0) {
597 INTOFF;
598 if (njobs == 0) {
599 jobtab = ckmalloc(4 * sizeof jobtab[0]);
600 } else {
601 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
602 memcpy(jp, jobtab, njobs * sizeof jp[0]);
603 /* Relocate `ps' pointers */
604 for (i = 0; i < njobs; i++)
605 if (jp[i].ps == &jobtab[i].ps0)
606 jp[i].ps = &jp[i].ps0;
607 ckfree(jobtab);
608 jobtab = jp;
609 }
610 jp = jobtab + njobs;
611 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
612 INTON;
613 break;
614 }
615 if (jp->used == 0)
616 break;
617 }
618 INTOFF;
619 jp->state = 0;
620 jp->used = 1;
621 jp->changed = 0;
622 jp->nprocs = 0;
623 #if JOBS
624 jp->jobctl = jobctl;
625 #endif
626 if (nprocs > 1) {
627 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
628 } else {
629 jp->ps = &jp->ps0;
630 }
631 INTON;
632 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
633 jp - jobtab + 1));
634 return jp;
635 }
636
637
638 /*
639 * Fork off a subshell. If we are doing job control, give the subshell its
640 * own process group. Jp is a job structure that the job is to be added to.
641 * N is the command that will be evaluated by the child. Both jp and n may
642 * be NULL. The mode parameter can be one of the following:
643 * FORK_FG - Fork off a foreground process.
644 * FORK_BG - Fork off a background process.
645 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
646 * process group even if job control is on.
647 *
648 * When job control is turned off, background processes have their standard
649 * input redirected to /dev/null (except for the second and later processes
650 * in a pipeline).
651 */
652
653 int
654 forkshell(jp, n, mode)
655 union node *n;
656 struct job *jp;
657 int mode;
658 {
659 int pid;
660
661 TRACE(("forkshell(%%%d, %p, %d) called\n", jp - jobtab, n, mode));
662 switch ((pid = fork())) {
663 case -1:
664 TRACE(("Fork failed, errno=%d", errno));
665 INTON;
666 error("Cannot fork");
667 break;
668 case 0:
669 forkchild(jp, n, mode, 0);
670 return 0;
671 default:
672 return forkparent(jp, n, mode, pid);
673 }
674 }
675
676 int
677 forkparent(jp, n, mode, pid)
678 union node *n;
679 struct job *jp;
680 int mode;
681 pid_t pid;
682 {
683 int pgrp;
684
685 if (rootshell && mode != FORK_NOJOB && mflag) {
686 if (jp == NULL || jp->nprocs == 0)
687 pgrp = pid;
688 else
689 pgrp = jp->ps[0].pid;
690 #ifdef notdef
691 if (setpgid(pid, pgrp) == -1)
692 error("Cannot set process group (%s) at %d",
693 strerror(errno), __LINE__);
694 #endif
695 }
696 if (mode == FORK_BG)
697 backgndpid = pid; /* set $! */
698 if (jp) {
699 struct procstat *ps = &jp->ps[jp->nprocs++];
700 ps->pid = pid;
701 ps->status = -1;
702 ps->cmd = nullstr;
703 if (iflag && rootshell && n)
704 ps->cmd = commandtext(n);
705 }
706 TRACE(("In parent shell: child = %d\n", pid));
707 return pid;
708 }
709
710 void
711 forkchild(jp, n, mode, vforked)
712 union node *n;
713 struct job *jp;
714 int mode;
715 int vforked;
716 {
717 struct job *p;
718 int wasroot;
719 int i;
720 int pgrp;
721 const char *devnull = _PATH_DEVNULL;
722 const char *nullerr = "Can't open %s";
723
724 TRACE(("Child shell %d\n", getpid()));
725 wasroot = rootshell;
726 if (!vforked) {
727 rootshell = 0;
728 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
729 if (p->used)
730 freejob(p);
731 }
732 closescript(vforked);
733 clear_traps(vforked);
734 #if JOBS
735 if (!vforked)
736 jobctl = 0; /* do job control only in root shell */
737 if (wasroot && mode != FORK_NOJOB && mflag) {
738 if (jp == NULL || jp->nprocs == 0)
739 pgrp = getpid();
740 else
741 pgrp = jp->ps[0].pid;
742 if (setpgid(0, pgrp) == -1)
743 error("Cannot set process group (%s) at %d",
744 strerror(errno), __LINE__);
745 if (mode == FORK_FG) {
746 if (tcsetpgrp(ttyfd, pgrp) == -1)
747 error("Cannot set tty process group (%s) at %d",
748 strerror(errno), __LINE__);
749 }
750 setsignal(SIGTSTP, vforked);
751 setsignal(SIGTTOU, vforked);
752 } else if (mode == FORK_BG) {
753 ignoresig(SIGINT, vforked);
754 ignoresig(SIGQUIT, vforked);
755 if ((jp == NULL || jp->nprocs == 0) &&
756 ! fd0_redirected_p ()) {
757 close(0);
758 if (open(devnull, O_RDONLY) != 0)
759 error(nullerr, devnull);
760 }
761 }
762 #else
763 if (mode == FORK_BG) {
764 ignoresig(SIGINT, vforked);
765 ignoresig(SIGQUIT, vforked);
766 if ((jp == NULL || jp->nprocs == 0) &&
767 ! fd0_redirected_p ()) {
768 close(0);
769 if (open(devnull, O_RDONLY) != 0)
770 error(nullerr, devnull);
771 }
772 }
773 #endif
774 if (wasroot && iflag) {
775 setsignal(SIGINT, vforked);
776 setsignal(SIGQUIT, vforked);
777 setsignal(SIGTERM, vforked);
778 }
779 }
780
781
782
783 /*
784 * Wait for job to finish.
785 *
786 * Under job control we have the problem that while a child process is
787 * running interrupts generated by the user are sent to the child but not
788 * to the shell. This means that an infinite loop started by an inter-
789 * active user may be hard to kill. With job control turned off, an
790 * interactive user may place an interactive program inside a loop. If
791 * the interactive program catches interrupts, the user doesn't want
792 * these interrupts to also abort the loop. The approach we take here
793 * is to have the shell ignore interrupt signals while waiting for a
794 * forground process to terminate, and then send itself an interrupt
795 * signal if the child process was terminated by an interrupt signal.
796 * Unfortunately, some programs want to do a bit of cleanup and then
797 * exit on interrupt; unless these processes terminate themselves by
798 * sending a signal to themselves (instead of calling exit) they will
799 * confuse this approach.
800 */
801
802 int
803 waitforjob(jp)
804 struct job *jp;
805 {
806 #if JOBS
807 int mypgrp = getpgrp();
808 #endif
809 int status;
810 int st;
811
812 INTOFF;
813 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
814 while (jp->state == 0) {
815 dowait(1, jp);
816 }
817 #if JOBS
818 if (jp->jobctl) {
819 if (tcsetpgrp(ttyfd, mypgrp) == -1)
820 error("Cannot set tty process group (%s) at %d",
821 strerror(errno), __LINE__);
822 }
823 if (jp->state == JOBSTOPPED)
824 curjob = jp - jobtab + 1;
825 #endif
826 status = jp->ps[jp->nprocs - 1].status;
827 /* convert to 8 bits */
828 if (WIFEXITED(status))
829 st = WEXITSTATUS(status);
830 #if JOBS
831 else if (WIFSTOPPED(status))
832 st = WSTOPSIG(status) + 128;
833 #endif
834 else
835 st = WTERMSIG(status) + 128;
836 #if JOBS
837 if (jp->jobctl) {
838 /*
839 * This is truly gross.
840 * If we're doing job control, then we did a TIOCSPGRP which
841 * caused us (the shell) to no longer be in the controlling
842 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
843 * intuit from the subprocess exit status whether a SIGINT
844 * occurred, and if so interrupt ourselves. Yuck. - mycroft
845 */
846 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
847 raise(SIGINT);
848 }
849 #endif
850 if (! JOBS || jp->state == JOBDONE)
851 freejob(jp);
852 INTON;
853 return st;
854 }
855
856
857
858 /*
859 * Wait for a process to terminate.
860 */
861
862 STATIC int
863 dowait(block, job)
864 int block;
865 struct job *job;
866 {
867 int pid;
868 int status;
869 struct procstat *sp;
870 struct job *jp;
871 struct job *thisjob;
872 int done;
873 int stopped;
874 int core;
875 int sig;
876 extern volatile char gotsig[];
877
878 TRACE(("dowait(%d) called\n", block));
879 do {
880 pid = waitproc(block, job, &status);
881 TRACE(("wait returns %d, status=%d\n", pid, status));
882 } while (pid == -1 && errno == EINTR && gotsig[SIGINT - 1] == 0);
883 if (pid <= 0)
884 return pid;
885 INTOFF;
886 thisjob = NULL;
887 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
888 if (jp->used) {
889 done = 1;
890 stopped = 1;
891 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
892 if (sp->pid == -1)
893 continue;
894 if (sp->pid == pid) {
895 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
896 sp->status = status;
897 thisjob = jp;
898 }
899 if (sp->status == -1)
900 stopped = 0;
901 else if (WIFSTOPPED(sp->status))
902 done = 0;
903 }
904 if (stopped) { /* stopped or done */
905 int state = done? JOBDONE : JOBSTOPPED;
906 if (jp->state != state) {
907 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
908 jp->state = state;
909 #if JOBS
910 if (done && curjob == jp - jobtab + 1)
911 curjob = 0; /* no current job */
912 #endif
913 }
914 }
915 }
916 }
917 if (! rootshell || ! iflag || (job && thisjob == job)) {
918 core = WCOREDUMP(status);
919 #if JOBS
920 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
921 else
922 #endif
923 if (WIFEXITED(status)) sig = 0;
924 else sig = WTERMSIG(status);
925
926 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
927 if (thisjob != job)
928 outfmt(out2, "%d: ", pid);
929 #if JOBS
930 if (sig == SIGTSTP && rootshell && iflag)
931 outfmt(out2, "%%%ld ",
932 (long)(job - jobtab + 1));
933 #endif
934 if (sig < NSIG && sys_siglist[sig])
935 out2str(sys_siglist[sig]);
936 else
937 outfmt(out2, "Signal %d", sig);
938 if (core)
939 out2str(" - core dumped");
940 out2c('\n');
941 flushout(&errout);
942 } else {
943 TRACE(("Not printing status: status=%d, sig=%d\n",
944 status, sig));
945 }
946 } else {
947 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
948 if (thisjob)
949 thisjob->changed = 1;
950 }
951 INTON;
952 return pid;
953 }
954
955
956
957 /*
958 * Do a wait system call. If job control is compiled in, we accept
959 * stopped processes. If block is zero, we return a value of zero
960 * rather than blocking.
961 *
962 * System V doesn't have a non-blocking wait system call. It does
963 * have a SIGCLD signal that is sent to a process when one of it's
964 * children dies. The obvious way to use SIGCLD would be to install
965 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
966 * was received, and have waitproc bump another counter when it got
967 * the status of a process. Waitproc would then know that a wait
968 * system call would not block if the two counters were different.
969 * This approach doesn't work because if a process has children that
970 * have not been waited for, System V will send it a SIGCLD when it
971 * installs a signal handler for SIGCLD. What this means is that when
972 * a child exits, the shell will be sent SIGCLD signals continuously
973 * until is runs out of stack space, unless it does a wait call before
974 * restoring the signal handler. The code below takes advantage of
975 * this (mis)feature by installing a signal handler for SIGCLD and
976 * then checking to see whether it was called. If there are any
977 * children to be waited for, it will be.
978 *
979 * If neither SYSV nor BSD is defined, we don't implement nonblocking
980 * waits at all. In this case, the user will not be informed when
981 * a background process until the next time she runs a real program
982 * (as opposed to running a builtin command or just typing return),
983 * and the jobs command may give out of date information.
984 */
985
986 #ifdef SYSV
987 STATIC int gotsigchild;
988
989 STATIC int onsigchild() {
990 gotsigchild = 1;
991 }
992 #endif
993
994
995 STATIC int
996 waitproc(block, jp, status)
997 int block;
998 struct job *jp;
999 int *status;
1000 {
1001 #ifdef BSD
1002 int flags = 0;
1003
1004 #if JOBS
1005 if (jp != NULL && jp->jobctl)
1006 flags |= WUNTRACED;
1007 #endif
1008 if (block == 0)
1009 flags |= WNOHANG;
1010 return wait3(status, flags, (struct rusage *)NULL);
1011 #else
1012 #ifdef SYSV
1013 int (*save)();
1014
1015 if (block == 0) {
1016 gotsigchild = 0;
1017 save = signal(SIGCLD, onsigchild);
1018 signal(SIGCLD, save);
1019 if (gotsigchild == 0)
1020 return 0;
1021 }
1022 return wait(status);
1023 #else
1024 if (block == 0)
1025 return 0;
1026 return wait(status);
1027 #endif
1028 #endif
1029 }
1030
1031 /*
1032 * return 1 if there are stopped jobs, otherwise 0
1033 */
1034 int job_warning = 0;
1035 int
1036 stoppedjobs()
1037 {
1038 int jobno;
1039 struct job *jp;
1040
1041 if (job_warning)
1042 return (0);
1043 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1044 if (jp->used == 0)
1045 continue;
1046 if (jp->state == JOBSTOPPED) {
1047 out2str("You have stopped jobs.\n");
1048 job_warning = 2;
1049 return (1);
1050 }
1051 }
1052
1053 return (0);
1054 }
1055
1056 /*
1057 * Return a string identifying a command (to be printed by the
1058 * jobs command.
1059 */
1060
1061 STATIC char *cmdnextc;
1062 STATIC int cmdnleft;
1063 #define MAXCMDTEXT 200
1064
1065 char *
1066 commandtext(n)
1067 union node *n;
1068 {
1069 char *name;
1070
1071 cmdnextc = name = ckmalloc(MAXCMDTEXT);
1072 cmdnleft = MAXCMDTEXT - 4;
1073 cmdtxt(n);
1074 *cmdnextc = '\0';
1075 return name;
1076 }
1077
1078
1079 STATIC void
1080 cmdtxt(n)
1081 union node *n;
1082 {
1083 union node *np;
1084 struct nodelist *lp;
1085 const char *p;
1086 int i;
1087 char s[2];
1088
1089 if (n == NULL)
1090 return;
1091 switch (n->type) {
1092 case NSEMI:
1093 cmdtxt(n->nbinary.ch1);
1094 cmdputs("; ");
1095 cmdtxt(n->nbinary.ch2);
1096 break;
1097 case NAND:
1098 cmdtxt(n->nbinary.ch1);
1099 cmdputs(" && ");
1100 cmdtxt(n->nbinary.ch2);
1101 break;
1102 case NOR:
1103 cmdtxt(n->nbinary.ch1);
1104 cmdputs(" || ");
1105 cmdtxt(n->nbinary.ch2);
1106 break;
1107 case NPIPE:
1108 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1109 cmdtxt(lp->n);
1110 if (lp->next)
1111 cmdputs(" | ");
1112 }
1113 break;
1114 case NSUBSHELL:
1115 cmdputs("(");
1116 cmdtxt(n->nredir.n);
1117 cmdputs(")");
1118 break;
1119 case NREDIR:
1120 case NBACKGND:
1121 cmdtxt(n->nredir.n);
1122 break;
1123 case NIF:
1124 cmdputs("if ");
1125 cmdtxt(n->nif.test);
1126 cmdputs("; then ");
1127 cmdtxt(n->nif.ifpart);
1128 cmdputs("...");
1129 break;
1130 case NWHILE:
1131 cmdputs("while ");
1132 goto until;
1133 case NUNTIL:
1134 cmdputs("until ");
1135 until:
1136 cmdtxt(n->nbinary.ch1);
1137 cmdputs("; do ");
1138 cmdtxt(n->nbinary.ch2);
1139 cmdputs("; done");
1140 break;
1141 case NFOR:
1142 cmdputs("for ");
1143 cmdputs(n->nfor.var);
1144 cmdputs(" in ...");
1145 break;
1146 case NCASE:
1147 cmdputs("case ");
1148 cmdputs(n->ncase.expr->narg.text);
1149 cmdputs(" in ...");
1150 break;
1151 case NDEFUN:
1152 cmdputs(n->narg.text);
1153 cmdputs("() ...");
1154 break;
1155 case NCMD:
1156 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1157 cmdtxt(np);
1158 if (np->narg.next)
1159 cmdputs(" ");
1160 }
1161 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1162 cmdputs(" ");
1163 cmdtxt(np);
1164 }
1165 break;
1166 case NARG:
1167 cmdputs(n->narg.text);
1168 break;
1169 case NTO:
1170 p = ">"; i = 1; goto redir;
1171 case NCLOBBER:
1172 p = ">|"; i = 1; goto redir;
1173 case NAPPEND:
1174 p = ">>"; i = 1; goto redir;
1175 case NTOFD:
1176 p = ">&"; i = 1; goto redir;
1177 case NFROM:
1178 p = "<"; i = 0; goto redir;
1179 case NFROMFD:
1180 p = "<&"; i = 0; goto redir;
1181 case NFROMTO:
1182 p = "<>"; i = 0; goto redir;
1183 redir:
1184 if (n->nfile.fd != i) {
1185 s[0] = n->nfile.fd + '0';
1186 s[1] = '\0';
1187 cmdputs(s);
1188 }
1189 cmdputs(p);
1190 if (n->type == NTOFD || n->type == NFROMFD) {
1191 s[0] = n->ndup.dupfd + '0';
1192 s[1] = '\0';
1193 cmdputs(s);
1194 } else {
1195 cmdtxt(n->nfile.fname);
1196 }
1197 break;
1198 case NHERE:
1199 case NXHERE:
1200 cmdputs("<<...");
1201 break;
1202 default:
1203 cmdputs("???");
1204 break;
1205 }
1206 }
1207
1208
1209
1210 STATIC void
1211 cmdputs(s)
1212 const char *s;
1213 {
1214 const char *p;
1215 char *q;
1216 char c;
1217 int subtype = 0;
1218
1219 if (cmdnleft <= 0)
1220 return;
1221 p = s;
1222 q = cmdnextc;
1223 while ((c = *p++) != '\0') {
1224 if (c == CTLESC)
1225 *q++ = *p++;
1226 else if (c == CTLVAR) {
1227 *q++ = '$';
1228 if (--cmdnleft > 0)
1229 *q++ = '{';
1230 subtype = *p++;
1231 } else if (c == '=' && subtype != 0) {
1232 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1233 subtype = 0;
1234 } else if (c == CTLENDVAR) {
1235 *q++ = '}';
1236 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1237 cmdnleft++; /* ignore it */
1238 else
1239 *q++ = c;
1240 if (--cmdnleft <= 0) {
1241 *q++ = '.';
1242 *q++ = '.';
1243 *q++ = '.';
1244 break;
1245 }
1246 }
1247 cmdnextc = q;
1248 }
1249