]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/sh/jobs.c
Convert devd's client socket to type SOCK_SEQPACKET.
[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         size_t namelen;
566         pid_t pid;
567         int i;
568
569         if (name == NULL) {
570 #if JOBS
571 currentjob:     if ((jp = getcurjob(NULL)) == NULL)
572                         error("No current job");
573                 return (jp);
574 #else
575                 error("No current job");
576 #endif
577         } else if (name[0] == '%') {
578                 if (is_digit(name[1])) {
579                         jobno = number(name + 1);
580                         if (jobno > 0 && jobno <= njobs
581                          && jobtab[jobno - 1].used != 0)
582                                 return &jobtab[jobno - 1];
583 #if JOBS
584                 } else if (name[1] == '%' && name[2] == '\0') {
585                         goto currentjob;
586                 } else if (name[1] == '+' && name[2] == '\0') {
587                         goto currentjob;
588                 } else if (name[1] == '-' && name[2] == '\0') {
589                         if ((jp = getcurjob(NULL)) == NULL ||
590                             (jp = getcurjob(jp)) == NULL)
591                                 error("No previous job");
592                         return (jp);
593 #endif
594                 } else if (name[1] == '?') {
595                         found = NULL;
596                         for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
597                                 if (jp->used && jp->nprocs > 0
598                                  && strstr(jp->ps[0].cmd, name + 2) != NULL) {
599                                         if (found)
600                                                 error("%s: ambiguous", name);
601                                         found = jp;
602                                 }
603                         }
604                         if (found != NULL)
605                                 return (found);
606                 } else {
607                         namelen = strlen(name);
608                         found = NULL;
609                         for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
610                                 if (jp->used && jp->nprocs > 0
611                                  && strncmp(jp->ps[0].cmd, name + 1,
612                                  namelen - 1) == 0) {
613                                         if (found)
614                                                 error("%s: ambiguous", name);
615                                         found = jp;
616                                 }
617                         }
618                         if (found)
619                                 return found;
620                 }
621         } else if (is_number(name)) {
622                 pid = (pid_t)number(name);
623                 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
624                         if (jp->used && jp->nprocs > 0
625                          && jp->ps[jp->nprocs - 1].pid == pid)
626                                 return jp;
627                 }
628         }
629         return NULL;
630 }
631
632
633 static struct job *
634 getjob(const char *name)
635 {
636         struct job *jp;
637
638         jp = getjob_nonotfound(name);
639         if (jp == NULL)
640                 error("No such job: %s", name);
641         return (jp);
642 }
643
644
645 int
646 killjob(const char *name, int sig)
647 {
648         struct job *jp;
649         int i, ret;
650
651         jp = getjob(name);
652         if (jp->state == JOBDONE)
653                 return 0;
654         if (jp->jobctl)
655                 return kill(-jp->ps[0].pid, sig);
656         ret = -1;
657         errno = ESRCH;
658         for (i = 0; i < jp->nprocs; i++)
659                 if (jp->ps[i].status == -1 || WIFSTOPPED(jp->ps[i].status)) {
660                         if (kill(jp->ps[i].pid, sig) == 0)
661                                 ret = 0;
662                 } else
663                         ret = 0;
664         return ret;
665 }
666
667 /*
668  * Return a new job structure,
669  */
670
671 struct job *
672 makejob(union node *node __unused, int nprocs)
673 {
674         int i;
675         struct job *jp;
676
677         for (i = njobs, jp = jobtab ; ; jp++) {
678                 if (--i < 0) {
679                         INTOFF;
680                         if (njobs == 0) {
681                                 jobtab = ckmalloc(4 * sizeof jobtab[0]);
682 #if JOBS
683                                 jobmru = NULL;
684 #endif
685                         } else {
686                                 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
687                                 memcpy(jp, jobtab, njobs * sizeof jp[0]);
688 #if JOBS
689                                 /* Relocate `next' pointers and list head */
690                                 if (jobmru != NULL)
691                                         jobmru = &jp[jobmru - jobtab];
692                                 for (i = 0; i < njobs; i++)
693                                         if (jp[i].next != NULL)
694                                                 jp[i].next = &jp[jp[i].next -
695                                                     jobtab];
696 #endif
697                                 if (bgjob != NULL)
698                                         bgjob = &jp[bgjob - jobtab];
699                                 /* Relocate `ps' pointers */
700                                 for (i = 0; i < njobs; i++)
701                                         if (jp[i].ps == &jobtab[i].ps0)
702                                                 jp[i].ps = &jp[i].ps0;
703                                 ckfree(jobtab);
704                                 jobtab = jp;
705                         }
706                         jp = jobtab + njobs;
707                         for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
708                                 ;
709                         INTON;
710                         break;
711                 }
712                 if (jp->used == 0)
713                         break;
714         }
715         INTOFF;
716         jp->state = 0;
717         jp->used = 1;
718         jp->changed = 0;
719         jp->nprocs = 0;
720         jp->foreground = 0;
721         jp->remembered = 0;
722 #if JOBS
723         jp->jobctl = jobctl;
724         jp->next = NULL;
725 #endif
726         if (nprocs > 1) {
727                 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
728         } else {
729                 jp->ps = &jp->ps0;
730         }
731         INTON;
732         TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
733             jp - jobtab + 1));
734         return jp;
735 }
736
737 #if JOBS
738 static void
739 setcurjob(struct job *cj)
740 {
741         struct job *jp, *prev;
742
743         for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
744                 if (jp == cj) {
745                         if (prev != NULL)
746                                 prev->next = jp->next;
747                         else
748                                 jobmru = jp->next;
749                         jp->next = jobmru;
750                         jobmru = cj;
751                         return;
752                 }
753         }
754         cj->next = jobmru;
755         jobmru = cj;
756 }
757
758 static void
759 deljob(struct job *j)
760 {
761         struct job *jp, *prev;
762
763         for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
764                 if (jp == j) {
765                         if (prev != NULL)
766                                 prev->next = jp->next;
767                         else
768                                 jobmru = jp->next;
769                         return;
770                 }
771         }
772 }
773
774 /*
775  * Return the most recently used job that isn't `nj', and preferably one
776  * that is stopped.
777  */
778 static struct job *
779 getcurjob(struct job *nj)
780 {
781         struct job *jp;
782
783         /* Try to find a stopped one.. */
784         for (jp = jobmru; jp != NULL; jp = jp->next)
785                 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
786                         return (jp);
787         /* Otherwise the most recently used job that isn't `nj' */
788         for (jp = jobmru; jp != NULL; jp = jp->next)
789                 if (jp->used && jp != nj)
790                         return (jp);
791
792         return (NULL);
793 }
794
795 #endif
796
797 /*
798  * Fork of a subshell.  If we are doing job control, give the subshell its
799  * own process group.  Jp is a job structure that the job is to be added to.
800  * N is the command that will be evaluated by the child.  Both jp and n may
801  * be NULL.  The mode parameter can be one of the following:
802  *      FORK_FG - Fork off a foreground process.
803  *      FORK_BG - Fork off a background process.
804  *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
805  *                   process group even if job control is on.
806  *
807  * When job control is turned off, background processes have their standard
808  * input redirected to /dev/null (except for the second and later processes
809  * in a pipeline).
810  */
811
812 pid_t
813 forkshell(struct job *jp, union node *n, int mode)
814 {
815         pid_t pid;
816         pid_t pgrp;
817
818         TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
819             mode));
820         INTOFF;
821         if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
822                 checkzombies();
823         flushall();
824         pid = fork();
825         if (pid == -1) {
826                 TRACE(("Fork failed, errno=%d\n", errno));
827                 INTON;
828                 error("Cannot fork: %s", strerror(errno));
829         }
830         if (pid == 0) {
831                 struct job *p;
832                 int wasroot;
833                 int i;
834
835                 TRACE(("Child shell %d\n", (int)getpid()));
836                 wasroot = rootshell;
837                 rootshell = 0;
838                 handler = &main_handler;
839                 closescript();
840                 INTON;
841                 forcelocal = 0;
842                 clear_traps();
843 #if JOBS
844                 jobctl = 0;             /* do job control only in root shell */
845                 if (wasroot && mode != FORK_NOJOB && mflag) {
846                         if (jp == NULL || jp->nprocs == 0)
847                                 pgrp = getpid();
848                         else
849                                 pgrp = jp->ps[0].pid;
850                         if (setpgid(0, pgrp) == 0 && mode == FORK_FG) {
851                                 /*** this causes superfluous TIOCSPGRPS ***/
852                                 if (tcsetpgrp(ttyfd, pgrp) < 0)
853                                         error("tcsetpgrp failed, errno=%d", errno);
854                         }
855                         setsignal(SIGTSTP);
856                         setsignal(SIGTTOU);
857                 } else if (mode == FORK_BG) {
858                         ignoresig(SIGINT);
859                         ignoresig(SIGQUIT);
860                         if ((jp == NULL || jp->nprocs == 0) &&
861                             ! fd0_redirected_p ()) {
862                                 close(0);
863                                 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
864                                         error("cannot open %s: %s",
865                                             _PATH_DEVNULL, strerror(errno));
866                         }
867                 }
868 #else
869                 if (mode == FORK_BG) {
870                         ignoresig(SIGINT);
871                         ignoresig(SIGQUIT);
872                         if ((jp == NULL || jp->nprocs == 0) &&
873                             ! fd0_redirected_p ()) {
874                                 close(0);
875                                 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
876                                         error("cannot open %s: %s",
877                                             _PATH_DEVNULL, strerror(errno));
878                         }
879                 }
880 #endif
881                 INTOFF;
882                 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
883                         if (p->used)
884                                 freejob(p);
885                 INTON;
886                 if (wasroot && iflag) {
887                         setsignal(SIGINT);
888                         setsignal(SIGQUIT);
889                         setsignal(SIGTERM);
890                 }
891                 return pid;
892         }
893         if (rootshell && mode != FORK_NOJOB && mflag) {
894                 if (jp == NULL || jp->nprocs == 0)
895                         pgrp = pid;
896                 else
897                         pgrp = jp->ps[0].pid;
898                 setpgid(pid, pgrp);
899         }
900         if (mode == FORK_BG) {
901                 if (bgjob != NULL && bgjob->state == JOBDONE &&
902                     !bgjob->remembered && !iflag)
903                         freejob(bgjob);
904                 backgndpid = pid;               /* set $! */
905                 bgjob = jp;
906         }
907         if (jp) {
908                 struct procstat *ps = &jp->ps[jp->nprocs++];
909                 ps->pid = pid;
910                 ps->status = -1;
911                 ps->cmd = nullstr;
912                 if (iflag && rootshell && n)
913                         ps->cmd = commandtext(n);
914                 jp->foreground = mode == FORK_FG;
915 #if JOBS
916                 setcurjob(jp);
917 #endif
918         }
919         INTON;
920         TRACE(("In parent shell:  child = %d\n", (int)pid));
921         return pid;
922 }
923
924
925 pid_t
926 vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
927 {
928         pid_t pid;
929         struct jmploc jmploc;
930         struct jmploc *savehandler;
931
932         TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
933             (void *)pip));
934         INTOFF;
935         flushall();
936         savehandler = handler;
937         pid = vfork();
938         if (pid == -1) {
939                 TRACE(("Vfork failed, errno=%d\n", errno));
940                 INTON;
941                 error("Cannot fork: %s", strerror(errno));
942         }
943         if (pid == 0) {
944                 TRACE(("Child shell %d\n", (int)getpid()));
945                 if (setjmp(jmploc.loc))
946                         _exit(exception == EXEXEC ? exerrno : 2);
947                 if (pip != NULL) {
948                         close(pip[0]);
949                         if (pip[1] != 1) {
950                                 dup2(pip[1], 1);
951                                 close(pip[1]);
952                         }
953                 }
954                 handler = &jmploc;
955                 shellexec(argv, envp, path, idx);
956         }
957         handler = savehandler;
958         if (jp) {
959                 struct procstat *ps = &jp->ps[jp->nprocs++];
960                 ps->pid = pid;
961                 ps->status = -1;
962                 ps->cmd = nullstr;
963                 jp->foreground = 1;
964 #if JOBS
965                 setcurjob(jp);
966 #endif
967         }
968         INTON;
969         TRACE(("In parent shell:  child = %d\n", (int)pid));
970         return pid;
971 }
972
973
974 /*
975  * Wait for job to finish.
976  *
977  * Under job control we have the problem that while a child process is
978  * running interrupts generated by the user are sent to the child but not
979  * to the shell.  This means that an infinite loop started by an inter-
980  * active user may be hard to kill.  With job control turned off, an
981  * interactive user may place an interactive program inside a loop.  If
982  * the interactive program catches interrupts, the user doesn't want
983  * these interrupts to also abort the loop.  The approach we take here
984  * is to have the shell ignore interrupt signals while waiting for a
985  * foreground process to terminate, and then send itself an interrupt
986  * signal if the child process was terminated by an interrupt signal.
987  * Unfortunately, some programs want to do a bit of cleanup and then
988  * exit on interrupt; unless these processes terminate themselves by
989  * sending a signal to themselves (instead of calling exit) they will
990  * confuse this approach.
991  */
992
993 int
994 waitforjob(struct job *jp, int *origstatus)
995 {
996 #if JOBS
997         int propagate_int = jp->jobctl && jp->foreground;
998 #endif
999         int status;
1000         int st;
1001
1002         INTOFF;
1003         TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
1004         while (jp->state == 0)
1005                 if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
1006                     DOWAIT_SIG_ANY : 0), jp) == -1)
1007                         dotrap();
1008 #if JOBS
1009         if (jp->jobctl) {
1010                 if (tcsetpgrp(ttyfd, rootpid) < 0)
1011                         error("tcsetpgrp failed, errno=%d\n", errno);
1012         }
1013         if (jp->state == JOBSTOPPED)
1014                 setcurjob(jp);
1015 #endif
1016         status = jp->ps[jp->nprocs - 1].status;
1017         if (origstatus != NULL)
1018                 *origstatus = status;
1019         /* convert to 8 bits */
1020         if (WIFEXITED(status))
1021                 st = WEXITSTATUS(status);
1022 #if JOBS
1023         else if (WIFSTOPPED(status))
1024                 st = WSTOPSIG(status) + 128;
1025 #endif
1026         else
1027                 st = WTERMSIG(status) + 128;
1028         if (! JOBS || jp->state == JOBDONE)
1029                 freejob(jp);
1030         if (int_pending()) {
1031                 if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
1032                         CLEAR_PENDING_INT;
1033         }
1034 #if JOBS
1035         else if (rootshell && iflag && propagate_int &&
1036                         WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1037                 kill(getpid(), SIGINT);
1038 #endif
1039         INTON;
1040         return st;
1041 }
1042
1043
1044 static void
1045 dummy_handler(int sig __unused)
1046 {
1047 }
1048
1049 /*
1050  * Wait for a process to terminate.
1051  */
1052
1053 static pid_t
1054 dowait(int mode, struct job *job)
1055 {
1056         struct sigaction sa, osa;
1057         sigset_t mask, omask;
1058         pid_t pid;
1059         int status;
1060         struct procstat *sp;
1061         struct job *jp;
1062         struct job *thisjob;
1063         const char *sigstr;
1064         int done;
1065         int stopped;
1066         int sig;
1067         int coredump;
1068         int wflags;
1069         int restore_sigchld;
1070
1071         TRACE(("dowait(%d, %p) called\n", mode, job));
1072         restore_sigchld = 0;
1073         if ((mode & DOWAIT_SIG) != 0) {
1074                 sigfillset(&mask);
1075                 sigprocmask(SIG_BLOCK, &mask, &omask);
1076                 INTOFF;
1077                 if (!issigchldtrapped()) {
1078                         restore_sigchld = 1;
1079                         sa.sa_handler = dummy_handler;
1080                         sa.sa_flags = 0;
1081                         sigemptyset(&sa.sa_mask);
1082                         sigaction(SIGCHLD, &sa, &osa);
1083                 }
1084         }
1085         do {
1086 #if JOBS
1087                 if (iflag)
1088                         wflags = WUNTRACED | WCONTINUED;
1089                 else
1090 #endif
1091                         wflags = 0;
1092                 if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1093                         wflags |= WNOHANG;
1094                 pid = wait3(&status, wflags, (struct rusage *)NULL);
1095                 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1096                 if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1097                         pid = -1;
1098                         if (((mode & DOWAIT_SIG_ANY) != 0 ?
1099                             pendingsig : pendingsig_waitcmd) != 0) {
1100                                 errno = EINTR;
1101                                 break;
1102                         }
1103                         sigsuspend(&omask);
1104                         if (int_pending())
1105                                 break;
1106                 }
1107         } while (pid == -1 && errno == EINTR);
1108         if (pid == -1 && errno == ECHILD && job != NULL)
1109                 job->state = JOBDONE;
1110         if ((mode & DOWAIT_SIG) != 0) {
1111                 if (restore_sigchld)
1112                         sigaction(SIGCHLD, &osa, NULL);
1113                 sigprocmask(SIG_SETMASK, &omask, NULL);
1114                 INTON;
1115         }
1116         if (pid <= 0)
1117                 return pid;
1118         INTOFF;
1119         thisjob = NULL;
1120         for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1121                 if (jp->used && jp->nprocs > 0) {
1122                         done = 1;
1123                         stopped = 1;
1124                         for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1125                                 if (sp->pid == -1)
1126                                         continue;
1127                                 if (sp->pid == pid && (sp->status == -1 ||
1128                                     WIFSTOPPED(sp->status))) {
1129                                         TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1130                                                    (int)pid, sp->status,
1131                                                    status));
1132                                         if (WIFCONTINUED(status)) {
1133                                                 sp->status = -1;
1134                                                 jp->state = 0;
1135                                         } else
1136                                                 sp->status = status;
1137                                         thisjob = jp;
1138                                 }
1139                                 if (sp->status == -1)
1140                                         stopped = 0;
1141                                 else if (WIFSTOPPED(sp->status))
1142                                         done = 0;
1143                         }
1144                         if (stopped) {          /* stopped or done */
1145                                 int state = done? JOBDONE : JOBSTOPPED;
1146                                 if (jp->state != state) {
1147                                         TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1148                                         jp->state = state;
1149                                         if (jp != job) {
1150                                                 if (done && !jp->remembered &&
1151                                                     !iflag && jp != bgjob)
1152                                                         freejob(jp);
1153 #if JOBS
1154                                                 else if (done)
1155                                                         deljob(jp);
1156 #endif
1157                                         }
1158                                 }
1159                         }
1160                 }
1161         }
1162         INTON;
1163         if (!thisjob || thisjob->state == 0)
1164                 ;
1165         else if ((!rootshell || !iflag || thisjob == job) &&
1166             thisjob->foreground && thisjob->state != JOBSTOPPED) {
1167                 sig = 0;
1168                 coredump = 0;
1169                 for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1170                         if (WIFSIGNALED(sp->status)) {
1171                                 sig = WTERMSIG(sp->status);
1172                                 coredump = WCOREDUMP(sp->status);
1173                         }
1174                 if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1175                         sigstr = strsignal(sig);
1176                         if (sigstr != NULL)
1177                                 out2str(sigstr);
1178                         else
1179                                 out2str("Unknown signal");
1180                         if (coredump)
1181                                 out2str(" (core dumped)");
1182                         out2c('\n');
1183                         flushout(out2);
1184                 }
1185         } else {
1186                 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1187                 thisjob->changed = 1;
1188         }
1189         return pid;
1190 }
1191
1192
1193
1194 /*
1195  * return 1 if there are stopped jobs, otherwise 0
1196  */
1197 int job_warning = 0;
1198 int
1199 stoppedjobs(void)
1200 {
1201         int jobno;
1202         struct job *jp;
1203
1204         if (job_warning)
1205                 return (0);
1206         for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1207                 if (jp->used == 0)
1208                         continue;
1209                 if (jp->state == JOBSTOPPED) {
1210                         out2fmt_flush("You have stopped jobs.\n");
1211                         job_warning = 2;
1212                         return (1);
1213                 }
1214         }
1215
1216         return (0);
1217 }
1218
1219
1220 static void
1221 checkzombies(void)
1222 {
1223         while (njobs > 0 && dowait(0, NULL) > 0)
1224                 ;
1225 }
1226
1227
1228 int
1229 backgndpidset(void)
1230 {
1231         return backgndpid != -1;
1232 }
1233
1234
1235 pid_t
1236 backgndpidval(void)
1237 {
1238         if (bgjob != NULL && !forcelocal)
1239                 bgjob->remembered = 1;
1240         return backgndpid;
1241 }
1242
1243 /*
1244  * Return a string identifying a command (to be printed by the
1245  * jobs command.
1246  */
1247
1248 static char *cmdnextc;
1249 static int cmdnleft;
1250 #define MAXCMDTEXT      200
1251
1252 char *
1253 commandtext(union node *n)
1254 {
1255         char *name;
1256
1257         cmdnextc = name = ckmalloc(MAXCMDTEXT);
1258         cmdnleft = MAXCMDTEXT - 4;
1259         cmdtxt(n);
1260         *cmdnextc = '\0';
1261         return name;
1262 }
1263
1264
1265 static void
1266 cmdtxt(union node *n)
1267 {
1268         union node *np;
1269         struct nodelist *lp;
1270         const char *p;
1271         int i;
1272         char s[2];
1273
1274         if (n == NULL)
1275                 return;
1276         switch (n->type) {
1277         case NSEMI:
1278                 cmdtxt(n->nbinary.ch1);
1279                 cmdputs("; ");
1280                 cmdtxt(n->nbinary.ch2);
1281                 break;
1282         case NAND:
1283                 cmdtxt(n->nbinary.ch1);
1284                 cmdputs(" && ");
1285                 cmdtxt(n->nbinary.ch2);
1286                 break;
1287         case NOR:
1288                 cmdtxt(n->nbinary.ch1);
1289                 cmdputs(" || ");
1290                 cmdtxt(n->nbinary.ch2);
1291                 break;
1292         case NPIPE:
1293                 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1294                         cmdtxt(lp->n);
1295                         if (lp->next)
1296                                 cmdputs(" | ");
1297                 }
1298                 break;
1299         case NSUBSHELL:
1300                 cmdputs("(");
1301                 cmdtxt(n->nredir.n);
1302                 cmdputs(")");
1303                 break;
1304         case NREDIR:
1305         case NBACKGND:
1306                 cmdtxt(n->nredir.n);
1307                 break;
1308         case NIF:
1309                 cmdputs("if ");
1310                 cmdtxt(n->nif.test);
1311                 cmdputs("; then ");
1312                 cmdtxt(n->nif.ifpart);
1313                 cmdputs("...");
1314                 break;
1315         case NWHILE:
1316                 cmdputs("while ");
1317                 goto until;
1318         case NUNTIL:
1319                 cmdputs("until ");
1320 until:
1321                 cmdtxt(n->nbinary.ch1);
1322                 cmdputs("; do ");
1323                 cmdtxt(n->nbinary.ch2);
1324                 cmdputs("; done");
1325                 break;
1326         case NFOR:
1327                 cmdputs("for ");
1328                 cmdputs(n->nfor.var);
1329                 cmdputs(" in ...");
1330                 break;
1331         case NCASE:
1332                 cmdputs("case ");
1333                 cmdputs(n->ncase.expr->narg.text);
1334                 cmdputs(" in ...");
1335                 break;
1336         case NDEFUN:
1337                 cmdputs(n->narg.text);
1338                 cmdputs("() ...");
1339                 break;
1340         case NNOT:
1341                 cmdputs("! ");
1342                 cmdtxt(n->nnot.com);
1343                 break;
1344         case NCMD:
1345                 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1346                         cmdtxt(np);
1347                         if (np->narg.next)
1348                                 cmdputs(" ");
1349                 }
1350                 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1351                         cmdputs(" ");
1352                         cmdtxt(np);
1353                 }
1354                 break;
1355         case NARG:
1356                 cmdputs(n->narg.text);
1357                 break;
1358         case NTO:
1359                 p = ">";  i = 1;  goto redir;
1360         case NAPPEND:
1361                 p = ">>";  i = 1;  goto redir;
1362         case NTOFD:
1363                 p = ">&";  i = 1;  goto redir;
1364         case NCLOBBER:
1365                 p = ">|"; i = 1; goto redir;
1366         case NFROM:
1367                 p = "<";  i = 0;  goto redir;
1368         case NFROMTO:
1369                 p = "<>";  i = 0;  goto redir;
1370         case NFROMFD:
1371                 p = "<&";  i = 0;  goto redir;
1372 redir:
1373                 if (n->nfile.fd != i) {
1374                         s[0] = n->nfile.fd + '0';
1375                         s[1] = '\0';
1376                         cmdputs(s);
1377                 }
1378                 cmdputs(p);
1379                 if (n->type == NTOFD || n->type == NFROMFD) {
1380                         if (n->ndup.dupfd >= 0)
1381                                 s[0] = n->ndup.dupfd + '0';
1382                         else
1383                                 s[0] = '-';
1384                         s[1] = '\0';
1385                         cmdputs(s);
1386                 } else {
1387                         cmdtxt(n->nfile.fname);
1388                 }
1389                 break;
1390         case NHERE:
1391         case NXHERE:
1392                 cmdputs("<<...");
1393                 break;
1394         default:
1395                 cmdputs("???");
1396                 break;
1397         }
1398 }
1399
1400
1401
1402 static void
1403 cmdputs(const char *s)
1404 {
1405         const char *p;
1406         char *q;
1407         char c;
1408         int subtype = 0;
1409
1410         if (cmdnleft <= 0)
1411                 return;
1412         p = s;
1413         q = cmdnextc;
1414         while ((c = *p++) != '\0') {
1415                 if (c == CTLESC)
1416                         *q++ = *p++;
1417                 else if (c == CTLVAR) {
1418                         *q++ = '$';
1419                         if (--cmdnleft > 0)
1420                                 *q++ = '{';
1421                         subtype = *p++;
1422                         if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1423                                 *q++ = '#';
1424                 } else if (c == '=' && subtype != 0) {
1425                         *q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1426                         if (*q)
1427                                 q++;
1428                         else
1429                                 cmdnleft++;
1430                         if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1431                             (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1432                             --cmdnleft > 0)
1433                                 *q = q[-1], q++;
1434                         subtype = 0;
1435                 } else if (c == CTLENDVAR) {
1436                         *q++ = '}';
1437                 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1438                         cmdnleft -= 5;
1439                         if (cmdnleft > 0) {
1440                                 *q++ = '$';
1441                                 *q++ = '(';
1442                                 *q++ = '.';
1443                                 *q++ = '.';
1444                                 *q++ = '.';
1445                                 *q++ = ')';
1446                         }
1447                 } else if (c == CTLARI) {
1448                         cmdnleft -= 2;
1449                         if (cmdnleft > 0) {
1450                                 *q++ = '$';
1451                                 *q++ = '(';
1452                                 *q++ = '(';
1453                         }
1454                         p++;
1455                 } else if (c == CTLENDARI) {
1456                         if (--cmdnleft > 0) {
1457                                 *q++ = ')';
1458                                 *q++ = ')';
1459                         }
1460                 } else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1461                         cmdnleft++; /* ignore */
1462                 else
1463                         *q++ = c;
1464                 if (--cmdnleft <= 0) {
1465                         *q++ = '.';
1466                         *q++ = '.';
1467                         *q++ = '.';
1468                         break;
1469                 }
1470         }
1471         cmdnextc = q;
1472 }