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