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