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