Imported from ../bash-2.0.tar.gz.
[platform/upstream/bash.git] / jobs.c
1 /* The thing that makes children, remembers them, and contains wait loops. */
2
3 /* This file works with both POSIX and BSD systems.  It implements job
4    control. */
5
6 /* Copyright (C) 1989, 1992 Free Software Foundation, Inc.
7
8    This file is part of GNU Bash, the Bourne Again SHell.
9
10    Bash is free software; you can redistribute it and/or modify it under
11    the terms of the GNU General Public License as published by the Free
12    Software Foundation; either version 1, or (at your option) any later
13    version.
14
15    Bash is distributed in the hope that it will be useful, but WITHOUT ANY
16    WARRANTY; without even the implied warranty of MERCHANTABILITY or
17    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18    for more details.
19
20    You should have received a copy of the GNU General Public License along
21    with Bash; see the file COPYING.  If not, write to the Free Software
22    Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
23
24 #include "config.h"
25
26 #include "bashtypes.h"
27 #include "trap.h"
28 #include <stdio.h>
29 #include <signal.h>
30 #include <errno.h>
31
32 #if defined (HAVE_UNISTD_H)
33 #  include <unistd.h>
34 #endif
35
36 #if defined (HAVE_SYS_TIME_H)
37 #  include <sys/time.h>
38 #endif
39
40 #if defined (HAVE_SYS_RESOURCE_H) && defined (HAVE_WAIT3) && !defined (_POSIX_VERSION)
41 #  include <sys/resource.h>
42 #endif /* !_POSIX_VERSION && HAVE_SYS_RESOURCE_H && HAVE_WAIT3 */
43
44 #include <sys/file.h>
45 #include "filecntl.h"
46 #include <sys/ioctl.h>
47 #include <sys/param.h>
48
49 #if defined (BUFFERED_INPUT)
50 #  include "input.h"
51 #endif
52
53 /* Need to include this up here for *_TTY_DRIVER definitions. */
54 #include "bashtty.h"
55
56 /* Define this if your output is getting swallowed.  It's a no-op on
57    machines with the termio or termios tty drivers. */
58 /* #define DRAIN_OUTPUT */
59
60 /* The _POSIX_SOURCE define is to avoid multiple symbol definitions
61    between sys/ioctl.h and termios.h.  Ditto for the test against SunOS4
62    and the undefining of several symbols. */
63 #if defined (TERMIOS_TTY_DRIVER)
64 #  if (defined (SunOS4) || defined (SunOS5)) && !defined (_POSIX_SOURCE)
65 #    define _POSIX_SOURCE
66 #  endif
67 #  if defined (SunOS4)
68 #    undef ECHO
69 #    undef NOFLSH
70 #    undef TOSTOP
71 #  endif /* SunOS4 */
72 #  include <termios.h>
73 #else /* !TERMIOS_TTY_DRIVER */
74 #  if defined (TERMIO_TTY_DRIVER)
75 #    include <termio.h>
76 #  else
77 #    include <sgtty.h>
78 #  endif
79 #endif /* !TERMIOS_TTY_DRIVER */
80
81 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
82 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
83 #  include <bsdtty.h>
84 #endif /* hpux && !TERMIOS_TTY_DRIVER */
85
86 /* For struct winsize on SCO */
87 /*   sys/ptem.h has winsize but needs mblk_t from sys/stream.h */
88 #if defined (HAVE_SYS_PTEM_H) && defined (TIOCGWINSZ) && defined (SIGWINCH)
89 #  if defined (HAVE_SYS_STREAM_H)
90 #    include <sys/stream.h>
91 #  endif
92 #  include <sys/ptem.h>
93 #endif
94
95 #include "bashansi.h"
96 #include "shell.h"
97 #include "jobs.h"
98 #include "flags.h"
99 #include "error.h"
100
101 #include "builtins/builtext.h"
102 #include "builtins/common.h"
103
104 #if !defined (errno)
105 extern int errno;
106 #endif /* !errno */
107
108 /* Take care of system dependencies that must be handled when waiting for
109    children.  The arguments to the WAITPID macro match those to the Posix.1
110    waitpid() function. */
111
112 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
113 #  define WAITPID(pid, statusp, options) \
114         wait3 ((union wait *)statusp, options, (struct rusage *)0)
115 #else
116 #  if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
117 #    define WAITPID(pid, statusp, options) \
118         waitpid ((pid_t)pid, statusp, options)
119 #  else
120 #    if defined (HAVE_WAIT3)
121 #      define WAITPID(pid, statusp, options) \
122         wait3 (statusp, options, (struct rusage *)0)
123 #    else
124 #      define WAITPID(pid, statusp, options) \
125         wait3 (statusp, options, (int *)0)
126 #    endif /* HAVE_WAIT3 */
127 #  endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
128 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
129
130 /* getpgrp () varies between systems.  Even systems that claim to be
131    Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
132 #if defined (GETPGRP_VOID)
133 #  define getpgid(p) getpgrp ()
134 #else
135 #  define getpgid(p) getpgrp (p)
136 #endif /* !GETPGRP_VOID */
137
138 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
139    handler for SIGCHLD. */
140 #if defined (MUST_REINSTALL_SIGHANDLERS)
141 #  define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
142 #else
143 #  define REINSTALL_SIGCHLD_HANDLER
144 #endif /* !MUST_REINSTALL_SIGHANDLERS */
145
146 /* The number of additional slots to allocate when we run out. */
147 #define JOB_SLOTS 8
148
149 /* Variables used here but defined in other files. */
150 extern int interactive, interactive_shell, asynchronous_notification;
151 extern int startup_state, subshell_environment, line_number;
152 extern int posixly_correct, no_symbolic_links, shell_level;
153 extern int interrupt_immediately, last_command_exit_value;
154 extern int loop_level, breaking;
155 extern Function *this_shell_builtin;
156 extern char *shell_name, *this_command_name;
157 extern sigset_t top_level_mask;
158
159 #if defined (ARRAY_VARS)
160 static int *pstatuses;          /* list of pipeline statuses */
161 static int statsize;
162 static void set_pipestatus_array ();
163 #endif
164 static void setjstatus ();
165 static void get_new_window_size ();
166
167 /* The array of known jobs. */
168 JOB **jobs = (JOB **)NULL;
169
170 /* The number of slots currently allocated to JOBS. */
171 int job_slots = 0;
172
173 /* The controlling tty for this shell. */
174 int shell_tty = -1;
175
176 /* The shell's process group. */
177 pid_t shell_pgrp = NO_PID;
178
179 /* The terminal's process group. */
180 pid_t terminal_pgrp = NO_PID;
181
182 /* The process group of the shell's parent. */
183 pid_t original_pgrp = NO_PID;
184
185 /* The process group of the pipeline currently being made. */
186 pid_t pipeline_pgrp = (pid_t)0;
187
188 #if defined (PGRP_PIPE)
189 /* Pipes which each shell uses to communicate with the process group leader
190    until all of the processes in a pipeline have been started.  Then the
191    process leader is allowed to continue. */
192 int pgrp_pipe[2] = { -1, -1 };
193 #endif
194
195 /* The job which is current; i.e. the one that `%+' stands for. */
196 int current_job = NO_JOB;
197
198 /* The previous job; i.e. the one that `%-' stands for. */
199 int previous_job = NO_JOB;
200
201 /* Last child made by the shell.  */
202 pid_t last_made_pid = NO_PID;
203
204 /* Pid of the last asynchronous child. */
205 pid_t last_asynchronous_pid = NO_PID;
206
207 /* The pipeline currently being built. */
208 PROCESS *the_pipeline = (PROCESS *)NULL;
209
210 /* If this is non-zero, do job control. */
211 int job_control = 1;
212
213 /* Call this when you start making children. */
214 int already_making_children = 0;
215
216 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
217    exits from get_tty_state(). */
218 int check_window_size;
219
220 /* Functions local to this file. */
221 static sighandler sigchld_handler ();
222 static int waitchld ();
223 static PROCESS *find_pipeline ();
224 static char *current_working_directory ();
225 static char *job_working_directory ();
226 static pid_t last_pid ();
227 static int set_new_line_discipline (), map_over_jobs (), last_running_job ();
228 static int most_recent_job_in_state (), last_stopped_job (), find_job ();
229 static void notify_of_job_status (), cleanup_dead_jobs (), discard_pipeline ();
230 static void add_process (), set_current_job (), reset_current ();
231 static void print_pipeline ();
232 static void pretty_print_job ();
233 static void mark_dead_jobs_as_notified ();
234 #if defined (PGRP_PIPE)
235 static void pipe_read (), pipe_close ();
236 #endif
237
238 /* Used to synchronize between wait_for and the SIGCHLD signal handler. */
239 static int sigchld;
240 static int waiting_for_job;
241
242 /* A place to temporarily save the current pipeline. */
243 static PROCESS *saved_pipeline;
244 static int saved_already_making_children;
245
246 /* Set this to non-zero whenever you don't want the jobs list to change at
247    all: no jobs deleted and no status change notifications.  This is used,
248    for example, when executing SIGCHLD traps, which may run arbitrary
249    commands. */
250 static int jobs_list_frozen;
251
252 #if !defined (_POSIX_VERSION)
253
254 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
255    library functions and system calls. */
256 #define setpgid(pid, pgrp)      setpgrp (pid, pgrp)
257 #define tcsetpgrp(fd, pgrp)     ioctl ((fd), TIOCSPGRP, &(pgrp))
258
259 pid_t
260 tcgetpgrp (fd)
261      int fd;
262 {
263   pid_t pgrp;
264
265   /* ioctl will handle setting errno correctly. */
266   if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
267     return (-1);
268   return (pgrp);
269 }
270
271 #endif /* !_POSIX_VERSION */
272
273 /* Return the working directory for the current process.  Unlike
274    job_working_directory, this does not call malloc (), nor do any
275    of the functions it calls.  This is so that it can safely be called
276    from a signal handler. */
277 static char *
278 current_working_directory ()
279 {
280   char *dir;
281   static char d[PATH_MAX];
282
283   dir = get_string_value ("PWD");
284
285   if (dir == 0 && the_current_working_directory && no_symbolic_links)
286     dir = the_current_working_directory;
287
288   if (dir == 0)
289     {
290       dir = getcwd (d, sizeof(d));
291       if (dir)
292         dir = d;
293     }
294
295   return (dir == 0) ? "<unknown>" : dir;
296 }
297
298 /* Return the working directory for the current process. */
299 static char *
300 job_working_directory ()
301 {
302   char *dir;
303
304   dir = get_string_value ("PWD");
305   if (dir)
306     return (savestring (dir));
307
308   dir = get_working_directory ("job-working-directory");
309   if (dir)
310     return (dir);
311
312   return (savestring ("<unknown>"));
313 }
314
315 void
316 making_children ()
317 {
318   if (already_making_children)
319     return;
320
321   already_making_children = 1;
322   start_pipeline ();
323 }
324
325 void
326 stop_making_children ()
327 {
328   already_making_children = 0;
329 }
330
331 void
332 cleanup_the_pipeline ()
333 {
334   if (the_pipeline)
335     {
336       discard_pipeline (the_pipeline);
337       the_pipeline = (PROCESS *)NULL;
338     }
339 }
340
341 void
342 save_pipeline (clear)
343      int clear;
344 {
345   saved_pipeline = the_pipeline;
346   saved_already_making_children = already_making_children;
347   if (clear)
348     the_pipeline = (PROCESS *)NULL;
349 }
350
351 void
352 restore_pipeline (discard)
353      int discard;
354 {
355   PROCESS *old_pipeline;
356
357   old_pipeline = the_pipeline;
358   the_pipeline = saved_pipeline;
359   already_making_children = saved_already_making_children;
360   if (discard)
361     discard_pipeline (old_pipeline);
362 }
363
364 /* Start building a pipeline.  */
365 void
366 start_pipeline ()
367 {
368   if (the_pipeline)
369     {
370       cleanup_the_pipeline ();
371       pipeline_pgrp = 0;
372 #if defined (PGRP_PIPE)
373       pipe_close (pgrp_pipe);
374 #endif
375     }
376
377 #if defined (PGRP_PIPE)
378   if (job_control)
379     {
380       if (pipe (pgrp_pipe) == -1)
381         sys_error ("start_pipeline: pgrp pipe");
382     }
383 #endif
384 }
385
386 /* Stop building a pipeline.  Install the process list in the job array.
387    This returns the index of the newly installed job.
388    DEFERRED is a command structure to be executed upon satisfactory
389    execution exit of this pipeline. */
390 int
391 stop_pipeline (async, deferred)
392      int async;
393      COMMAND *deferred;
394 {
395   register int i, j;
396   JOB *newjob;
397   sigset_t set, oset;
398
399   BLOCK_CHILD (set, oset);
400
401 #if defined (PGRP_PIPE)
402   /* The parent closes the process group synchronization pipe. */
403   pipe_close (pgrp_pipe);
404 #endif
405
406   cleanup_dead_jobs ();
407
408   if (job_slots == 0)
409     {
410       job_slots = JOB_SLOTS;
411       jobs = (JOB **)xmalloc (job_slots * sizeof (JOB *));
412
413       /* Now blank out these new entries. */
414       for (i = 0; i < job_slots; i++)
415         jobs[i] = (JOB *)NULL;
416     }
417
418   /* Scan from the last slot backward, looking for the next free one. */
419   if (interactive)
420     {
421       for (i = job_slots; i; i--)
422         if (jobs[i - 1])
423           break;
424     }
425   else
426     {
427       /* If we're not interactive, we don't need to monotonically increase
428          the job number (in fact, we don't care about the job number at all),
429          so we can simply scan for the first free slot.  This helps to keep
430          us from continuously reallocating the jobs array when running
431          certain kinds of shell loops, and saves time spent searching. */
432       for (i = 0; i < job_slots; i++)
433         if (jobs[i] == 0)
434           break;
435     }
436
437   /* Do we need more room? */
438   if (i == job_slots)
439     {
440       job_slots += JOB_SLOTS;
441       jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
442
443       for (j = i; j < job_slots; j++)
444         jobs[j] = (JOB *)NULL;
445     }
446
447   /* Add the current pipeline to the job list. */
448   if (the_pipeline)
449     {
450       register PROCESS *p;
451       int any_alive, any_stopped;
452
453       newjob = (JOB *)xmalloc (sizeof (JOB));
454
455       for (p = the_pipeline; p->next != the_pipeline; p = p->next)
456         ;
457       p->next = (PROCESS *)NULL;
458       newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
459       for (p = newjob->pipe; p->next; p = p->next)
460         ;
461       p->next = newjob->pipe;
462
463       the_pipeline = (PROCESS *)NULL;
464       newjob->pgrp = pipeline_pgrp;
465       pipeline_pgrp = 0;
466
467       newjob->flags = 0;
468
469       /* Flag to see if in another pgrp. */
470       if (job_control)
471         newjob->flags |= J_JOBCONTROL;
472
473       /* Set the state of this pipeline. */
474       p = newjob->pipe;
475       any_alive = any_stopped = 0;
476       do
477         {
478           any_alive |= p->running;
479           any_stopped |= WIFSTOPPED (p->status);
480           p = p->next;
481         }
482       while (p != newjob->pipe);
483
484       newjob->state = any_alive ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
485       newjob->wd = job_working_directory ();
486       newjob->deferred = deferred;
487
488       newjob->j_cleanup = (VFunction *)NULL;
489       newjob->cleanarg = (PTR_T) NULL;
490
491       jobs[i] = newjob;
492       if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
493         setjstatus (i);
494     }
495   else
496     newjob = (JOB *)NULL;
497
498   if (async)
499     {
500       if (newjob)
501         newjob->flags &= ~J_FOREGROUND;
502       reset_current ();
503     }
504   else
505     {
506       if (newjob)
507         {
508           newjob->flags |= J_FOREGROUND;
509           /*
510            *            !!!!! NOTE !!!!!  (chet@ins.cwru.edu)
511            *
512            * The currently-accepted job control wisdom says to set the
513            * terminal's process group n+1 times in an n-step pipeline:
514            * once in the parent and once in each child.  This is where
515            * the parent gives it away.
516            *
517            */
518           if (job_control && newjob->pgrp)
519             give_terminal_to (newjob->pgrp);
520         }
521     }
522
523   stop_making_children ();
524   UNBLOCK_CHILD (oset);
525   return (current_job);
526 }
527
528 /* Delete all DEAD jobs that the user had received notification about. */
529 static void
530 cleanup_dead_jobs ()
531 {
532   register int i;
533   sigset_t set, oset;
534
535   if (job_slots == 0 || jobs_list_frozen)
536     return;
537
538   BLOCK_CHILD (set, oset);
539
540   for (i = 0; i < job_slots; i++)
541     if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
542       delete_job (i);
543
544   UNBLOCK_CHILD (oset);
545 }
546
547 /* Delete the job at INDEX from the job list.  Must be called
548    with SIGCHLD blocked. */
549 void
550 delete_job (job_index)
551      int job_index;
552 {
553   register JOB *temp;
554
555   if (jobs_list_frozen)
556     return;
557
558   temp = jobs[job_index];
559   if (job_index == current_job || job_index == previous_job)
560     reset_current ();
561
562   jobs[job_index] = (JOB *)NULL;
563
564   free (temp->wd);
565   discard_pipeline (temp->pipe);
566
567   if (temp->deferred)
568     dispose_command (temp->deferred);
569
570   free (temp);
571 }
572
573 /* Must be called with SIGCHLD blocked. */
574 void
575 nohup_job (job_index)
576      int job_index;
577 {
578   register JOB *temp;
579
580   temp = jobs[job_index];
581   if (temp)
582     temp->flags |= J_NOHUP;
583 }
584
585 /* Get rid of the data structure associated with a process chain. */
586 static void
587 discard_pipeline (chain)
588      register PROCESS *chain;
589 {
590   register PROCESS *this, *next;
591
592   this = chain;
593   do
594     {
595       next = this->next;
596       FREE (this->command);
597       free (this);
598       this = next;
599     }
600   while (this != chain);
601 }
602
603 /* Add this process to the chain being built in the_pipeline.
604    NAME is the command string that will be exec'ed later.
605    PID is the process id of the child. */
606 static void
607 add_process (name, pid)
608      char *name;
609      pid_t pid;
610 {
611   PROCESS *t, *p;
612
613   t = (PROCESS *)xmalloc (sizeof (PROCESS));
614   t->next = the_pipeline;
615   t->pid = pid;
616   WSTATUS (t->status) = 0;
617   t->running = 1;
618   t->command = name;
619   the_pipeline = t;
620
621   if (t->next == 0)
622     t->next = t;
623   else
624     {
625       p = t->next;
626       while (p->next != t->next)
627         p = p->next;
628       p->next = t;
629     }
630 }
631
632 #if 0
633 /* Take the last job and make it the first job.  Must be called with
634    SIGCHLD blocked. */
635 int
636 rotate_the_pipeline ()
637 {
638   PROCESS *p;
639
640   if (the_pipeline->next == the_pipeline)
641     return;
642   for (p = the_pipeline; p->next != the_pipeline; p = p->next)
643     ;
644   the_pipeline = p;
645 }
646
647 /* Reverse the order of the processes in the_pipeline.  Must be called with
648    SIGCHLD blocked. */
649 int
650 reverse_the_pipeline ()
651 {
652   PROCESS *p, *n;
653
654   if (the_pipeline->next == the_pipeline)
655     return;
656
657   for (p = the_pipeline; p->next != the_pipeline; p = p->next)
658     ;
659   p->next = (PROCESS *)NULL;
660
661   n = REVERSE_LIST (the_pipeline, PROCESS *);
662
663   the_pipeline = n;
664   for (p = the_pipeline; p->next; p = p->next)
665     ;
666   p->next = the_pipeline;
667 }
668 #endif
669
670 /* Map FUNC over the list of jobs.  If FUNC returns non-zero,
671    then it is time to stop mapping, and that is the return value
672    for map_over_jobs.  FUNC is called with a JOB, arg1, arg2,
673    and INDEX. */
674 static int
675 map_over_jobs (func, arg1, arg2)
676      Function *func;
677      int arg1, arg2;
678 {
679   register int i;
680   int result;
681   sigset_t set, oset;
682
683   BLOCK_CHILD (set, oset);
684
685   for (i = result = 0; i < job_slots; i++)
686     {
687       if (jobs[i])
688         {
689           result = (*func)(jobs[i], arg1, arg2, i);
690           if (result)
691             break;
692         }
693     }
694
695   UNBLOCK_CHILD (oset);
696
697   return (result);
698 }
699
700 /* Cause all the jobs in the current pipeline to exit. */
701 void
702 terminate_current_pipeline ()
703 {
704   if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
705     {
706       killpg (pipeline_pgrp, SIGTERM);
707       killpg (pipeline_pgrp, SIGCONT);
708     }
709 }
710
711 /* Cause all stopped jobs to exit. */
712 void
713 terminate_stopped_jobs ()
714 {
715   register int i;
716
717   for (i = 0; i < job_slots; i++)
718     {
719       if (jobs[i] && STOPPED (i))
720         {
721           killpg (jobs[i]->pgrp, SIGTERM);
722           killpg (jobs[i]->pgrp, SIGCONT);
723         }
724     }
725 }
726
727 /* Cause all jobs, running or stopped, to receive a hangup signal.  If
728    a job is marked J_NOHUP, don't send the SIGHUP. */
729 void
730 hangup_all_jobs ()
731 {
732   register int i;
733
734   for (i = 0; i < job_slots; i++)
735     {
736       if (jobs[i])
737         {
738           if  ((jobs[i]->flags & J_NOHUP) == 0)
739             killpg (jobs[i]->pgrp, SIGHUP);
740           if (STOPPED (i))
741             killpg (jobs[i]->pgrp, SIGCONT);
742         }
743     }
744 }
745
746 void
747 kill_current_pipeline ()
748 {
749   stop_making_children ();
750   start_pipeline ();
751 }
752
753 /* Return the pipeline that PID belongs to.  Note that the pipeline
754    doesn't have to belong to a job.  Must be called with SIGCHLD blocked. */
755 static PROCESS *
756 find_pipeline (pid)
757      pid_t pid;
758 {
759   int job;
760   register PROCESS *p;
761
762   /* See if this process is in the pipeline that we are building. */
763   if (the_pipeline)
764     {
765       p = the_pipeline;
766       do
767         {
768           /* Return it if we found it. */
769           if (p->pid == pid)
770             return (p);
771
772           p = p->next;
773         }
774       while (p != the_pipeline);
775     }
776
777   job = find_job (pid);
778
779   return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
780 }
781
782 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
783    belong to any job.  Must be called with SIGCHLD blocked. */
784 static int
785 find_job (pid)
786      pid_t pid;
787 {
788   register int i;
789   register PROCESS *p;
790
791   for (i = 0; i < job_slots; i++)
792     {
793       if (jobs[i])
794         {
795           p = jobs[i]->pipe;
796
797           do
798             {
799               if (p->pid == pid)
800                 return (i);
801
802               p = p->next;
803             }
804           while (p != jobs[i]->pipe);
805         }
806     }
807
808   return (NO_JOB);
809 }
810
811 /* Print descriptive information about the job with leader pid PID. */
812 void
813 describe_pid (pid)
814      pid_t pid;
815 {
816   int job;
817   sigset_t set, oset;
818
819   BLOCK_CHILD (set, oset);
820
821   job = find_job (pid);
822
823   if (job != NO_JOB)
824     printf ("[%d] %d\n", job + 1, (int)pid);
825   else
826     programming_error ("describe_pid: %d: no such pid", (int)pid);
827
828   UNBLOCK_CHILD (oset);
829 }
830
831 /* This is the way to print out information on a job if you
832    know the index.  FORMAT is:
833
834     JLIST_NORMAL)   [1]+ Running           emacs
835     JLIST_LONG  )   [1]+ 2378 Running      emacs
836     -1    )   [1]+ 2378       emacs
837
838     JLIST_NORMAL)   [1]+ Stopped           ls | more
839     JLIST_LONG  )   [1]+ 2369 Stopped      ls
840                          2367       | more
841     JLIST_PID_ONLY)
842         Just list the pid of the process group leader (really
843         the process group).
844     JLIST_CHANGED_ONLY)
845         Use format JLIST_NORMAL, but list only jobs about which
846         the user has not been notified. */
847
848 /* Print status for pipeline P.  If JOB_INDEX is >= 0, it is the index into
849    the JOBS array corresponding to this pipeline.  FORMAT is as described
850    above.  Must be called with SIGCHLD blocked.
851
852    If you're printing a pipeline that's not in the jobs array, like the
853    current pipeline as it's being created, pass -1 for JOB_INDEX */
854 static void
855 print_pipeline (p, job_index, format, stream)
856      PROCESS *p;
857      int job_index, format;
858      FILE *stream;
859 {
860   PROCESS *first, *last, *show;
861   int es, name_padding;
862   char retcode_name_buffer[20], *temp;
863
864   if (p == 0)
865     return;
866
867   first = last = p;
868   while (last->next != first)
869     last = last->next;
870
871   for (;;)
872     {
873       if (p != first)
874         fprintf (stream, format ? "     " : " |");
875
876       if (format != JLIST_STANDARD)
877         fprintf (stream, "%5d", (int)p->pid);
878
879       fprintf (stream, " ");
880
881       if (format > -1 && job_index >= 0)
882         {
883           show = format ? p : last;
884           temp = "Done";
885
886           if (STOPPED (job_index) && format == 0)
887             temp = "Stopped";
888
889           else if (RUNNING (job_index))
890             temp = "Running";
891           else
892             {
893               if (WIFSTOPPED (show->status))
894                 temp = strsignal (WSTOPSIG (show->status));
895               else if (WIFSIGNALED (show->status))
896                 temp = strsignal (WTERMSIG (show->status));
897               else if (WIFEXITED (show->status))
898                 {
899                   temp = retcode_name_buffer;
900                   es = WEXITSTATUS (show->status);
901
902                   if (es == 0)
903                     strcpy (temp, "Done");
904                   else if (posixly_correct)
905                     sprintf (temp, "Done(%d)", es);
906                   else
907                     sprintf (temp, "Exit %d", es);
908                 }
909               else
910                 temp = "Unknown status";
911             }
912
913           if (p != first)
914             {
915               if (format)
916                 {
917                   if (show->running == first->running &&
918                       WSTATUS (show->status) == WSTATUS (first->status))
919                     temp = "";
920                 }
921               else
922                 temp = (char *)NULL;
923             }
924
925           if (temp)
926             {
927               fprintf (stream, "%s", temp);
928
929               es = STRLEN (temp);
930               if (es == 0)
931                 es = 2; /* strlen ("| ") */
932               name_padding = LONGEST_SIGNAL_DESC - es;
933
934               fprintf (stream, "%*s", name_padding, "");
935
936               if ((WIFSTOPPED (show->status) == 0) && WIFCORED (show->status))
937                 fprintf (stream, "(core dumped) ");
938             }
939         }
940
941       if (p != first && format)
942         fprintf (stream, "| ");
943
944       if (p->command)
945         fprintf (stream, "%s", p->command);
946
947       if (p == last && job_index >= 0)
948         {
949           temp = current_working_directory ();
950
951           if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
952             fprintf (stream, " &");
953
954           if (strcmp (temp, jobs[job_index]->wd) != 0)
955             fprintf (stream,
956               "  (wd: %s)", polite_directory_format (jobs[job_index]->wd));
957         }
958
959       if (format || (p == last))
960         fprintf (stream, "\r\n");
961
962       if (p == last)
963         break;
964       p = p->next;
965     }
966   fflush (stream);
967 }
968
969 static void
970 pretty_print_job (job_index, format, stream)
971      int job_index, format;
972      FILE *stream;
973 {
974   register PROCESS *p;
975   sigset_t set, oset;
976
977   BLOCK_CHILD (set, oset);
978
979   /* Format only pid information about the process group leader? */
980   if (format == JLIST_PID_ONLY)
981     {
982       fprintf (stream, "%d\n", (int)jobs[job_index]->pipe->pid);
983       UNBLOCK_CHILD (oset);
984       return;
985     }
986
987   if (format == JLIST_CHANGED_ONLY)
988     {
989       if (IS_NOTIFIED (job_index))
990         {
991           UNBLOCK_CHILD (oset);
992           return;
993         }
994       format = JLIST_STANDARD;
995     }
996
997   if (format != JLIST_NONINTERACTIVE)
998     fprintf (stream, "[%d]%c ", job_index + 1,
999               (job_index == current_job) ? '+':
1000                 (job_index == previous_job) ? '-' : ' ');
1001
1002   if (format == JLIST_NONINTERACTIVE)
1003     format = JLIST_LONG;
1004
1005   p = jobs[job_index]->pipe;
1006
1007   /* We have printed information about this job.  When the job's
1008      status changes, waitchld () sets the notification flag to 0. */
1009   jobs[job_index]->flags |= J_NOTIFIED;
1010
1011   print_pipeline (p, job_index, format, stream);
1012
1013   UNBLOCK_CHILD (oset);
1014 }
1015
1016 static int
1017 print_job (job, format, state, job_index)
1018      JOB *job;
1019      int format, state, job_index;
1020 {
1021   if (state == -1 || (JOB_STATE)state == job->state)
1022     pretty_print_job (job_index, format, stdout);
1023   return (0);
1024 }
1025
1026 void
1027 list_one_job (job, format, ignore, job_index)
1028      JOB *job;
1029      int format, ignore, job_index;
1030 {
1031   print_job (job, format, -1, job_index);
1032 }
1033
1034 void
1035 list_stopped_jobs (format)
1036      int format;
1037 {
1038   cleanup_dead_jobs ();
1039   map_over_jobs (print_job, format, (int)JSTOPPED);
1040 }
1041
1042 void
1043 list_running_jobs (format)
1044      int format;
1045 {
1046   cleanup_dead_jobs ();
1047   map_over_jobs (print_job, format, (int)JRUNNING);
1048 }
1049
1050 /* List jobs.  If FORMAT is non-zero, then the long form of the information
1051    is printed, else just a short version. */
1052 void
1053 list_all_jobs (format)
1054      int format;
1055 {
1056   cleanup_dead_jobs ();
1057   map_over_jobs (print_job, format, -1);
1058 }
1059
1060 /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
1061    COMMAND is just for remembering the name of the command; we don't do
1062    anything else with it.  ASYNC_P says what to do with the tty.  If
1063    non-zero, then don't give it away. */
1064 pid_t
1065 make_child (command, async_p)
1066      char *command;
1067      int async_p;
1068 {
1069   sigset_t set, oset;
1070   pid_t pid;
1071
1072   sigemptyset (&set);
1073   sigaddset (&set, SIGCHLD);
1074   sigaddset (&set, SIGINT);
1075   sigemptyset (&oset);
1076   sigprocmask (SIG_BLOCK, &set, &oset);
1077
1078   making_children ();
1079
1080 #if defined (BUFFERED_INPUT)
1081   /* If default_buffered_input is active, we are reading a script.  If
1082      the command is asynchronous, we have already duplicated /dev/null
1083      as fd 0, but have not changed the buffered stream corresponding to
1084      the old fd 0.  We don't want to sync the stream in this case. */
1085   if (default_buffered_input != -1 &&
1086       (!async_p || default_buffered_input > 0))
1087     sync_buffered_stream (default_buffered_input);
1088 #endif /* BUFFERED_INPUT */
1089
1090   /* Create the child, handle severe errors. */
1091   if ((pid = fork ()) < 0)
1092     {
1093       sys_error ("fork");
1094
1095       /* Kill all of the processes in the current pipeline. */
1096       terminate_current_pipeline ();
1097
1098       /* Discard the current pipeline, if any. */
1099       if (the_pipeline)
1100         kill_current_pipeline ();
1101
1102       throw_to_top_level ();    /* Reset signals, etc. */
1103     }
1104
1105   if (pid == 0)
1106     {
1107       /* In the child.  Give this child the right process group, set the
1108          signals to the default state for a new process. */
1109       pid_t mine;
1110
1111       mine = getpid ();
1112 #if defined (BUFFERED_INPUT)
1113       /* Close default_buffered_input if it's > 0.  We don't close it if it's
1114          0 because that's the file descriptor used when redirecting input,
1115          and it's wrong to close the file in that case. */
1116       if (default_buffered_input > 0)
1117         {
1118           close_buffered_fd (default_buffered_input);
1119           default_buffered_input = bash_input.location.buffered_fd = -1;
1120         }
1121 #endif /* BUFFERED_INPUT */
1122
1123       /* Restore top-level signal mask. */
1124       sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1125
1126       if (job_control)
1127         {
1128           /* All processes in this pipeline belong in the same
1129              process group. */
1130
1131           if (pipeline_pgrp == 0)       /* This is the first child. */
1132             pipeline_pgrp = mine;
1133
1134           /* Check for running command in backquotes. */
1135           if (pipeline_pgrp == shell_pgrp)
1136             ignore_tty_job_signals ();
1137           else
1138             default_tty_job_signals ();
1139
1140           /* Set the process group before trying to mess with the terminal's
1141              process group.  This is mandated by POSIX. */
1142           /* This is in accordance with the Posix 1003.1 standard,
1143              section B.7.2.4, which says that trying to set the terminal
1144              process group with tcsetpgrp() to an unused pgrp value (like
1145              this would have for the first child) is an error.  Section
1146              B.4.3.3, p. 237 also covers this, in the context of job control
1147              shells. */
1148           if (setpgid (mine, pipeline_pgrp) < 0)
1149             sys_error ("child setpgid (%d to %d)", mine, pipeline_pgrp);
1150 #if defined (PGRP_PIPE)
1151           if (pipeline_pgrp == mine)
1152             {
1153 #endif
1154               if (async_p == 0)
1155                 give_terminal_to (pipeline_pgrp);
1156
1157 #if defined (PGRP_PIPE)
1158               pipe_read (pgrp_pipe);
1159             }
1160 #endif
1161         }
1162       else                      /* Without job control... */
1163         {
1164           if (pipeline_pgrp == 0)
1165             pipeline_pgrp = shell_pgrp;
1166
1167           /* If these signals are set to SIG_DFL, we encounter the curious
1168              situation of an interactive ^Z to a running process *working*
1169              and stopping the process, but being unable to do anything with
1170              that process to change its state.  On the other hand, if they
1171              are set to SIG_IGN, jobs started from scripts do not stop when
1172              the shell running the script gets a SIGTSTP and stops. */
1173
1174           default_tty_job_signals ();
1175         }
1176
1177 #if defined (PGRP_PIPE)
1178       /* Release the process group pipe, since our call to setpgid ()
1179          is done.  The last call to pipe_close is done in stop_pipeline. */
1180       pipe_close (pgrp_pipe);
1181 #endif /* PGRP_PIPE */
1182
1183       if (async_p)
1184         last_asynchronous_pid = getpid ();
1185     }
1186   else
1187     {
1188       /* In the parent.  Remember the pid of the child just created
1189          as the proper pgrp if this is the first child. */
1190
1191       if (job_control)
1192         {
1193           if (pipeline_pgrp == 0)
1194             {
1195               pipeline_pgrp = pid;
1196               /* Don't twiddle terminal pgrps in the parent!  This is the bug,
1197                  not the good thing of twiddling them in the child! */
1198               /* give_terminal_to (pipeline_pgrp); */
1199             }
1200           /* This is done on the recommendation of the Rationale section of
1201              the POSIX 1003.1 standard, where it discusses job control and
1202              shells.  It is done to avoid possible race conditions. (Ref.
1203              1003.1 Rationale, section B.4.3.3, page 236). */
1204           setpgid (pid, pipeline_pgrp);
1205         }
1206       else
1207         {
1208           if (pipeline_pgrp == 0)
1209             pipeline_pgrp = shell_pgrp;
1210         }
1211
1212       /* Place all processes into the jobs array regardless of the
1213          state of job_control. */
1214       add_process (command, pid);
1215
1216       if (async_p)
1217         last_asynchronous_pid = pid;
1218
1219       last_made_pid = pid;
1220
1221       /* Unblock SIGINT and SIGCHLD. */
1222       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1223     }
1224
1225   return (pid);
1226 }
1227
1228 void
1229 ignore_tty_job_signals ()
1230 {
1231   set_signal_handler (SIGTSTP, SIG_IGN);
1232   set_signal_handler (SIGTTIN, SIG_IGN);
1233   set_signal_handler (SIGTTOU, SIG_IGN);
1234 }
1235
1236 void
1237 default_tty_job_signals ()
1238 {
1239   set_signal_handler (SIGTSTP, SIG_DFL);
1240   set_signal_handler (SIGTTIN, SIG_DFL);
1241   set_signal_handler (SIGTTOU, SIG_DFL);
1242 }
1243
1244 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1245    state kept in here.  When a job ends normally, we set the state in here
1246    to the state of the tty. */
1247
1248 #if defined (NEW_TTY_DRIVER)
1249 static struct sgttyb shell_tty_info;
1250 static struct tchars shell_tchars;
1251 static struct ltchars shell_ltchars;
1252 #endif /* NEW_TTY_DRIVER */
1253
1254 #if defined (TERMIO_TTY_DRIVER)
1255 static struct termio shell_tty_info;
1256 #endif /* TERMIO_TTY_DRIVER */
1257
1258 #if defined (TERMIOS_TTY_DRIVER)
1259 static struct termios shell_tty_info;
1260 #endif /* TERMIOS_TTY_DRIVER */
1261
1262 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1263 /* Since the BSD tty driver does not allow us to change the tty modes
1264    while simultaneously waiting for output to drain and preserving
1265    typeahead, we have to drain the output ourselves before calling
1266    ioctl.  We cheat by finding the length of the output queue, and
1267    using select to wait for an appropriate length of time.  This is
1268    a hack, and should be labeled as such (it's a hastily-adapted
1269    mutation of a `usleep' implementation).  It's only reason for
1270    existing is the flaw in the BSD tty driver. */
1271
1272 static int ttspeeds[] =
1273 {
1274   0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1275   1800, 2400, 4800, 9600, 19200, 38400
1276 };
1277
1278 static void
1279 draino (fd, ospeed)
1280      int fd, ospeed;
1281 {
1282   register int delay = ttspeeds[ospeed];
1283   int n;
1284
1285   if (!delay)
1286     return;
1287
1288   while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1289     {
1290       if (n > (delay / 100))
1291         {
1292           struct timeval tv;
1293
1294           n *= 10;              /* 2 bits more for conservativeness. */
1295           tv.tv_sec = n / delay;
1296           tv.tv_usec = ((n % delay) * 1000000) / delay;
1297           select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1298         }
1299       else
1300         break;
1301     }
1302 }
1303 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1304
1305 /* Return the fd from which we are actually getting input. */
1306 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1307
1308 /* Fill the contents of shell_tty_info with the current tty info. */
1309 int
1310 get_tty_state ()
1311 {
1312   int tty;
1313
1314   tty = input_tty ();
1315   if (tty != -1)
1316     {
1317 #if defined (NEW_TTY_DRIVER)
1318       ioctl (tty, TIOCGETP, &shell_tty_info);
1319       ioctl (tty, TIOCGETC, &shell_tchars);
1320       ioctl (tty, TIOCGLTC, &shell_ltchars);
1321 #endif /* NEW_TTY_DRIVER */
1322
1323 #if defined (TERMIO_TTY_DRIVER)
1324       ioctl (tty, TCGETA, &shell_tty_info);
1325 #endif /* TERMIO_TTY_DRIVER */
1326
1327 #if defined (TERMIOS_TTY_DRIVER)
1328       if (tcgetattr (tty, &shell_tty_info) < 0)
1329         {
1330 #if 0
1331           /* Only print an error message if we're really interactive at
1332              this time. */
1333           if (interactive)
1334             sys_error ("[%d: %d] tcgetattr", getpid (), shell_level);
1335 #endif
1336           return -1;
1337         }
1338 #endif /* TERMIOS_TTY_DRIVER */
1339       if (check_window_size)
1340         get_new_window_size (0);
1341     }
1342   return 0;
1343 }
1344
1345 /* Make the current tty use the state in shell_tty_info. */
1346 int
1347 set_tty_state ()
1348 {
1349   int tty = input_tty ();
1350
1351   if (tty != -1)
1352     {
1353 #if defined (NEW_TTY_DRIVER)
1354 #  if defined (DRAIN_OUTPUT)
1355       draino (tty, shell_tty_info.sg_ospeed);
1356 #  endif /* DRAIN_OUTPUT */
1357       ioctl (tty, TIOCSETN, &shell_tty_info);
1358       ioctl (tty, TIOCSETC, &shell_tchars);
1359       ioctl (tty, TIOCSLTC, &shell_ltchars);
1360 #endif /* NEW_TTY_DRIVER */
1361
1362 #if defined (TERMIO_TTY_DRIVER)
1363       ioctl (tty, TCSETAW, &shell_tty_info);
1364 #endif /* TERMIO_TTY_DRIVER */
1365
1366 #if defined (TERMIOS_TTY_DRIVER)
1367       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1368         {
1369           /* Only print an error message if we're really interactive at
1370              this time. */
1371           if (interactive)
1372             sys_error ("[%d: %d] tcsetattr", getpid (), shell_level);
1373           return -1;
1374         }
1375 #endif /* TERMIOS_TTY_DRIVER */
1376     }
1377   return 0;
1378 }
1379
1380 /* Given an index into the jobs array JOB, return the pid of the last
1381    process in that job's pipeline.  This is the one whose exit status
1382    counts. */
1383 static pid_t
1384 last_pid (job)
1385      int job;
1386 {
1387   register PROCESS *p;
1388   sigset_t set, oset;
1389
1390   BLOCK_CHILD (set, oset);
1391
1392   p = jobs[job]->pipe;
1393   while (p->next != jobs[job]->pipe)
1394     p = p->next;
1395
1396   UNBLOCK_CHILD (oset);
1397   return (p->pid);
1398 }
1399
1400 /* Wait for a particular child of the shell to finish executing.
1401    This low-level function prints an error message if PID is not
1402    a child of this shell.  It returns -1 if it fails, or 0 if not. */
1403 int
1404 wait_for_single_pid (pid)
1405      pid_t pid;
1406 {
1407   register PROCESS *child;
1408   sigset_t set, oset;
1409
1410   BLOCK_CHILD (set, oset);
1411   child = find_pipeline (pid);
1412   UNBLOCK_CHILD (oset);
1413
1414   if (child == 0)
1415     {
1416       internal_error ("wait: pid %d is not a child of this shell", pid);
1417       return (127);
1418     }
1419
1420   return (wait_for (pid));
1421 }
1422
1423 /* Wait for all of the backgrounds of this shell to finish. */
1424 void
1425 wait_for_background_pids ()
1426 {
1427   register int i, count;
1428   sigset_t set, oset;
1429   pid_t pid;
1430
1431   for (;;)
1432     {
1433       BLOCK_CHILD (set, oset);
1434
1435       count = 0;
1436       for (i = 0; i < job_slots; i++)
1437         if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1438           {
1439             count++;
1440             break;
1441           }
1442
1443       if (count == 0)
1444         {
1445           UNBLOCK_CHILD (oset);
1446           break;
1447         }
1448
1449       for (i = 0; i < job_slots; i++)
1450         if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1451           {
1452             pid = last_pid (i);
1453             UNBLOCK_CHILD (oset);
1454             QUIT;
1455             wait_for_single_pid (pid);
1456             break;
1457           }
1458     }
1459 }
1460
1461 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
1462 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
1463 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
1464
1465 static void
1466 restore_sigint_handler ()
1467 {
1468   if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1469     {
1470       set_signal_handler (SIGINT, old_sigint_handler);
1471       old_sigint_handler = INVALID_SIGNAL_HANDLER;
1472     }
1473 }
1474
1475 static int wait_sigint_received;
1476
1477 /* Handle SIGINT while we are waiting for children in a script to exit.
1478    The `wait' builtin should be interruptible, but all others should be
1479    effectively ignored (i.e. not cause the shell to exit). */
1480 static sighandler
1481 wait_sigint_handler (sig)
1482      int sig;
1483 {
1484   if (interrupt_immediately ||
1485       (this_shell_builtin && this_shell_builtin == wait_builtin))
1486     {
1487       last_command_exit_value = EXECUTION_FAILURE;
1488       restore_sigint_handler ();
1489       ADDINTERRUPT;
1490       QUIT;
1491     }
1492
1493   /* XXX - should this be interrupt_state?  If it is, the shell will act
1494      as if it got the SIGINT interrupt. */
1495   wait_sigint_received = 1;
1496
1497   /* Otherwise effectively ignore the SIGINT and allow the running job to
1498      be killed. */
1499   SIGRETURN (0);
1500 }
1501
1502 static int
1503 process_exit_status (status)
1504      WAIT status;
1505 {
1506   if (WIFSIGNALED (status))
1507     return (128 + WTERMSIG (status));
1508   else if (WIFSTOPPED (status) == 0)
1509     return (WEXITSTATUS (status));
1510   else
1511     return (EXECUTION_SUCCESS);
1512 }
1513
1514 static int
1515 job_exit_status (job)
1516      int job;
1517 {
1518   register PROCESS *p;
1519   for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
1520     ;
1521   return (process_exit_status (p->status));
1522 }
1523
1524 /* Wait for pid (one of our children) to terminate, then
1525    return the termination state. */
1526 #define FIND_CHILD(pid, child) \
1527   do \
1528     { \
1529       child = find_pipeline (pid); \
1530       if (child == 0) \
1531         { \
1532           give_terminal_to (shell_pgrp); \
1533           UNBLOCK_CHILD (oset); \
1534           internal_error ("wait_for: No record of process %d", pid); \
1535           restore_sigint_handler (); \
1536           return (termination_state = 127); \
1537         } \
1538     } \
1539   while (0)
1540
1541 int
1542 wait_for (pid)
1543      pid_t pid;
1544 {
1545   int job, termination_state;
1546   register PROCESS *child;
1547   sigset_t set, oset;
1548 #if 0
1549   register PROCESS *p;
1550   int job_state, any_stopped;
1551 #endif
1552
1553   /* In the case that this code is interrupted, and we longjmp () out of it,
1554      we are relying on the code in throw_to_top_level () to restore the
1555      top-level signal mask. */
1556   BLOCK_CHILD (set, oset);
1557
1558   /* Ignore interrupts while waiting for a job run without job control
1559      to finish.  We don't want the shell to exit if an interrupt is
1560      received, only if one of the jobs run is killed via SIGINT.  If
1561      job control is not set, the job will be run in the same pgrp as
1562      the shell, and the shell will see any signals the job gets. */
1563
1564   /* This is possibly a race condition -- should it go in stop_pipeline? */
1565   wait_sigint_received = 0;
1566   if (job_control == 0)
1567     old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
1568
1569   termination_state = last_command_exit_value;
1570
1571   if (interactive && job_control == 0)
1572     QUIT;
1573
1574   /* If we say wait_for (), then we have a record of this child somewhere.
1575      If it and none of its peers are running, don't call waitchld(). */
1576
1577   job = NO_JOB;
1578   do
1579     {
1580       FIND_CHILD (pid, child);
1581
1582       /* If this child is part of a job, then we are really waiting for the
1583          job to finish.  Otherwise, we are waiting for the child to finish.
1584          We check for JDEAD in case the job state has been set by waitchld
1585          after receipt of a SIGCHLD. */
1586       if (job == NO_JOB)
1587         job = find_job (pid);
1588
1589 #if 0
1590       /* XXX - let waitchld take care of setting this.  If the job has
1591          already exited before this is called, sigchld_handler will have
1592          called waitchld and this will be set to JDEAD. */
1593       if (job != NO_JOB && JOBSTATE (job) != JDEAD)
1594         {
1595           job_state = any_stopped = 0;
1596           p = jobs[job]->pipe;
1597           do
1598             {
1599               job_state |= p->running;
1600               if (p->running == 0)
1601                 any_stopped |= WIFSTOPPED (p->status);
1602               p = p->next;
1603             }
1604           while (p != jobs[job]->pipe);
1605
1606           if (job_state == 0)
1607             jobs[job]->state = any_stopped ? JSTOPPED : JDEAD;
1608         }
1609 #endif
1610
1611       if (child->running || (job != NO_JOB && RUNNING (job)))
1612         {
1613 #if defined (WAITPID_BROKEN)    /* SCOv4 */
1614           sigset_t suspend_set;
1615           sigemptyset (&suspend_set);
1616           sigsuspend (&suspend_set);
1617 #else /* !WAITPID_BROKEN */
1618 #  if defined (MUST_UNBLOCK_CHLD)
1619           struct sigaction act, oact;
1620           sigset_t nullset, chldset;
1621
1622           sigemptyset (&nullset);
1623           sigemptyset (&chldset);
1624           sigprocmask (SIG_SETMASK, &nullset, &chldset);
1625           act.sa_handler = SIG_DFL;
1626           sigemptyset (&act.sa_mask);
1627           sigemptyset (&oact.sa_mask);
1628           act.sa_flags = 0;
1629           sigaction (SIGCHLD, &act, &oact);
1630 #  endif
1631           waiting_for_job = 1;
1632           waitchld (pid, 1);
1633 #  if defined (MUST_UNBLOCK_CHLD)
1634           sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
1635           sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
1636 #  endif
1637           waiting_for_job = 0;
1638 #endif /* WAITPID_BROKEN */
1639         }
1640
1641       /* If the shell is interactive, and job control is disabled, see
1642          if the foreground process has died due to SIGINT and jump out
1643          of the wait loop if it has.  waitchld has already restored the
1644          old SIGINT signal handler. */
1645       if (interactive && job_control == 0)
1646         QUIT;
1647     }
1648   while (child->running || (job != NO_JOB && RUNNING (job)));
1649
1650   /* The exit state of the command is either the termination state of the
1651      child, or the termination state of the job.  If a job, the status
1652      of the last child in the pipeline is the significant one. */
1653
1654   if (job != NO_JOB)
1655     termination_state = job_exit_status (job);
1656   else
1657     termination_state = process_exit_status (child->status);
1658
1659   if (job == NO_JOB || IS_JOBCONTROL (job))
1660     give_terminal_to (shell_pgrp);
1661
1662   /* If the command did not exit cleanly, or the job is just
1663      being stopped, then reset the tty state back to what it
1664      was before this command.  Reset the tty state and notify
1665      the user of the job termination only if the shell is
1666      interactive.  Clean up any dead jobs in either case. */
1667   if (job != NO_JOB)
1668     {
1669       if (interactive_shell && subshell_environment == 0)
1670         {
1671           if (WIFSIGNALED (child->status) || WIFSTOPPED (child->status))
1672             set_tty_state ();
1673           else
1674             get_tty_state ();
1675
1676           /* If job control is enabled, the job was started with job
1677              control, the job was the foreground job, and it was killed
1678              by SIGINT, then print a newline to compensate for the kernel
1679              printing the ^C without a trailing newline. */
1680           if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
1681                 WIFSIGNALED (child->status) &&
1682                 WTERMSIG (child->status) == SIGINT)
1683             {
1684               /* If SIGINT is not trapped and the shell is in a for, while,
1685                  or until loop, act as if the shell received SIGINT as
1686                  well, so the loop can be broken.  This doesn't call the
1687                  SIGINT signal handler; maybe it should. */
1688               if (signal_is_trapped (SIGINT) == 0 && loop_level)
1689                 ADDINTERRUPT;
1690               else
1691                 {
1692                   putchar ('\n');
1693                   fflush (stdout);
1694                 }
1695             }
1696
1697           notify_and_cleanup ();
1698         }
1699       else
1700         {
1701           /* If this job is dead, and the shell is not interactive, make
1702              sure we turn on the notify bit so we don't get an unwanted
1703              message about the job's termination, and so delete_job really
1704              clears the slot in the jobs table. */
1705 #if 0
1706           if (DEADJOB (job))
1707             jobs[job]->flags |= J_NOTIFIED;
1708           cleanup_dead_jobs ();
1709 #else
1710           notify_and_cleanup ();
1711 #endif
1712         }
1713     }
1714
1715   UNBLOCK_CHILD (oset);
1716
1717   /* Restore the original SIGINT signal handler before we return. */
1718   restore_sigint_handler ();
1719
1720   return (termination_state);
1721 }
1722
1723 /* Wait for the last process in the pipeline for JOB. */
1724 int
1725 wait_for_job (job)
1726      int job;
1727 {
1728   pid_t pid;
1729
1730   pid = last_pid (job);
1731   return (wait_for (pid));
1732 }
1733
1734 /* Print info about dead jobs, and then delete them from the list
1735    of known jobs.  This does not actually delete jobs when the
1736    shell is not interactive, because the dead jobs are not marked
1737    as notified. */
1738 void
1739 notify_and_cleanup ()
1740 {
1741   if (jobs_list_frozen)
1742     return;
1743
1744   if (interactive || interactive_shell == 0)
1745     notify_of_job_status ();
1746
1747   cleanup_dead_jobs ();
1748 }
1749
1750 /* Make dead jobs disappear from the jobs array without notification.
1751    This is used when the shell is not interactive. */
1752 void
1753 reap_dead_jobs ()
1754 {
1755   mark_dead_jobs_as_notified ();
1756   cleanup_dead_jobs ();
1757 }
1758
1759 /* Return the next closest (chronologically) job to JOB which is in
1760    STATE.  STATE can be JSTOPPED, JRUNNING.  NO_JOB is returned if
1761    there is no next recent job. */
1762 static int
1763 most_recent_job_in_state (job, state)
1764      int job;
1765      JOB_STATE state;
1766 {
1767   register int i, result;
1768   sigset_t set, oset;
1769
1770   BLOCK_CHILD (set, oset);
1771   for (result = NO_JOB, i = job - 1; i >= 0; i--)
1772     {
1773       if (jobs[i] && (JOBSTATE (i) == state))
1774         {
1775           result = i;
1776           break;
1777         }
1778     }
1779   UNBLOCK_CHILD (oset);
1780
1781   return (result);
1782 }
1783
1784 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
1785    found. */
1786 static int
1787 last_stopped_job (job)
1788      int job;
1789 {
1790   return (most_recent_job_in_state (job, JSTOPPED));
1791 }
1792
1793 /* Return the newest *running* job older than JOB, or NO_JOB if not
1794    found. */
1795 static int
1796 last_running_job (job)
1797      int job;
1798 {
1799   return (most_recent_job_in_state (job, JRUNNING));
1800 }
1801
1802 /* Make JOB be the current job, and make previous be useful.  Must be
1803    called with SIGCHLD blocked. */
1804 static void
1805 set_current_job (job)
1806      int job;
1807 {
1808   int candidate;
1809
1810   if (current_job != job)
1811     {
1812       previous_job = current_job;
1813       current_job = job;
1814     }
1815
1816   /* First choice for previous_job is the old current_job. */
1817   if (previous_job != current_job &&
1818       previous_job != NO_JOB &&
1819       jobs[previous_job] &&
1820       STOPPED (previous_job))
1821     return;
1822
1823   /* Second choice:  Newest stopped job that is older than
1824      the current job. */
1825   candidate = NO_JOB;
1826   if (STOPPED (current_job))
1827     {
1828       candidate = last_stopped_job (current_job);
1829
1830       if (candidate != NO_JOB)
1831         {
1832           previous_job = candidate;
1833           return;
1834         }
1835     }
1836
1837   /* If we get here, there is either only one stopped job, in which case it is
1838      the current job and the previous job should be set to the newest running
1839      job, or there are only running jobs and the previous job should be set to
1840      the newest running job older than the current job.  We decide on which
1841      alternative to use based on whether or not JOBSTATE(current_job) is
1842      JSTOPPED. */
1843
1844   candidate = RUNNING (current_job) ? last_running_job (current_job)
1845                                     : last_running_job (job_slots);
1846
1847   if (candidate != NO_JOB)
1848     {
1849       previous_job = candidate;
1850       return;
1851     }
1852
1853   /* There is only a single job, and it is both `+' and `-'. */
1854   previous_job = current_job;
1855 }
1856
1857 /* Make current_job be something useful, if it isn't already. */
1858
1859 /* Here's the deal:  The newest non-running job should be `+', and the
1860    next-newest non-running job should be `-'.  If there is only a single
1861    stopped job, the previous_job is the newest non-running job.  If there
1862    are only running jobs, the newest running job is `+' and the
1863    next-newest running job is `-'.  Must be called with SIGCHLD blocked. */
1864
1865 static void
1866 reset_current ()
1867 {
1868   int candidate;
1869
1870   if (job_slots && current_job != NO_JOB && jobs[current_job] && STOPPED (current_job))
1871     candidate = current_job;
1872   else
1873     {
1874       candidate = NO_JOB;
1875
1876       /* First choice: the previous job. */
1877       if (previous_job != NO_JOB && jobs[previous_job] && STOPPED (previous_job))
1878         candidate = previous_job;
1879
1880       /* Second choice: the most recently stopped job. */
1881       if (candidate == NO_JOB)
1882         candidate = last_stopped_job (job_slots);
1883
1884       /* Third choice: the newest running job. */
1885       if (candidate == NO_JOB)
1886         candidate = last_running_job (job_slots);
1887     }
1888
1889   /* If we found a job to use, then use it.  Otherwise, there
1890      are no jobs period. */
1891   if (candidate != NO_JOB)
1892     set_current_job (candidate);
1893   else
1894     current_job = previous_job = NO_JOB;
1895 }
1896
1897 /* Start a job.  FOREGROUND if non-zero says to do that.  Otherwise,
1898    start the job in the background.  JOB is a zero-based index into
1899    JOBS.  Returns -1 if it is unable to start a job, and the return
1900    status of the job otherwise. */
1901 int
1902 start_job (job, foreground)
1903      int job, foreground;
1904 {
1905   register PROCESS *p;
1906   int already_running;
1907   sigset_t set, oset;
1908   char *wd;
1909 #if defined (NEW_TTY_DRIVER)
1910   static struct sgttyb save_stty;
1911 #endif
1912 #if defined (TERMIO_TTY_DRIVER)
1913   static struct termio save_stty;
1914 #endif
1915 #if defined (TERMIOS_TTY_DRIVER)
1916   static struct termios save_stty;
1917 #endif
1918
1919   BLOCK_CHILD (set, oset);
1920
1921   if (DEADJOB (job))
1922     {
1923       internal_error ("%s: job has terminated", this_command_name);
1924       UNBLOCK_CHILD (oset);
1925       return (-1);
1926     }
1927
1928   already_running = RUNNING (job);
1929
1930   if (foreground == 0 && already_running)
1931     {
1932       internal_error ("%s: bg background job?", this_command_name);
1933       UNBLOCK_CHILD (oset);
1934       return (-1);
1935     }
1936
1937   wd = current_working_directory ();
1938
1939   /* You don't know about the state of this job.  Do you? */
1940   jobs[job]->flags &= ~J_NOTIFIED;
1941
1942   if (foreground)
1943     {
1944       set_current_job (job);
1945       jobs[job]->flags |= J_FOREGROUND;
1946     }
1947
1948   /* Tell the outside world what we're doing. */
1949   p = jobs[job]->pipe;
1950
1951   if (foreground == 0)
1952     fprintf (stderr, "[%d]%c ", job + 1,
1953            (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
1954
1955   do
1956     {
1957       fprintf (stderr, "%s%s",
1958                p->command ? p->command : "",
1959                p->next != jobs[job]->pipe? " | " : "");
1960       p = p->next;
1961     }
1962   while (p != jobs[job]->pipe);
1963
1964   if (foreground == 0)
1965     fprintf (stderr, " &");
1966
1967   if (strcmp (wd, jobs[job]->wd) != 0)
1968     fprintf (stderr, "  (wd: %s)", polite_directory_format (jobs[job]->wd));
1969
1970   fprintf (stderr, "\n");
1971
1972   /* Run the job. */
1973   if (already_running == 0)
1974     {
1975       /* Each member of the pipeline is now running. */
1976       p = jobs[job]->pipe;
1977
1978       do
1979         {
1980           if (WIFSTOPPED (p->status))
1981             p->running = 1;
1982           p = p->next;
1983         }
1984       while (p != jobs[job]->pipe);
1985
1986       /* This means that the job is running. */
1987       JOBSTATE (job) = JRUNNING;
1988     }
1989
1990   /* Save the tty settings before we start the job in the foreground. */
1991   if (foreground)
1992     {
1993       get_tty_state ();
1994       save_stty = shell_tty_info;
1995       /* Give the terminal to this job. */
1996       if (IS_JOBCONTROL (job))
1997         give_terminal_to (jobs[job]->pgrp);
1998     }
1999   else
2000     jobs[job]->flags &= ~J_FOREGROUND;
2001
2002   /* If the job is already running, then don't bother jump-starting it. */
2003   if (already_running == 0)
2004     {
2005       jobs[job]->flags |= J_NOTIFIED;
2006       killpg (jobs[job]->pgrp, SIGCONT);
2007     }
2008
2009   UNBLOCK_CHILD (oset);
2010
2011   if (foreground)
2012     {
2013       pid_t pid;
2014       int s;
2015
2016       pid = last_pid (job);
2017       s = wait_for (pid);
2018       shell_tty_info = save_stty;
2019       set_tty_state ();
2020       return (s);
2021     }
2022   else
2023     {
2024       BLOCK_CHILD (set, oset);
2025       reset_current ();
2026       UNBLOCK_CHILD (oset);
2027       return (0);
2028     }
2029 }
2030
2031 /* Give PID SIGNAL.  This determines what job the pid belongs to (if any).
2032    If PID does belong to a job, and the job is stopped, then CONTinue the
2033    job after giving it SIGNAL.  Returns -1 on failure.  If GROUP is non-null,
2034    then kill the process group associated with PID. */
2035 int
2036 kill_pid (pid, sig, group)
2037      pid_t pid;
2038      int sig, group;
2039 {
2040   register PROCESS *p;
2041   int job, result;
2042   sigset_t set, oset;
2043
2044   BLOCK_CHILD (set, oset);
2045   p = find_pipeline (pid);
2046   job = find_job (pid);
2047
2048   result = EXECUTION_SUCCESS;
2049   if (group)
2050     {
2051       if (job != NO_JOB)
2052         {
2053           jobs[job]->flags &= ~J_NOTIFIED;
2054
2055           /* Kill process in backquotes or one started without job control? */
2056           if (jobs[job]->pgrp == shell_pgrp)
2057             {
2058               p = jobs[job]->pipe;
2059
2060               do
2061                 {
2062                   kill (p->pid, sig);
2063                   if (p->running == 0 && (sig == SIGTERM || sig == SIGHUP))
2064                     kill (p->pid, SIGCONT);
2065                   p = p->next;
2066                 }
2067               while (p != jobs[job]->pipe);
2068             }
2069           else
2070             {
2071               result = killpg (jobs[job]->pgrp, sig);
2072               if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2073                 killpg (jobs[job]->pgrp, SIGCONT);
2074             }
2075         }
2076       else
2077         result = killpg (pid, sig);
2078     }
2079   else
2080     result = kill (pid, sig);
2081
2082   UNBLOCK_CHILD (oset);
2083   return (result);
2084 }
2085
2086 /* sigchld_handler () flushes at least one of the children that we are
2087    waiting for.  It gets run when we have gotten a SIGCHLD signal. */
2088 static sighandler
2089 sigchld_handler (sig)
2090      int sig;
2091 {
2092   int n;
2093
2094   REINSTALL_SIGCHLD_HANDLER;
2095   sigchld++;
2096   n = 0;
2097   if (waiting_for_job == 0)
2098     n = waitchld (-1, 0);
2099   SIGRETURN (n);
2100 }
2101
2102 /* waitchld() reaps dead or stopped children.  It's called by wait_for and
2103    flush_child, and runs until there aren't any children terminating any more.
2104    If BLOCK is 1, this is to be a blocking wait for a single child, although
2105    an arriving SIGCHLD could cause the wait to be non-blocking. */
2106 static int
2107 waitchld (wpid, block)
2108      pid_t wpid;
2109      int block;
2110 {
2111   WAIT status;
2112   PROCESS *child;
2113   pid_t pid;
2114   int call_set_current, last_stopped_job, job, children_exited;
2115   int job_state, any_stopped, any_tstped, waitpid_flags, tstatus;
2116
2117   call_set_current = children_exited = 0;
2118   last_stopped_job = NO_JOB;
2119
2120   do
2121     {
2122       /* We don't want to be notified about jobs stopping if we're not
2123          interactive. */
2124       waitpid_flags = (interactive_shell && subshell_environment == 0)
2125                         ? WUNTRACED
2126                         : 0;
2127       if (sigchld || block == 0)
2128         waitpid_flags |= WNOHANG;
2129       pid = WAITPID (-1, &status, waitpid_flags);
2130       /* The check for WNOHANG is to make sure we decrement sigchld only
2131          if it was non-zero before we called waitpid. */
2132       if (sigchld > 0 && (waitpid_flags & WNOHANG))
2133         sigchld--;
2134
2135       /* If waitpid returns 0, there are running children. */
2136       if (pid <= 0)
2137         continue;       /* jumps right to the test */
2138
2139       children_exited++;
2140
2141       /* Locate our PROCESS for this pid. */
2142       child = find_pipeline (pid);
2143
2144       /* It is not an error to have a child terminate that we did
2145          not have a record of.  This child could have been part of
2146          a pipeline in backquote substitution.  Even so, I'm not
2147          sure child is ever non-zero. */
2148       if (child == 0)
2149         continue;
2150
2151       while (child->pid != pid)
2152         child = child->next;
2153
2154       /* Remember status, and fact that process is not running. */
2155       child->status = status;
2156       child->running = 0;
2157
2158       job = find_job (pid);
2159       if (job == NO_JOB)
2160         continue;
2161
2162       /* Note that we're resetting `child' here because we now want to
2163          deal with the job. */
2164       child = jobs[job]->pipe;
2165       jobs[job]->flags &= ~J_NOTIFIED;
2166
2167       /* If all children are not running, but any of them is
2168          stopped, then the job is stopped, not dead. */
2169       job_state = any_stopped = any_tstped = 0;
2170       do
2171         {
2172           job_state |= child->running;
2173           if (child->running == 0 && (WIFSTOPPED (child->status)))
2174             {
2175               any_stopped = 1;
2176               any_tstped |= interactive && job_control &&
2177                             (WSTOPSIG (child->status) == SIGTSTP);
2178             }
2179           child = child->next;
2180         }
2181       while (child != jobs[job]->pipe);
2182
2183       /* If job_state != 0, the job is still running, so don't bother with
2184          setting the process exit status and job state. */
2185       if (job_state != 0)
2186         continue;
2187
2188       /* The job is either stopped or dead.  Set the state of the job
2189          accordingly. */
2190       if (any_stopped)
2191         {
2192           jobs[job]->state = JSTOPPED;
2193           jobs[job]->flags &= ~J_FOREGROUND;
2194           call_set_current++;
2195           last_stopped_job = job;
2196           /* Suspending a job with SIGTSTP breaks all active loops. */
2197           if (any_tstped && loop_level)
2198             breaking = loop_level;
2199         }
2200       else
2201         {
2202           /* ASSERT(child == jobs[job]->pipe); */
2203           jobs[job]->state = JDEAD;
2204           if (job == last_stopped_job)
2205             last_stopped_job = NO_JOB;
2206
2207           if (IS_FOREGROUND (job))
2208             setjstatus (job);           /* XXX */
2209
2210           /* If this job has a cleanup function associated with it, call it
2211              with `cleanarg' as the single argument, then set the function
2212              pointer to NULL so it is not inadvertently called twice.  The
2213              cleanup function is responsible for deallocating cleanarg. */
2214           if (jobs[job]->j_cleanup)
2215             {
2216               (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
2217               jobs[job]->j_cleanup = (VFunction *)NULL;
2218             }
2219
2220           /* XXX
2221              If we're running a shell script and we get a SIGINT with a
2222              SIGINT trap handler, but the foreground job handles it and
2223              does not exit due to SIGINT, run the trap handler but do not
2224              otherwise act as if we got the interrupt. */
2225           if (wait_sigint_received && interactive_shell == 0 &&
2226               WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
2227               signal_is_trapped (SIGINT))
2228             {
2229               wait_sigint_received = 0;
2230               last_command_exit_value = process_exit_status (child->status);
2231
2232               jobs_list_frozen = 1;
2233               tstatus = maybe_call_trap_handler (SIGINT);
2234               jobs_list_frozen = 0;
2235             }
2236
2237           /* If the foreground job is killed by SIGINT when
2238              job control is not active, we need to perform
2239              some special handling.
2240
2241              The check of wait_sigint_received is a way to
2242              determine if the SIGINT came from the keyboard
2243              (in which case the shell has already seen it,
2244              and wait_sigint_received is non-zero, because
2245              keyboard signals are sent to process groups)
2246              or via kill(2) to the foreground process by
2247              another process (or itself).  If the shell did
2248              receive the SIGINT, it needs to perform normal
2249              SIGINT processing. */
2250           else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
2251               IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
2252             {
2253               wait_sigint_received = 0;
2254
2255               /* If SIGINT is trapped, set the exit status so
2256                  that the trap handler can see it. */
2257               if (signal_is_trapped (SIGINT))
2258                 last_command_exit_value = process_exit_status (child->status);
2259
2260               /* If the signal is trapped, let the trap handler
2261                  get it no matter what and simply return if
2262                  the trap handler returns.
2263                  maybe_call_trap_handler() may cause dead jobs
2264                  to be removed from the job table because of
2265                  a call to execute_command.  Watch out for this. */
2266               jobs_list_frozen = 1;
2267               tstatus = maybe_call_trap_handler (SIGINT);
2268               jobs_list_frozen = 0;
2269               if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
2270                 {
2271                   /* wait_sigint_handler () has already seen SIGINT and
2272                      allowed the wait builtin to jump out.  We need to
2273                      call the original SIGINT handler. */
2274                   SigHandler *temp_handler;
2275                   temp_handler = old_sigint_handler;
2276                   restore_sigint_handler ();
2277                   if (temp_handler != SIG_IGN)
2278                     (*temp_handler) (SIGINT);
2279                 }
2280             }
2281         }
2282     }
2283   while ((sigchld || block == 0) && pid > (pid_t)0);
2284
2285   /* If a job was running and became stopped, then set the current
2286      job.  Otherwise, don't change a thing. */
2287   if (call_set_current)
2288     if (last_stopped_job != NO_JOB)
2289       set_current_job (last_stopped_job);
2290     else
2291       reset_current ();
2292
2293   /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
2294   if (job_control && signal_is_trapped (SIGCHLD) &&
2295       trap_list[SIGCHLD] != (char *)IGNORE_SIG)
2296     {
2297       char *trap_command;
2298       int i;
2299
2300       /* Turn off the trap list during the call to parse_and_execute ()
2301          to avoid potentially infinite recursive calls.  Preserve the
2302          values of last_command_exit_value, last_made_pid, and the_pipeline
2303          around the execution of the trap commands. */
2304       trap_command = savestring (trap_list[SIGCHLD]);
2305
2306       begin_unwind_frame ("SIGCHLD trap");
2307       unwind_protect_int (last_command_exit_value);
2308       if (sizeof (pid_t) == sizeof (short))
2309         unwind_protect_short (last_made_pid);
2310       else
2311         unwind_protect_int (last_made_pid);
2312       unwind_protect_int (interrupt_immediately);
2313       unwind_protect_int (jobs_list_frozen);
2314       unwind_protect_pointer (the_pipeline);
2315
2316       /* We have to add the commands this way because they will be run
2317          in reverse order of adding.  We don't want maybe_set_sigchld_trap ()
2318          to reference freed memory. */
2319       add_unwind_protect ((Function *)xfree, trap_command);
2320       add_unwind_protect ((Function *)maybe_set_sigchld_trap, trap_command);
2321
2322       the_pipeline = (PROCESS *)NULL;
2323       restore_default_signal (SIGCHLD);
2324       jobs_list_frozen = 1;
2325       for (i = 0; i < children_exited; i++)
2326         {
2327           interrupt_immediately = 1;
2328           parse_and_execute (savestring (trap_command), "trap", -1);
2329         }
2330
2331       run_unwind_frame ("SIGCHLD trap");
2332     }
2333
2334   /* We have successfully recorded the useful information about this process
2335      that has just changed state.  If we notify asynchronously, and the job
2336      that this process belongs to is no longer running, then notify the user
2337      of that fact now. */
2338   if (asynchronous_notification && interactive)
2339     notify_of_job_status ();
2340
2341   return (children_exited);
2342 }
2343
2344 /* Function to call when you want to notify people of changes
2345    in job status.  This prints out all jobs which are pending
2346    notification to stderr, and marks those printed as already
2347    notified, thus making them candidates for cleanup. */
2348 static void
2349 notify_of_job_status ()
2350 {
2351   register int job, termsig;
2352   char *dir;
2353   sigset_t set, oset;
2354   WAIT s;
2355
2356   sigemptyset (&set);
2357   sigaddset (&set, SIGCHLD);
2358   sigaddset (&set, SIGTTOU);
2359   sigemptyset (&oset);
2360   sigprocmask (SIG_BLOCK, &set, &oset);
2361
2362   for (job = 0, dir = (char *)NULL; job < job_slots; job++)
2363     {
2364       if (jobs[job] && IS_NOTIFIED (job) == 0)
2365         {
2366           s = jobs[job]->pipe->status;
2367           termsig = WTERMSIG (s);
2368
2369           /* If job control is disabled, don't print the status messages.
2370              Mark dead jobs as notified so that they get cleaned up.  If
2371              startup_state == 2, we were started to run `-c command', so
2372              don't print anything.  If the shell is not interactive, don't
2373              print anything unless the job was killed by a signal. */
2374           if ((job_control == 0 && interactive_shell) || startup_state == 2 ||
2375                 (startup_state == 0 && WIFSIGNALED (s) == 0))
2376             {
2377               if (DEADJOB (job))
2378                 jobs[job]->flags |= J_NOTIFIED;
2379               continue;
2380             }
2381
2382           /* Print info on jobs that are running in the background,
2383              and on foreground jobs that were killed by anything
2384              except SIGINT. */
2385           switch (JOBSTATE (job))
2386             {
2387             case JDEAD:
2388               if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
2389                   signal_is_trapped (termsig) == 0)
2390                 {
2391                   fprintf (stderr, "%s: line %d: ", get_name_for_error (), line_number);
2392                   pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
2393                 }
2394               else if (IS_FOREGROUND (job))
2395                 {
2396                   if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2397                     {
2398                       fprintf (stderr, "%s", strsignal (termsig));
2399
2400                       if (WIFCORED (s))
2401                         fprintf (stderr, " (core dumped)");
2402
2403                       fprintf (stderr, "\n");
2404                     }
2405                 }
2406               else
2407                 {
2408                   if (dir == 0)
2409                     dir = current_working_directory ();
2410                   pretty_print_job (job, JLIST_STANDARD, stderr);
2411                   if (dir && strcmp (dir, jobs[job]->wd) != 0)
2412                     fprintf (stderr,
2413                              "(wd now: %s)\n", polite_directory_format (dir));
2414                 }
2415
2416               jobs[job]->flags |= J_NOTIFIED;
2417               break;
2418
2419             case JSTOPPED:
2420               fprintf (stderr, "\n");
2421               if (dir == 0)
2422                 dir = current_working_directory ();
2423               pretty_print_job (job, JLIST_STANDARD, stderr);
2424               if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2425                 fprintf (stderr,
2426                          "(wd now: %s)\n", polite_directory_format (dir));
2427               jobs[job]->flags |= J_NOTIFIED;
2428               break;
2429
2430             case JRUNNING:
2431             case JMIXED:
2432               break;
2433
2434             default:
2435               programming_error ("notify_of_job_status");
2436             }
2437         }
2438     }
2439   sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2440 }
2441
2442 /* Initialize the job control mechanism, and set up the tty stuff. */
2443 int
2444 initialize_jobs ()
2445 {
2446   shell_pgrp = getpgid (0);
2447
2448   if (shell_pgrp == -1)
2449     {
2450       sys_error ("initialize_jobs: getpgrp failed");
2451       exit (1);
2452     }
2453
2454   /* We can only have job control if we are interactive. */
2455   if (interactive == 0)
2456     {
2457       job_control = 0;
2458       original_pgrp = NO_PID;
2459     }
2460   else
2461     {
2462       /* Get our controlling terminal.  If job_control is set, or
2463          interactive is set, then this is an interactive shell no
2464          matter where fd 2 is directed. */
2465       shell_tty = dup (fileno (stderr));        /* fd 2 */
2466
2467       shell_tty = move_to_high_fd (shell_tty, 1);
2468
2469       /* Compensate for a bug in systems that compiled the BSD
2470          rlogind with DEBUG defined, like NeXT and Alliant. */
2471       if (shell_pgrp == 0)
2472         {
2473           shell_pgrp = getpid ();
2474           setpgid (0, shell_pgrp);
2475           tcsetpgrp (shell_tty, shell_pgrp);
2476         }
2477
2478       while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2479         {
2480           if (shell_pgrp != terminal_pgrp)
2481             {
2482               SigHandler *old_ttin;
2483
2484               old_ttin = set_signal_handler(SIGTTIN, SIG_DFL);
2485               kill (0, SIGTTIN);
2486               set_signal_handler (SIGTTIN, old_ttin);
2487               continue;
2488             }
2489           break;
2490         }
2491
2492       /* Make sure that we are using the new line discipline. */
2493       if (set_new_line_discipline (shell_tty) < 0)
2494         {
2495           sys_error ("initialize_jobs: line discipline");
2496           job_control = 0;
2497         }
2498       else
2499         {
2500           original_pgrp = shell_pgrp;
2501           shell_pgrp = getpid ();
2502
2503           if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
2504             {
2505               sys_error ("initialize_jobs: setpgid");
2506               shell_pgrp = original_pgrp;
2507             }
2508
2509           job_control = 1;
2510
2511           /* If (and only if) we just set our process group to our pid,
2512              thereby becoming a process group leader, and the terminal
2513              is not in the same process group as our (new) process group,
2514              then set the terminal's process group to our (new) process
2515              group.  If that fails, set our process group back to what it
2516              was originally (so we can still read from the terminal) and
2517              turn off job control.  */
2518           if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
2519             {
2520               if (give_terminal_to (shell_pgrp) < 0)            /* XXX */
2521                 {
2522                   setpgid (0, original_pgrp);                   /* XXX */
2523                   shell_pgrp = original_pgrp;                   /* XXX */
2524                   job_control = 0;                              /* XXX */
2525                 }
2526             }
2527         }
2528       if (job_control == 0)
2529         internal_error ("no job control in this shell");        /* XXX */
2530     }
2531
2532   if (shell_tty != fileno (stderr))
2533     SET_CLOSE_ON_EXEC (shell_tty);
2534
2535   set_signal_handler (SIGCHLD, sigchld_handler);
2536
2537   change_flag ('m', job_control ? '-' : '+');
2538
2539   if (interactive)
2540     get_tty_state ();
2541
2542   return job_control;
2543 }
2544
2545 /* Set the line discipline to the best this system has to offer.
2546    Return -1 if this is not possible. */
2547 static int
2548 set_new_line_discipline (tty)
2549      int tty;
2550 {
2551 #if defined (NEW_TTY_DRIVER)
2552   int ldisc;
2553
2554   if (ioctl (tty, TIOCGETD, &ldisc) < 0)
2555     return (-1);
2556
2557   if (ldisc != NTTYDISC)
2558     {
2559       ldisc = NTTYDISC;
2560
2561       if (ioctl (tty, TIOCSETD, &ldisc) < 0)
2562         return (-1);
2563     }
2564   return (0);
2565 #endif /* NEW_TTY_DRIVER */
2566
2567 #if defined (TERMIO_TTY_DRIVER)
2568 #  if defined (TERMIO_LDISC) && (NTTYDISC)
2569   if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
2570     return (-1);
2571
2572   if (shell_tty_info.c_line != NTTYDISC)
2573     {
2574       shell_tty_info.c_line = NTTYDISC;
2575       if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
2576         return (-1);
2577     }
2578 #  endif /* TERMIO_LDISC && NTTYDISC */
2579   return (0);
2580 #endif /* TERMIO_TTY_DRIVER */
2581
2582 #if defined (TERMIOS_TTY_DRIVER)
2583 #  if defined (TERMIOS_LDISC) && defined (NTTYDISC)
2584   if (tcgetattr (tty, &shell_tty_info) < 0)
2585     return (-1);
2586
2587   if (shell_tty_info.c_line != NTTYDISC)
2588     {
2589       shell_tty_info.c_line = NTTYDISC;
2590       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2591         return (-1);
2592     }
2593 #  endif /* TERMIOS_LDISC && NTTYDISC */
2594   return (0);
2595 #endif /* TERMIOS_TTY_DRIVER */
2596
2597 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
2598   return (-1);
2599 #endif
2600 }
2601
2602 static SigHandler *old_tstp, *old_ttou, *old_ttin;
2603 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
2604 static sighandler stop_signal_handler (), cont_signal_handler ();
2605
2606 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2607 static SigHandler *old_winch = (SigHandler *)SIG_DFL;
2608
2609 static void
2610 get_new_window_size (from_sig)
2611      int from_sig;
2612 {
2613   struct winsize win;
2614
2615   if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
2616       win.ws_row > 0 && win.ws_col > 0)
2617     {
2618 #if defined (aixpc)
2619       shell_tty_info.c_winsize = win;   /* structure copying */
2620 #endif
2621       set_lines_and_columns (win.ws_row, win.ws_col);
2622 #if defined (READLINE)
2623       _rl_set_screen_size (win.ws_row, win.ws_col);
2624 #endif
2625     }
2626 }
2627
2628 static sighandler
2629 sigwinch_sighandler (sig)
2630      int sig;
2631 {
2632 #if defined (MUST_REINSTALL_SIGHANDLERS)
2633   set_signal_handler (SIGWINCH, sigwinch_sighandler);
2634 #endif /* MUST_REINSTALL_SIGHANDLERS */
2635   get_new_window_size (1);
2636 }
2637 #else
2638 static void
2639 get_new_window_size (from_sig)
2640      int from_sig;
2641 {
2642 }
2643 #endif /* TIOCGWINSZ && SIGWINCH */
2644
2645 void
2646 set_sigwinch_handler ()
2647 {
2648 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2649  old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
2650 #endif
2651 }
2652
2653 void
2654 unset_sigwinch_handler ()
2655 {
2656 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2657   set_signal_handler (SIGWINCH, old_winch);
2658 #endif
2659 }
2660
2661 /* Setup this shell to handle C-C, etc. */
2662 void
2663 initialize_job_signals ()
2664 {
2665   if (interactive)
2666     {
2667       set_signal_handler (SIGINT, sigint_sighandler);
2668       set_signal_handler (SIGTSTP, SIG_IGN);
2669       set_signal_handler (SIGTTOU, SIG_IGN);
2670       set_signal_handler (SIGTTIN, SIG_IGN);
2671       set_sigwinch_handler ();
2672     }
2673   else if (job_control)
2674     {
2675       old_tstp = set_signal_handler (SIGTSTP, stop_signal_handler);
2676       old_ttou = set_signal_handler (SIGTTOU, stop_signal_handler);
2677       old_ttin = set_signal_handler (SIGTTIN, stop_signal_handler);
2678     }
2679   /* Leave these things alone for non-interactive shells without job
2680      control. */
2681 }
2682
2683 /* Here we handle CONT signals. */
2684 static sighandler
2685 cont_signal_handler (sig)
2686      int sig;
2687 {
2688   initialize_job_signals ();
2689   set_signal_handler (SIGCONT, old_cont);
2690   kill (getpid (), SIGCONT);
2691
2692   SIGRETURN (0);
2693 }
2694
2695 /* Here we handle stop signals while we are running not as a login shell. */
2696 static sighandler
2697 stop_signal_handler (sig)
2698      int sig;
2699 {
2700   set_signal_handler (SIGTSTP, old_tstp);
2701   set_signal_handler (SIGTTOU, old_ttou);
2702   set_signal_handler (SIGTTIN, old_ttin);
2703
2704   old_cont = set_signal_handler (SIGCONT, cont_signal_handler);
2705
2706   give_terminal_to (shell_pgrp);
2707
2708   kill (getpid (), sig);
2709
2710   SIGRETURN (0);
2711 }
2712
2713 /* Give the terminal to PGRP.  */
2714 int
2715 give_terminal_to (pgrp)
2716      pid_t pgrp;
2717 {
2718   sigset_t set, oset;
2719   int r;
2720
2721   r = 0;
2722   if (job_control)
2723     {
2724       sigemptyset (&set);
2725       sigaddset (&set, SIGTTOU);
2726       sigaddset (&set, SIGTTIN);
2727       sigaddset (&set, SIGTSTP);
2728       sigaddset (&set, SIGCHLD);
2729       sigemptyset (&oset);
2730       sigprocmask (SIG_BLOCK, &set, &oset);
2731
2732       if (tcsetpgrp (shell_tty, pgrp) < 0)
2733         {
2734           /* Maybe we should print an error message? */
2735 #if 0
2736           sys_error ("tcsetpgrp(%d) failed: pid %d to pgrp %d",
2737             shell_tty, getpid(), pgrp);
2738 #endif
2739           r = -1;
2740         }
2741       else
2742         terminal_pgrp = pgrp;
2743       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2744     }
2745
2746   return r;
2747 }
2748
2749 /* Clear out any jobs in the job array.  This is intended to be used by
2750    children of the shell, who should not have any job structures as baggage
2751    when they start executing (forking subshells for parenthesized execution
2752    and functions with pipes are the two that spring to mind). */
2753 static void
2754 delete_all_jobs ()
2755 {
2756   register int i;
2757   sigset_t set, oset;
2758
2759   BLOCK_CHILD (set, oset);
2760
2761   if (job_slots)
2762     {
2763       current_job = previous_job = NO_JOB;
2764
2765       for (i = 0; i < job_slots; i++)
2766         if (jobs[i])
2767           delete_job (i);
2768
2769       free ((char *)jobs);
2770       job_slots = 0;
2771     }
2772
2773   UNBLOCK_CHILD (oset);
2774 }
2775
2776 /* Mark all dead jobs as notified, so delete_job () cleans them out
2777    of the job table properly. */
2778 static void
2779 mark_dead_jobs_as_notified ()
2780 {
2781   register int i;
2782   sigset_t set, oset;
2783
2784   if (job_slots)
2785     {
2786       BLOCK_CHILD (set, oset);
2787
2788       for (i = 0; i < job_slots; i++)
2789         if (jobs[i] && DEADJOB (i))
2790           jobs[i]->flags |= J_NOTIFIED;
2791
2792       UNBLOCK_CHILD (oset);
2793     }
2794 }
2795
2796 /* Here to allow other parts of the shell (like the trap stuff) to
2797    unfreeze the jobs list. */
2798 void
2799 unfreeze_jobs_list ()
2800 {
2801   jobs_list_frozen = 0;
2802 }
2803
2804 /* Allow or disallow job control to take place.  Returns the old value
2805    of job_control. */
2806 int
2807 set_job_control (arg)
2808      int arg;
2809 {
2810   int old;
2811
2812   old = job_control;
2813   job_control = arg;
2814   return (old);
2815 }
2816
2817 /* Turn off all traces of job control.  This is run by children of the shell
2818    which are going to do shellsy things, like wait (), etc. */
2819 void
2820 without_job_control ()
2821 {
2822   stop_making_children ();
2823   start_pipeline ();
2824   delete_all_jobs ();
2825   set_job_control (0);
2826 }
2827
2828 /* If this shell is interactive, terminate all stopped jobs and
2829    restore the original terminal process group.  This is done
2830    before the `exec' builtin calls shell_execve. */
2831 void
2832 end_job_control ()
2833 {
2834   if (interactive_shell)                /* XXX - should it be interactive? */
2835     {
2836       terminate_stopped_jobs ();
2837
2838       if (original_pgrp >= 0)
2839         give_terminal_to (original_pgrp);
2840     }
2841
2842   if (original_pgrp >= 0)
2843     setpgid (0, original_pgrp);
2844 }
2845
2846 /* Restart job control by closing shell tty and reinitializing.  This is
2847    called after an exec fails in an interactive shell and we do not exit. */
2848 void
2849 restart_job_control ()
2850 {
2851   if (shell_tty != -1)
2852     close (shell_tty);
2853   initialize_jobs ();
2854 }
2855
2856 /* Set the handler to run when the shell receives a SIGCHLD signal. */
2857 void
2858 set_sigchld_handler ()
2859 {
2860   set_signal_handler (SIGCHLD, sigchld_handler);
2861 }
2862
2863 #if defined (PGRP_PIPE)
2864 /* Read from the read end of a pipe.  This is how the process group leader
2865    blocks until all of the processes in a pipeline have been made. */
2866 static void
2867 pipe_read (pp)
2868      int *pp;
2869 {
2870   char ch;
2871
2872   if (pp[1] >= 0)
2873     {
2874       close (pp[1]);
2875       pp[1] = -1;
2876     }
2877
2878   if (pp[0] >= 0)
2879     {
2880       while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
2881         continue;
2882     }
2883 }
2884
2885 /* Close the read and write ends of PP, an array of file descriptors. */
2886 static void
2887 pipe_close (pp)
2888      int *pp;
2889 {
2890   if (pp[0] >= 0)
2891     close (pp[0]);
2892
2893   if (pp[1] >= 0)
2894     close (pp[1]);
2895
2896   pp[0] = pp[1] = -1;
2897 }
2898
2899 /* Functional interface closes our local-to-job-control pipes. */
2900 void
2901 close_pgrp_pipe ()
2902 {
2903   pipe_close (pgrp_pipe);
2904 }
2905
2906 #endif /* PGRP_PIPE */
2907
2908 static void
2909 setjstatus (j)
2910      int j;
2911 {
2912 #if defined (ARRAY_VARS)
2913   register int i;
2914   register PROCESS *p;
2915
2916   for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
2917     ;
2918   i++;
2919   if (statsize <= i)
2920     {
2921       pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
2922       statsize = i;
2923     }
2924   i = 0;
2925   p = jobs[j]->pipe;
2926   do
2927     {
2928       pstatuses[i++] = process_exit_status (p->status);
2929       p = p->next;
2930     }
2931   while (p != jobs[j]->pipe);
2932
2933   pstatuses[i] = -1;    /* sentinel */
2934   set_pipestatus_array (pstatuses);
2935 #endif
2936 }
2937
2938 #if defined (ARRAY_VARS)
2939 static void
2940 set_pipestatus_array (ps)
2941      int *ps;
2942 {
2943   SHELL_VAR *v;
2944   ARRAY *a;
2945   register int i;
2946   char *t;
2947
2948   v = find_variable ("PIPESTATUS");
2949   if (v == 0)
2950     v = make_new_array_variable ("PIPESTATUS");
2951   if (array_p (v) == 0)
2952     return;             /* Do nothing if not an array variable. */
2953   a = array_cell (v);
2954   if (a)
2955     empty_array (a);
2956   for (i = 0; ps[i] != -1; i++)
2957     {
2958       t = itos (ps[i]);
2959       array_add_element (a, i, t);
2960       free (t);
2961     }
2962 }
2963 #endif