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