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