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