jobs.c revision 1.79.6.3 1 /* $NetBSD: jobs.c,v 1.79.6.3 2017/05/19 00:22:51 pgoyette 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.79.6.3 2017/05/19 00:22:51 pgoyette 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 SHELL_FORKED();
873 forkchild(jp, n, mode, 0);
874 return 0;
875 default:
876 return forkparent(jp, n, mode, pid);
877 }
878 }
879
880 int
881 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
882 {
883 int pgrp;
884
885 if (rootshell && mode != FORK_NOJOB && mflag) {
886 if (jp == NULL || jp->nprocs == 0)
887 pgrp = pid;
888 else
889 pgrp = jp->ps[0].pid;
890 /* This can fail because we are doing it in the child also */
891 (void)setpgid(pid, pgrp);
892 }
893 if (mode == FORK_BG)
894 backgndpid = pid; /* set $! */
895 if (jp) {
896 struct procstat *ps = &jp->ps[jp->nprocs++];
897 ps->pid = pid;
898 ps->status = -1;
899 ps->cmd[0] = 0;
900 if (/* iflag && rootshell && */ n)
901 commandtext(ps, n);
902 }
903 TRACE(("In parent shell: child = %d\n", pid));
904 return pid;
905 }
906
907 void
908 forkchild(struct job *jp, union node *n, int mode, int vforked)
909 {
910 int wasroot;
911 int pgrp;
912 const char *devnull = _PATH_DEVNULL;
913 const char *nullerr = "Can't open %s";
914
915 wasroot = rootshell;
916 TRACE(("Child shell %d\n", getpid()));
917 if (!vforked)
918 rootshell = 0;
919
920 closescript(vforked);
921 clear_traps(vforked);
922 #if JOBS
923 if (!vforked)
924 jobctl = 0; /* do job control only in root shell */
925 if (wasroot && mode != FORK_NOJOB && mflag) {
926 if (jp == NULL || jp->nprocs == 0)
927 pgrp = getpid();
928 else
929 pgrp = jp->ps[0].pid;
930 /* This can fail because we are doing it in the parent also */
931 (void)setpgid(0, pgrp);
932 if (mode == FORK_FG) {
933 if (tcsetpgrp(ttyfd, pgrp) == -1)
934 error("Cannot set tty process group (%s) at %d",
935 strerror(errno), __LINE__);
936 }
937 setsignal(SIGTSTP, vforked);
938 setsignal(SIGTTOU, vforked);
939 } else if (mode == FORK_BG) {
940 ignoresig(SIGINT, vforked);
941 ignoresig(SIGQUIT, vforked);
942 if ((jp == NULL || jp->nprocs == 0) &&
943 ! fd0_redirected_p ()) {
944 close(0);
945 if (open(devnull, O_RDONLY) != 0)
946 error(nullerr, devnull);
947 }
948 }
949 #else
950 if (mode == FORK_BG) {
951 ignoresig(SIGINT, vforked);
952 ignoresig(SIGQUIT, vforked);
953 if ((jp == NULL || jp->nprocs == 0) &&
954 ! fd0_redirected_p ()) {
955 close(0);
956 if (open(devnull, O_RDONLY) != 0)
957 error(nullerr, devnull);
958 }
959 }
960 #endif
961 if (wasroot && iflag) {
962 setsignal(SIGINT, vforked);
963 setsignal(SIGQUIT, vforked);
964 setsignal(SIGTERM, vforked);
965 }
966
967 if (!vforked)
968 jobs_invalid = 1;
969 }
970
971 /*
972 * Wait for job to finish.
973 *
974 * Under job control we have the problem that while a child process is
975 * running interrupts generated by the user are sent to the child but not
976 * to the shell. This means that an infinite loop started by an inter-
977 * active user may be hard to kill. With job control turned off, an
978 * interactive user may place an interactive program inside a loop. If
979 * the interactive program catches interrupts, the user doesn't want
980 * these interrupts to also abort the loop. The approach we take here
981 * is to have the shell ignore interrupt signals while waiting for a
982 * forground process to terminate, and then send itself an interrupt
983 * signal if the child process was terminated by an interrupt signal.
984 * Unfortunately, some programs want to do a bit of cleanup and then
985 * exit on interrupt; unless these processes terminate themselves by
986 * sending a signal to themselves (instead of calling exit) they will
987 * confuse this approach.
988 */
989
990 int
991 waitforjob(struct job *jp)
992 {
993 #if JOBS
994 int mypgrp = getpgrp();
995 #endif
996 int status;
997 int st;
998
999 INTOFF;
1000 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
1001 while (jp->state == JOBRUNNING) {
1002 dowait(WBLOCK, jp);
1003 }
1004 #if JOBS
1005 if (jp->jobctl) {
1006 if (tcsetpgrp(ttyfd, mypgrp) == -1)
1007 error("Cannot set tty process group (%s) at %d",
1008 strerror(errno), __LINE__);
1009 }
1010 if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
1011 set_curjob(jp, 2);
1012 #endif
1013 status = jp->ps[jp->nprocs - 1].status;
1014 /* convert to 8 bits */
1015 if (WIFEXITED(status))
1016 st = WEXITSTATUS(status);
1017 #if JOBS
1018 else if (WIFSTOPPED(status))
1019 st = WSTOPSIG(status) + 128;
1020 #endif
1021 else
1022 st = WTERMSIG(status) + 128;
1023 TRACE(("waitforjob: job %d, nproc %d, status %x, st %x\n",
1024 jp - jobtab + 1, jp->nprocs, status, st ));
1025 #if JOBS
1026 if (jp->jobctl) {
1027 /*
1028 * This is truly gross.
1029 * If we're doing job control, then we did a TIOCSPGRP which
1030 * caused us (the shell) to no longer be in the controlling
1031 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
1032 * intuit from the subprocess exit status whether a SIGINT
1033 * occurred, and if so interrupt ourselves. Yuck. - mycroft
1034 */
1035 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1036 raise(SIGINT);
1037 }
1038 #endif
1039 if (! JOBS || jp->state == JOBDONE)
1040 freejob(jp);
1041 INTON;
1042 return st;
1043 }
1044
1045
1046
1047 /*
1048 * Wait for a process to terminate.
1049 */
1050
1051 STATIC int
1052 dowait(int flags, struct job *job)
1053 {
1054 int pid;
1055 int status;
1056 struct procstat *sp;
1057 struct job *jp;
1058 struct job *thisjob;
1059 int done;
1060 int stopped;
1061
1062 TRACE(("dowait(%x) called\n", flags));
1063 do {
1064 pid = waitproc(flags & WBLOCK, job, &status);
1065 TRACE(("wait returns pid %d, status %d\n", pid, status));
1066 } while (pid == -1 && errno == EINTR && pendingsigs == 0);
1067 if (pid <= 0)
1068 return pid;
1069 INTOFF;
1070 thisjob = NULL;
1071 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1072 if (jp->used) {
1073 done = 1;
1074 stopped = 1;
1075 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1076 if (sp->pid == -1)
1077 continue;
1078 if (sp->pid == pid) {
1079 TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jp - jobtab + 1, pid, sp->status, status));
1080 sp->status = status;
1081 thisjob = jp;
1082 }
1083 if (sp->status == -1)
1084 stopped = 0;
1085 else if (WIFSTOPPED(sp->status))
1086 done = 0;
1087 }
1088 if (stopped) { /* stopped or done */
1089 int state = done ? JOBDONE : JOBSTOPPED;
1090 if (jp->state != state) {
1091 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1092 jp->state = state;
1093 #if JOBS
1094 if (done)
1095 set_curjob(jp, 0);
1096 #endif
1097 }
1098 }
1099 }
1100 }
1101
1102 if (thisjob && thisjob->state != JOBRUNNING) {
1103 int mode = 0;
1104 if (!rootshell || !iflag)
1105 mode = SHOW_SIGNALLED;
1106 if ((job == thisjob && (flags & WNOFREE) == 0) ||
1107 (job != thisjob && (flags & WNOFREE) != 0))
1108 mode = SHOW_SIGNALLED | SHOW_NO_FREE;
1109 if (mode)
1110 showjob(out2, thisjob, mode);
1111 else {
1112 TRACE(("Not printing status, rootshell=%d, job=%p\n",
1113 rootshell, job));
1114 thisjob->changed = 1;
1115 }
1116 }
1117
1118 INTON;
1119 return pid;
1120 }
1121
1122
1123
1124 /*
1125 * Do a wait system call. If job control is compiled in, we accept
1126 * stopped processes. If block is zero, we return a value of zero
1127 * rather than blocking.
1128 *
1129 * System V doesn't have a non-blocking wait system call. It does
1130 * have a SIGCLD signal that is sent to a process when one of its
1131 * children dies. The obvious way to use SIGCLD would be to install
1132 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
1133 * was received, and have waitproc bump another counter when it got
1134 * the status of a process. Waitproc would then know that a wait
1135 * system call would not block if the two counters were different.
1136 * This approach doesn't work because if a process has children that
1137 * have not been waited for, System V will send it a SIGCLD when it
1138 * installs a signal handler for SIGCLD. What this means is that when
1139 * a child exits, the shell will be sent SIGCLD signals continuously
1140 * until is runs out of stack space, unless it does a wait call before
1141 * restoring the signal handler. The code below takes advantage of
1142 * this (mis)feature by installing a signal handler for SIGCLD and
1143 * then checking to see whether it was called. If there are any
1144 * children to be waited for, it will be.
1145 *
1146 * If neither SYSV nor BSD is defined, we don't implement nonblocking
1147 * waits at all. In this case, the user will not be informed when
1148 * a background process until the next time she runs a real program
1149 * (as opposed to running a builtin command or just typing return),
1150 * and the jobs command may give out of date information.
1151 */
1152
1153 #ifdef SYSV
1154 STATIC int gotsigchild;
1155
1156 STATIC int onsigchild() {
1157 gotsigchild = 1;
1158 }
1159 #endif
1160
1161
1162 STATIC int
1163 waitproc(int block, struct job *jp, int *status)
1164 {
1165 #ifdef BSD
1166 int flags = 0;
1167
1168 #if JOBS
1169 if (jp != NULL && jp->jobctl)
1170 flags |= WUNTRACED;
1171 #endif
1172 if (block == 0)
1173 flags |= WNOHANG;
1174 return waitpid(-1, status, flags);
1175 #else
1176 #ifdef SYSV
1177 int (*save)();
1178
1179 if (block == 0) {
1180 gotsigchild = 0;
1181 save = signal(SIGCLD, onsigchild);
1182 signal(SIGCLD, save);
1183 if (gotsigchild == 0)
1184 return 0;
1185 }
1186 return wait(status);
1187 #else
1188 if (block == 0)
1189 return 0;
1190 return wait(status);
1191 #endif
1192 #endif
1193 }
1194
1195 /*
1196 * return 1 if there are stopped jobs, otherwise 0
1197 */
1198 int job_warning = 0;
1199 int
1200 stoppedjobs(void)
1201 {
1202 int jobno;
1203 struct job *jp;
1204
1205 if (job_warning || jobs_invalid)
1206 return (0);
1207 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1208 if (jp->used == 0)
1209 continue;
1210 if (jp->state == JOBSTOPPED) {
1211 out2str("You have stopped jobs.\n");
1212 job_warning = 2;
1213 return (1);
1214 }
1215 }
1216
1217 return (0);
1218 }
1219
1220 /*
1221 * Return a string identifying a command (to be printed by the
1222 * jobs command).
1223 */
1224
1225 STATIC char *cmdnextc;
1226 STATIC int cmdnleft;
1227
1228 void
1229 commandtext(struct procstat *ps, union node *n)
1230 {
1231 int len;
1232
1233 cmdnextc = ps->cmd;
1234 if (iflag || mflag || sizeof ps->cmd < 100)
1235 len = sizeof(ps->cmd);
1236 else
1237 len = sizeof(ps->cmd) / 10;
1238 cmdnleft = len;
1239 cmdtxt(n);
1240 if (cmdnleft <= 0) {
1241 char *p = ps->cmd + len - 4;
1242 p[0] = '.';
1243 p[1] = '.';
1244 p[2] = '.';
1245 p[3] = 0;
1246 } else
1247 *cmdnextc = '\0';
1248 TRACE(("commandtext: ps->cmd %x, end %x, left %d\n\t\"%s\"\n",
1249 ps->cmd, cmdnextc, cmdnleft, ps->cmd));
1250 }
1251
1252
1253 STATIC void
1254 cmdtxt(union node *n)
1255 {
1256 union node *np;
1257 struct nodelist *lp;
1258 const char *p;
1259 int i;
1260
1261 if (n == NULL || cmdnleft <= 0)
1262 return;
1263 switch (n->type) {
1264 case NSEMI:
1265 cmdtxt(n->nbinary.ch1);
1266 cmdputs("; ");
1267 cmdtxt(n->nbinary.ch2);
1268 break;
1269 case NAND:
1270 cmdtxt(n->nbinary.ch1);
1271 cmdputs(" && ");
1272 cmdtxt(n->nbinary.ch2);
1273 break;
1274 case NOR:
1275 cmdtxt(n->nbinary.ch1);
1276 cmdputs(" || ");
1277 cmdtxt(n->nbinary.ch2);
1278 break;
1279 case NDNOT:
1280 cmdputs("! ");
1281 /* FALLTHROUGH */
1282 case NNOT:
1283 cmdputs("! ");
1284 cmdtxt(n->nnot.com);
1285 break;
1286 case NPIPE:
1287 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1288 cmdtxt(lp->n);
1289 if (lp->next)
1290 cmdputs(" | ");
1291 }
1292 if (n->npipe.backgnd)
1293 cmdputs(" &");
1294 break;
1295 case NSUBSHELL:
1296 cmdputs("(");
1297 cmdtxt(n->nredir.n);
1298 cmdputs(")");
1299 break;
1300 case NREDIR:
1301 case NBACKGND:
1302 cmdtxt(n->nredir.n);
1303 break;
1304 case NIF:
1305 cmdputs("if ");
1306 cmdtxt(n->nif.test);
1307 cmdputs("; then ");
1308 cmdtxt(n->nif.ifpart);
1309 if (n->nif.elsepart) {
1310 cmdputs("; else ");
1311 cmdtxt(n->nif.elsepart);
1312 }
1313 cmdputs("; fi");
1314 break;
1315 case NWHILE:
1316 cmdputs("while ");
1317 goto until;
1318 case NUNTIL:
1319 cmdputs("until ");
1320 until:
1321 cmdtxt(n->nbinary.ch1);
1322 cmdputs("; do ");
1323 cmdtxt(n->nbinary.ch2);
1324 cmdputs("; done");
1325 break;
1326 case NFOR:
1327 cmdputs("for ");
1328 cmdputs(n->nfor.var);
1329 cmdputs(" in ");
1330 cmdlist(n->nfor.args, 1);
1331 cmdputs("; do ");
1332 cmdtxt(n->nfor.body);
1333 cmdputs("; done");
1334 break;
1335 case NCASE:
1336 cmdputs("case ");
1337 cmdputs(n->ncase.expr->narg.text);
1338 cmdputs(" in ");
1339 for (np = n->ncase.cases; np; np = np->nclist.next) {
1340 cmdtxt(np->nclist.pattern);
1341 cmdputs(") ");
1342 cmdtxt(np->nclist.body);
1343 switch (n->type) { /* switch (not if) for later */
1344 case NCLISTCONT:
1345 cmdputs(";& ");
1346 break;
1347 default:
1348 cmdputs(";; ");
1349 break;
1350 }
1351 }
1352 cmdputs("esac");
1353 break;
1354 case NDEFUN:
1355 cmdputs(n->narg.text);
1356 cmdputs("() { ... }");
1357 break;
1358 case NCMD:
1359 cmdlist(n->ncmd.args, 1);
1360 cmdlist(n->ncmd.redirect, 0);
1361 if (n->ncmd.backgnd)
1362 cmdputs(" &");
1363 break;
1364 case NARG:
1365 cmdputs(n->narg.text);
1366 break;
1367 case NTO:
1368 p = ">"; i = 1; goto redir;
1369 case NCLOBBER:
1370 p = ">|"; i = 1; goto redir;
1371 case NAPPEND:
1372 p = ">>"; i = 1; goto redir;
1373 case NTOFD:
1374 p = ">&"; i = 1; goto redir;
1375 case NFROM:
1376 p = "<"; i = 0; goto redir;
1377 case NFROMFD:
1378 p = "<&"; i = 0; goto redir;
1379 case NFROMTO:
1380 p = "<>"; i = 0; goto redir;
1381 redir:
1382 if (n->nfile.fd != i)
1383 cmdputi(n->nfile.fd);
1384 cmdputs(p);
1385 if (n->type == NTOFD || n->type == NFROMFD) {
1386 if (n->ndup.dupfd < 0)
1387 cmdputs("-");
1388 else
1389 cmdputi(n->ndup.dupfd);
1390 } else {
1391 cmdtxt(n->nfile.fname);
1392 }
1393 break;
1394 case NHERE:
1395 case NXHERE:
1396 cmdputs("<<...");
1397 break;
1398 default:
1399 cmdputs("???");
1400 break;
1401 }
1402 }
1403
1404 STATIC void
1405 cmdlist(union node *np, int sep)
1406 {
1407 for (; np; np = np->narg.next) {
1408 if (!sep)
1409 cmdputs(" ");
1410 cmdtxt(np);
1411 if (sep && np->narg.next)
1412 cmdputs(" ");
1413 }
1414 }
1415
1416
1417 STATIC void
1418 cmdputs(const char *s)
1419 {
1420 const char *p, *str = 0;
1421 char c, cc[2] = " ";
1422 char *nextc;
1423 int nleft;
1424 int subtype = 0;
1425 int quoted = 0;
1426 static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
1427 "#", "##", "%", "%%", "}" };
1428
1429 p = s;
1430 nextc = cmdnextc;
1431 nleft = cmdnleft;
1432 while (nleft > 0 && (c = *p++) != 0) {
1433 switch (c) {
1434 case CTLESC:
1435 c = *p++;
1436 break;
1437 case CTLVAR:
1438 subtype = *p++;
1439 if (subtype & VSLINENO) {
1440 if ((subtype & VSTYPE) == VSLENGTH)
1441 str = "${#LINENO";
1442 else
1443 str = "${LINENO";
1444 while (is_digit(*p))
1445 p++;
1446 } else if ((subtype & VSTYPE) == VSLENGTH)
1447 str = "${#";
1448 else
1449 str = "${";
1450 if (!(subtype & VSQUOTE) != !(quoted & 1)) {
1451 quoted ^= 1;
1452 c = '"';
1453 } else {
1454 c = *str++;
1455 }
1456 break;
1457 case CTLENDVAR:
1458 c = '}';
1459 if (quoted & 1)
1460 str = "\"";
1461 quoted >>= 1;
1462 subtype = 0;
1463 break;
1464 case CTLBACKQ:
1465 c = '$';
1466 str = "(...)";
1467 break;
1468 case CTLBACKQ+CTLQUOTE:
1469 c = '"';
1470 str = "$(...)\"";
1471 break;
1472 case CTLARI:
1473 c = '$';
1474 str = "((";
1475 break;
1476 case CTLENDARI:
1477 c = ')';
1478 str = ")";
1479 break;
1480 case CTLQUOTEMARK:
1481 quoted ^= 1;
1482 c = '"';
1483 break;
1484 case CTLQUOTEEND:
1485 quoted >>= 1;
1486 c = '"';
1487 break;
1488 case '=':
1489 if (subtype == 0)
1490 break;
1491 str = vstype[subtype & VSTYPE];
1492 if (subtype & VSNUL)
1493 c = ':';
1494 else
1495 c = *str++;
1496 if (c != '}')
1497 quoted <<= 1;
1498 else if (*p == CTLENDVAR)
1499 c = *str++;
1500 subtype = 0;
1501 break;
1502 case '\'':
1503 case '\\':
1504 case '"':
1505 case '$':
1506 /* These can only happen inside quotes */
1507 cc[0] = c;
1508 str = cc;
1509 c = '\\';
1510 break;
1511 default:
1512 break;
1513 }
1514 if (c != '\0') do { /* c == 0 implies nothing in str */
1515 *nextc++ = c;
1516 } while (--nleft > 0 && str && (c = *str++));
1517 str = 0;
1518 }
1519 if ((quoted & 1) && nleft) {
1520 *nextc++ = '"';
1521 nleft--;
1522 }
1523 cmdnleft = nleft;
1524 cmdnextc = nextc;
1525 }
1526