]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/sh/jobs.c
Remove support for the "old" tty driver by unifdef -UOLD_TTY_DRIVER;
[FreeBSD/FreeBSD.git] / bin / sh / jobs.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)jobs.c      8.5 (Berkeley) 5/4/95";
40 #endif
41 #endif /* not lint */
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <stdlib.h>
50 #include <sys/param.h>
51 #ifdef BSD
52 #include <sys/wait.h>
53 #include <sys/time.h>
54 #include <sys/resource.h>
55 #include <paths.h>
56 #endif
57 #include <sys/ioctl.h>
58
59 #include "shell.h"
60 #if JOBS
61 #include <termios.h>
62 #undef CEOF                     /* syntax.h redefines this */
63 #endif
64 #include "redir.h"
65 #include "show.h"
66 #include "main.h"
67 #include "parser.h"
68 #include "nodes.h"
69 #include "jobs.h"
70 #include "options.h"
71 #include "trap.h"
72 #include "syntax.h"
73 #include "input.h"
74 #include "output.h"
75 #include "memalloc.h"
76 #include "error.h"
77 #include "mystring.h"
78
79
80 struct job *jobtab;             /* array of jobs */
81 int njobs;                      /* size of array */
82 MKINIT pid_t backgndpid = -1;   /* pid of last background process */
83 #if JOBS
84 struct job *jobmru;             /* most recently used job list */
85 int initialpgrp;                /* pgrp of shell on invocation */
86 #endif
87 int in_waitcmd = 0;             /* are we in waitcmd()? */
88 int in_dowait = 0;              /* are we in dowait()? */
89 volatile sig_atomic_t breakwaitcmd = 0; /* should wait be terminated? */
90
91 #if JOBS
92 STATIC void restartjob(struct job *);
93 #endif
94 STATIC void freejob(struct job *);
95 STATIC struct job *getjob(char *);
96 STATIC int dowait(int, struct job *);
97 #if SYSV
98 STATIC int onsigchild(void);
99 #endif
100 STATIC int waitproc(int, int *);
101 STATIC void cmdtxt(union node *);
102 STATIC void cmdputs(char *);
103 #if JOBS
104 STATIC void setcurjob(struct job *);
105 STATIC void deljob(struct job *);
106 STATIC struct job *getcurjob(struct job *);
107 #endif
108 STATIC void showjob(struct job *, pid_t, int, int);
109
110
111 /*
112  * Turn job control on and off.
113  *
114  * Note:  This code assumes that the third arg to ioctl is a character
115  * pointer, which is true on Berkeley systems but not System V.  Since
116  * System V doesn't have job control yet, this isn't a problem now.
117  */
118
119 MKINIT int jobctl;
120
121 #if JOBS
122 void
123 setjobctl(int on)
124 {
125
126         if (on == jobctl || rootshell == 0)
127                 return;
128         if (on) {
129                 do { /* while we are in the background */
130                         initialpgrp = tcgetpgrp(2);
131                         if (initialpgrp < 0) {
132                                 out2str("sh: can't access tty; job control turned off\n");
133                                 mflag = 0;
134                                 return;
135                         }
136                         if (initialpgrp == -1)
137                                 initialpgrp = getpgrp();
138                         else if (initialpgrp != getpgrp()) {
139                                 killpg(initialpgrp, SIGTTIN);
140                                 continue;
141                         }
142                 } while (0);
143                 setsignal(SIGTSTP);
144                 setsignal(SIGTTOU);
145                 setsignal(SIGTTIN);
146                 setpgid(0, rootpid);
147                 tcsetpgrp(2, rootpid);
148         } else { /* turning job control off */
149                 setpgid(0, initialpgrp);
150                 tcsetpgrp(2, initialpgrp);
151                 setsignal(SIGTSTP);
152                 setsignal(SIGTTOU);
153                 setsignal(SIGTTIN);
154         }
155         jobctl = on;
156 }
157 #endif
158
159
160 #ifdef mkinit
161 INCLUDE <sys/types.h>
162 INCLUDE <stdlib.h>
163
164 SHELLPROC {
165         backgndpid = -1;
166 #if JOBS
167         jobctl = 0;
168 #endif
169 }
170
171 #endif
172
173
174
175 #if JOBS
176 int
177 fgcmd(int argc __unused, char **argv)
178 {
179         struct job *jp;
180         int pgrp;
181         int status;
182
183         jp = getjob(argv[1]);
184         if (jp->jobctl == 0)
185                 error("job not created under job control");
186         out1str(jp->ps[0].cmd);
187         out1c('\n');
188         flushout(&output);
189         pgrp = jp->ps[0].pid;
190         tcsetpgrp(2, pgrp);
191         restartjob(jp);
192         INTOFF;
193         status = waitforjob(jp, (int *)NULL);
194         INTON;
195         return status;
196 }
197
198
199 int
200 bgcmd(int argc, char **argv)
201 {
202         char s[64];
203         struct job *jp;
204
205         do {
206                 jp = getjob(*++argv);
207                 if (jp->jobctl == 0)
208                         error("job not created under job control");
209                 if (jp->state == JOBDONE)
210                         continue;
211                 restartjob(jp);
212                 fmtstr(s, 64, "[%d] ", jp - jobtab + 1);
213                 out1str(s);
214                 out1str(jp->ps[0].cmd);
215                 out1c('\n');
216         } while (--argc > 1);
217         return 0;
218 }
219
220
221 STATIC void
222 restartjob(struct job *jp)
223 {
224         struct procstat *ps;
225         int i;
226
227         if (jp->state == JOBDONE)
228                 return;
229         setcurjob(jp);
230         INTOFF;
231         killpg(jp->ps[0].pid, SIGCONT);
232         for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
233                 if (WIFSTOPPED(ps->status)) {
234                         ps->status = -1;
235                         jp->state = 0;
236                 }
237         }
238         INTON;
239 }
240 #endif
241
242
243 int
244 jobscmd(int argc, char *argv[])
245 {
246         char *id;
247         int ch, sformat, lformat;
248
249         optind = optreset = 1;
250         sformat = lformat = 0;
251         while ((ch = getopt(argc, argv, "ls")) != -1) {
252                 switch (ch) {
253                 case 'l':
254                         lformat = 1;
255                         break;
256                 case 's':
257                         sformat = 1;
258                         break;
259                 case '?':
260                 default:
261                         error("unknown option: -%c", optopt);
262                 }
263         }
264         argc -= optind;
265         argv += optind;
266
267         if (argc == 0)
268                 showjobs(0, sformat, lformat);
269         else
270                 while ((id = *argv++) != NULL)
271                         showjob(getjob(id), 0, sformat, lformat);
272
273         return (0);
274 }
275
276 STATIC void
277 showjob(struct job *jp, pid_t pid, int sformat, int lformat)
278 {
279         char s[64];
280         struct procstat *ps;
281         struct job *j;
282         int col, curr, i, jobno, prev, procno;
283         char c;
284
285         procno = jp->nprocs;
286         jobno = jp - jobtab + 1;
287         curr = prev = 0;
288 #if JOBS
289         if ((j = getcurjob(NULL)) != NULL) {
290                 curr = j - jobtab + 1;
291                 if ((j = getcurjob(j)) != NULL)
292                         prev = j - jobtab + 1;
293         }
294 #endif
295         for (ps = jp->ps ; ; ps++) {    /* for each process */
296                 if (sformat) {
297                         out1fmt("%d\n", ps->pid);
298                         goto skip;
299                 }
300                 if (!lformat && ps != jp->ps && pid == 0)
301                         goto skip;
302                 if (pid != 0 && pid != ps->pid)
303                         goto skip;
304                 if (jobno == curr && ps == jp->ps)
305                         c = '+';
306                 else if (jobno == prev && ps == jp->ps)
307                         c = '-';
308                 else
309                         c = ' ';
310                 if (ps == jp->ps)
311                         fmtstr(s, 64, "[%d] %c ", jobno, c);
312                 else
313                         fmtstr(s, 64, "    %c ", c);
314                 out1str(s);
315                 col = strlen(s);
316                 if (lformat) {
317                         fmtstr(s, 64, "%d ", ps->pid);
318                         out1str(s);
319                         col += strlen(s);
320                 }
321                 s[0] = '\0';
322                 if (ps != jp->ps) {
323                         *s = '\0';
324                 } else if (ps->status == -1) {
325                         strcpy(s, "Running");
326                 } else if (WIFEXITED(ps->status)) {
327                         if (WEXITSTATUS(ps->status) == 0)
328                                 strcpy(s, "Done");
329                         else
330                                 fmtstr(s, 64, "Done (%d)",
331                                     WEXITSTATUS(ps->status));
332                 } else {
333 #if JOBS
334                         if (WIFSTOPPED(ps->status)) 
335                                 i = WSTOPSIG(ps->status);
336                         else
337 #endif
338                                 i = WTERMSIG(ps->status);
339                         if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
340                                 scopy(sys_siglist[i & 0x7F], s);
341                         else
342                                 fmtstr(s, 64, "Signal %d", i & 0x7F);
343                         if (WCOREDUMP(ps->status))
344                                 strcat(s, " (core dumped)");
345                 }
346                 out1str(s);
347                 col += strlen(s);
348                 do {
349                         out1c(' ');
350                         col++;
351                 } while (col < 30);
352                 out1str(ps->cmd);
353                 out1c('\n');
354 skip:           if (--procno <= 0)
355                         break;
356         }
357 }
358
359 /*
360  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
361  * statuses have changed since the last call to showjobs.
362  *
363  * If the shell is interrupted in the process of creating a job, the
364  * result may be a job structure containing zero processes.  Such structures
365  * will be freed here.
366  */
367
368 void
369 showjobs(int change, int sformat, int lformat)
370 {
371         int jobno;
372         struct job *jp;
373
374         TRACE(("showjobs(%d) called\n", change));
375         while (dowait(0, (struct job *)NULL) > 0);
376         for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
377                 if (! jp->used)
378                         continue;
379                 if (jp->nprocs == 0) {
380                         freejob(jp);
381                         continue;
382                 }
383                 if (change && ! jp->changed)
384                         continue;
385                 showjob(jp, 0, sformat, lformat);
386                 jp->changed = 0;
387                 if (jp->state == JOBDONE) {
388                         freejob(jp);
389                 }
390         }
391 }
392
393
394 /*
395  * Mark a job structure as unused.
396  */
397
398 STATIC void
399 freejob(struct job *jp)
400 {
401         struct procstat *ps;
402         int i;
403
404         INTOFF;
405         for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
406                 if (ps->cmd != nullstr)
407                         ckfree(ps->cmd);
408         }
409         if (jp->ps != &jp->ps0)
410                 ckfree(jp->ps);
411         jp->used = 0;
412 #if JOBS
413         deljob(jp);
414 #endif
415         INTON;
416 }
417
418
419
420 int
421 waitcmd(int argc, char **argv)
422 {
423         struct job *job;
424         int status, retval;
425         struct job *jp;
426
427         if (argc > 1) {
428                 job = getjob(argv[1]);
429         } else {
430                 job = NULL;
431         }
432
433         /*
434          * Loop until a process is terminated or stopped, or a SIGINT is
435          * received.
436          */
437
438         in_waitcmd++;
439         do {
440                 if (job != NULL) {
441                         if (job->state) {
442                                 status = job->ps[job->nprocs - 1].status;
443                                 if (WIFEXITED(status))
444                                         retval = WEXITSTATUS(status);
445 #if JOBS
446                                 else if (WIFSTOPPED(status))
447                                         retval = WSTOPSIG(status) + 128;
448 #endif
449                                 else
450                                         retval = WTERMSIG(status) + 128;
451                                 if (! iflag)
452                                         freejob(job);
453                                 in_waitcmd--;
454                                 return retval;
455                         }
456                 } else {
457                         for (jp = jobtab ; ; jp++) {
458                                 if (jp >= jobtab + njobs) {     /* no running procs */
459                                         in_waitcmd--;
460                                         return 0;
461                                 }
462                                 if (jp->used && jp->state == 0)
463                                         break;
464                         }
465                 }
466         } while (dowait(1, (struct job *)NULL) != -1);
467         in_waitcmd--;
468
469         return 0;
470 }
471
472
473
474 int
475 jobidcmd(int argc __unused, char **argv)
476 {
477         struct job *jp;
478         int i;
479
480         jp = getjob(argv[1]);
481         for (i = 0 ; i < jp->nprocs ; ) {
482                 out1fmt("%d", jp->ps[i].pid);
483                 out1c(++i < jp->nprocs? ' ' : '\n');
484         }
485         return 0;
486 }
487
488
489
490 /*
491  * Convert a job name to a job structure.
492  */
493
494 STATIC struct job *
495 getjob(char *name)
496 {
497         int jobno;
498         struct job *found, *jp;
499         int pid;
500         int i;
501
502         if (name == NULL) {
503 #if JOBS
504 currentjob:     if ((jp = getcurjob(NULL)) == NULL)
505                         error("No current job");
506                 return (jp);
507 #else
508                 error("No current job");
509 #endif
510         } else if (name[0] == '%') {
511                 if (is_digit(name[1])) {
512                         jobno = number(name + 1);
513                         if (jobno > 0 && jobno <= njobs
514                          && jobtab[jobno - 1].used != 0)
515                                 return &jobtab[jobno - 1];
516 #if JOBS
517                 } else if (name[1] == '%' && name[2] == '\0') {
518                         goto currentjob;
519                 } else if (name[1] == '+' && name[2] == '\0') {
520                         goto currentjob;
521                 } else if (name[1] == '-' && name[2] == '\0') {
522                         if ((jp = getcurjob(NULL)) == NULL ||
523                             (jp = getcurjob(jp)) == NULL)
524                                 error("No previous job");
525                         return (jp);
526 #endif
527                 } else if (name[1] == '?') {
528                         found = NULL;
529                         for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
530                                 if (jp->used && jp->nprocs > 0
531                                  && strstr(jp->ps[0].cmd, name + 2) != NULL) {
532                                         if (found)
533                                                 error("%s: ambiguous", name);
534                                         found = jp;
535                                 }
536                         }
537                         if (found != NULL)
538                                 return (found);
539                 } else {
540                         found = NULL;
541                         for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
542                                 if (jp->used && jp->nprocs > 0
543                                  && prefix(name + 1, jp->ps[0].cmd)) {
544                                         if (found)
545                                                 error("%s: ambiguous", name);
546                                         found = jp;
547                                 }
548                         }
549                         if (found)
550                                 return found;
551                 }
552         } else if (is_number(name)) {
553                 pid = number(name);
554                 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
555                         if (jp->used && jp->nprocs > 0
556                          && jp->ps[jp->nprocs - 1].pid == pid)
557                                 return jp;
558                 }
559         }
560         error("No such job: %s", name);
561         /*NOTREACHED*/
562         return NULL;
563 }
564
565
566
567 /*
568  * Return a new job structure,
569  */
570
571 struct job *
572 makejob(union node *node __unused, int nprocs)
573 {
574         int i;
575         struct job *jp;
576
577         for (i = njobs, jp = jobtab ; ; jp++) {
578                 if (--i < 0) {
579                         INTOFF;
580                         if (njobs == 0) {
581                                 jobtab = ckmalloc(4 * sizeof jobtab[0]);
582 #if JOBS
583                                 jobmru = NULL;
584 #endif
585                         } else {
586                                 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
587                                 memcpy(jp, jobtab, njobs * sizeof jp[0]);
588 #if JOBS
589                                 /* Relocate `next' pointers and list head */
590                                 if (jobmru != NULL)
591                                         jobmru = &jp[jobmru - jobtab];
592                                 for (i = 0; i < njobs; i++)
593                                         if (jp[i].next != NULL)
594                                                 jp[i].next = &jp[jp[i].next -
595                                                     jobtab];
596 #endif
597                                 /* Relocate `ps' pointers */
598                                 for (i = 0; i < njobs; i++)
599                                         if (jp[i].ps == &jobtab[i].ps0)
600                                                 jp[i].ps = &jp[i].ps0;
601                                 ckfree(jobtab);
602                                 jobtab = jp;
603                         }
604                         jp = jobtab + njobs;
605                         for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
606                         INTON;
607                         break;
608                 }
609                 if (jp->used == 0)
610                         break;
611         }
612         INTOFF;
613         jp->state = 0;
614         jp->used = 1;
615         jp->changed = 0;
616         jp->nprocs = 0;
617 #if JOBS
618         jp->jobctl = jobctl;
619         jp->next = NULL;
620 #endif
621         if (nprocs > 1) {
622                 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
623         } else {
624                 jp->ps = &jp->ps0;
625         }
626         INTON;
627         TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
628             jp - jobtab + 1));
629         return jp;
630 }
631
632 #if JOBS
633 STATIC void
634 setcurjob(struct job *cj)
635 {
636         struct job *jp, *prev;
637
638         for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
639                 if (jp == cj) {
640                         if (prev != NULL)
641                                 prev->next = jp->next;
642                         else
643                                 jobmru = jp->next;
644                         jp->next = jobmru;
645                         jobmru = cj;
646                         return;
647                 }
648         }
649         cj->next = jobmru;
650         jobmru = cj;
651 }
652
653 STATIC void
654 deljob(struct job *j)
655 {
656         struct job *jp, *prev;
657
658         for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
659                 if (jp == j) {
660                         if (prev != NULL)
661                                 prev->next = jp->next;
662                         else
663                                 jobmru = jp->next;
664                         return;
665                 }
666         }
667 }
668
669 /*
670  * Return the most recently used job that isn't `nj', and preferably one
671  * that is stopped.
672  */
673 STATIC struct job *
674 getcurjob(struct job *nj)
675 {
676         struct job *jp;
677
678         /* Try to find a stopped one.. */
679         for (jp = jobmru; jp != NULL; jp = jp->next)
680                 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
681                         return (jp);
682         /* Otherwise the most recently used job that isn't `nj' */
683         for (jp = jobmru; jp != NULL; jp = jp->next)
684                 if (jp->used && jp != nj)
685                         return (jp);
686
687         return (NULL);
688 }
689
690 #endif
691
692 /*
693  * Fork of a subshell.  If we are doing job control, give the subshell its
694  * own process group.  Jp is a job structure that the job is to be added to.
695  * N is the command that will be evaluated by the child.  Both jp and n may
696  * be NULL.  The mode parameter can be one of the following:
697  *      FORK_FG - Fork off a foreground process.
698  *      FORK_BG - Fork off a background process.
699  *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
700  *                   process group even if job control is on.
701  *
702  * When job control is turned off, background processes have their standard
703  * input redirected to /dev/null (except for the second and later processes
704  * in a pipeline).
705  */
706
707 int
708 forkshell(struct job *jp, union node *n, int mode)
709 {
710         int pid;
711         int pgrp;
712
713         TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
714             mode));
715         INTOFF;
716         pid = fork();
717         if (pid == -1) {
718                 TRACE(("Fork failed, errno=%d\n", errno));
719                 INTON;
720                 error("Cannot fork: %s", strerror(errno));
721         }
722         if (pid == 0) {
723                 struct job *p;
724                 int wasroot;
725                 int i;
726
727                 TRACE(("Child shell %d\n", getpid()));
728                 wasroot = rootshell;
729                 rootshell = 0;
730                 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
731                         if (p->used)
732                                 freejob(p);
733                 closescript();
734                 INTON;
735                 clear_traps();
736 #if JOBS
737                 jobctl = 0;             /* do job control only in root shell */
738                 if (wasroot && mode != FORK_NOJOB && mflag) {
739                         if (jp == NULL || jp->nprocs == 0)
740                                 pgrp = getpid();
741                         else
742                                 pgrp = jp->ps[0].pid;
743                         if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
744                                 /*** this causes superfluous TIOCSPGRPS ***/
745                                 if (tcsetpgrp(2, pgrp) < 0)
746                                         error("tcsetpgrp failed, errno=%d", errno);
747                         }
748                         setsignal(SIGTSTP);
749                         setsignal(SIGTTOU);
750                 } else if (mode == FORK_BG) {
751                         ignoresig(SIGINT);
752                         ignoresig(SIGQUIT);
753                         if ((jp == NULL || jp->nprocs == 0) &&
754                             ! fd0_redirected_p ()) {
755                                 close(0);
756                                 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
757                                         error("Can't open %s: %s",
758                                             _PATH_DEVNULL, strerror(errno));
759                         }
760                 }
761 #else
762                 if (mode == FORK_BG) {
763                         ignoresig(SIGINT);
764                         ignoresig(SIGQUIT);
765                         if ((jp == NULL || jp->nprocs == 0) &&
766                             ! fd0_redirected_p ()) {
767                                 close(0);
768                                 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
769                                         error("Can't open %s: %s", 
770                                             _PATH_DEVNULL, strerror(errno));
771                         }
772                 }
773 #endif
774                 if (wasroot && iflag) {
775                         setsignal(SIGINT);
776                         setsignal(SIGQUIT);
777                         setsignal(SIGTERM);
778                 }
779                 return pid;
780         }
781         if (rootshell && mode != FORK_NOJOB && mflag) {
782                 if (jp == NULL || jp->nprocs == 0)
783                         pgrp = pid;
784                 else
785                         pgrp = jp->ps[0].pid;
786                 setpgid(pid, pgrp);
787         }
788         if (mode == FORK_BG)
789                 backgndpid = pid;               /* set $! */
790         if (jp) {
791                 struct procstat *ps = &jp->ps[jp->nprocs++];
792                 ps->pid = pid;
793                 ps->status = -1;
794                 ps->cmd = nullstr;
795                 if (iflag && rootshell && n)
796                         ps->cmd = commandtext(n);
797 #if JOBS
798                 setcurjob(jp);
799 #endif
800         }
801         INTON;
802         TRACE(("In parent shell:  child = %d\n", pid));
803         return pid;
804 }
805
806
807
808 /*
809  * Wait for job to finish.
810  *
811  * Under job control we have the problem that while a child process is
812  * running interrupts generated by the user are sent to the child but not
813  * to the shell.  This means that an infinite loop started by an inter-
814  * active user may be hard to kill.  With job control turned off, an
815  * interactive user may place an interactive program inside a loop.  If
816  * the interactive program catches interrupts, the user doesn't want
817  * these interrupts to also abort the loop.  The approach we take here
818  * is to have the shell ignore interrupt signals while waiting for a
819  * foreground process to terminate, and then send itself an interrupt
820  * signal if the child process was terminated by an interrupt signal.
821  * Unfortunately, some programs want to do a bit of cleanup and then
822  * exit on interrupt; unless these processes terminate themselves by
823  * sending a signal to themselves (instead of calling exit) they will
824  * confuse this approach.
825  */
826
827 int
828 waitforjob(struct job *jp, int *origstatus)
829 {
830 #if JOBS
831         int mypgrp = getpgrp();
832 #endif
833         int status;
834         int st;
835
836         INTOFF;
837         TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
838         while (jp->state == 0)
839                 if (dowait(1, jp) == -1)
840                         dotrap();
841 #if JOBS
842         if (jp->jobctl) {
843                 if (tcsetpgrp(2, mypgrp) < 0)
844                         error("tcsetpgrp failed, errno=%d\n", errno);
845         }
846         if (jp->state == JOBSTOPPED)
847                 setcurjob(jp);
848 #endif
849         status = jp->ps[jp->nprocs - 1].status;
850         if (origstatus != NULL)
851                 *origstatus = status;
852         /* convert to 8 bits */
853         if (WIFEXITED(status))
854                 st = WEXITSTATUS(status);
855 #if JOBS
856         else if (WIFSTOPPED(status))
857                 st = WSTOPSIG(status) + 128;
858 #endif
859         else
860                 st = WTERMSIG(status) + 128;
861         if (! JOBS || jp->state == JOBDONE)
862                 freejob(jp);
863         if (int_pending()) {
864                 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
865                         kill(getpid(), SIGINT);
866                 else
867                         CLEAR_PENDING_INT;
868         }
869         INTON;
870         return st;
871 }
872
873
874
875 /*
876  * Wait for a process to terminate.
877  */
878
879 STATIC int
880 dowait(int block, struct job *job)
881 {
882         int pid;
883         int status;
884         struct procstat *sp;
885         struct job *jp;
886         struct job *thisjob;
887         int done;
888         int stopped;
889         int sig;
890
891         in_dowait++;
892         TRACE(("dowait(%d) called\n", block));
893         do {
894                 pid = waitproc(block, &status);
895                 TRACE(("wait returns %d, status=%d\n", pid, status));
896         } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
897             (WIFSTOPPED(status) && !iflag));
898         in_dowait--;
899         if (breakwaitcmd != 0) {
900                 breakwaitcmd = 0;
901                 return -1;
902         }
903         if (pid <= 0)
904                 return pid;
905         INTOFF;
906         thisjob = NULL;
907         for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
908                 if (jp->used) {
909                         done = 1;
910                         stopped = 1;
911                         for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
912                                 if (sp->pid == -1)
913                                         continue;
914                                 if (sp->pid == pid) {
915                                         TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
916                                                    pid, sp->status, status));
917                                         sp->status = status;
918                                         thisjob = jp;
919                                 }
920                                 if (sp->status == -1)
921                                         stopped = 0;
922                                 else if (WIFSTOPPED(sp->status))
923                                         done = 0;
924                         }
925                         if (stopped) {          /* stopped or done */
926                                 int state = done? JOBDONE : JOBSTOPPED;
927                                 if (jp->state != state) {
928                                         TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
929                                         jp->state = state;
930 #if JOBS
931                                         if (done)
932                                                 deljob(jp);
933 #endif
934                                 }
935                         }
936                 }
937         }
938         INTON;
939         if (! rootshell || ! iflag || (job && thisjob == job)) {
940 #if JOBS
941                 if (WIFSTOPPED(status))
942                         sig = WSTOPSIG(status);
943                 else
944 #endif
945                 {
946                         if (WIFEXITED(status))
947                                 sig = 0;
948                         else
949                                 sig = WTERMSIG(status);
950                 }
951                 if (sig != 0 && sig != SIGINT && sig != SIGPIPE)
952                         showjob(thisjob, pid, 0, 1);
953         } else {
954                 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
955                 if (thisjob)
956                         thisjob->changed = 1;
957         }
958         return pid;
959 }
960
961
962
963 /*
964  * Do a wait system call.  If job control is compiled in, we accept
965  * stopped processes.  If block is zero, we return a value of zero
966  * rather than blocking.
967  *
968  * System V doesn't have a non-blocking wait system call.  It does
969  * have a SIGCLD signal that is sent to a process when one of it's
970  * children dies.  The obvious way to use SIGCLD would be to install
971  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
972  * was received, and have waitproc bump another counter when it got
973  * the status of a process.  Waitproc would then know that a wait
974  * system call would not block if the two counters were different.
975  * This approach doesn't work because if a process has children that
976  * have not been waited for, System V will send it a SIGCLD when it
977  * installs a signal handler for SIGCLD.  What this means is that when
978  * a child exits, the shell will be sent SIGCLD signals continuously
979  * until is runs out of stack space, unless it does a wait call before
980  * restoring the signal handler.  The code below takes advantage of
981  * this (mis)feature by installing a signal handler for SIGCLD and
982  * then checking to see whether it was called.  If there are any
983  * children to be waited for, it will be.
984  *
985  * If neither SYSV nor BSD is defined, we don't implement nonblocking
986  * waits at all.  In this case, the user will not be informed when
987  * a background process until the next time she runs a real program
988  * (as opposed to running a builtin command or just typing return),
989  * and the jobs command may give out of date information.
990  */
991
992 #ifdef SYSV
993 STATIC sig_atomic_t gotsigchild;
994
995 STATIC int onsigchild() {
996         gotsigchild = 1;
997 }
998 #endif
999
1000
1001 STATIC int
1002 waitproc(int block, int *status)
1003 {
1004 #ifdef BSD
1005         int flags;
1006
1007 #if JOBS
1008         flags = WUNTRACED;
1009 #else
1010         flags = 0;
1011 #endif
1012         if (block == 0)
1013                 flags |= WNOHANG;
1014         return wait3(status, flags, (struct rusage *)NULL);
1015 #else
1016 #ifdef SYSV
1017         int (*save)();
1018
1019         if (block == 0) {
1020                 gotsigchild = 0;
1021                 save = signal(SIGCLD, onsigchild);
1022                 signal(SIGCLD, save);
1023                 if (gotsigchild == 0)
1024                         return 0;
1025         }
1026         return wait(status);
1027 #else
1028         if (block == 0)
1029                 return 0;
1030         return wait(status);
1031 #endif
1032 #endif
1033 }
1034
1035 /*
1036  * return 1 if there are stopped jobs, otherwise 0
1037  */
1038 int job_warning = 0;
1039 int
1040 stoppedjobs(void)
1041 {
1042         int jobno;
1043         struct job *jp;
1044
1045         if (job_warning)
1046                 return (0);
1047         for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1048                 if (jp->used == 0)
1049                         continue;
1050                 if (jp->state == JOBSTOPPED) {
1051                         out2str("You have stopped jobs.\n");
1052                         job_warning = 2;
1053                         return (1);
1054                 }
1055         }
1056
1057         return (0);
1058 }
1059
1060 /*
1061  * Return a string identifying a command (to be printed by the
1062  * jobs command.
1063  */
1064
1065 STATIC char *cmdnextc;
1066 STATIC int cmdnleft;
1067 #define MAXCMDTEXT      200
1068
1069 char *
1070 commandtext(union node *n)
1071 {
1072         char *name;
1073
1074         cmdnextc = name = ckmalloc(MAXCMDTEXT);
1075         cmdnleft = MAXCMDTEXT - 4;
1076         cmdtxt(n);
1077         *cmdnextc = '\0';
1078         return name;
1079 }
1080
1081
1082 STATIC void
1083 cmdtxt(union node *n)
1084 {
1085         union node *np;
1086         struct nodelist *lp;
1087         char *p;
1088         int i;
1089         char s[2];
1090
1091         if (n == NULL)
1092                 return;
1093         switch (n->type) {
1094         case NSEMI:
1095                 cmdtxt(n->nbinary.ch1);
1096                 cmdputs("; ");
1097                 cmdtxt(n->nbinary.ch2);
1098                 break;
1099         case NAND:
1100                 cmdtxt(n->nbinary.ch1);
1101                 cmdputs(" && ");
1102                 cmdtxt(n->nbinary.ch2);
1103                 break;
1104         case NOR:
1105                 cmdtxt(n->nbinary.ch1);
1106                 cmdputs(" || ");
1107                 cmdtxt(n->nbinary.ch2);
1108                 break;
1109         case NPIPE:
1110                 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1111                         cmdtxt(lp->n);
1112                         if (lp->next)
1113                                 cmdputs(" | ");
1114                 }
1115                 break;
1116         case NSUBSHELL:
1117                 cmdputs("(");
1118                 cmdtxt(n->nredir.n);
1119                 cmdputs(")");
1120                 break;
1121         case NREDIR:
1122         case NBACKGND:
1123                 cmdtxt(n->nredir.n);
1124                 break;
1125         case NIF:
1126                 cmdputs("if ");
1127                 cmdtxt(n->nif.test);
1128                 cmdputs("; then ");
1129                 cmdtxt(n->nif.ifpart);
1130                 cmdputs("...");
1131                 break;
1132         case NWHILE:
1133                 cmdputs("while ");
1134                 goto until;
1135         case NUNTIL:
1136                 cmdputs("until ");
1137 until:
1138                 cmdtxt(n->nbinary.ch1);
1139                 cmdputs("; do ");
1140                 cmdtxt(n->nbinary.ch2);
1141                 cmdputs("; done");
1142                 break;
1143         case NFOR:
1144                 cmdputs("for ");
1145                 cmdputs(n->nfor.var);
1146                 cmdputs(" in ...");
1147                 break;
1148         case NCASE:
1149                 cmdputs("case ");
1150                 cmdputs(n->ncase.expr->narg.text);
1151                 cmdputs(" in ...");
1152                 break;
1153         case NDEFUN:
1154                 cmdputs(n->narg.text);
1155                 cmdputs("() ...");
1156                 break;
1157         case NCMD:
1158                 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1159                         cmdtxt(np);
1160                         if (np->narg.next)
1161                                 cmdputs(" ");
1162                 }
1163                 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1164                         cmdputs(" ");
1165                         cmdtxt(np);
1166                 }
1167                 break;
1168         case NARG:
1169                 cmdputs(n->narg.text);
1170                 break;
1171         case NTO:
1172                 p = ">";  i = 1;  goto redir;
1173         case NAPPEND:
1174                 p = ">>";  i = 1;  goto redir;
1175         case NTOFD:
1176                 p = ">&";  i = 1;  goto redir;
1177         case NCLOBBER:
1178                 p = ">|"; i = 1; goto redir;
1179         case NFROM:
1180                 p = "<";  i = 0;  goto redir;
1181         case NFROMTO:
1182                 p = "<>";  i = 0;  goto redir;
1183         case NFROMFD:
1184                 p = "<&";  i = 0;  goto redir;
1185 redir:
1186                 if (n->nfile.fd != i) {
1187                         s[0] = n->nfile.fd + '0';
1188                         s[1] = '\0';
1189                         cmdputs(s);
1190                 }
1191                 cmdputs(p);
1192                 if (n->type == NTOFD || n->type == NFROMFD) {
1193                         if (n->ndup.dupfd >= 0)
1194                                 s[0] = n->ndup.dupfd + '0';
1195                         else
1196                                 s[0] = '-';
1197                         s[1] = '\0';
1198                         cmdputs(s);
1199                 } else {
1200                         cmdtxt(n->nfile.fname);
1201                 }
1202                 break;
1203         case NHERE:
1204         case NXHERE:
1205                 cmdputs("<<...");
1206                 break;
1207         default:
1208                 cmdputs("???");
1209                 break;
1210         }
1211 }
1212
1213
1214
1215 STATIC void
1216 cmdputs(char *s)
1217 {
1218         char *p, *q;
1219         char c;
1220         int subtype = 0;
1221
1222         if (cmdnleft <= 0)
1223                 return;
1224         p = s;
1225         q = cmdnextc;
1226         while ((c = *p++) != '\0') {
1227                 if (c == CTLESC)
1228                         *q++ = *p++;
1229                 else if (c == CTLVAR) {
1230                         *q++ = '$';
1231                         if (--cmdnleft > 0)
1232                                 *q++ = '{';
1233                         subtype = *p++;
1234                 } else if (c == '=' && subtype != 0) {
1235                         *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
1236                         subtype = 0;
1237                 } else if (c == CTLENDVAR) {
1238                         *q++ = '}';
1239                 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
1240                         cmdnleft++;             /* ignore it */
1241                 else
1242                         *q++ = c;
1243                 if (--cmdnleft <= 0) {
1244                         *q++ = '.';
1245                         *q++ = '.';
1246                         *q++ = '.';
1247                         break;
1248                 }
1249         }
1250         cmdnextc = q;
1251 }