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