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