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