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