jobs.c revision 1.98.4.1 1 /* $NetBSD: jobs.c,v 1.98.4.1 2019/06/10 21:41:03 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.98.4.1 2019/06/10 21:41:03 christos Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <stdlib.h>
50 #include <paths.h>
51 #include <sys/types.h>
52 #include <sys/param.h>
53 #ifdef BSD
54 #include <sys/wait.h>
55 #include <sys/time.h>
56 #include <sys/resource.h>
57 #endif
58 #include <sys/ioctl.h>
59
60 #include "shell.h"
61 #if JOBS
62 #if OLD_TTY_DRIVER
63 #include "sgtty.h"
64 #else
65 #include <termios.h>
66 #endif
67 #undef CEOF /* syntax.h redefines this */
68 #endif
69 #include "redir.h"
70 #include "show.h"
71 #include "main.h"
72 #include "parser.h"
73 #include "nodes.h"
74 #include "jobs.h"
75 #include "var.h"
76 #include "options.h"
77 #include "builtins.h"
78 #include "trap.h"
79 #include "syntax.h"
80 #include "input.h"
81 #include "output.h"
82 #include "memalloc.h"
83 #include "error.h"
84 #include "mystring.h"
85
86
87 #ifndef WCONTINUED
88 #define WCONTINUED 0 /* So we can compile on old systems */
89 #endif
90 #ifndef WIFCONTINUED
91 #define WIFCONTINUED(x) (0) /* ditto */
92 #endif
93
94
95 static struct job *jobtab; /* array of jobs */
96 static int njobs; /* size of array */
97 static int jobs_invalid; /* set in child */
98 MKINIT pid_t backgndpid = -1; /* pid of last background process */
99 #if JOBS
100 int initialpgrp; /* pgrp of shell on invocation */
101 static int curjob = -1; /* current job */
102 #endif
103 static int ttyfd = -1;
104
105 STATIC void restartjob(struct job *);
106 STATIC void freejob(struct job *);
107 STATIC struct job *getjob(const char *, int);
108 STATIC int dowait(int, struct job *, struct job **);
109 #define WBLOCK 1
110 #define WNOFREE 2
111 #define WSILENT 4
112 STATIC int jobstatus(const struct job *, int);
113 STATIC int waitproc(int, struct job *, int *);
114 STATIC void cmdtxt(union node *);
115 STATIC void cmdlist(union node *, int);
116 STATIC void cmdputs(const char *);
117 inline static void cmdputi(int);
118
119 #ifdef SYSV
120 STATIC int onsigchild(void);
121 #endif
122
123 #ifdef OLD_TTY_DRIVER
124 static pid_t tcgetpgrp(int fd);
125 static int tcsetpgrp(int fd, pid_t pgrp);
126
127 static pid_t
128 tcgetpgrp(int fd)
129 {
130 pid_t pgrp;
131 if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
132 return -1;
133 else
134 return pgrp;
135 }
136
137 static int
138 tcsetpgrp(int fd, pid_tpgrp)
139 {
140 return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
141 }
142 #endif
143
144 static void
145 ttyfd_change(int from, int to)
146 {
147 if (ttyfd == from)
148 ttyfd = to;
149 }
150
151 /*
152 * Turn job control on and off.
153 *
154 * Note: This code assumes that the third arg to ioctl is a character
155 * pointer, which is true on Berkeley systems but not System V. Since
156 * System V doesn't have job control yet, this isn't a problem now.
157 */
158
159 MKINIT int jobctl;
160
161 void
162 setjobctl(int on)
163 {
164 #ifdef OLD_TTY_DRIVER
165 int ldisc;
166 #endif
167
168 if (on == jobctl || rootshell == 0)
169 return;
170 if (on) {
171 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
172 int i;
173
174 if (ttyfd != -1)
175 sh_close(ttyfd);
176 if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
177 for (i = 0; i < 3; i++) {
178 if (isatty(i) && (ttyfd = dup(i)) != -1)
179 break;
180 }
181 if (i == 3)
182 goto out;
183 }
184 ttyfd = to_upper_fd(ttyfd); /* Move to a high fd */
185 register_sh_fd(ttyfd, ttyfd_change);
186 #else
187 out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
188 goto out;
189 #endif
190 do { /* while we are in the background */
191 if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
192 out:
193 out2str("sh: can't access tty; job control turned off\n");
194 mflag = 0;
195 return;
196 }
197 if (initialpgrp == -1)
198 initialpgrp = getpgrp();
199 else if (initialpgrp != getpgrp()) {
200 killpg(0, SIGTTIN);
201 continue;
202 }
203 } while (0);
204
205 #ifdef OLD_TTY_DRIVER
206 if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
207 || ldisc != NTTYDISC) {
208 out2str("sh: need new tty driver to run job control; job control turned off\n");
209 mflag = 0;
210 return;
211 }
212 #endif
213 setsignal(SIGTSTP, 0);
214 setsignal(SIGTTOU, 0);
215 setsignal(SIGTTIN, 0);
216 if (getpgrp() != rootpid && setpgid(0, rootpid) == -1)
217 error("Cannot set process group (%s) at %d",
218 strerror(errno), __LINE__);
219 if (tcsetpgrp(ttyfd, rootpid) == -1)
220 error("Cannot set tty process group (%s) at %d",
221 strerror(errno), __LINE__);
222 } else { /* turning job control off */
223 if (getpgrp() != initialpgrp && setpgid(0, initialpgrp) == -1)
224 error("Cannot set process group (%s) at %d",
225 strerror(errno), __LINE__);
226 if (tcsetpgrp(ttyfd, initialpgrp) == -1)
227 error("Cannot set tty process group (%s) at %d",
228 strerror(errno), __LINE__);
229 sh_close(ttyfd);
230 ttyfd = -1;
231 setsignal(SIGTSTP, 0);
232 setsignal(SIGTTOU, 0);
233 setsignal(SIGTTIN, 0);
234 }
235 jobctl = on;
236 }
237
238
239 #ifdef mkinit
240 INCLUDE <stdlib.h>
241
242 SHELLPROC {
243 backgndpid = -1;
244 #if JOBS
245 jobctl = 0;
246 #endif
247 }
248
249 #endif
250
251
252
253 #if JOBS
254 static int
255 do_fgcmd(const char *arg_ptr)
256 {
257 struct job *jp;
258 int i;
259 int status;
260
261 if (jobs_invalid)
262 error("No current jobs");
263 jp = getjob(arg_ptr, 0);
264 if (jp->jobctl == 0)
265 error("job not created under job control");
266 out1fmt("%s", jp->ps[0].cmd);
267 for (i = 1; i < jp->nprocs; i++)
268 out1fmt(" | %s", jp->ps[i].cmd );
269 out1c('\n');
270 flushall();
271
272 for (i = 0; i < jp->nprocs; i++)
273 if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
274 break;
275
276 if (i >= jp->nprocs) {
277 error("Cannot set tty process group (%s) at %d",
278 strerror(errno), __LINE__);
279 }
280 INTOFF;
281 restartjob(jp);
282 status = waitforjob(jp);
283 INTON;
284 return status;
285 }
286
287 int
288 fgcmd(int argc, char **argv)
289 {
290 nextopt("");
291 return do_fgcmd(*argptr);
292 }
293
294 int
295 fgcmd_percent(int argc, char **argv)
296 {
297 nextopt("");
298 return do_fgcmd(*argv);
299 }
300
301 static void
302 set_curjob(struct job *jp, int mode)
303 {
304 struct job *jp1, *jp2;
305 int i, ji;
306
307 ji = jp - jobtab;
308
309 /* first remove from list */
310 if (ji == curjob)
311 curjob = jp->prev_job;
312 else {
313 for (i = 0; i < njobs; i++) {
314 if (jobtab[i].prev_job != ji)
315 continue;
316 jobtab[i].prev_job = jp->prev_job;
317 break;
318 }
319 }
320
321 /* Then re-insert in correct position */
322 switch (mode) {
323 case 0: /* job being deleted */
324 jp->prev_job = -1;
325 break;
326 case 1: /* newly created job or backgrounded job,
327 put after all stopped jobs. */
328 if (curjob != -1 && jobtab[curjob].state == JOBSTOPPED) {
329 for (jp1 = jobtab + curjob; ; jp1 = jp2) {
330 if (jp1->prev_job == -1)
331 break;
332 jp2 = jobtab + jp1->prev_job;
333 if (jp2->state != JOBSTOPPED)
334 break;
335 }
336 jp->prev_job = jp1->prev_job;
337 jp1->prev_job = ji;
338 break;
339 }
340 /* FALLTHROUGH */
341 case 2: /* newly stopped job - becomes curjob */
342 jp->prev_job = curjob;
343 curjob = ji;
344 break;
345 }
346 }
347
348 int
349 bgcmd(int argc, char **argv)
350 {
351 struct job *jp;
352 int i;
353
354 nextopt("");
355 if (jobs_invalid)
356 error("No current jobs");
357 do {
358 jp = getjob(*argptr, 0);
359 if (jp->jobctl == 0)
360 error("job not created under job control");
361 set_curjob(jp, 1);
362 out1fmt("[%ld] %s", (long)(jp - jobtab + 1), jp->ps[0].cmd);
363 for (i = 1; i < jp->nprocs; i++)
364 out1fmt(" | %s", jp->ps[i].cmd );
365 out1c('\n');
366 flushall();
367 restartjob(jp);
368 } while (*argptr && *++argptr);
369 return 0;
370 }
371
372
373 STATIC void
374 restartjob(struct job *jp)
375 {
376 struct procstat *ps;
377 int i, e;
378
379 if (jp->state == JOBDONE)
380 return;
381 INTOFF;
382 for (e = i = 0; i < jp->nprocs; i++) {
383 if (killpg(jp->ps[i].pid, SIGCONT) != -1)
384 break;
385 if (e == 0 && errno != ESRCH)
386 e = errno;
387 }
388 if (i >= jp->nprocs)
389 error("Cannot continue job (%s)", strerror(e ? e : ESRCH));
390 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
391 if (WIFSTOPPED(ps->status)) {
392 VTRACE(DBG_JOBS, (
393 "restartjob: [%zu] pid %d status change"
394 " from %#x (stopped) to -1 (running)\n",
395 (size_t)(jp-jobtab+1), ps->pid, ps->status));
396 ps->status = -1;
397 jp->state = JOBRUNNING;
398 }
399 }
400 INTON;
401 }
402 #endif
403
404 inline static void
405 cmdputi(int n)
406 {
407 char str[20];
408
409 fmtstr(str, sizeof str, "%d", n);
410 cmdputs(str);
411 }
412
413 static void
414 showjob(struct output *out, struct job *jp, int mode)
415 {
416 int procno;
417 int st;
418 struct procstat *ps;
419 int col;
420 char s[64];
421
422 #if JOBS
423 if (mode & SHOW_PGID) {
424 /* just output process (group) id of pipeline */
425 outfmt(out, "%ld\n", (long)jp->ps->pid);
426 return;
427 }
428 #endif
429
430 procno = jp->nprocs;
431 if (!procno)
432 return;
433
434 if (mode & SHOW_PID)
435 mode |= SHOW_MULTILINE;
436
437 if ((procno > 1 && !(mode & SHOW_MULTILINE))
438 || (mode & SHOW_SIGNALLED)) {
439 /* See if we have more than one status to report */
440 ps = jp->ps;
441 st = ps->status;
442 do {
443 int st1 = ps->status;
444 if (st1 != st)
445 /* yes - need multi-line output */
446 mode |= SHOW_MULTILINE;
447 if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
448 continue;
449 if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
450 && st1 != SIGINT && st1 != SIGPIPE))
451 mode |= SHOW_ISSIG;
452
453 } while (ps++, --procno);
454 procno = jp->nprocs;
455 }
456
457 if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
458 if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
459 VTRACE(DBG_JOBS, ("showjob: freeing job %d\n",
460 jp - jobtab + 1));
461 freejob(jp);
462 }
463 return;
464 }
465
466 for (ps = jp->ps; --procno >= 0; ps++) { /* for each process */
467 if (ps == jp->ps)
468 fmtstr(s, 16, "[%ld] %c ",
469 (long)(jp - jobtab + 1),
470 #if JOBS
471 jp - jobtab == curjob ?
472 '+' :
473 curjob != -1 &&
474 jp - jobtab == jobtab[curjob].prev_job ?
475 '-' :
476 #endif
477 ' ');
478 else
479 fmtstr(s, 16, " " );
480 col = strlen(s);
481 if (mode & SHOW_PID) {
482 fmtstr(s + col, 16, "%ld ", (long)ps->pid);
483 col += strlen(s + col);
484 }
485 if (ps->status == -1) {
486 scopy("Running", s + col);
487 } else if (WIFEXITED(ps->status)) {
488 st = WEXITSTATUS(ps->status);
489 if (st)
490 fmtstr(s + col, 16, "Done(%d)", st);
491 else
492 fmtstr(s + col, 16, "Done");
493 } else {
494 #if JOBS
495 if (WIFSTOPPED(ps->status))
496 st = WSTOPSIG(ps->status);
497 else /* WIFSIGNALED(ps->status) */
498 #endif
499 st = WTERMSIG(ps->status);
500 scopyn(strsignal(st), s + col, 32);
501 if (WCOREDUMP(ps->status)) {
502 col += strlen(s + col);
503 scopyn(" (core dumped)", s + col, 64 - col);
504 }
505 }
506 col += strlen(s + col);
507 outstr(s, out);
508 do {
509 outc(' ', out);
510 col++;
511 } while (col < 30);
512 outstr(ps->cmd, out);
513 if (mode & SHOW_MULTILINE) {
514 if (procno > 0) {
515 outc(' ', out);
516 outc('|', out);
517 }
518 } else {
519 while (--procno >= 0)
520 outfmt(out, " | %s", (++ps)->cmd );
521 }
522 outc('\n', out);
523 }
524 flushout(out);
525 jp->flags &= ~JOBCHANGED;
526 if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
527 freejob(jp);
528 }
529
530 int
531 jobscmd(int argc, char **argv)
532 {
533 int mode, m;
534
535 mode = 0;
536 while ((m = nextopt("lp")))
537 if (m == 'l')
538 mode = SHOW_PID;
539 else
540 mode = SHOW_PGID;
541
542 if (!iflag && !posix)
543 mode |= SHOW_NO_FREE;
544
545 if (*argptr) {
546 do
547 showjob(out1, getjob(*argptr,0), mode);
548 while (*++argptr);
549 } else
550 showjobs(out1, mode);
551 return 0;
552 }
553
554
555 /*
556 * Print a list of jobs. If "change" is nonzero, only print jobs whose
557 * statuses have changed since the last call to showjobs.
558 *
559 * If the shell is interrupted in the process of creating a job, the
560 * result may be a job structure containing zero processes. Such structures
561 * will be freed here.
562 */
563
564 void
565 showjobs(struct output *out, int mode)
566 {
567 int jobno;
568 struct job *jp;
569 int silent = 0, gotpid;
570
571 CTRACE(DBG_JOBS, ("showjobs(%x) called\n", mode));
572
573 /* If not even one one job changed, there is nothing to do */
574 gotpid = dowait(WSILENT, NULL, NULL);
575 while (dowait(WSILENT, NULL, NULL) > 0)
576 continue;
577 #ifdef JOBS
578 /*
579 * Check if we are not in our foreground group, and if not
580 * put us in it.
581 */
582 if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
583 if (tcsetpgrp(ttyfd, getpid()) == -1)
584 error("Cannot set tty process group (%s) at %d",
585 strerror(errno), __LINE__);
586 VTRACE(DBG_JOBS|DBG_INPUT, ("repaired tty process group\n"));
587 silent = 1;
588 }
589 #endif
590
591 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
592 if (!jp->used)
593 continue;
594 if (jp->nprocs == 0) {
595 if (!jobs_invalid)
596 freejob(jp);
597 continue;
598 }
599 if ((mode & SHOW_CHANGED) && !(jp->flags & JOBCHANGED))
600 continue;
601 if (silent && (jp->flags & JOBCHANGED)) {
602 jp->flags &= ~JOBCHANGED;
603 continue;
604 }
605 showjob(out, jp, mode);
606 }
607 }
608
609 /*
610 * Mark a job structure as unused.
611 */
612
613 STATIC void
614 freejob(struct job *jp)
615 {
616 INTOFF;
617 if (jp->ps != &jp->ps0) {
618 ckfree(jp->ps);
619 jp->ps = &jp->ps0;
620 }
621 jp->nprocs = 0;
622 jp->used = 0;
623 #if JOBS
624 set_curjob(jp, 0);
625 #endif
626 INTON;
627 }
628
629 /*
630 * Extract the status of a completed job (for $?)
631 */
632 STATIC int
633 jobstatus(const struct job *jp, int raw)
634 {
635 int status = 0;
636 int retval;
637
638 if ((jp->flags & JPIPEFAIL) && jp->nprocs) {
639 int i;
640
641 for (i = 0; i < jp->nprocs; i++)
642 if (jp->ps[i].status != 0)
643 status = jp->ps[i].status;
644 } else
645 status = jp->ps[jp->nprocs ? jp->nprocs - 1 : 0].status;
646
647 if (raw)
648 return status;
649
650 if (WIFEXITED(status))
651 retval = WEXITSTATUS(status);
652 #if JOBS
653 else if (WIFSTOPPED(status))
654 retval = WSTOPSIG(status) + 128;
655 #endif
656 else {
657 /* XXX: limits number of signals */
658 retval = WTERMSIG(status) + 128;
659 }
660
661 return retval;
662 }
663
664
665
666 int
667 waitcmd(int argc, char **argv)
668 {
669 struct job *job, *last;
670 int retval;
671 struct job *jp;
672 int i;
673 int any = 0;
674 int found;
675 char *pid = NULL, *fpid;
676 char **arg;
677 char idstring[20];
678
679 while ((i = nextopt("np:")) != '\0') {
680 switch (i) {
681 case 'n':
682 any = 1;
683 break;
684 case 'p':
685 if (pid)
686 error("more than one -p unsupported");
687 pid = optionarg;
688 break;
689 }
690 }
691
692 if (pid != NULL) {
693 if (!validname(pid, '\0', NULL))
694 error("invalid name: -p '%s'", pid);
695 if (unsetvar(pid, 0))
696 error("%s readonly", pid);
697 }
698
699 /*
700 * If we have forked, and not yet created any new jobs, then
701 * we have no children, whatever jobtab claims,
702 * so simply return in that case.
703 *
704 * The return code is 127 if we had any pid args (none are found)
705 * or if we had -n (nothing exited), but 0 for plain old "wait".
706 */
707 if (jobs_invalid) {
708 CTRACE(DBG_WAIT, ("builtin wait%s%s in child, invalid jobtab\n",
709 any ? " -n" : "", *argptr ? " pid..." : ""));
710 return (any || *argptr) ? 127 : 0;
711 }
712
713 /*
714 * clear stray flags left from previous waitcmd
715 * or set them instead if anything will do ("wait -n")
716 */
717 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
718 if (any && *argptr == NULL)
719 jp->flags |= JOBWANTED;
720 else
721 jp->flags &= ~JOBWANTED;
722 jp->ref = NULL;
723 }
724
725 CTRACE(DBG_WAIT,
726 ("builtin wait%s%s\n", any ? " -n" : "", *argptr ? " pid..." : ""));
727
728 /*
729 * First, validate the jobnum args, count how many refer to
730 * (different) running jobs, and if we had -n, and found that one has
731 * already finished, we return that one. Otherwise remember
732 * which ones we are looking for (JOBWANTED).
733 */
734 found = 0;
735 last = NULL;
736 for (arg = argptr; *arg; arg++) {
737 last = jp = getjob(*arg, 1);
738 if (!jp)
739 continue;
740 if (jp->ref == NULL)
741 jp->ref = *arg;
742 if (any && jp->state == JOBDONE) {
743 /*
744 * We just want any of them, and this one is
745 * ready for consumption, bon apetit ...
746 */
747 retval = jobstatus(jp, 0);
748 if (pid)
749 setvar(pid, *arg, 0);
750 if (!iflag)
751 freejob(jp);
752 CTRACE(DBG_WAIT, ("wait -n found %s already done: %d\n", *arg, retval));
753 return retval;
754 }
755 if (!(jp->flags & JOBWANTED)) {
756 /*
757 * It is possible to list the same job several
758 * times - the obvious "wait 1 1 1" or
759 * "wait %% %2 102" where job 2 is current and pid 102
760 * However many times it is requested, it is found once.
761 */
762 found++;
763 jp->flags |= JOBWANTED;
764 }
765 job = jp;
766 }
767
768 VTRACE(DBG_WAIT, ("wait %s%s%sfound %d candidates (last %s)\n",
769 any ? "-n " : "", *argptr ? *argptr : "",
770 argptr[0] && argptr[1] ? "... " : " ", found,
771 job ? (job->ref ? job->ref : "<no-arg>") : "none"));
772
773 /*
774 * If we were given a list of jobnums:
775 * and none of those exist, then we're done.
776 */
777 if (*argptr && found == 0)
778 return 127;
779
780 /*
781 * Otherwise we need to wait for something to complete
782 * When it does, we check and see if it is one of the
783 * jobs we're waiting on, and if so, we clean it up.
784 * If we had -n, then we're done, otherwise we do it all again
785 * until all we had listed are done, of if there were no
786 * jobnum args, all are done.
787 */
788
789 retval = any || *argptr ? 127 : 0;
790 fpid = NULL;
791 for (;;) {
792 VTRACE(DBG_WAIT, ("wait waiting (%d remain): ", found));
793 job = NULL;
794 for (jp = jobtab, i = njobs; --i >= 0; jp++) {
795 if (jp->used && jp->flags & JOBWANTED &&
796 jp->state == JOBDONE) {
797 job = jp;
798 break;
799 }
800 if (jp->used && jp->state == JOBRUNNING)
801 job = jp;
802 }
803 if (i < 0 && job == NULL) {
804 CTRACE(DBG_WAIT, ("nothing running (ret: %d) fpid %s\n",
805 retval, fpid ? fpid : "unset"));
806 if (pid && fpid)
807 setvar(pid, fpid, 0);
808 return retval;
809 }
810 jp = job;
811 VTRACE(DBG_WAIT, ("found @%d/%d state: %d\n", njobs-i, njobs,
812 jp->state));
813
814 /*
815 * There is at least 1 job running, so we can
816 * safely wait() for something to exit.
817 */
818 if (jp->state == JOBRUNNING) {
819 job = NULL;
820 if ((i = dowait(WBLOCK|WNOFREE, NULL, &job)) == -1)
821 return 128 + lastsig();
822
823 /*
824 * one of the job's processes exited,
825 * but there are more
826 */
827 if (job->state == JOBRUNNING)
828 continue;
829 } else
830 job = jp; /* we want this, and it is done */
831
832 if (job->flags & JOBWANTED) {
833 int rv;
834
835 job->flags &= ~JOBWANTED; /* got it */
836 rv = jobstatus(job, 0);
837 VTRACE(DBG_WAIT, (
838 "wanted %d (%s) done: st=%d", i,
839 job->ref ? job->ref : "", rv));
840 if (any || job == last) {
841 retval = rv;
842 fpid = job->ref;
843
844 VTRACE(DBG_WAIT, (" save"));
845 if (pid) {
846 /*
847 * don't need fpid unless we are going
848 * to return it.
849 */
850 if (fpid == NULL) {
851 /*
852 * this only happens with "wait -n"
853 * (that is, no pid args)
854 */
855 snprintf(idstring, sizeof idstring,
856 "%d", job->ps[ job->nprocs ?
857 job->nprocs-1 :
858 0 ].pid);
859 fpid = idstring;
860 }
861 VTRACE(DBG_WAIT, (" (for %s)", fpid));
862 }
863 }
864
865 if (job->state == JOBDONE) {
866 VTRACE(DBG_WAIT, (" free"));
867 freejob(job);
868 }
869
870 if (any || (found > 0 && --found == 0)) {
871 if (pid && fpid)
872 setvar(pid, fpid, 0);
873 VTRACE(DBG_WAIT, (" return %d\n", retval));
874 return retval;
875 }
876 VTRACE(DBG_WAIT, ("\n"));
877 continue;
878 }
879
880 /* this is to handle "wait" (no args) */
881 if (found == 0 && job->state == JOBDONE) {
882 VTRACE(DBG_JOBS|DBG_WAIT, ("Cleanup: %d\n", i));
883 freejob(job);
884 }
885 }
886 }
887
888
889 int
890 jobidcmd(int argc, char **argv)
891 {
892 struct job *jp;
893 int i;
894 int pg = 0, onep = 0, job = 0;
895
896 while ((i = nextopt("gjp"))) {
897 switch (i) {
898 case 'g': pg = 1; break;
899 case 'j': job = 1; break;
900 case 'p': onep = 1; break;
901 }
902 }
903 CTRACE(DBG_JOBS, ("jobidcmd%s%s%s%s %s\n", pg ? " -g" : "",
904 onep ? " -p" : "", job ? " -j" : "", jobs_invalid ? " [inv]" : "",
905 *argptr ? *argptr : "<implicit %%>"));
906 if (pg + onep + job > 1)
907 error("-g -j and -p options cannot be combined");
908
909 if (argptr[0] && argptr[1])
910 error("usage: jobid [-g|-p|-r] jobid");
911
912 jp = getjob(*argptr, 0);
913 if (job) {
914 out1fmt("%%%zu\n", (size_t)(jp - jobtab + 1));
915 return 0;
916 }
917 if (pg) {
918 if (jp->pgrp != 0) {
919 out1fmt("%ld\n", (long)jp->pgrp);
920 return 0;
921 }
922 return 1;
923 }
924 if (onep) {
925 i = jp->nprocs - 1;
926 if (i < 0)
927 return 1;
928 out1fmt("%ld\n", (long)jp->ps[i].pid);
929 return 0;
930 }
931 for (i = 0 ; i < jp->nprocs ; ) {
932 out1fmt("%ld", (long)jp->ps[i].pid);
933 out1c(++i < jp->nprocs ? ' ' : '\n');
934 }
935 return 0;
936 }
937
938 int
939 getjobpgrp(const char *name)
940 {
941 struct job *jp;
942
943 if (jobs_invalid)
944 error("No such job: %s", name);
945 jp = getjob(name, 1);
946 if (jp == 0)
947 return 0;
948 return -jp->ps[0].pid;
949 }
950
951 /*
952 * Convert a job name to a job structure.
953 */
954
955 STATIC struct job *
956 getjob(const char *name, int noerror)
957 {
958 int jobno = -1;
959 struct job *jp;
960 int pid;
961 int i;
962 const char *err_msg = "No such job: %s";
963
964 if (name == NULL) {
965 #if JOBS
966 jobno = curjob;
967 #endif
968 err_msg = "No current job";
969 } else if (name[0] == '%') {
970 if (is_number(name + 1)) {
971 jobno = number(name + 1) - 1;
972 } else if (!name[1] || !name[2]) {
973 switch (name[1]) {
974 #if JOBS
975 case 0:
976 case '+':
977 case '%':
978 jobno = curjob;
979 err_msg = "No current job";
980 break;
981 case '-':
982 jobno = curjob;
983 if (jobno != -1)
984 jobno = jobtab[jobno].prev_job;
985 err_msg = "No previous job";
986 break;
987 #endif
988 default:
989 goto check_pattern;
990 }
991 } else {
992 struct job *found;
993 check_pattern:
994 found = NULL;
995 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
996 if (!jp->used || jp->nprocs <= 0)
997 continue;
998 if ((name[1] == '?'
999 && strstr(jp->ps[0].cmd, name + 2))
1000 || prefix(name + 1, jp->ps[0].cmd)) {
1001 if (found) {
1002 err_msg = "%s: ambiguous";
1003 found = 0;
1004 break;
1005 }
1006 found = jp;
1007 }
1008 }
1009 if (found)
1010 return found;
1011 }
1012
1013 } else if (is_number(name)) {
1014 pid = number(name);
1015 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
1016 if (jp->used && jp->nprocs > 0
1017 && jp->ps[jp->nprocs - 1].pid == pid)
1018 return jp;
1019 }
1020 }
1021
1022 if (jobno >= 0 && jobno < njobs) {
1023 jp = jobtab + jobno;
1024 if (jp->used)
1025 return jp;
1026 }
1027 if (!noerror)
1028 error(err_msg, name);
1029 return 0;
1030 }
1031
1032
1033
1034 /*
1035 * Return a new job structure,
1036 */
1037
1038 struct job *
1039 makejob(union node *node, int nprocs)
1040 {
1041 int i;
1042 struct job *jp;
1043
1044 if (jobs_invalid) {
1045 for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
1046 if (jp->used)
1047 freejob(jp);
1048 }
1049 jobs_invalid = 0;
1050 }
1051
1052 for (i = njobs, jp = jobtab ; ; jp++) {
1053 if (--i < 0) {
1054 INTOFF;
1055 if (njobs == 0) {
1056 jobtab = ckmalloc(4 * sizeof jobtab[0]);
1057 } else {
1058 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
1059 memcpy(jp, jobtab, njobs * sizeof jp[0]);
1060 /* Relocate `ps' pointers */
1061 for (i = 0; i < njobs; i++)
1062 if (jp[i].ps == &jobtab[i].ps0)
1063 jp[i].ps = &jp[i].ps0;
1064 ckfree(jobtab);
1065 jobtab = jp;
1066 }
1067 jp = jobtab + njobs;
1068 for (i = 4 ; --i >= 0 ; njobs++) {
1069 jobtab[njobs].used = 0;
1070 jobtab[njobs].prev_job = -1;
1071 }
1072 INTON;
1073 break;
1074 }
1075 if (jp->used == 0)
1076 break;
1077 }
1078 INTOFF;
1079 jp->state = JOBRUNNING;
1080 jp->used = 1;
1081 jp->flags = pipefail ? JPIPEFAIL : 0;
1082 jp->nprocs = 0;
1083 jp->pgrp = 0;
1084 #if JOBS
1085 jp->jobctl = jobctl;
1086 set_curjob(jp, 1);
1087 #endif
1088 if (nprocs > 1) {
1089 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
1090 } else {
1091 jp->ps = &jp->ps0;
1092 }
1093 INTON;
1094 VTRACE(DBG_JOBS, ("makejob(%p, %d)%s returns %%%d\n", (void *)node,
1095 nprocs, (jp->flags&JPIPEFAIL)?" PF":"", jp - jobtab + 1));
1096 return jp;
1097 }
1098
1099
1100 /*
1101 * Fork off a subshell. If we are doing job control, give the subshell its
1102 * own process group. Jp is a job structure that the job is to be added to.
1103 * N is the command that will be evaluated by the child. Both jp and n may
1104 * be NULL. The mode parameter can be one of the following:
1105 * FORK_FG - Fork off a foreground process.
1106 * FORK_BG - Fork off a background process.
1107 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
1108 * process group even if job control is on.
1109 *
1110 * When job control is turned off, background processes have their standard
1111 * input redirected to /dev/null (except for the second and later processes
1112 * in a pipeline).
1113 */
1114
1115 int
1116 forkshell(struct job *jp, union node *n, int mode)
1117 {
1118 pid_t pid;
1119 int serrno;
1120
1121 CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
1122 jp - jobtab, n, mode));
1123
1124 switch ((pid = fork())) {
1125 case -1:
1126 serrno = errno;
1127 VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
1128 error("Cannot fork (%s)", strerror(serrno));
1129 break;
1130 case 0:
1131 SHELL_FORKED();
1132 forkchild(jp, n, mode, 0);
1133 return 0;
1134 default:
1135 return forkparent(jp, n, mode, pid);
1136 }
1137 }
1138
1139 int
1140 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
1141 {
1142 int pgrp;
1143
1144 if (rootshell && mode != FORK_NOJOB && mflag) {
1145 if (jp == NULL || jp->nprocs == 0)
1146 pgrp = pid;
1147 else
1148 pgrp = jp->ps[0].pid;
1149 jp->pgrp = pgrp;
1150 /* This can fail because we are doing it in the child also */
1151 (void)setpgid(pid, pgrp);
1152 }
1153 if (mode == FORK_BG)
1154 backgndpid = pid; /* set $! */
1155 if (jp) {
1156 struct procstat *ps = &jp->ps[jp->nprocs++];
1157 ps->pid = pid;
1158 ps->status = -1;
1159 ps->cmd[0] = 0;
1160 if (/* iflag && rootshell && */ n)
1161 commandtext(ps, n);
1162 }
1163 CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
1164 return pid;
1165 }
1166
1167 void
1168 forkchild(struct job *jp, union node *n, int mode, int vforked)
1169 {
1170 int wasroot;
1171 int pgrp;
1172 const char *devnull = _PATH_DEVNULL;
1173 const char *nullerr = "Can't open %s";
1174
1175 wasroot = rootshell;
1176 CTRACE(DBG_JOBS, ("Child shell %d %sforked from %d (mode %d)\n",
1177 getpid(), vforked?"v":"", getppid(), mode));
1178
1179 if (!vforked) {
1180 rootshell = 0;
1181 handler = &main_handler;
1182 }
1183
1184 closescript(vforked);
1185 clear_traps(vforked);
1186 #if JOBS
1187 if (!vforked)
1188 jobctl = 0; /* do job control only in root shell */
1189 if (wasroot && mode != FORK_NOJOB && mflag) {
1190 if (jp == NULL || jp->nprocs == 0)
1191 pgrp = getpid();
1192 else
1193 pgrp = jp->ps[0].pid;
1194 /* This can fail because we are doing it in the parent also */
1195 (void)setpgid(0, pgrp);
1196 if (mode == FORK_FG) {
1197 if (tcsetpgrp(ttyfd, pgrp) == -1)
1198 error("Cannot set tty process group (%s) at %d",
1199 strerror(errno), __LINE__);
1200 }
1201 setsignal(SIGTSTP, vforked);
1202 setsignal(SIGTTOU, vforked);
1203 } else if (mode == FORK_BG) {
1204 ignoresig(SIGINT, vforked);
1205 ignoresig(SIGQUIT, vforked);
1206 if ((jp == NULL || jp->nprocs == 0) &&
1207 ! fd0_redirected_p ()) {
1208 close(0);
1209 if (open(devnull, O_RDONLY) != 0)
1210 error(nullerr, devnull);
1211 }
1212 }
1213 #else
1214 if (mode == FORK_BG) {
1215 ignoresig(SIGINT, vforked);
1216 ignoresig(SIGQUIT, vforked);
1217 if ((jp == NULL || jp->nprocs == 0) &&
1218 ! fd0_redirected_p ()) {
1219 close(0);
1220 if (open(devnull, O_RDONLY) != 0)
1221 error(nullerr, devnull);
1222 }
1223 }
1224 #endif
1225 if (wasroot && iflag) {
1226 setsignal(SIGINT, vforked);
1227 setsignal(SIGQUIT, vforked);
1228 setsignal(SIGTERM, vforked);
1229 }
1230
1231 if (!vforked)
1232 jobs_invalid = 1;
1233 }
1234
1235 /*
1236 * Wait for job to finish.
1237 *
1238 * Under job control we have the problem that while a child process is
1239 * running interrupts generated by the user are sent to the child but not
1240 * to the shell. This means that an infinite loop started by an inter-
1241 * active user may be hard to kill. With job control turned off, an
1242 * interactive user may place an interactive program inside a loop. If
1243 * the interactive program catches interrupts, the user doesn't want
1244 * these interrupts to also abort the loop. The approach we take here
1245 * is to have the shell ignore interrupt signals while waiting for a
1246 * forground process to terminate, and then send itself an interrupt
1247 * signal if the child process was terminated by an interrupt signal.
1248 * Unfortunately, some programs want to do a bit of cleanup and then
1249 * exit on interrupt; unless these processes terminate themselves by
1250 * sending a signal to themselves (instead of calling exit) they will
1251 * confuse this approach.
1252 */
1253
1254 int
1255 waitforjob(struct job *jp)
1256 {
1257 #if JOBS
1258 int mypgrp = getpgrp();
1259 #endif
1260 int status;
1261 int st;
1262
1263 INTOFF;
1264 VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", jp - jobtab + 1));
1265 while (jp->state == JOBRUNNING) {
1266 dowait(WBLOCK, jp, NULL);
1267 }
1268 #if JOBS
1269 if (jp->jobctl) {
1270 if (tcsetpgrp(ttyfd, mypgrp) == -1)
1271 error("Cannot set tty process group (%s) at %d",
1272 strerror(errno), __LINE__);
1273 }
1274 if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
1275 set_curjob(jp, 2);
1276 #endif
1277 status = jobstatus(jp, 1);
1278
1279 /* convert to 8 bits */
1280 if (WIFEXITED(status))
1281 st = WEXITSTATUS(status);
1282 #if JOBS
1283 else if (WIFSTOPPED(status))
1284 st = WSTOPSIG(status) + 128;
1285 #endif
1286 else
1287 st = WTERMSIG(status) + 128;
1288
1289 VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
1290 jp - jobtab + 1, jp->nprocs, status, st));
1291 #if JOBS
1292 if (jp->jobctl) {
1293 /*
1294 * This is truly gross.
1295 * If we're doing job control, then we did a TIOCSPGRP which
1296 * caused us (the shell) to no longer be in the controlling
1297 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
1298 * intuit from the subprocess exit status whether a SIGINT
1299 * occurred, and if so interrupt ourselves. Yuck. - mycroft
1300 */
1301 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1302 raise(SIGINT);
1303 }
1304 #endif
1305 if (! JOBS || jp->state == JOBDONE)
1306 freejob(jp);
1307 INTON;
1308 return st;
1309 }
1310
1311
1312
1313 /*
1314 * Wait for a process to terminate.
1315 */
1316
1317 STATIC int
1318 dowait(int flags, struct job *job, struct job **changed)
1319 {
1320 int pid;
1321 int status;
1322 struct procstat *sp;
1323 struct job *jp;
1324 struct job *thisjob;
1325 int done;
1326 int stopped;
1327
1328 VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called\n", flags));
1329
1330 if (changed != NULL)
1331 *changed = NULL;
1332
1333 do {
1334 pid = waitproc(flags & WBLOCK, job, &status);
1335 VTRACE(DBG_JOBS|DBG_PROCS, ("wait returns pid %d, status %#x\n",
1336 pid, status));
1337 } while (pid == -1 && errno == EINTR && pendingsigs == 0);
1338 if (pid <= 0)
1339 return pid;
1340 INTOFF;
1341 thisjob = NULL;
1342 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1343 if (jp->used) {
1344 done = 1;
1345 stopped = 1;
1346 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1347 if (sp->pid == -1)
1348 continue;
1349 if (sp->pid == pid &&
1350 (sp->status==-1 || WIFSTOPPED(sp->status))) {
1351 VTRACE(DBG_JOBS | DBG_PROCS,
1352 ("Job %d: changing status of proc %d from %#x to %#x\n",
1353 jp - jobtab + 1, pid,
1354 sp->status, status));
1355 if (WIFCONTINUED(status)) {
1356 if (sp->status != -1)
1357 jp->flags |= JOBCHANGED;
1358 sp->status = -1;
1359 jp->state = 0;
1360 } else
1361 sp->status = status;
1362 thisjob = jp;
1363 if (changed != NULL)
1364 *changed = jp;
1365 }
1366 if (sp->status == -1)
1367 stopped = 0;
1368 else if (WIFSTOPPED(sp->status))
1369 done = 0;
1370 }
1371 if (stopped) { /* stopped or done */
1372 int state = done ? JOBDONE : JOBSTOPPED;
1373
1374 if (jp->state != state) {
1375 VTRACE(DBG_JOBS,
1376 ("Job %d: changing state from %d to %d\n",
1377 jp - jobtab + 1, jp->state, state));
1378 jp->state = state;
1379 #if JOBS
1380 if (done)
1381 set_curjob(jp, 0);
1382 #endif
1383 }
1384 }
1385 }
1386 }
1387
1388 if (thisjob &&
1389 (thisjob->state != JOBRUNNING || thisjob->flags & JOBCHANGED)) {
1390 int mode = 0;
1391
1392 if (!rootshell || !iflag)
1393 mode = SHOW_SIGNALLED;
1394 if ((job == thisjob && (flags & WNOFREE) == 0) ||
1395 job != thisjob)
1396 mode = SHOW_SIGNALLED | SHOW_NO_FREE;
1397 if (mode && (flags & WSILENT) == 0)
1398 showjob(out2, thisjob, mode);
1399 else {
1400 VTRACE(DBG_JOBS,
1401 ("Not printing status, rootshell=%d, job=%p\n",
1402 rootshell, job));
1403 thisjob->flags |= JOBCHANGED;
1404 }
1405 }
1406
1407 INTON;
1408 return pid;
1409 }
1410
1411
1412
1413 /*
1414 * Do a wait system call. If job control is compiled in, we accept
1415 * stopped processes. If block is zero, we return a value of zero
1416 * rather than blocking.
1417 *
1418 * System V doesn't have a non-blocking wait system call. It does
1419 * have a SIGCLD signal that is sent to a process when one of its
1420 * children dies. The obvious way to use SIGCLD would be to install
1421 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
1422 * was received, and have waitproc bump another counter when it got
1423 * the status of a process. Waitproc would then know that a wait
1424 * system call would not block if the two counters were different.
1425 * This approach doesn't work because if a process has children that
1426 * have not been waited for, System V will send it a SIGCLD when it
1427 * installs a signal handler for SIGCLD. What this means is that when
1428 * a child exits, the shell will be sent SIGCLD signals continuously
1429 * until is runs out of stack space, unless it does a wait call before
1430 * restoring the signal handler. The code below takes advantage of
1431 * this (mis)feature by installing a signal handler for SIGCLD and
1432 * then checking to see whether it was called. If there are any
1433 * children to be waited for, it will be.
1434 *
1435 * If neither SYSV nor BSD is defined, we don't implement nonblocking
1436 * waits at all. In this case, the user will not be informed when
1437 * a background process until the next time she runs a real program
1438 * (as opposed to running a builtin command or just typing return),
1439 * and the jobs command may give out of date information.
1440 */
1441
1442 #ifdef SYSV
1443 STATIC int gotsigchild;
1444
1445 STATIC int onsigchild() {
1446 gotsigchild = 1;
1447 }
1448 #endif
1449
1450
1451 STATIC int
1452 waitproc(int block, struct job *jp, int *status)
1453 {
1454 #ifdef BSD
1455 int flags = 0;
1456
1457 #if JOBS
1458 if (mflag || (jp != NULL && jp->jobctl))
1459 flags |= WUNTRACED | WCONTINUED;
1460 #endif
1461 if (block == 0)
1462 flags |= WNOHANG;
1463 VTRACE(DBG_WAIT, ("waitproc: doing waitpid(flags=%#x)\n", flags));
1464 return waitpid(-1, status, flags);
1465 #else
1466 #ifdef SYSV
1467 int (*save)();
1468
1469 if (block == 0) {
1470 gotsigchild = 0;
1471 save = signal(SIGCLD, onsigchild);
1472 signal(SIGCLD, save);
1473 if (gotsigchild == 0)
1474 return 0;
1475 }
1476 return wait(status);
1477 #else
1478 if (block == 0)
1479 return 0;
1480 return wait(status);
1481 #endif
1482 #endif
1483 }
1484
1485 /*
1486 * return 1 if there are stopped jobs, otherwise 0
1487 */
1488 int job_warning = 0;
1489 int
1490 stoppedjobs(void)
1491 {
1492 int jobno;
1493 struct job *jp;
1494
1495 if (job_warning || jobs_invalid)
1496 return (0);
1497 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1498 if (jp->used == 0)
1499 continue;
1500 if (jp->state == JOBSTOPPED) {
1501 out2str("You have stopped jobs.\n");
1502 job_warning = 2;
1503 return (1);
1504 }
1505 }
1506
1507 return (0);
1508 }
1509
1510 /*
1511 * Return a string identifying a command (to be printed by the
1512 * jobs command).
1513 */
1514
1515 STATIC char *cmdnextc;
1516 STATIC int cmdnleft;
1517
1518 void
1519 commandtext(struct procstat *ps, union node *n)
1520 {
1521 int len;
1522
1523 cmdnextc = ps->cmd;
1524 if (iflag || mflag || sizeof(ps->cmd) <= 60)
1525 len = sizeof(ps->cmd);
1526 else if (sizeof ps->cmd <= 400)
1527 len = 50;
1528 else if (sizeof ps->cmd <= 800)
1529 len = 80;
1530 else
1531 len = sizeof(ps->cmd) / 10;
1532 cmdnleft = len;
1533 cmdtxt(n);
1534 if (cmdnleft <= 0) {
1535 char *p = ps->cmd + len - 4;
1536 p[0] = '.';
1537 p[1] = '.';
1538 p[2] = '.';
1539 p[3] = 0;
1540 } else
1541 *cmdnextc = '\0';
1542
1543 VTRACE(DBG_JOBS,
1544 ("commandtext: ps->cmd %p, end %p, left %d\n\t\"%s\"\n",
1545 ps->cmd, cmdnextc, cmdnleft, ps->cmd));
1546 }
1547
1548
1549 STATIC void
1550 cmdtxt(union node *n)
1551 {
1552 union node *np;
1553 struct nodelist *lp;
1554 const char *p;
1555 int i;
1556
1557 if (n == NULL || cmdnleft <= 0)
1558 return;
1559 switch (n->type) {
1560 case NSEMI:
1561 cmdtxt(n->nbinary.ch1);
1562 cmdputs("; ");
1563 cmdtxt(n->nbinary.ch2);
1564 break;
1565 case NAND:
1566 cmdtxt(n->nbinary.ch1);
1567 cmdputs(" && ");
1568 cmdtxt(n->nbinary.ch2);
1569 break;
1570 case NOR:
1571 cmdtxt(n->nbinary.ch1);
1572 cmdputs(" || ");
1573 cmdtxt(n->nbinary.ch2);
1574 break;
1575 case NDNOT:
1576 cmdputs("! ");
1577 /* FALLTHROUGH */
1578 case NNOT:
1579 cmdputs("! ");
1580 cmdtxt(n->nnot.com);
1581 break;
1582 case NPIPE:
1583 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1584 cmdtxt(lp->n);
1585 if (lp->next)
1586 cmdputs(" | ");
1587 }
1588 if (n->npipe.backgnd)
1589 cmdputs(" &");
1590 break;
1591 case NSUBSHELL:
1592 cmdputs("(");
1593 cmdtxt(n->nredir.n);
1594 cmdputs(")");
1595 break;
1596 case NREDIR:
1597 case NBACKGND:
1598 cmdtxt(n->nredir.n);
1599 break;
1600 case NIF:
1601 cmdputs("if ");
1602 cmdtxt(n->nif.test);
1603 cmdputs("; then ");
1604 cmdtxt(n->nif.ifpart);
1605 if (n->nif.elsepart) {
1606 cmdputs("; else ");
1607 cmdtxt(n->nif.elsepart);
1608 }
1609 cmdputs("; fi");
1610 break;
1611 case NWHILE:
1612 cmdputs("while ");
1613 goto until;
1614 case NUNTIL:
1615 cmdputs("until ");
1616 until:
1617 cmdtxt(n->nbinary.ch1);
1618 cmdputs("; do ");
1619 cmdtxt(n->nbinary.ch2);
1620 cmdputs("; done");
1621 break;
1622 case NFOR:
1623 cmdputs("for ");
1624 cmdputs(n->nfor.var);
1625 cmdputs(" in ");
1626 cmdlist(n->nfor.args, 1);
1627 cmdputs("; do ");
1628 cmdtxt(n->nfor.body);
1629 cmdputs("; done");
1630 break;
1631 case NCASE:
1632 cmdputs("case ");
1633 cmdputs(n->ncase.expr->narg.text);
1634 cmdputs(" in ");
1635 for (np = n->ncase.cases; np; np = np->nclist.next) {
1636 cmdtxt(np->nclist.pattern);
1637 cmdputs(") ");
1638 cmdtxt(np->nclist.body);
1639 switch (n->type) { /* switch (not if) for later */
1640 case NCLISTCONT:
1641 cmdputs(";& ");
1642 break;
1643 default:
1644 cmdputs(";; ");
1645 break;
1646 }
1647 }
1648 cmdputs("esac");
1649 break;
1650 case NDEFUN:
1651 cmdputs(n->narg.text);
1652 cmdputs("() { ... }");
1653 break;
1654 case NCMD:
1655 cmdlist(n->ncmd.args, 1);
1656 cmdlist(n->ncmd.redirect, 0);
1657 if (n->ncmd.backgnd)
1658 cmdputs(" &");
1659 break;
1660 case NARG:
1661 cmdputs(n->narg.text);
1662 break;
1663 case NTO:
1664 p = ">"; i = 1; goto redir;
1665 case NCLOBBER:
1666 p = ">|"; i = 1; goto redir;
1667 case NAPPEND:
1668 p = ">>"; i = 1; goto redir;
1669 case NTOFD:
1670 p = ">&"; i = 1; goto redir;
1671 case NFROM:
1672 p = "<"; i = 0; goto redir;
1673 case NFROMFD:
1674 p = "<&"; i = 0; goto redir;
1675 case NFROMTO:
1676 p = "<>"; i = 0; goto redir;
1677 redir:
1678 if (n->nfile.fd != i)
1679 cmdputi(n->nfile.fd);
1680 cmdputs(p);
1681 if (n->type == NTOFD || n->type == NFROMFD) {
1682 if (n->ndup.dupfd < 0)
1683 cmdputs("-");
1684 else
1685 cmdputi(n->ndup.dupfd);
1686 } else {
1687 cmdtxt(n->nfile.fname);
1688 }
1689 break;
1690 case NHERE:
1691 case NXHERE:
1692 cmdputs("<<...");
1693 break;
1694 default:
1695 cmdputs("???");
1696 break;
1697 }
1698 }
1699
1700 STATIC void
1701 cmdlist(union node *np, int sep)
1702 {
1703 for (; np; np = np->narg.next) {
1704 if (!sep)
1705 cmdputs(" ");
1706 cmdtxt(np);
1707 if (sep && np->narg.next)
1708 cmdputs(" ");
1709 }
1710 }
1711
1712
1713 STATIC void
1714 cmdputs(const char *s)
1715 {
1716 const char *p, *str = 0;
1717 char c, cc[2] = " ";
1718 char *nextc;
1719 int nleft;
1720 int subtype = 0;
1721 int quoted = 0;
1722 static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
1723 "#", "##", "%", "%%", "}" };
1724
1725 p = s;
1726 nextc = cmdnextc;
1727 nleft = cmdnleft;
1728 while (nleft > 0 && (c = *p++) != 0) {
1729 switch (c) {
1730 case CTLNONL:
1731 c = '\0';
1732 break;
1733 case CTLESC:
1734 c = *p++;
1735 break;
1736 case CTLVAR:
1737 subtype = *p++;
1738 if (subtype & VSLINENO) { /* undo LINENO hack */
1739 if ((subtype & VSTYPE) == VSLENGTH)
1740 str = "${#LINENO"; /*}*/
1741 else
1742 str = "${LINENO"; /*}*/
1743 while (is_digit(*p))
1744 p++;
1745 } else if ((subtype & VSTYPE) == VSLENGTH)
1746 str = "${#"; /*}*/
1747 else
1748 str = "${"; /*}*/
1749 if (!(subtype & VSQUOTE) != !(quoted & 1)) {
1750 quoted ^= 1;
1751 c = '"';
1752 } else {
1753 c = *str++;
1754 }
1755 break;
1756 case CTLENDVAR: /*{*/
1757 c = '}';
1758 if (quoted & 1)
1759 str = "\"";
1760 quoted >>= 1;
1761 subtype = 0;
1762 break;
1763 case CTLBACKQ:
1764 c = '$';
1765 str = "(...)";
1766 break;
1767 case CTLBACKQ+CTLQUOTE:
1768 c = '"';
1769 str = "$(...)\"";
1770 break;
1771 case CTLARI:
1772 c = '$';
1773 if (*p == ' ')
1774 p++;
1775 str = "(("; /*))*/
1776 break;
1777 case CTLENDARI: /*((*/
1778 c = ')';
1779 str = ")";
1780 break;
1781 case CTLQUOTEMARK:
1782 quoted ^= 1;
1783 c = '"';
1784 break;
1785 case CTLQUOTEEND:
1786 quoted >>= 1;
1787 c = '"';
1788 break;
1789 case '=':
1790 if (subtype == 0)
1791 break;
1792 str = vstype[subtype & VSTYPE];
1793 if (subtype & VSNUL)
1794 c = ':';
1795 else
1796 c = *str++; /*{*/
1797 if (c != '}')
1798 quoted <<= 1;
1799 else if (*p == CTLENDVAR)
1800 c = *str++;
1801 subtype = 0;
1802 break;
1803 case '\'':
1804 case '\\':
1805 case '"':
1806 case '$':
1807 /* These can only happen inside quotes */
1808 cc[0] = c;
1809 str = cc;
1810 c = '\\';
1811 break;
1812 default:
1813 break;
1814 }
1815 if (c != '\0') do { /* c == 0 implies nothing in str */
1816 *nextc++ = c;
1817 } while (--nleft > 0 && str && (c = *str++));
1818 str = 0;
1819 }
1820 if ((quoted & 1) && nleft) {
1821 *nextc++ = '"';
1822 nleft--;
1823 }
1824 cmdnleft = nleft;
1825 cmdnextc = nextc;
1826 }
1827