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