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