Merge branch 'vendor/GCC47'
[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: src/bin/sh/jobs.c,v 1.98 2012/04/02 17:16:24 jilles Exp $
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 int in_dowait = 0;              /* are we in dowait()? */
87 volatile sig_atomic_t breakwaitcmd = 0; /* should wait be terminated? */
88 static int ttyfd = -1;
89
90 #if JOBS
91 static void restartjob(struct job *);
92 #endif
93 static void freejob(struct job *);
94 static struct job *getjob(char *);
95 static pid_t dowait(int, struct job *);
96 static pid_t waitproc(int, int *);
97 static void checkzombies(void);
98 static void cmdtxt(union node *);
99 static void cmdputs(const char *);
100 #if JOBS
101 static void setcurjob(struct job *);
102 static void deljob(struct job *);
103 static struct job *getcurjob(struct job *);
104 #endif
105 static void printjobcmd(struct job *);
106 static void showjob(struct job *, int);
107
108
109 /*
110  * Turn job control on and off.
111  */
112
113 MKINIT int jobctl;
114
115 #if JOBS
116 void
117 setjobctl(int on)
118 {
119         int i;
120
121         if (on == jobctl || rootshell == 0)
122                 return;
123         if (on) {
124                 if (ttyfd != -1)
125                         close(ttyfd);
126                 if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
127                         i = 0;
128                         while (i <= 2 && !isatty(i))
129                                 i++;
130                         if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
131                                 goto out;
132                 }
133                 if (ttyfd < 10) {
134                         /*
135                          * Keep our TTY file descriptor out of the way of
136                          * the user's redirections.
137                          */
138                         if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
139                                 close(ttyfd);
140                                 ttyfd = -1;
141                                 goto out;
142                         }
143                         close(ttyfd);
144                         ttyfd = i;
145                 }
146                 if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
147                         close(ttyfd);
148                         ttyfd = -1;
149                         goto out;
150                 }
151                 do { /* while we are in the background */
152                         initialpgrp = tcgetpgrp(ttyfd);
153                         if (initialpgrp < 0) {
154 out:                            out2fmt_flush("sh: can't access tty; job control turned off\n");
155                                 mflag = 0;
156                                 return;
157                         }
158                         if (initialpgrp != getpgrp()) {
159                                 kill(0, SIGTTIN);
160                                 continue;
161                         }
162                 } while (0);
163                 setsignal(SIGTSTP);
164                 setsignal(SIGTTOU);
165                 setsignal(SIGTTIN);
166                 setpgid(0, rootpid);
167                 tcsetpgrp(ttyfd, rootpid);
168         } else { /* turning job control off */
169                 setpgid(0, initialpgrp);
170                 tcsetpgrp(ttyfd, initialpgrp);
171                 close(ttyfd);
172                 ttyfd = -1;
173                 setsignal(SIGTSTP);
174                 setsignal(SIGTTOU);
175                 setsignal(SIGTTIN);
176         }
177         jobctl = on;
178 }
179 #endif
180
181
182 #if JOBS
183 int
184 fgcmd(int argc __unused, char **argv)
185 {
186         struct job *jp;
187         pid_t pgrp;
188         int status;
189
190         jp = getjob(argv[1]);
191         if (jp->jobctl == 0)
192                 error("job not created under job control");
193         printjobcmd(jp);
194         flushout(&output);
195         pgrp = jp->ps[0].pid;
196         tcsetpgrp(ttyfd, pgrp);
197         restartjob(jp);
198         jp->foreground = 1;
199         INTOFF;
200         status = waitforjob(jp, NULL);
201         INTON;
202         return status;
203 }
204
205
206 int
207 bgcmd(int argc, char **argv)
208 {
209         struct job *jp;
210
211         do {
212                 jp = getjob(*++argv);
213                 if (jp->jobctl == 0)
214                         error("job not created under job control");
215                 if (jp->state == JOBDONE)
216                         continue;
217                 restartjob(jp);
218                 jp->foreground = 0;
219                 out1fmt("[%td] ", jp - jobtab + 1);
220                 printjobcmd(jp);
221         } while (--argc > 1);
222         return 0;
223 }
224
225
226 static void
227 restartjob(struct job *jp)
228 {
229         struct procstat *ps;
230         int i;
231
232         if (jp->state == JOBDONE)
233                 return;
234         setcurjob(jp);
235         INTOFF;
236         kill(-jp->ps[0].pid, SIGCONT);
237         for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
238                 if (WIFSTOPPED(ps->status)) {
239                         ps->status = -1;
240                         jp->state = 0;
241                 }
242         }
243         INTON;
244 }
245 #endif
246
247
248 int
249 jobscmd(int argc, char *argv[])
250 {
251         char *id;
252         int ch, mode;
253
254         optind = optreset = 1;
255         opterr = 0;
256         mode = SHOWJOBS_DEFAULT;
257         while ((ch = getopt(argc, argv, "lps")) != -1) {
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                 case '?':
269                 default:
270                         error("unknown option: -%c", optopt);
271                 }
272         }
273         argc -= optind;
274         argv += optind;
275
276         if (argc == 0)
277                 showjobs(0, mode);
278         else
279                 while ((id = *argv++) != NULL)
280                         showjob(getjob(id), mode);
281
282         return (0);
283 }
284
285 static void
286 printjobcmd(struct job *jp)
287 {
288         struct procstat *ps;
289         int i;
290
291         for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
292                 out1str(ps->cmd);
293                 if (i > 0)
294                         out1str(" | ");
295         }
296         out1c('\n');
297 }
298
299 static void
300 showjob(struct job *jp, int mode)
301 {
302         char s[64];
303         char statestr[64];
304         struct procstat *ps;
305         struct job *j;
306         int col, curr, i, jobno, prev, procno;
307         char c;
308
309         procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
310         jobno = jp - jobtab + 1;
311         curr = prev = 0;
312 #if JOBS
313         if ((j = getcurjob(NULL)) != NULL) {
314                 curr = j - jobtab + 1;
315                 if ((j = getcurjob(j)) != NULL)
316                         prev = j - jobtab + 1;
317         }
318 #endif
319         ps = jp->ps + jp->nprocs - 1;
320         if (jp->state == 0) {
321                 strcpy(statestr, "Running");
322 #if JOBS
323         } else if (jp->state == JOBSTOPPED) {
324                 while (!WIFSTOPPED(ps->status) && ps > jp->ps)
325                         ps--;
326                 if (WIFSTOPPED(ps->status))
327                         i = WSTOPSIG(ps->status);
328                 else
329                         i = -1;
330                 if (i > 0 && i < sys_nsig && sys_siglist[i])
331                         strcpy(statestr, sys_siglist[i]);
332                 else
333                         strcpy(statestr, "Suspended");
334 #endif
335         } else if (WIFEXITED(ps->status)) {
336                 if (WEXITSTATUS(ps->status) == 0)
337                         strcpy(statestr, "Done");
338                 else
339                         fmtstr(statestr, 64, "Done(%d)",
340                             WEXITSTATUS(ps->status));
341         } else {
342                 i = WTERMSIG(ps->status);
343                 if (i > 0 && i < sys_nsig && sys_siglist[i])
344                         strcpy(statestr, sys_siglist[i]);
345                 else
346                         fmtstr(statestr, 64, "Signal %d", i);
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(1, NULL) != -1);
522         in_waitcmd--;
523
524         return 0;
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(1, 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
1007 /*
1008  * Wait for a process to terminate.
1009  */
1010
1011 static pid_t
1012 dowait(int block, struct job *job)
1013 {
1014         pid_t pid;
1015         int status;
1016         struct procstat *sp;
1017         struct job *jp;
1018         struct job *thisjob;
1019         int done;
1020         int stopped;
1021         int sig;
1022         int coredump;
1023
1024         in_dowait++;
1025         TRACE(("dowait(%d) called\n", block));
1026         do {
1027                 pid = waitproc(block, &status);
1028                 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1029         } while ((pid == -1 && errno == EINTR && breakwaitcmd == 0) ||
1030                  (pid > 0 && WIFSTOPPED(status) && !iflag));
1031         in_dowait--;
1032         if (pid == -1 && errno == ECHILD && job != NULL)
1033                 job->state = JOBDONE;
1034         if (breakwaitcmd != 0) {
1035                 breakwaitcmd = 0;
1036                 /*
1037                  * Do not early terminate if the pid is positive, else the
1038                  * job will not be properly recorded.
1039                  */
1040                 if (pid <= 0)
1041                         return -1;
1042         }
1043         if (pid <= 0)
1044                 return pid;
1045         INTOFF;
1046         thisjob = NULL;
1047         for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1048                 if (jp->used && jp->nprocs > 0) {
1049                         done = 1;
1050                         stopped = 1;
1051                         for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1052                                 if (sp->pid == -1)
1053                                         continue;
1054                                 if (sp->pid == pid) {
1055                                         TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1056                                                    (int)pid, sp->status,
1057                                                    status));
1058                                         sp->status = status;
1059                                         thisjob = jp;
1060                                 }
1061                                 if (sp->status == -1)
1062                                         stopped = 0;
1063                                 else if (WIFSTOPPED(sp->status))
1064                                         done = 0;
1065                         }
1066                         if (stopped) {          /* stopped or done */
1067                                 int state = done? JOBDONE : JOBSTOPPED;
1068                                 if (jp->state != state) {
1069                                         TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1070                                         jp->state = state;
1071                                         if (jp != job) {
1072                                                 if (done && !jp->remembered &&
1073                                                     !iflag && jp != bgjob)
1074                                                         freejob(jp);
1075 #if JOBS
1076                                                 else if (done)
1077                                                         deljob(jp);
1078 #endif
1079                                         }
1080                                 }
1081                         }
1082                 }
1083         }
1084         INTON;
1085         if (!thisjob || thisjob->state == 0)
1086                 ;
1087         else if ((!rootshell || !iflag || thisjob == job) &&
1088             thisjob->foreground && thisjob->state != JOBSTOPPED) {
1089                 sig = 0;
1090                 coredump = 0;
1091                 for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1092                         if (WIFSIGNALED(sp->status)) {
1093                                 sig = WTERMSIG(sp->status);
1094                                 coredump = WCOREDUMP(sp->status);
1095                         }
1096                 if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1097                         if (sig < sys_nsig && sys_siglist[sig])
1098                                 out2str(sys_siglist[sig]);
1099                         else
1100                                 outfmt(out2, "Signal %d", sig);
1101                         if (coredump)
1102                                 out2str(" (core dumped)");
1103                         out2c('\n');
1104                         flushout(out2);
1105                 }
1106         } else {
1107                 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1108                 thisjob->changed = 1;
1109         }
1110         return pid;
1111 }
1112
1113
1114
1115 /*
1116  * Do a wait system call.  If job control is compiled in, we accept
1117  * stopped processes.  If block is zero, we return a value of zero
1118  * rather than blocking.
1119  */
1120 static pid_t
1121 waitproc(int block, int *status)
1122 {
1123         int flags;
1124
1125 #if JOBS
1126         flags = WUNTRACED;
1127 #else
1128         flags = 0;
1129 #endif
1130         if (block == 0)
1131                 flags |= WNOHANG;
1132         return wait3(status, flags, NULL);
1133 }
1134
1135 /*
1136  * return 1 if there are stopped jobs, otherwise 0
1137  */
1138 int job_warning = 0;
1139 int
1140 stoppedjobs(void)
1141 {
1142         int jobno;
1143         struct job *jp;
1144
1145         if (job_warning)
1146                 return (0);
1147         for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1148                 if (jp->used == 0)
1149                         continue;
1150                 if (jp->state == JOBSTOPPED) {
1151                         out2fmt_flush("You have stopped jobs.\n");
1152                         job_warning = 2;
1153                         return (1);
1154                 }
1155         }
1156
1157         return (0);
1158 }
1159
1160
1161 static void
1162 checkzombies(void)
1163 {
1164         while (njobs > 0 && dowait(0, NULL) > 0)
1165                 ;
1166 }
1167
1168
1169 int
1170 backgndpidset(void)
1171 {
1172         return backgndpid != -1;
1173 }
1174
1175
1176 pid_t
1177 backgndpidval(void)
1178 {
1179         if (bgjob != NULL && !forcelocal)
1180                 bgjob->remembered = 1;
1181         return backgndpid;
1182 }
1183
1184 /*
1185  * Return a string identifying a command (to be printed by the
1186  * jobs command.
1187  */
1188
1189 static char *cmdnextc;
1190 static int cmdnleft;
1191 #define MAXCMDTEXT      200
1192
1193 char *
1194 commandtext(union node *n)
1195 {
1196         char *name;
1197
1198         cmdnextc = name = ckmalloc(MAXCMDTEXT);
1199         cmdnleft = MAXCMDTEXT - 4;
1200         cmdtxt(n);
1201         *cmdnextc = '\0';
1202         return name;
1203 }
1204
1205
1206 static void
1207 cmdtxt(union node *n)
1208 {
1209         union node *np;
1210         struct nodelist *lp;
1211         const char *p;
1212         int i;
1213         char s[2];
1214
1215         if (n == NULL)
1216                 return;
1217         switch (n->type) {
1218         case NSEMI:
1219                 cmdtxt(n->nbinary.ch1);
1220                 cmdputs("; ");
1221                 cmdtxt(n->nbinary.ch2);
1222                 break;
1223         case NAND:
1224                 cmdtxt(n->nbinary.ch1);
1225                 cmdputs(" && ");
1226                 cmdtxt(n->nbinary.ch2);
1227                 break;
1228         case NOR:
1229                 cmdtxt(n->nbinary.ch1);
1230                 cmdputs(" || ");
1231                 cmdtxt(n->nbinary.ch2);
1232                 break;
1233         case NPIPE:
1234                 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1235                         cmdtxt(lp->n);
1236                         if (lp->next)
1237                                 cmdputs(" | ");
1238                 }
1239                 break;
1240         case NSUBSHELL:
1241                 cmdputs("(");
1242                 cmdtxt(n->nredir.n);
1243                 cmdputs(")");
1244                 break;
1245         case NREDIR:
1246         case NBACKGND:
1247                 cmdtxt(n->nredir.n);
1248                 break;
1249         case NIF:
1250                 cmdputs("if ");
1251                 cmdtxt(n->nif.test);
1252                 cmdputs("; then ");
1253                 cmdtxt(n->nif.ifpart);
1254                 cmdputs("...");
1255                 break;
1256         case NWHILE:
1257                 cmdputs("while ");
1258                 goto until;
1259         case NUNTIL:
1260                 cmdputs("until ");
1261 until:
1262                 cmdtxt(n->nbinary.ch1);
1263                 cmdputs("; do ");
1264                 cmdtxt(n->nbinary.ch2);
1265                 cmdputs("; done");
1266                 break;
1267         case NFOR:
1268                 cmdputs("for ");
1269                 cmdputs(n->nfor.var);
1270                 cmdputs(" in ...");
1271                 break;
1272         case NCASE:
1273                 cmdputs("case ");
1274                 cmdputs(n->ncase.expr->narg.text);
1275                 cmdputs(" in ...");
1276                 break;
1277         case NDEFUN:
1278                 cmdputs(n->narg.text);
1279                 cmdputs("() ...");
1280                 break;
1281         case NCMD:
1282                 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1283                         cmdtxt(np);
1284                         if (np->narg.next)
1285                                 cmdputs(" ");
1286                 }
1287                 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1288                         cmdputs(" ");
1289                         cmdtxt(np);
1290                 }
1291                 break;
1292         case NARG:
1293                 cmdputs(n->narg.text);
1294                 break;
1295         case NTO:
1296                 p = ">";  i = 1;  goto redir;
1297         case NAPPEND:
1298                 p = ">>";  i = 1;  goto redir;
1299         case NTOFD:
1300                 p = ">&";  i = 1;  goto redir;
1301         case NCLOBBER:
1302                 p = ">|"; i = 1; goto redir;
1303         case NFROM:
1304                 p = "<";  i = 0;  goto redir;
1305         case NFROMTO:
1306                 p = "<>";  i = 0;  goto redir;
1307         case NFROMFD:
1308                 p = "<&";  i = 0;  goto redir;
1309 redir:
1310                 if (n->nfile.fd != i) {
1311                         s[0] = n->nfile.fd + '0';
1312                         s[1] = '\0';
1313                         cmdputs(s);
1314                 }
1315                 cmdputs(p);
1316                 if (n->type == NTOFD || n->type == NFROMFD) {
1317                         if (n->ndup.dupfd >= 0)
1318                                 s[0] = n->ndup.dupfd + '0';
1319                         else
1320                                 s[0] = '-';
1321                         s[1] = '\0';
1322                         cmdputs(s);
1323                 } else {
1324                         cmdtxt(n->nfile.fname);
1325                 }
1326                 break;
1327         case NHERE:
1328         case NXHERE:
1329                 cmdputs("<<...");
1330                 break;
1331         default:
1332                 cmdputs("???");
1333                 break;
1334         }
1335 }
1336
1337
1338
1339 static void
1340 cmdputs(const char *s)
1341 {
1342         const char *p;
1343         char *q;
1344         char c;
1345         int subtype = 0;
1346
1347         if (cmdnleft <= 0)
1348                 return;
1349         p = s;
1350         q = cmdnextc;
1351         while ((c = *p++) != '\0') {
1352                 if (c == CTLESC)
1353                         *q++ = *p++;
1354                 else if (c == CTLVAR) {
1355                         *q++ = '$';
1356                         if (--cmdnleft > 0)
1357                                 *q++ = '{';
1358                         subtype = *p++;
1359                         if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1360                                 *q++ = '#';
1361                 } else if (c == '=' && subtype != 0) {
1362                         *q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1363                         if (*q)
1364                                 q++;
1365                         else
1366                                 cmdnleft++;
1367                         if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1368                             (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1369                             --cmdnleft > 0)
1370                                 *q = q[-1], q++;
1371                         subtype = 0;
1372                 } else if (c == CTLENDVAR) {
1373                         *q++ = '}';
1374                 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1375                         cmdnleft -= 5;
1376                         if (cmdnleft > 0) {
1377                                 *q++ = '$';
1378                                 *q++ = '(';
1379                                 *q++ = '.';
1380                                 *q++ = '.';
1381                                 *q++ = '.';
1382                                 *q++ = ')';
1383                         }
1384                 } else if (c == CTLARI) {
1385                         cmdnleft -= 2;
1386                         if (cmdnleft > 0) {
1387                                 *q++ = '$';
1388                                 *q++ = '(';
1389                                 *q++ = '(';
1390                         }
1391                         p++;
1392                 } else if (c == CTLENDARI) {
1393                         if (--cmdnleft > 0) {
1394                                 *q++ = ')';
1395                                 *q++ = ')';
1396                         }
1397                 } else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1398                         cmdnleft++; /* ignore */
1399                 else
1400                         *q++ = c;
1401                 if (--cmdnleft <= 0) {
1402                         *q++ = '.';
1403                         *q++ = '.';
1404                         *q++ = '.';
1405                         break;
1406                 }
1407         }
1408         cmdnextc = q;
1409 }