VirtualBox

source: kBuild/trunk/src/kash/jobs.c@ 1202

Last change on this file since 1202 was 1202, checked in by bird, 17 years ago

Added psh parameter to the remaining global functions.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette