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