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