Imported from ../bash-4.0-rc1.tar.gz.
[platform/upstream/bash.git] / jobs.c
1 /* jobs.c - functions that make children, remember them, and handle their termination. */
2
3 /* This file works with both POSIX and BSD systems.  It implements job
4    control. */
5
6 /* Copyright (C) 1989-2009 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
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation, either version 3 of the License, or
13    (at your option) any later version.
14
15    Bash is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with Bash.  If not, see <http://www.gnu.org/licenses/>.
22 */
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 #include "posixtime.h"
37
38 #if defined (HAVE_SYS_RESOURCE_H) && defined (HAVE_WAIT3) && !defined (_POSIX_VERSION) && !defined (RLIMTYPE)
39 #  include <sys/resource.h>
40 #endif /* !_POSIX_VERSION && HAVE_SYS_RESOURCE_H && HAVE_WAIT3 && !RLIMTYPE */
41
42 #if defined (HAVE_SYS_FILE_H)
43 #  include <sys/file.h>
44 #endif
45
46 #include "filecntl.h"
47 #include <sys/ioctl.h>
48 #include <sys/param.h>
49
50 #if defined (BUFFERED_INPUT)
51 #  include "input.h"
52 #endif
53
54 /* Need to include this up here for *_TTY_DRIVER definitions. */
55 #include "shtty.h"
56
57 /* Define this if your output is getting swallowed.  It's a no-op on
58    machines with the termio or termios tty drivers. */
59 /* #define DRAIN_OUTPUT */
60
61 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
62 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
63 #  include <bsdtty.h>
64 #endif /* hpux && !TERMIOS_TTY_DRIVER */
65
66 #include "bashansi.h"
67 #include "bashintl.h"
68 #include "shell.h"
69 #include "jobs.h"
70 #include "execute_cmd.h"
71 #include "flags.h"
72
73 #include "builtins/builtext.h"
74 #include "builtins/common.h"
75
76 #if !defined (errno)
77 extern int errno;
78 #endif /* !errno */
79
80 #define DEFAULT_CHILD_MAX 32
81 #if !defined (DEBUG)
82 #define MAX_JOBS_IN_ARRAY 4096          /* production */
83 #else
84 #define MAX_JOBS_IN_ARRAY 128           /* testing */
85 #endif
86
87 /* Flag values for second argument to delete_job */
88 #define DEL_WARNSTOPPED         1       /* warn about deleting stopped jobs */
89 #define DEL_NOBGPID             2       /* don't add pgrp leader to bgpids */
90
91 /* Take care of system dependencies that must be handled when waiting for
92    children.  The arguments to the WAITPID macro match those to the Posix.1
93    waitpid() function. */
94
95 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
96 #  define WAITPID(pid, statusp, options) \
97         wait3 ((union wait *)statusp, options, (struct rusage *)0)
98 #else
99 #  if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
100 #    define WAITPID(pid, statusp, options) \
101         waitpid ((pid_t)pid, statusp, options)
102 #  else
103 #    if defined (HAVE_WAIT3)
104 #      define WAITPID(pid, statusp, options) \
105         wait3 (statusp, options, (struct rusage *)0)
106 #    else
107 #      define WAITPID(pid, statusp, options) \
108         wait3 (statusp, options, (int *)0)
109 #    endif /* HAVE_WAIT3 */
110 #  endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
111 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
112
113 /* getpgrp () varies between systems.  Even systems that claim to be
114    Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
115 #if defined (GETPGRP_VOID)
116 #  define getpgid(p) getpgrp ()
117 #else
118 #  define getpgid(p) getpgrp (p)
119 #endif /* !GETPGRP_VOID */
120
121 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
122    handler for SIGCHLD. */
123 #if defined (MUST_REINSTALL_SIGHANDLERS)
124 #  define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
125 #else
126 #  define REINSTALL_SIGCHLD_HANDLER
127 #endif /* !MUST_REINSTALL_SIGHANDLERS */
128
129 /* Some systems let waitpid(2) tell callers about stopped children. */
130 #if !defined (WCONTINUED) || defined (WCONTINUED_BROKEN)
131 #  undef WCONTINUED
132 #  define WCONTINUED 0
133 #endif
134 #if !defined (WIFCONTINUED)
135 #  define WIFCONTINUED(s)       (0)
136 #endif
137
138 /* The number of additional slots to allocate when we run out. */
139 #define JOB_SLOTS 8
140
141 typedef int sh_job_map_func_t __P((JOB *, int, int, int));
142
143 /* Variables used here but defined in other files. */
144 extern int subshell_environment, line_number;
145 extern int posixly_correct, shell_level;
146 extern int last_command_exit_value, last_command_exit_signal;
147 extern int loop_level, breaking;
148 extern int executing_list;
149 extern int sourcelevel;
150 extern int running_trap;
151 extern sh_builtin_func_t *this_shell_builtin;
152 extern char *shell_name, *this_command_name;
153 extern sigset_t top_level_mask;
154 extern procenv_t wait_intr_buf;
155 extern int wait_signal_received;
156 extern WORD_LIST *subst_assign_varlist;
157
158 static struct jobstats zerojs = { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB, NO_JOB, 0, 0 };
159 struct jobstats js = { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB, NO_JOB, 0, 0 };
160
161 struct bgpids bgpids = { 0, 0, 0 };
162
163 /* The array of known jobs. */
164 JOB **jobs = (JOB **)NULL;
165
166 #if 0
167 /* The number of slots currently allocated to JOBS. */
168 int job_slots = 0;
169 #endif
170
171 /* The controlling tty for this shell. */
172 int shell_tty = -1;
173
174 /* The shell's process group. */
175 pid_t shell_pgrp = NO_PID;
176
177 /* The terminal's process group. */
178 pid_t terminal_pgrp = NO_PID;
179
180 /* The process group of the shell's parent. */
181 pid_t original_pgrp = NO_PID;
182
183 /* The process group of the pipeline currently being made. */
184 pid_t pipeline_pgrp = (pid_t)0;
185
186 #if defined (PGRP_PIPE)
187 /* Pipes which each shell uses to communicate with the process group leader
188    until all of the processes in a pipeline have been started.  Then the
189    process leader is allowed to continue. */
190 int pgrp_pipe[2] = { -1, -1 };
191 #endif
192
193 #if 0
194 /* The job which is current; i.e. the one that `%+' stands for. */
195 int current_job = NO_JOB;
196
197 /* The previous job; i.e. the one that `%-' stands for. */
198 int previous_job = NO_JOB;
199 #endif
200
201 /* Last child made by the shell.  */
202 pid_t last_made_pid = NO_PID;
203
204 /* Pid of the last asynchronous child. */
205 pid_t last_asynchronous_pid = NO_PID;
206
207 /* The pipeline currently being built. */
208 PROCESS *the_pipeline = (PROCESS *)NULL;
209
210 /* If this is non-zero, do job control. */
211 int job_control = 1;
212
213 /* Call this when you start making children. */
214 int already_making_children = 0;
215
216 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
217    exits from get_tty_state(). */
218 int check_window_size;
219
220 /* Functions local to this file. */
221
222 static sighandler wait_sigint_handler __P((int));
223 static sighandler sigchld_handler __P((int));
224 static sighandler sigcont_sighandler __P((int));
225 static sighandler sigstop_sighandler __P((int));
226
227 static int waitchld __P((pid_t, int));
228
229 static PROCESS *find_pipeline __P((pid_t, int, int *));
230 static PROCESS *find_process __P((pid_t, int, int *));
231
232 static char *current_working_directory __P((void));
233 static char *job_working_directory __P((void));
234 static char *j_strsignal __P((int));
235 static char *printable_job_status __P((int, PROCESS *, int));
236
237 static PROCESS *find_last_proc __P((int, int));
238 static pid_t find_last_pid __P((int, int));
239
240 static int set_new_line_discipline __P((int));
241 static int map_over_jobs __P((sh_job_map_func_t *, int, int));
242 static int job_last_stopped __P((int));
243 static int job_last_running __P((int));
244 static int most_recent_job_in_state __P((int, JOB_STATE));
245 static int find_job __P((pid_t, int, PROCESS **));
246 static int print_job __P((JOB *, int, int, int));
247 static int process_exit_status __P((WAIT));
248 static int process_exit_signal __P((WAIT));
249 static int job_exit_status __P((int));
250 static int job_exit_signal __P((int));
251 static int set_job_status_and_cleanup __P((int));
252
253 static WAIT job_signal_status __P((int));
254 static WAIT raw_job_exit_status __P((int));
255
256 static void notify_of_job_status __P((void));
257 static void reset_job_indices __P((void));
258 static void cleanup_dead_jobs __P((void));
259 static int processes_in_job __P((int));
260 static void realloc_jobs_list __P((void));
261 static int compact_jobs_list __P((int));
262 static int discard_pipeline __P((PROCESS *));
263 static void add_process __P((char *, pid_t));
264 static void print_pipeline __P((PROCESS *, int, int, FILE *));
265 static void pretty_print_job __P((int, int, FILE *));
266 static void set_current_job __P((int));
267 static void reset_current __P((void));
268 static void set_job_running __P((int));
269 static void setjstatus __P((int));
270 static int maybe_give_terminal_to __P((pid_t, pid_t, int));
271 static void mark_all_jobs_as_dead __P((void));
272 static void mark_dead_jobs_as_notified __P((int));
273 static void restore_sigint_handler __P((void));
274 #if defined (PGRP_PIPE)
275 static void pipe_read __P((int *));
276 #endif
277
278 static struct pidstat *bgp_alloc __P((pid_t, int));
279 static struct pidstat *bgp_add __P((pid_t, int));
280 static int bgp_delete __P((pid_t));
281 static void bgp_clear __P((void));
282 static int bgp_search __P((pid_t));
283 static void bgp_prune __P((void));
284
285 #if defined (ARRAY_VARS)
286 static int *pstatuses;          /* list of pipeline statuses */
287 static int statsize;
288 #endif
289
290 /* Used to synchronize between wait_for and other functions and the SIGCHLD
291    signal handler. */
292 static int sigchld;
293 static int queue_sigchld;
294
295 #define QUEUE_SIGCHLD(os)       (os) = sigchld, queue_sigchld++
296
297 #define UNQUEUE_SIGCHLD(os) \
298         do { \
299           queue_sigchld--; \
300           if (queue_sigchld == 0 && os != sigchld) \
301             waitchld (-1, 0); \
302         } while (0)
303
304 static SigHandler *old_tstp, *old_ttou, *old_ttin;
305 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
306
307 /* A place to temporarily save the current pipeline. */
308 static PROCESS *saved_pipeline;
309 static int saved_already_making_children;
310
311 /* Set this to non-zero whenever you don't want the jobs list to change at
312    all: no jobs deleted and no status change notifications.  This is used,
313    for example, when executing SIGCHLD traps, which may run arbitrary
314    commands. */
315 static int jobs_list_frozen;
316
317 static char retcode_name_buffer[64];
318
319 /* flags to detect pid wraparound */
320 static pid_t first_pid = NO_PID;
321 static int pid_wrap = -1;
322
323 #if !defined (_POSIX_VERSION)
324
325 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
326    library functions and system calls. */
327 #define setpgid(pid, pgrp)      setpgrp (pid, pgrp)
328 #define tcsetpgrp(fd, pgrp)     ioctl ((fd), TIOCSPGRP, &(pgrp))
329
330 pid_t
331 tcgetpgrp (fd)
332      int fd;
333 {
334   pid_t pgrp;
335
336   /* ioctl will handle setting errno correctly. */
337   if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
338     return (-1);
339   return (pgrp);
340 }
341
342 #endif /* !_POSIX_VERSION */
343
344 /* Initialize the global job stats structure and other bookkeeping variables */
345 void
346 init_job_stats ()
347 {
348   js = zerojs;
349   first_pid = NO_PID;
350   pid_wrap = -1;
351 }
352
353 /* Return the working directory for the current process.  Unlike
354    job_working_directory, this does not call malloc (), nor do any
355    of the functions it calls.  This is so that it can safely be called
356    from a signal handler. */
357 static char *
358 current_working_directory ()
359 {
360   char *dir;
361   static char d[PATH_MAX];
362
363   dir = get_string_value ("PWD");
364
365   if (dir == 0 && the_current_working_directory && no_symbolic_links)
366     dir = the_current_working_directory;
367
368   if (dir == 0)
369     {
370       dir = getcwd (d, sizeof(d));
371       if (dir)
372         dir = d;
373     }
374
375   return (dir == 0) ? "<unknown>" : dir;
376 }
377
378 /* Return the working directory for the current process. */
379 static char *
380 job_working_directory ()
381 {
382   char *dir;
383
384   dir = get_string_value ("PWD");
385   if (dir)
386     return (savestring (dir));
387
388   dir = get_working_directory ("job-working-directory");
389   if (dir)
390     return (dir);
391
392   return (savestring ("<unknown>"));
393 }
394
395 void
396 making_children ()
397 {
398   if (already_making_children)
399     return;
400
401   already_making_children = 1;
402   start_pipeline ();
403 }
404
405 void
406 stop_making_children ()
407 {
408   already_making_children = 0;
409 }
410
411 void
412 cleanup_the_pipeline ()
413 {
414   PROCESS *disposer;
415   sigset_t set, oset;
416
417   BLOCK_CHILD (set, oset);
418   disposer = the_pipeline;
419   the_pipeline = (PROCESS *)NULL;
420   UNBLOCK_CHILD (oset);
421
422   if (disposer)
423     discard_pipeline (disposer);
424 }
425
426 void
427 save_pipeline (clear)
428      int clear;
429 {
430   saved_pipeline = the_pipeline;
431   if (clear)
432     the_pipeline = (PROCESS *)NULL;
433   saved_already_making_children = already_making_children;
434 }
435
436 void
437 restore_pipeline (discard)
438      int discard;
439 {
440   PROCESS *old_pipeline;
441
442   old_pipeline = the_pipeline;
443   the_pipeline = saved_pipeline;
444   already_making_children = saved_already_making_children;
445   if (discard)
446     discard_pipeline (old_pipeline);
447 }
448
449 /* Start building a pipeline.  */
450 void
451 start_pipeline ()
452 {
453   if (the_pipeline)
454     {
455       cleanup_the_pipeline ();
456       pipeline_pgrp = 0;
457 #if defined (PGRP_PIPE)
458       sh_closepipe (pgrp_pipe);
459 #endif
460     }
461
462 #if defined (PGRP_PIPE)
463   if (job_control)
464     {
465       if (pipe (pgrp_pipe) == -1)
466         sys_error (_("start_pipeline: pgrp pipe"));
467     }
468 #endif
469 }
470
471 /* Stop building a pipeline.  Install the process list in the job array.
472    This returns the index of the newly installed job.
473    DEFERRED is a command structure to be executed upon satisfactory
474    execution exit of this pipeline. */
475 int
476 stop_pipeline (async, deferred)
477      int async;
478      COMMAND *deferred;
479 {
480   register int i, j;
481   JOB *newjob;
482   sigset_t set, oset;
483
484   BLOCK_CHILD (set, oset);
485
486 #if defined (PGRP_PIPE)
487   /* The parent closes the process group synchronization pipe. */
488   sh_closepipe (pgrp_pipe);
489 #endif
490
491   cleanup_dead_jobs ();
492
493   if (js.j_jobslots == 0)
494     {
495       js.j_jobslots = JOB_SLOTS;
496       jobs = (JOB **)xmalloc (js.j_jobslots * sizeof (JOB *));
497
498       /* Now blank out these new entries. */
499       for (i = 0; i < js.j_jobslots; i++)
500         jobs[i] = (JOB *)NULL;
501
502       js.j_firstj = js.j_lastj = js.j_njobs = 0;
503     }
504
505   /* Scan from the last slot backward, looking for the next free one. */
506   /* XXX - revisit this interactive assumption */
507   /* XXX - this way for now */
508   if (interactive)
509     {
510       for (i = js.j_jobslots; i; i--)
511         if (jobs[i - 1])
512           break;
513     }
514   else
515     {
516 #if 0
517       /* This wraps around, but makes it inconvenient to extend the array */
518       for (i = js.j_lastj+1; i != js.j_lastj; i++)
519         {
520           if (i >= js.j_jobslots)
521             i = 0;
522           if (jobs[i] == 0)
523             break;
524         }       
525       if (i == js.j_lastj)
526         i = js.j_jobslots;
527 #else
528       /* This doesn't wrap around yet. */
529       for (i = js.j_lastj ? js.j_lastj + 1 : js.j_lastj; i < js.j_jobslots; i++)
530         if (jobs[i] == 0)
531           break;
532 #endif
533     }
534
535   /* Do we need more room? */
536
537   /* First try compaction */
538   if ((interactive_shell == 0 || subshell_environment) && i == js.j_jobslots && js.j_jobslots >= MAX_JOBS_IN_ARRAY)
539     i = compact_jobs_list (0);
540
541   /* If we can't compact, reallocate */
542   if (i == js.j_jobslots)
543     {
544       js.j_jobslots += JOB_SLOTS;
545       jobs = (JOB **)xrealloc (jobs, (js.j_jobslots * sizeof (JOB *)));
546
547       for (j = i; j < js.j_jobslots; j++)
548         jobs[j] = (JOB *)NULL;
549     }
550
551   /* Add the current pipeline to the job list. */
552   if (the_pipeline)
553     {
554       register PROCESS *p;
555       int any_running, any_stopped, n;
556
557       newjob = (JOB *)xmalloc (sizeof (JOB));
558
559       for (n = 1, p = the_pipeline; p->next != the_pipeline; n++, p = p->next)
560         ;
561       p->next = (PROCESS *)NULL;
562       newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
563       for (p = newjob->pipe; p->next; p = p->next)
564         ;
565       p->next = newjob->pipe;
566
567       the_pipeline = (PROCESS *)NULL;
568       newjob->pgrp = pipeline_pgrp;
569       pipeline_pgrp = 0;
570
571       newjob->flags = 0;
572
573       /* Flag to see if in another pgrp. */
574       if (job_control)
575         newjob->flags |= J_JOBCONTROL;
576
577       /* Set the state of this pipeline. */
578       p = newjob->pipe;
579       any_running = any_stopped = 0;
580       do
581         {
582           any_running |= PRUNNING (p);
583           any_stopped |= PSTOPPED (p);
584           p = p->next;
585         }
586       while (p != newjob->pipe);
587
588       newjob->state = any_running ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
589       newjob->wd = job_working_directory ();
590       newjob->deferred = deferred;
591
592       newjob->j_cleanup = (sh_vptrfunc_t *)NULL;
593       newjob->cleanarg = (PTR_T) NULL;
594
595       jobs[i] = newjob;
596       if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
597         setjstatus (i);
598       if (newjob->state == JDEAD)
599         {
600           js.c_reaped += n;     /* wouldn't have been done since this was not part of a job */
601           js.j_ndead++;
602         }
603       js.c_injobs += n;
604
605       js.j_lastj = i;
606       js.j_njobs++;
607     }
608   else
609     newjob = (JOB *)NULL;
610
611   if (newjob)
612     js.j_lastmade = newjob;
613
614   if (async)
615     {
616       if (newjob)
617         {
618           newjob->flags &= ~J_FOREGROUND;
619           newjob->flags |= J_ASYNC;
620           js.j_lastasync = newjob;
621         }
622       reset_current ();
623     }
624   else
625     {
626       if (newjob)
627         {
628           newjob->flags |= J_FOREGROUND;
629           /*
630            *            !!!!! NOTE !!!!!  (chet@ins.cwru.edu)
631            *
632            * The currently-accepted job control wisdom says to set the
633            * terminal's process group n+1 times in an n-step pipeline:
634            * once in the parent and once in each child.  This is where
635            * the parent gives it away.
636            *
637            * Don't give the terminal away if this shell is an asynchronous
638            * subshell.
639            *
640            */
641           if (job_control && newjob->pgrp && (subshell_environment&SUBSHELL_ASYNC) == 0)
642             maybe_give_terminal_to (shell_pgrp, newjob->pgrp, 0);
643         }
644     }
645
646   stop_making_children ();
647   UNBLOCK_CHILD (oset);
648   return (js.j_current);
649 }
650
651 /* Functions to manage the list of exited background pids whose status has
652    been saved. */
653
654 static struct pidstat *
655 bgp_alloc (pid, status)
656      pid_t pid;
657      int status;
658 {
659   struct pidstat *ps;
660
661   ps = (struct pidstat *)xmalloc (sizeof (struct pidstat));
662   ps->pid = pid;
663   ps->status = status;
664   ps->next = (struct pidstat *)0;
665   return ps;
666 }
667
668 static struct pidstat *
669 bgp_add (pid, status)
670      pid_t pid;
671      int status;
672 {
673   struct pidstat *ps;
674
675   ps = bgp_alloc (pid, status);
676
677   if (bgpids.list == 0)
678     {
679       bgpids.list = bgpids.end = ps;
680       bgpids.npid = 0;                  /* just to make sure */
681     }
682   else
683     {
684       bgpids.end->next = ps;
685       bgpids.end = ps;
686     }
687   bgpids.npid++;
688
689   if (bgpids.npid > js.c_childmax)
690     bgp_prune ();
691
692   return ps;
693 }
694
695 static int
696 bgp_delete (pid)
697      pid_t pid;
698 {
699   struct pidstat *prev, *p;
700
701   for (prev = p = bgpids.list; p; prev = p, p = p->next)
702     if (p->pid == pid)
703       {
704         prev->next = p->next;   /* remove from list */
705         break;
706       }
707
708   if (p == 0)
709     return 0;           /* not found */
710
711 #if defined (DEBUG)
712   itrace("bgp_delete: deleting %d", pid);
713 #endif
714
715   /* Housekeeping in the border cases. */
716   if (p == bgpids.list)
717     bgpids.list = bgpids.list->next;
718   else if (p == bgpids.end)
719     bgpids.end = prev;
720
721   bgpids.npid--;
722   if (bgpids.npid == 0)
723     bgpids.list = bgpids.end = 0;
724   else if (bgpids.npid == 1)
725     bgpids.end = bgpids.list;           /* just to make sure */
726
727   free (p);
728   return 1;
729 }
730
731 /* Clear out the list of saved statuses */
732 static void
733 bgp_clear ()
734 {
735   struct pidstat *ps, *p;
736
737   for (ps = bgpids.list; ps; )
738     {
739       p = ps;
740       ps = ps->next;
741       free (p);
742     }
743   bgpids.list = bgpids.end = 0;
744   bgpids.npid = 0;
745 }
746
747 /* Search for PID in the list of saved background pids; return its status if
748    found.  If not found, return -1. */
749 static int
750 bgp_search (pid)
751      pid_t pid;
752 {
753   struct pidstat *ps;
754
755   for (ps = bgpids.list ; ps; ps = ps->next)
756     if (ps->pid == pid)
757       return ps->status;
758   return -1;
759 }
760
761 static void
762 bgp_prune ()
763 {
764   struct pidstat *ps;
765
766   while (bgpids.npid > js.c_childmax)
767     {
768       ps = bgpids.list;
769       bgpids.list = bgpids.list->next;
770       free (ps);
771       bgpids.npid--;
772     }
773 }
774
775 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
776    been deleted.  The caller should check whether js.j_njobs is 0 before
777    calling this.  This wraps around, but the rest of the code does not.  At
778    this point, it should not matter. */
779 static void
780 reset_job_indices ()
781 {
782   int old;
783
784   if (jobs[js.j_firstj] == 0)
785     {
786       old = js.j_firstj++;
787       if (old >= js.j_jobslots)
788         old = js.j_jobslots - 1;
789       while (js.j_firstj != old)
790         {
791           if (js.j_firstj >= js.j_jobslots)
792             js.j_firstj = 0;
793           if (jobs[js.j_firstj] || js.j_firstj == old)  /* needed if old == 0 */
794             break;
795           js.j_firstj++;
796         }
797       if (js.j_firstj == old)
798         js.j_firstj = js.j_lastj = js.j_njobs = 0;
799     }
800   if (jobs[js.j_lastj] == 0)
801     {
802       old = js.j_lastj--;
803       if (old < 0)
804         old = 0;
805       while (js.j_lastj != old)
806         {
807           if (js.j_lastj < 0)
808             js.j_lastj = js.j_jobslots - 1;
809           if (jobs[js.j_lastj] || js.j_lastj == old)    /* needed if old == js.j_jobslots */
810             break;
811           js.j_lastj--;
812         }
813       if (js.j_lastj == old)
814         js.j_firstj = js.j_lastj = js.j_njobs = 0;
815     }
816 }
817       
818 /* Delete all DEAD jobs that the user had received notification about. */
819 static void
820 cleanup_dead_jobs ()
821 {
822   register int i;
823   int os;
824
825   if (js.j_jobslots == 0 || jobs_list_frozen)
826     return;
827
828   QUEUE_SIGCHLD(os);
829
830   /* XXX could use js.j_firstj and js.j_lastj here */
831   for (i = 0; i < js.j_jobslots; i++)
832     {
833 #if defined (DEBUG)
834       if (i < js.j_firstj && jobs[i])
835         itrace("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
836       if (i > js.j_lastj && jobs[i])
837         itrace("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
838 #endif
839
840       if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
841         delete_job (i, 0);
842     }
843   UNQUEUE_SIGCHLD(os);
844 }
845
846 static int
847 processes_in_job (job)
848      int job;
849 {
850   int nproc;
851   register PROCESS *p;
852
853   nproc = 0;
854   p = jobs[job]->pipe;
855   do
856     {
857       p = p->next;
858       nproc++;
859     }
860   while (p != jobs[job]->pipe);
861
862   return nproc;
863 }
864
865 static void
866 delete_old_job (pid)
867      pid_t pid;
868 {
869   PROCESS *p;
870   int job;
871
872   job = find_job (pid, 0, &p);
873   if (job != NO_JOB)
874     {
875 #ifdef DEBUG
876       itrace ("delete_old_job: found pid %d in job %d with state %d", pid, job, jobs[job]->state);
877 #endif
878       if (JOBSTATE (job) == JDEAD)
879         delete_job (job, DEL_NOBGPID);
880       else
881         {
882           internal_warning (_("forked pid %d appears in running job %d"), pid, job);
883           if (p)
884             p->pid = 0;
885         }
886     }
887 }
888
889 /* Reallocate and compress the jobs list.  This returns with a jobs array
890    whose size is a multiple of JOB_SLOTS and can hold the current number of
891    jobs.  Heuristics are used to minimize the number of new reallocs. */
892 static void
893 realloc_jobs_list ()
894 {
895   sigset_t set, oset;
896   int nsize, i, j, ncur, nprev;
897   JOB **nlist;
898
899   ncur = nprev = NO_JOB;
900   nsize = ((js.j_njobs + JOB_SLOTS - 1) / JOB_SLOTS);
901   nsize *= JOB_SLOTS;
902   i = js.j_njobs % JOB_SLOTS;
903   if (i == 0 || i > (JOB_SLOTS >> 1))
904     nsize += JOB_SLOTS;
905
906   BLOCK_CHILD (set, oset);
907   nlist = (js.j_jobslots == nsize) ? jobs : (JOB **) xmalloc (nsize * sizeof (JOB *));
908
909   js.c_reaped = js.j_ndead = 0;
910   for (i = j = 0; i < js.j_jobslots; i++)
911     if (jobs[i])
912       {
913         if (i == js.j_current)
914           ncur = j;
915         if (i == js.j_previous)
916           nprev = j;
917         nlist[j++] = jobs[i];
918         if (jobs[i]->state == JDEAD)
919           {
920             js.j_ndead++;
921             js.c_reaped += processes_in_job (i);
922           }
923       }
924
925 #if defined (DEBUG)
926   itrace ("realloc_jobs_list: resize jobs list from %d to %d", js.j_jobslots, nsize);
927   itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js.j_lastj, (j > 0) ? j - 1 : 0);
928   itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js.j_njobs, j);
929   itrace ("realloc_jobs_list: js.j_ndead %d js.c_reaped %d", js.j_ndead, js.c_reaped);
930 #endif
931
932   js.j_firstj = 0;
933   js.j_lastj = (j > 0) ? j - 1 : 0;
934   js.j_njobs = j;
935   js.j_jobslots = nsize;
936
937   /* Zero out remaining slots in new jobs list */
938   for ( ; j < nsize; j++)
939     nlist[j] = (JOB *)NULL;
940
941   if (jobs != nlist)
942     {
943       free (jobs);
944       jobs = nlist;
945     }
946
947   if (ncur != NO_JOB)
948     js.j_current = ncur;
949   if (nprev != NO_JOB)
950     js.j_previous = nprev;
951
952   /* Need to reset these */
953   if (js.j_current == NO_JOB || js.j_previous == NO_JOB || js.j_current > js.j_lastj || js.j_previous > js.j_lastj)
954     reset_current ();
955
956 #ifdef DEBUG
957   itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js.j_current, js.j_previous);
958 #endif
959
960   UNBLOCK_CHILD (oset);
961 }
962
963 /* Compact the jobs list by removing dead jobs.  Assumed that we have filled
964    the jobs array to some predefined maximum.  Called when the shell is not
965    the foreground process (subshell_environment != 0).  Returns the first
966    available slot in the compacted list.  If that value is js.j_jobslots, then
967    the list needs to be reallocated.  The jobs array may be in new memory if
968    this returns > 0 and < js.j_jobslots.  FLAGS is reserved for future use. */
969 static int
970 compact_jobs_list (flags)
971      int flags;
972 {
973   if (js.j_jobslots == 0 || jobs_list_frozen)
974     return js.j_jobslots;
975
976   reap_dead_jobs ();
977   realloc_jobs_list ();
978
979 #ifdef DEBUG
980   itrace("compact_jobs_list: returning %d", (js.j_lastj || jobs[js.j_lastj]) ? js.j_lastj + 1 : 0);
981 #endif
982
983   return ((js.j_lastj || jobs[js.j_lastj]) ? js.j_lastj + 1 : 0);
984 }
985
986 /* Delete the job at INDEX from the job list.  Must be called
987    with SIGCHLD blocked. */
988 void
989 delete_job (job_index, dflags)
990      int job_index, dflags;
991 {
992   register JOB *temp;
993   PROCESS *proc;
994   int ndel;
995
996   if (js.j_jobslots == 0 || jobs_list_frozen)
997     return;
998
999   if ((dflags & DEL_WARNSTOPPED) && subshell_environment == 0 && STOPPED (job_index))
1000     internal_warning (_("deleting stopped job %d with process group %ld"), job_index+1, (long)jobs[job_index]->pgrp);
1001   temp = jobs[job_index];
1002   if (temp == 0)
1003     return;
1004
1005   if ((dflags & DEL_NOBGPID) == 0)
1006     {
1007       proc = find_last_proc (job_index, 0);
1008       /* Could do this just for J_ASYNC jobs, but we save all. */
1009       if (proc)
1010         bgp_add (proc->pid, process_exit_status (proc->status));
1011     }
1012
1013   jobs[job_index] = (JOB *)NULL;
1014   if (temp == js.j_lastmade)
1015     js.j_lastmade = 0;
1016   else if (temp == js.j_lastasync)
1017     js.j_lastasync = 0;
1018
1019   free (temp->wd);
1020   ndel = discard_pipeline (temp->pipe);
1021
1022   js.c_injobs -= ndel;
1023   if (temp->state == JDEAD)
1024     {
1025       js.c_reaped -= ndel;
1026       js.j_ndead--;
1027       if (js.c_reaped < 0)
1028         {
1029 #ifdef DEBUG
1030           itrace("delete_job (%d pgrp %d): js.c_reaped (%d) < 0 ndel = %d js.j_ndead = %d", job_index, temp->pgrp, js.c_reaped, ndel, js.j_ndead);
1031 #endif
1032           js.c_reaped = 0;
1033         }
1034     }
1035
1036   if (temp->deferred)
1037     dispose_command (temp->deferred);
1038
1039   free (temp);
1040
1041   js.j_njobs--;
1042   if (js.j_njobs == 0)
1043     js.j_firstj = js.j_lastj = 0;
1044   else if (jobs[js.j_firstj] == 0 || jobs[js.j_lastj] == 0)
1045     reset_job_indices ();
1046
1047   if (job_index == js.j_current || job_index == js.j_previous)
1048     reset_current ();
1049 }
1050
1051 /* Must be called with SIGCHLD blocked. */
1052 void
1053 nohup_job (job_index)
1054      int job_index;
1055 {
1056   register JOB *temp;
1057
1058   if (js.j_jobslots == 0)
1059     return;
1060
1061   if (temp = jobs[job_index])
1062     temp->flags |= J_NOHUP;
1063 }
1064
1065 /* Get rid of the data structure associated with a process chain. */
1066 static int
1067 discard_pipeline (chain)
1068      register PROCESS *chain;
1069 {
1070   register PROCESS *this, *next;
1071   int n;
1072
1073   this = chain;
1074   n = 0;
1075   do
1076     {
1077       next = this->next;
1078       FREE (this->command);
1079       free (this);
1080       n++;
1081       this = next;
1082     }
1083   while (this != chain);
1084
1085   return n;
1086 }
1087
1088 /* Add this process to the chain being built in the_pipeline.
1089    NAME is the command string that will be exec'ed later.
1090    PID is the process id of the child. */
1091 static void
1092 add_process (name, pid)
1093      char *name;
1094      pid_t pid;
1095 {
1096   PROCESS *t, *p;
1097
1098 #if defined (RECYCLES_PIDS)
1099   int j;
1100   p = find_process (pid, 0, &j);
1101   if (p)
1102     {
1103 #  ifdef DEBUG
1104       if (j == NO_JOB)
1105         internal_warning (_("add_process: process %5ld (%s) in the_pipeline"), (long)p->pid, p->command);
1106 #  endif
1107       if (PALIVE (p))
1108         internal_warning (_("add_process: pid %5ld (%s) marked as still alive"), (long)p->pid, p->command);
1109       p->running = PS_RECYCLED;         /* mark as recycled */
1110     }
1111 #endif
1112
1113   t = (PROCESS *)xmalloc (sizeof (PROCESS));
1114   t->next = the_pipeline;
1115   t->pid = pid;
1116   WSTATUS (t->status) = 0;
1117   t->running = PS_RUNNING;
1118   t->command = name;
1119   the_pipeline = t;
1120
1121   if (t->next == 0)
1122     t->next = t;
1123   else
1124     {
1125       p = t->next;
1126       while (p->next != t->next)
1127         p = p->next;
1128       p->next = t;
1129     }
1130 }
1131
1132 #if 0
1133 /* Take the last job and make it the first job.  Must be called with
1134    SIGCHLD blocked. */
1135 int
1136 rotate_the_pipeline ()
1137 {
1138   PROCESS *p;
1139
1140   if (the_pipeline->next == the_pipeline)
1141     return;
1142   for (p = the_pipeline; p->next != the_pipeline; p = p->next)
1143     ;
1144   the_pipeline = p;
1145 }
1146
1147 /* Reverse the order of the processes in the_pipeline.  Must be called with
1148    SIGCHLD blocked. */
1149 int
1150 reverse_the_pipeline ()
1151 {
1152   PROCESS *p, *n;
1153
1154   if (the_pipeline->next == the_pipeline)
1155     return;
1156
1157   for (p = the_pipeline; p->next != the_pipeline; p = p->next)
1158     ;
1159   p->next = (PROCESS *)NULL;
1160
1161   n = REVERSE_LIST (the_pipeline, PROCESS *);
1162
1163   the_pipeline = n;
1164   for (p = the_pipeline; p->next; p = p->next)
1165     ;
1166   p->next = the_pipeline;
1167 }
1168 #endif
1169
1170 /* Map FUNC over the list of jobs.  If FUNC returns non-zero,
1171    then it is time to stop mapping, and that is the return value
1172    for map_over_jobs.  FUNC is called with a JOB, arg1, arg2,
1173    and INDEX. */
1174 static int
1175 map_over_jobs (func, arg1, arg2)
1176      sh_job_map_func_t *func;
1177      int arg1, arg2;
1178 {
1179   register int i;
1180   int result;
1181   sigset_t set, oset;
1182
1183   if (js.j_jobslots == 0)
1184     return 0;
1185
1186   BLOCK_CHILD (set, oset);
1187
1188   /* XXX could use js.j_firstj here */
1189   for (i = result = 0; i < js.j_jobslots; i++)
1190     {
1191 #if defined (DEBUG)
1192       if (i < js.j_firstj && jobs[i])
1193         itrace("map_over_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
1194       if (i > js.j_lastj && jobs[i])
1195         itrace("map_over_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
1196 #endif
1197       if (jobs[i])
1198         {
1199           result = (*func)(jobs[i], arg1, arg2, i);
1200           if (result)
1201             break;
1202         }
1203     }
1204
1205   UNBLOCK_CHILD (oset);
1206
1207   return (result);
1208 }
1209
1210 /* Cause all the jobs in the current pipeline to exit. */
1211 void
1212 terminate_current_pipeline ()
1213 {
1214   if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
1215     {
1216       killpg (pipeline_pgrp, SIGTERM);
1217       killpg (pipeline_pgrp, SIGCONT);
1218     }
1219 }
1220
1221 /* Cause all stopped jobs to exit. */
1222 void
1223 terminate_stopped_jobs ()
1224 {
1225   register int i;
1226
1227   /* XXX could use js.j_firstj here */
1228   for (i = 0; i < js.j_jobslots; i++)
1229     {
1230       if (jobs[i] && STOPPED (i))
1231         {
1232           killpg (jobs[i]->pgrp, SIGTERM);
1233           killpg (jobs[i]->pgrp, SIGCONT);
1234         }
1235     }
1236 }
1237
1238 /* Cause all jobs, running or stopped, to receive a hangup signal.  If
1239    a job is marked J_NOHUP, don't send the SIGHUP. */
1240 void
1241 hangup_all_jobs ()
1242 {
1243   register int i;
1244
1245   /* XXX could use js.j_firstj here */
1246   for (i = 0; i < js.j_jobslots; i++)
1247     {
1248       if (jobs[i])
1249         {
1250           if  (jobs[i]->flags & J_NOHUP)
1251             continue;
1252           killpg (jobs[i]->pgrp, SIGHUP);
1253           if (STOPPED (i))
1254             killpg (jobs[i]->pgrp, SIGCONT);
1255         }
1256     }
1257 }
1258
1259 void
1260 kill_current_pipeline ()
1261 {
1262   stop_making_children ();
1263   start_pipeline ();
1264 }
1265
1266 /* Return the pipeline that PID belongs to.  Note that the pipeline
1267    doesn't have to belong to a job.  Must be called with SIGCHLD blocked.
1268    If JOBP is non-null, return the index of the job containing PID.  */
1269 static PROCESS *
1270 find_pipeline (pid, alive_only, jobp)
1271      pid_t pid;
1272      int alive_only;
1273      int *jobp;         /* index into jobs list or NO_JOB */
1274 {
1275   int job;
1276   PROCESS *p;
1277
1278   /* See if this process is in the pipeline that we are building. */
1279   if (jobp)
1280     *jobp = NO_JOB;
1281   if (the_pipeline)
1282     {
1283       p = the_pipeline;
1284       do
1285         {
1286           /* Return it if we found it.  Don't ever return a recycled pid. */
1287           if (p->pid == pid && ((alive_only == 0 && PRECYCLED(p) == 0) || PALIVE(p)))
1288             return (p);
1289
1290           p = p->next;
1291         }
1292       while (p != the_pipeline);
1293     }
1294
1295   job = find_job (pid, alive_only, &p);
1296   if (jobp)
1297     *jobp = job;
1298   return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
1299 }
1300
1301 /* Return the PROCESS * describing PID.  If JOBP is non-null return the index
1302    into the jobs array of the job containing PID.  Must be called with
1303    SIGCHLD blocked. */
1304 static PROCESS *
1305 find_process (pid, alive_only, jobp)
1306      pid_t pid;
1307      int alive_only;
1308      int *jobp;         /* index into jobs list or NO_JOB */
1309 {
1310   PROCESS *p;
1311
1312   p = find_pipeline (pid, alive_only, jobp);
1313   while (p && p->pid != pid)
1314     p = p->next;
1315   return p;
1316 }
1317
1318 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1319    belong to any job.  Must be called with SIGCHLD blocked. */
1320 static int
1321 find_job (pid, alive_only, procp)
1322      pid_t pid;
1323      int alive_only;
1324      PROCESS **procp;
1325 {
1326   register int i;
1327   PROCESS *p;
1328
1329   /* XXX could use js.j_firstj here, and should check js.j_lastj */
1330   for (i = 0; i < js.j_jobslots; i++)
1331     {
1332 #if defined (DEBUG)
1333       if (i < js.j_firstj && jobs[i])
1334         itrace("find_job: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
1335       if (i > js.j_lastj && jobs[i])
1336         itrace("find_job: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
1337 #endif
1338       if (jobs[i])
1339         {
1340           p = jobs[i]->pipe;
1341
1342           do
1343             {
1344               if (p->pid == pid && ((alive_only == 0 && PRECYCLED(p) == 0) || PALIVE(p)))
1345                 {
1346                   if (procp)
1347                     *procp = p;
1348                   return (i);
1349                 }
1350
1351               p = p->next;
1352             }
1353           while (p != jobs[i]->pipe);
1354         }
1355     }
1356
1357   return (NO_JOB);
1358 }
1359
1360 /* Find a job given a PID.  If BLOCK is non-zero, block SIGCHLD as
1361    required by find_job. */
1362 int
1363 get_job_by_pid (pid, block)
1364      pid_t pid;
1365      int block;
1366 {
1367   int job;
1368   sigset_t set, oset;
1369
1370   if (block)
1371     BLOCK_CHILD (set, oset);
1372
1373   job = find_job (pid, 0, NULL);
1374
1375   if (block)
1376     UNBLOCK_CHILD (oset);
1377
1378   return job;
1379 }
1380
1381 /* Print descriptive information about the job with leader pid PID. */
1382 void
1383 describe_pid (pid)
1384      pid_t pid;
1385 {
1386   int job;
1387   sigset_t set, oset;
1388
1389   BLOCK_CHILD (set, oset);
1390
1391   job = find_job (pid, 0, NULL);
1392
1393   if (job != NO_JOB)
1394     fprintf (stderr, "[%d] %ld\n", job + 1, (long)pid);
1395   else
1396     programming_error (_("describe_pid: %ld: no such pid"), (long)pid);
1397
1398   UNBLOCK_CHILD (oset);
1399 }
1400
1401 static char *
1402 j_strsignal (s)
1403      int s;
1404 {
1405   char *x;
1406
1407   x = strsignal (s);
1408   if (x == 0)
1409     {
1410       x = retcode_name_buffer;
1411       sprintf (x, _("Signal %d"), s);
1412     }
1413   return x;
1414 }
1415
1416 static char *
1417 printable_job_status (j, p, format)
1418      int j;
1419      PROCESS *p;
1420      int format;
1421 {
1422   static char *temp;
1423   int es;
1424
1425   temp = _("Done");
1426
1427   if (STOPPED (j) && format == 0)
1428     {
1429       if (posixly_correct == 0 || p == 0 || (WIFSTOPPED (p->status) == 0))
1430         temp = _("Stopped");
1431       else
1432         {
1433           temp = retcode_name_buffer;
1434           sprintf (temp, _("Stopped(%s)"), signal_name (WSTOPSIG (p->status)));
1435         }
1436     }
1437   else if (RUNNING (j))
1438     temp = _("Running");
1439   else
1440     {
1441       if (WIFSTOPPED (p->status))
1442         temp = j_strsignal (WSTOPSIG (p->status));
1443       else if (WIFSIGNALED (p->status))
1444         temp = j_strsignal (WTERMSIG (p->status));
1445       else if (WIFEXITED (p->status))
1446         {
1447           temp = retcode_name_buffer;
1448           es = WEXITSTATUS (p->status);
1449           if (es == 0)
1450             strcpy (temp, _("Done"));
1451           else if (posixly_correct)
1452             sprintf (temp, _("Done(%d)"), es);
1453           else
1454             sprintf (temp, _("Exit %d"), es);
1455         }
1456       else
1457         temp = _("Unknown status");
1458     }
1459
1460   return temp;
1461 }
1462
1463 /* This is the way to print out information on a job if you
1464    know the index.  FORMAT is:
1465
1466     JLIST_NORMAL)   [1]+ Running           emacs
1467     JLIST_LONG  )   [1]+ 2378 Running      emacs
1468     -1    )   [1]+ 2378       emacs
1469
1470     JLIST_NORMAL)   [1]+ Stopped           ls | more
1471     JLIST_LONG  )   [1]+ 2369 Stopped      ls
1472                          2367       | more
1473     JLIST_PID_ONLY)
1474         Just list the pid of the process group leader (really
1475         the process group).
1476     JLIST_CHANGED_ONLY)
1477         Use format JLIST_NORMAL, but list only jobs about which
1478         the user has not been notified. */
1479
1480 /* Print status for pipeline P.  If JOB_INDEX is >= 0, it is the index into
1481    the JOBS array corresponding to this pipeline.  FORMAT is as described
1482    above.  Must be called with SIGCHLD blocked.
1483
1484    If you're printing a pipeline that's not in the jobs array, like the
1485    current pipeline as it's being created, pass -1 for JOB_INDEX */
1486 static void
1487 print_pipeline (p, job_index, format, stream)
1488      PROCESS *p;
1489      int job_index, format;
1490      FILE *stream;
1491 {
1492   PROCESS *first, *last, *show;
1493   int es, name_padding;
1494   char *temp;
1495
1496   if (p == 0)
1497     return;
1498
1499   first = last = p;
1500   while (last->next != first)
1501     last = last->next;
1502
1503   for (;;)
1504     {
1505       if (p != first)
1506         fprintf (stream, format ? "     " : " |");
1507
1508       if (format != JLIST_STANDARD)
1509         fprintf (stream, "%5ld", (long)p->pid);
1510
1511       fprintf (stream, " ");
1512
1513       if (format > -1 && job_index >= 0)
1514         {
1515           show = format ? p : last;
1516           temp = printable_job_status (job_index, show, format);
1517
1518           if (p != first)
1519             {
1520               if (format)
1521                 {
1522                   if (show->running == first->running &&
1523                       WSTATUS (show->status) == WSTATUS (first->status))
1524                     temp = "";
1525                 }
1526               else
1527                 temp = (char *)NULL;
1528             }
1529
1530           if (temp)
1531             {
1532               fprintf (stream, "%s", temp);
1533
1534               es = STRLEN (temp);
1535               if (es == 0)
1536                 es = 2; /* strlen ("| ") */
1537               name_padding = LONGEST_SIGNAL_DESC - es;
1538
1539               fprintf (stream, "%*s", name_padding, "");
1540
1541               if ((WIFSTOPPED (show->status) == 0) &&
1542                   (WIFCONTINUED (show->status) == 0) &&
1543                   WIFCORED (show->status))
1544                 fprintf (stream, _("(core dumped) "));
1545             }
1546         }
1547
1548       if (p != first && format)
1549         fprintf (stream, "| ");
1550
1551       if (p->command)
1552         fprintf (stream, "%s", p->command);
1553
1554       if (p == last && job_index >= 0)
1555         {
1556           temp = current_working_directory ();
1557
1558           if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
1559             fprintf (stream, " &");
1560
1561           if (strcmp (temp, jobs[job_index]->wd) != 0)
1562             fprintf (stream,
1563               _("  (wd: %s)"), polite_directory_format (jobs[job_index]->wd));
1564         }
1565
1566       if (format || (p == last))
1567         {
1568           /* We need to add a CR only if this is an interactive shell, and
1569              we're reporting the status of a completed job asynchronously.
1570              We can't really check whether this particular job is being
1571              reported asynchronously, so just add the CR if the shell is
1572              currently interactive and asynchronous notification is enabled. */
1573           if (asynchronous_notification && interactive)
1574             fprintf (stream, "\r\n");
1575           else
1576             fprintf (stream, "\n");
1577         }
1578
1579       if (p == last)
1580         break;
1581       p = p->next;
1582     }
1583   fflush (stream);
1584 }
1585
1586 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1587    Must be called with SIGCHLD blocked or queued with queue_sigchld */
1588 static void
1589 pretty_print_job (job_index, format, stream)
1590      int job_index, format;
1591      FILE *stream;
1592 {
1593   register PROCESS *p;
1594
1595   /* Format only pid information about the process group leader? */
1596   if (format == JLIST_PID_ONLY)
1597     {
1598       fprintf (stream, "%ld\n", (long)jobs[job_index]->pipe->pid);
1599       return;
1600     }
1601
1602   if (format == JLIST_CHANGED_ONLY)
1603     {
1604       if (IS_NOTIFIED (job_index))
1605         return;
1606       format = JLIST_STANDARD;
1607     }
1608
1609   if (format != JLIST_NONINTERACTIVE)
1610     fprintf (stream, "[%d]%c ", job_index + 1,
1611               (job_index == js.j_current) ? '+':
1612                 (job_index == js.j_previous) ? '-' : ' ');
1613
1614   if (format == JLIST_NONINTERACTIVE)
1615     format = JLIST_LONG;
1616
1617   p = jobs[job_index]->pipe;
1618
1619   print_pipeline (p, job_index, format, stream);
1620
1621   /* We have printed information about this job.  When the job's
1622      status changes, waitchld () sets the notification flag to 0. */
1623   jobs[job_index]->flags |= J_NOTIFIED;
1624 }
1625
1626 static int
1627 print_job (job, format, state, job_index)
1628      JOB *job;
1629      int format, state, job_index;
1630 {
1631   if (state == -1 || (JOB_STATE)state == job->state)
1632     pretty_print_job (job_index, format, stdout);
1633   return (0);
1634 }
1635
1636 void
1637 list_one_job (job, format, ignore, job_index)
1638      JOB *job;
1639      int format, ignore, job_index;
1640 {
1641   pretty_print_job (job_index, format, stdout);
1642 }
1643
1644 void
1645 list_stopped_jobs (format)
1646      int format;
1647 {
1648   cleanup_dead_jobs ();
1649   map_over_jobs (print_job, format, (int)JSTOPPED);
1650 }
1651
1652 void
1653 list_running_jobs (format)
1654      int format;
1655 {
1656   cleanup_dead_jobs ();
1657   map_over_jobs (print_job, format, (int)JRUNNING);
1658 }
1659
1660 /* List jobs.  If FORMAT is non-zero, then the long form of the information
1661    is printed, else just a short version. */
1662 void
1663 list_all_jobs (format)
1664      int format;
1665 {
1666   cleanup_dead_jobs ();
1667   map_over_jobs (print_job, format, -1);
1668 }
1669
1670 /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
1671    COMMAND is just for remembering the name of the command; we don't do
1672    anything else with it.  ASYNC_P says what to do with the tty.  If
1673    non-zero, then don't give it away. */
1674 pid_t
1675 make_child (command, async_p)
1676      char *command;
1677      int async_p;
1678 {
1679   int forksleep;
1680   sigset_t set, oset;
1681   pid_t pid;
1682
1683   sigemptyset (&set);
1684   sigaddset (&set, SIGCHLD);
1685   sigaddset (&set, SIGINT);
1686   sigemptyset (&oset);
1687   sigprocmask (SIG_BLOCK, &set, &oset);
1688
1689   making_children ();
1690
1691   forksleep = 1;
1692
1693 #if defined (BUFFERED_INPUT)
1694   /* If default_buffered_input is active, we are reading a script.  If
1695      the command is asynchronous, we have already duplicated /dev/null
1696      as fd 0, but have not changed the buffered stream corresponding to
1697      the old fd 0.  We don't want to sync the stream in this case. */
1698   if (default_buffered_input != -1 &&
1699       (!async_p || default_buffered_input > 0))
1700     sync_buffered_stream (default_buffered_input);
1701 #endif /* BUFFERED_INPUT */
1702
1703   /* Create the child, handle severe errors.  Retry on EAGAIN. */
1704   while ((pid = fork ()) < 0 && errno == EAGAIN && forksleep < FORKSLEEP_MAX)
1705     {
1706       sys_error ("fork: retry");
1707       if (sleep (forksleep) != 0)
1708         break;
1709       forksleep <<= 1;
1710     }
1711
1712   if (pid < 0)
1713     {
1714       sys_error ("fork");
1715
1716       /* Kill all of the processes in the current pipeline. */
1717       terminate_current_pipeline ();
1718
1719       /* Discard the current pipeline, if any. */
1720       if (the_pipeline)
1721         kill_current_pipeline ();
1722
1723       throw_to_top_level ();    /* Reset signals, etc. */
1724     }
1725
1726   if (pid == 0)
1727     {
1728       /* In the child.  Give this child the right process group, set the
1729          signals to the default state for a new process. */
1730       pid_t mypid;
1731
1732       mypid = getpid ();
1733 #if defined (BUFFERED_INPUT)
1734       /* Close default_buffered_input if it's > 0.  We don't close it if it's
1735          0 because that's the file descriptor used when redirecting input,
1736          and it's wrong to close the file in that case. */
1737       unset_bash_input (0);
1738 #endif /* BUFFERED_INPUT */
1739
1740       /* Restore top-level signal mask. */
1741       sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1742
1743       if (job_control)
1744         {
1745           /* All processes in this pipeline belong in the same
1746              process group. */
1747
1748           if (pipeline_pgrp == 0)       /* This is the first child. */
1749             pipeline_pgrp = mypid;
1750
1751           /* Check for running command in backquotes. */
1752           if (pipeline_pgrp == shell_pgrp)
1753             ignore_tty_job_signals ();
1754           else
1755             default_tty_job_signals ();
1756
1757           /* Set the process group before trying to mess with the terminal's
1758              process group.  This is mandated by POSIX. */
1759           /* This is in accordance with the Posix 1003.1 standard,
1760              section B.7.2.4, which says that trying to set the terminal
1761              process group with tcsetpgrp() to an unused pgrp value (like
1762              this would have for the first child) is an error.  Section
1763              B.4.3.3, p. 237 also covers this, in the context of job control
1764              shells. */
1765           if (setpgid (mypid, pipeline_pgrp) < 0)
1766             sys_error (_("child setpgid (%ld to %ld)"), (long)mypid, (long)pipeline_pgrp);
1767
1768           /* By convention (and assumption above), if
1769              pipeline_pgrp == shell_pgrp, we are making a child for
1770              command substitution.
1771              In this case, we don't want to give the terminal to the
1772              shell's process group (we could be in the middle of a
1773              pipeline, for example). */
1774           if (async_p == 0 && pipeline_pgrp != shell_pgrp && ((subshell_environment&SUBSHELL_ASYNC) == 0))
1775             give_terminal_to (pipeline_pgrp, 0);
1776
1777 #if defined (PGRP_PIPE)
1778           if (pipeline_pgrp == mypid)
1779             pipe_read (pgrp_pipe);
1780 #endif
1781         }
1782       else                      /* Without job control... */
1783         {
1784           if (pipeline_pgrp == 0)
1785             pipeline_pgrp = shell_pgrp;
1786
1787           /* If these signals are set to SIG_DFL, we encounter the curious
1788              situation of an interactive ^Z to a running process *working*
1789              and stopping the process, but being unable to do anything with
1790              that process to change its state.  On the other hand, if they
1791              are set to SIG_IGN, jobs started from scripts do not stop when
1792              the shell running the script gets a SIGTSTP and stops. */
1793
1794           default_tty_job_signals ();
1795         }
1796
1797 #if defined (PGRP_PIPE)
1798       /* Release the process group pipe, since our call to setpgid ()
1799          is done.  The last call to sh_closepipe is done in stop_pipeline. */
1800       sh_closepipe (pgrp_pipe);
1801 #endif /* PGRP_PIPE */
1802
1803 #if 0
1804       /* Don't set last_asynchronous_pid in the child */
1805       if (async_p)
1806         last_asynchronous_pid = mypid;          /* XXX */
1807       else
1808 #endif
1809 #if defined (RECYCLES_PIDS)
1810       if (last_asynchronous_pid == mypid)
1811         /* Avoid pid aliasing.  1 seems like a safe, unusual pid value. */
1812         last_asynchronous_pid = 1;
1813 #endif
1814     }
1815   else
1816     {
1817       /* In the parent.  Remember the pid of the child just created
1818          as the proper pgrp if this is the first child. */
1819
1820       if (first_pid == NO_PID)
1821         first_pid = pid;
1822       else if (pid_wrap == -1 && pid < first_pid)
1823         pid_wrap = 0;
1824       else if (pid_wrap == 0 && pid >= first_pid)
1825         pid_wrap = 1;
1826
1827       if (job_control)
1828         {
1829           if (pipeline_pgrp == 0)
1830             {
1831               pipeline_pgrp = pid;
1832               /* Don't twiddle terminal pgrps in the parent!  This is the bug,
1833                  not the good thing of twiddling them in the child! */
1834               /* give_terminal_to (pipeline_pgrp, 0); */
1835             }
1836           /* This is done on the recommendation of the Rationale section of
1837              the POSIX 1003.1 standard, where it discusses job control and
1838              shells.  It is done to avoid possible race conditions. (Ref.
1839              1003.1 Rationale, section B.4.3.3, page 236). */
1840           setpgid (pid, pipeline_pgrp);
1841         }
1842       else
1843         {
1844           if (pipeline_pgrp == 0)
1845             pipeline_pgrp = shell_pgrp;
1846         }
1847
1848       /* Place all processes into the jobs array regardless of the
1849          state of job_control. */
1850       add_process (command, pid);
1851
1852       if (async_p)
1853         last_asynchronous_pid = pid;
1854 #if defined (RECYCLES_PIDS)
1855       else if (last_asynchronous_pid == pid)
1856         /* Avoid pid aliasing.  1 seems like a safe, unusual pid value. */
1857         last_asynchronous_pid = 1;
1858 #endif
1859
1860       if (pid_wrap > 0)
1861         delete_old_job (pid);
1862
1863 #if !defined (RECYCLES_PIDS)
1864       /* Only check for saved status if we've saved more than CHILD_MAX
1865          statuses, unless the system recycles pids. */
1866       if ((js.c_reaped + bgpids.npid) >= js.c_childmax)
1867 #endif
1868         bgp_delete (pid);               /* new process, discard any saved status */
1869
1870       last_made_pid = pid;
1871
1872       /* keep stats */
1873       js.c_totforked++;
1874       js.c_living++;
1875
1876       /* Unblock SIGINT and SIGCHLD unless creating a pipeline, in which case
1877          SIGCHLD remains blocked until all commands in the pipeline have been
1878          created. */
1879       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1880     }
1881
1882   return (pid);
1883 }
1884
1885 /* These two functions are called only in child processes. */
1886 void
1887 ignore_tty_job_signals ()
1888 {
1889   set_signal_handler (SIGTSTP, SIG_IGN);
1890   set_signal_handler (SIGTTIN, SIG_IGN);
1891   set_signal_handler (SIGTTOU, SIG_IGN);
1892 }
1893
1894 void
1895 default_tty_job_signals ()
1896 {
1897   set_signal_handler (SIGTSTP, SIG_DFL);
1898   set_signal_handler (SIGTTIN, SIG_DFL);
1899   set_signal_handler (SIGTTOU, SIG_DFL);
1900 }
1901
1902 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1903    state kept in here.  When a job ends normally, we set the state in here
1904    to the state of the tty. */
1905
1906 static TTYSTRUCT shell_tty_info;
1907
1908 #if defined (NEW_TTY_DRIVER)
1909 static struct tchars shell_tchars;
1910 static struct ltchars shell_ltchars;
1911 #endif /* NEW_TTY_DRIVER */
1912
1913 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1914 /* Since the BSD tty driver does not allow us to change the tty modes
1915    while simultaneously waiting for output to drain and preserving
1916    typeahead, we have to drain the output ourselves before calling
1917    ioctl.  We cheat by finding the length of the output queue, and
1918    using select to wait for an appropriate length of time.  This is
1919    a hack, and should be labeled as such (it's a hastily-adapted
1920    mutation of a `usleep' implementation).  It's only reason for
1921    existing is the flaw in the BSD tty driver. */
1922
1923 static int ttspeeds[] =
1924 {
1925   0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1926   1800, 2400, 4800, 9600, 19200, 38400
1927 };
1928
1929 static void
1930 draino (fd, ospeed)
1931      int fd, ospeed;
1932 {
1933   register int delay = ttspeeds[ospeed];
1934   int n;
1935
1936   if (!delay)
1937     return;
1938
1939   while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1940     {
1941       if (n > (delay / 100))
1942         {
1943           struct timeval tv;
1944
1945           n *= 10;              /* 2 bits more for conservativeness. */
1946           tv.tv_sec = n / delay;
1947           tv.tv_usec = ((n % delay) * 1000000) / delay;
1948           select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1949         }
1950       else
1951         break;
1952     }
1953 }
1954 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1955
1956 /* Return the fd from which we are actually getting input. */
1957 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1958
1959 /* Fill the contents of shell_tty_info with the current tty info. */
1960 int
1961 get_tty_state ()
1962 {
1963   int tty;
1964
1965   tty = input_tty ();
1966   if (tty != -1)
1967     {
1968 #if defined (NEW_TTY_DRIVER)
1969       ioctl (tty, TIOCGETP, &shell_tty_info);
1970       ioctl (tty, TIOCGETC, &shell_tchars);
1971       ioctl (tty, TIOCGLTC, &shell_ltchars);
1972 #endif /* NEW_TTY_DRIVER */
1973
1974 #if defined (TERMIO_TTY_DRIVER)
1975       ioctl (tty, TCGETA, &shell_tty_info);
1976 #endif /* TERMIO_TTY_DRIVER */
1977
1978 #if defined (TERMIOS_TTY_DRIVER)
1979       if (tcgetattr (tty, &shell_tty_info) < 0)
1980         {
1981 #if 0
1982           /* Only print an error message if we're really interactive at
1983              this time. */
1984           if (interactive)
1985             sys_error ("[%ld: %d (%d)] tcgetattr", (long)getpid (), shell_level, tty);
1986 #endif
1987           return -1;
1988         }
1989 #endif /* TERMIOS_TTY_DRIVER */
1990       if (check_window_size)
1991         get_new_window_size (0, (int *)0, (int *)0);
1992     }
1993   return 0;
1994 }
1995
1996 /* Make the current tty use the state in shell_tty_info. */
1997 int
1998 set_tty_state ()
1999 {
2000   int tty;
2001
2002   tty = input_tty ();
2003   if (tty != -1)
2004     {
2005 #if defined (NEW_TTY_DRIVER)
2006 #  if defined (DRAIN_OUTPUT)
2007       draino (tty, shell_tty_info.sg_ospeed);
2008 #  endif /* DRAIN_OUTPUT */
2009       ioctl (tty, TIOCSETN, &shell_tty_info);
2010       ioctl (tty, TIOCSETC, &shell_tchars);
2011       ioctl (tty, TIOCSLTC, &shell_ltchars);
2012 #endif /* NEW_TTY_DRIVER */
2013
2014 #if defined (TERMIO_TTY_DRIVER)
2015       ioctl (tty, TCSETAW, &shell_tty_info);
2016 #endif /* TERMIO_TTY_DRIVER */
2017
2018 #if defined (TERMIOS_TTY_DRIVER)
2019       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2020         {
2021           /* Only print an error message if we're really interactive at
2022              this time. */
2023           if (interactive)
2024             sys_error ("[%ld: %d (%d)] tcsetattr", (long)getpid (), shell_level, tty);
2025           return -1;
2026         }
2027 #endif /* TERMIOS_TTY_DRIVER */
2028     }
2029   return 0;
2030 }
2031
2032 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2033    process in that job's pipeline.  This is the one whose exit status
2034    counts.  Must be called with SIGCHLD blocked or queued. */
2035 static PROCESS *
2036 find_last_proc (job, block)
2037      int job;
2038      int block;
2039 {
2040   register PROCESS *p;
2041   sigset_t set, oset;
2042
2043   if (block)
2044     BLOCK_CHILD (set, oset);
2045
2046   p = jobs[job]->pipe;
2047   while (p && p->next != jobs[job]->pipe)
2048     p = p->next;
2049
2050   if (block)
2051     UNBLOCK_CHILD (oset);
2052
2053   return (p);
2054 }
2055
2056 static pid_t
2057 find_last_pid (job, block)
2058      int job;
2059      int block;
2060 {
2061   PROCESS *p;
2062
2063   p = find_last_proc (job, block);
2064   /* Possible race condition here. */
2065   return p->pid;
2066 }     
2067
2068 /* Wait for a particular child of the shell to finish executing.
2069    This low-level function prints an error message if PID is not
2070    a child of this shell.  It returns -1 if it fails, or whatever
2071    wait_for returns otherwise.  If the child is not found in the
2072    jobs table, it returns 127. */
2073 int
2074 wait_for_single_pid (pid)
2075      pid_t pid;
2076 {
2077   register PROCESS *child;
2078   sigset_t set, oset;
2079   int r, job;
2080
2081   BLOCK_CHILD (set, oset);
2082   child = find_pipeline (pid, 0, (int *)NULL);
2083   UNBLOCK_CHILD (oset);
2084
2085   if (child == 0)
2086     {
2087       r = bgp_search (pid);
2088       if (r >= 0)
2089         return r;
2090     }
2091
2092   if (child == 0)
2093     {
2094       internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid);
2095       return (127);
2096     }
2097
2098   r = wait_for (pid);
2099
2100   /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2101      table. */
2102   BLOCK_CHILD (set, oset);
2103   job = find_job (pid, 0, NULL);
2104   if (job != NO_JOB && jobs[job] && DEADJOB (job))
2105     jobs[job]->flags |= J_NOTIFIED;
2106   UNBLOCK_CHILD (oset);
2107
2108   /* If running in posix mode, remove the job from the jobs table immediately */
2109   if (posixly_correct)
2110     {
2111       cleanup_dead_jobs ();
2112       bgp_delete (pid);
2113     }
2114
2115   return r;
2116 }
2117
2118 /* Wait for all of the backgrounds of this shell to finish. */
2119 void
2120 wait_for_background_pids ()
2121 {
2122   register int i, r, waited_for;
2123   sigset_t set, oset;
2124   pid_t pid;
2125
2126   for (waited_for = 0;;)
2127     {
2128       BLOCK_CHILD (set, oset);
2129
2130       /* find first running job; if none running in foreground, break */
2131       /* XXX could use js.j_firstj and js.j_lastj here */
2132       for (i = 0; i < js.j_jobslots; i++)
2133         {
2134 #if defined (DEBUG)
2135           if (i < js.j_firstj && jobs[i])
2136             itrace("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
2137           if (i > js.j_lastj && jobs[i])
2138             itrace("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
2139 #endif
2140           if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
2141             break;
2142         }
2143       if (i == js.j_jobslots)
2144         {
2145           UNBLOCK_CHILD (oset);
2146           break;
2147         }
2148
2149       /* now wait for the last pid in that job. */
2150       pid = find_last_pid (i, 0);
2151       UNBLOCK_CHILD (oset);
2152       QUIT;
2153       errno = 0;                /* XXX */
2154       r = wait_for_single_pid (pid);
2155       if (r == -1)
2156         {
2157           /* If we're mistaken about job state, compensate. */
2158           if (errno == ECHILD)
2159             mark_all_jobs_as_dead ();
2160         }
2161       else
2162         waited_for++;
2163     }
2164
2165   /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2166      `wait' is called with no arguments. */
2167   mark_dead_jobs_as_notified (1);
2168   cleanup_dead_jobs ();
2169   bgp_clear ();
2170 }
2171
2172 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2173 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2174 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
2175
2176 static void
2177 restore_sigint_handler ()
2178 {
2179   if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
2180     {
2181       set_signal_handler (SIGINT, old_sigint_handler);
2182       old_sigint_handler = INVALID_SIGNAL_HANDLER;
2183     }
2184 }
2185
2186 static int wait_sigint_received;
2187
2188 /* Handle SIGINT while we are waiting for children in a script to exit.
2189    The `wait' builtin should be interruptible, but all others should be
2190    effectively ignored (i.e. not cause the shell to exit). */
2191 static sighandler
2192 wait_sigint_handler (sig)
2193      int sig;
2194 {
2195   SigHandler *sigint_handler;
2196
2197   if (interrupt_immediately ||
2198       (this_shell_builtin && this_shell_builtin == wait_builtin))
2199     {
2200       last_command_exit_value = EXECUTION_FAILURE;
2201       restore_sigint_handler ();
2202       /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2203          what POSIX.2 says (see builtins/wait.def for more info). */
2204       if (this_shell_builtin && this_shell_builtin == wait_builtin &&
2205           signal_is_trapped (SIGINT) &&
2206           ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
2207         {
2208           interrupt_immediately = 0;
2209           trap_handler (SIGINT);        /* set pending_traps[SIGINT] */
2210           wait_signal_received = SIGINT;
2211           longjmp (wait_intr_buf, 1);
2212         }
2213       
2214       ADDINTERRUPT;
2215       QUIT;
2216     }
2217
2218   /* XXX - should this be interrupt_state?  If it is, the shell will act
2219      as if it got the SIGINT interrupt. */
2220   wait_sigint_received = 1;
2221
2222   /* Otherwise effectively ignore the SIGINT and allow the running job to
2223      be killed. */
2224   SIGRETURN (0);
2225 }
2226
2227 static int
2228 process_exit_signal (status)
2229      WAIT status;
2230 {
2231   return (WIFSIGNALED (status) ? WTERMSIG (status) : 0);
2232 }
2233
2234 static int
2235 process_exit_status (status)
2236      WAIT status;
2237 {
2238   if (WIFSIGNALED (status))
2239     return (128 + WTERMSIG (status));
2240   else if (WIFSTOPPED (status) == 0)
2241     return (WEXITSTATUS (status));
2242   else
2243     return (EXECUTION_SUCCESS);
2244 }
2245
2246 static WAIT
2247 job_signal_status (job)
2248      int job;
2249 {
2250   register PROCESS *p;
2251   WAIT s;
2252
2253   p = jobs[job]->pipe;
2254   do
2255     {
2256       s = p->status;
2257       if (WIFSIGNALED(s) || WIFSTOPPED(s))
2258         break;
2259       p = p->next;
2260     }
2261   while (p != jobs[job]->pipe);
2262
2263   return s;
2264 }
2265   
2266 /* Return the exit status of the last process in the pipeline for job JOB.
2267    This is the exit status of the entire job. */
2268 static WAIT
2269 raw_job_exit_status (job)
2270      int job;
2271 {
2272   register PROCESS *p;
2273   int fail;
2274   WAIT ret;
2275
2276   if (pipefail_opt)
2277     {
2278       fail = 0;
2279       p = jobs[job]->pipe;
2280       do
2281         {
2282           if (WSTATUS (p->status) != EXECUTION_SUCCESS)
2283             fail = WSTATUS(p->status);
2284           p = p->next;
2285         }
2286       while (p != jobs[job]->pipe);
2287       WSTATUS (ret) = fail;
2288       return ret;
2289     }
2290
2291   for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
2292     ;
2293   return (p->status);
2294 }
2295
2296 /* Return the exit status of job JOB.  This is the exit status of the last
2297    (rightmost) process in the job's pipeline, modified if the job was killed
2298    by a signal or stopped. */
2299 static int
2300 job_exit_status (job)
2301      int job;
2302 {
2303   return (process_exit_status (raw_job_exit_status (job)));
2304 }
2305
2306 static int
2307 job_exit_signal (job)
2308      int job;
2309 {
2310   return (process_exit_signal (raw_job_exit_status (job)));
2311 }
2312
2313 #define FIND_CHILD(pid, child) \
2314   do \
2315     { \
2316       child = find_pipeline (pid, 0, (int *)NULL); \
2317       if (child == 0) \
2318         { \
2319           give_terminal_to (shell_pgrp, 0); \
2320           UNBLOCK_CHILD (oset); \
2321           internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2322           restore_sigint_handler (); \
2323           return (termination_state = 127); \
2324         } \
2325     } \
2326   while (0)
2327
2328 /* Wait for pid (one of our children) to terminate, then
2329    return the termination state.  Returns 127 if PID is not found in
2330    the jobs table.  Returns -1 if waitchld() returns -1, indicating
2331    that there are no unwaited-for child processes. */
2332 int
2333 wait_for (pid)
2334      pid_t pid;
2335 {
2336   int job, termination_state, r;
2337   WAIT s;
2338   register PROCESS *child;
2339   sigset_t set, oset;
2340   register PROCESS *p;
2341
2342   /* In the case that this code is interrupted, and we longjmp () out of it,
2343      we are relying on the code in throw_to_top_level () to restore the
2344      top-level signal mask. */
2345   BLOCK_CHILD (set, oset);
2346
2347   /* Ignore interrupts while waiting for a job run without job control
2348      to finish.  We don't want the shell to exit if an interrupt is
2349      received, only if one of the jobs run is killed via SIGINT.  If
2350      job control is not set, the job will be run in the same pgrp as
2351      the shell, and the shell will see any signals the job gets.  In
2352      fact, we want this set every time the waiting shell and the waited-
2353      for process are in the same process group, including command
2354      substitution. */
2355
2356   /* This is possibly a race condition -- should it go in stop_pipeline? */
2357   wait_sigint_received = 0;
2358   if (job_control == 0 || (subshell_environment&SUBSHELL_COMSUB))
2359     {
2360       old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
2361       if (old_sigint_handler == SIG_IGN)
2362         set_signal_handler (SIGINT, old_sigint_handler);
2363     }
2364
2365   termination_state = last_command_exit_value;
2366
2367   if (interactive && job_control == 0)
2368     QUIT;
2369
2370   /* If we say wait_for (), then we have a record of this child somewhere.
2371      If it and none of its peers are running, don't call waitchld(). */
2372
2373   job = NO_JOB;
2374   do
2375     {
2376       FIND_CHILD (pid, child);
2377
2378       /* If this child is part of a job, then we are really waiting for the
2379          job to finish.  Otherwise, we are waiting for the child to finish.
2380          We check for JDEAD in case the job state has been set by waitchld
2381          after receipt of a SIGCHLD. */
2382       if (job == NO_JOB)
2383         job = find_job (pid, 0, NULL);
2384
2385       /* waitchld() takes care of setting the state of the job.  If the job
2386          has already exited before this is called, sigchld_handler will have
2387          called waitchld and the state will be set to JDEAD. */
2388
2389       if (PRUNNING(child) || (job != NO_JOB && RUNNING (job)))
2390         {
2391 #if defined (WAITPID_BROKEN)    /* SCOv4 */
2392           sigset_t suspend_set;
2393           sigemptyset (&suspend_set);
2394           sigsuspend (&suspend_set);
2395 #else /* !WAITPID_BROKEN */
2396 #  if defined (MUST_UNBLOCK_CHLD)
2397           struct sigaction act, oact;
2398           sigset_t nullset, chldset;
2399
2400           sigemptyset (&nullset);
2401           sigemptyset (&chldset);
2402           sigprocmask (SIG_SETMASK, &nullset, &chldset);
2403           act.sa_handler = SIG_DFL;
2404           sigemptyset (&act.sa_mask);
2405           sigemptyset (&oact.sa_mask);
2406           act.sa_flags = 0;
2407           sigaction (SIGCHLD, &act, &oact);
2408 #  endif
2409           queue_sigchld = 1;
2410           r = waitchld (pid, 1);
2411 #  if defined (MUST_UNBLOCK_CHLD)
2412           sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
2413           sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
2414 #  endif
2415           queue_sigchld = 0;
2416           if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
2417             {
2418               termination_state = -1;
2419               goto wait_for_return;
2420             }
2421
2422           /* If child is marked as running, but waitpid() returns -1/ECHILD,
2423              there is something wrong.  Somewhere, wait should have returned
2424              that child's pid.  Mark the child as not running and the job,
2425              if it exists, as JDEAD. */
2426           if (r == -1 && errno == ECHILD)
2427             {
2428               child->running = PS_DONE;
2429               WSTATUS (child->status) = 0;      /* XXX -- can't find true status */
2430               js.c_living = 0;          /* no living child processes */
2431               if (job != NO_JOB)
2432                 {
2433                   jobs[job]->state = JDEAD;
2434                   js.c_reaped++;
2435                   js.j_ndead++;
2436                 }
2437             }
2438 #endif /* WAITPID_BROKEN */
2439         }
2440
2441       /* If the shell is interactive, and job control is disabled, see
2442          if the foreground process has died due to SIGINT and jump out
2443          of the wait loop if it has.  waitchld has already restored the
2444          old SIGINT signal handler. */
2445       if (interactive && job_control == 0)
2446         QUIT;
2447     }
2448   while (PRUNNING (child) || (job != NO_JOB && RUNNING (job)));
2449
2450   /* The exit state of the command is either the termination state of the
2451      child, or the termination state of the job.  If a job, the status
2452      of the last child in the pipeline is the significant one.  If the command
2453      or job was terminated by a signal, note that value also. */
2454   termination_state = (job != NO_JOB) ? job_exit_status (job)
2455                                       : process_exit_status (child->status);
2456   last_command_exit_signal = (job != NO_JOB) ? job_exit_signal (job)
2457                                              : process_exit_signal (child->status);
2458
2459   /* XXX */
2460   if ((job != NO_JOB && JOBSTATE (job) == JSTOPPED) || WIFSTOPPED (child->status))
2461     termination_state = 128 + WSTOPSIG (child->status);
2462
2463   if (job == NO_JOB || IS_JOBCONTROL (job))
2464     {
2465       /* XXX - under what circumstances is a job not present in the jobs
2466          table (job == NO_JOB)?
2467                 1.  command substitution
2468
2469          In the case of command substitution, at least, it's probably not
2470          the right thing to give the terminal to the shell's process group,
2471          even though there is code in subst.c:command_substitute to work
2472          around it.
2473
2474          Things that don't:
2475                 $PROMPT_COMMAND execution
2476                 process substitution
2477        */
2478 #if 0
2479 if (job == NO_JOB)
2480   itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp);
2481 #endif
2482       give_terminal_to (shell_pgrp, 0);
2483     }
2484
2485   /* If the command did not exit cleanly, or the job is just
2486      being stopped, then reset the tty state back to what it
2487      was before this command.  Reset the tty state and notify
2488      the user of the job termination only if the shell is
2489      interactive.  Clean up any dead jobs in either case. */
2490   if (job != NO_JOB)
2491     {
2492       if (interactive_shell && subshell_environment == 0)
2493         {
2494           /* This used to use `child->status'.  That's wrong, however, for
2495              pipelines.  `child' is the first process in the pipeline.  It's
2496              likely that the process we want to check for abnormal termination
2497              or stopping is the last process in the pipeline, especially if
2498              it's long-lived and the first process is short-lived.  Since we
2499              know we have a job here, we can check all the processes in this
2500              job's pipeline and see if one of them stopped or terminated due
2501              to a signal.  We might want to change this later to just check
2502              the last process in the pipeline.  If no process exits due to a
2503              signal, S is left as the status of the last job in the pipeline. */
2504           s = job_signal_status (job);
2505
2506           if (WIFSIGNALED (s) || WIFSTOPPED (s))
2507             {
2508               set_tty_state ();
2509
2510               /* If the current job was stopped or killed by a signal, and
2511                  the user has requested it, get a possibly new window size */
2512               if (check_window_size && (job == js.j_current || IS_FOREGROUND (job)))
2513                 get_new_window_size (0, (int *)0, (int *)0);
2514             }
2515           else
2516             get_tty_state ();
2517
2518           /* If job control is enabled, the job was started with job
2519              control, the job was the foreground job, and it was killed
2520              by SIGINT, then print a newline to compensate for the kernel
2521              printing the ^C without a trailing newline. */
2522           if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
2523                 WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
2524             {
2525               /* If SIGINT is not trapped and the shell is in a for, while,
2526                  or until loop, act as if the shell received SIGINT as
2527                  well, so the loop can be broken.  This doesn't call the
2528                  SIGINT signal handler; maybe it should. */
2529               if (signal_is_trapped (SIGINT) == 0 && (loop_level || (shell_compatibility_level > 32 && executing_list)))
2530                 ADDINTERRUPT;
2531               else
2532                 {
2533                   putchar ('\n');
2534                   fflush (stdout);
2535                 }
2536             }
2537         }
2538       else if ((subshell_environment & SUBSHELL_COMSUB) && wait_sigint_received)
2539         {
2540           /* If waiting for a job in a subshell started to do command
2541              substitution, simulate getting and being killed by the SIGINT to
2542              pass the status back to our parent. */
2543           s = job_signal_status (job);
2544         
2545           if (WIFSIGNALED (s) && WTERMSIG (s) == SIGINT && signal_is_trapped (SIGINT) == 0)
2546             {
2547               UNBLOCK_CHILD (oset);
2548               restore_sigint_handler ();
2549               old_sigint_handler = set_signal_handler (SIGINT, SIG_DFL);
2550               if (old_sigint_handler == SIG_IGN)
2551                 restore_sigint_handler ();
2552               else
2553                 kill (getpid (), SIGINT);
2554             }
2555         }
2556
2557       /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
2558          signal handler path */
2559       if (DEADJOB (job) && IS_FOREGROUND (job) /*&& subshell_environment == 0*/)
2560         setjstatus (job);
2561
2562       /* If this job is dead, notify the user of the status.  If the shell
2563          is interactive, this will display a message on the terminal.  If
2564          the shell is not interactive, make sure we turn on the notify bit
2565          so we don't get an unwanted message about the job's termination,
2566          and so delete_job really clears the slot in the jobs table. */
2567       notify_and_cleanup ();
2568     }
2569
2570 wait_for_return:
2571
2572   UNBLOCK_CHILD (oset);
2573
2574   /* Restore the original SIGINT signal handler before we return. */
2575   restore_sigint_handler ();
2576
2577   return (termination_state);
2578 }
2579
2580 /* Wait for the last process in the pipeline for JOB.  Returns whatever
2581    wait_for returns: the last process's termination state or -1 if there
2582    are no unwaited-for child processes or an error occurs. */
2583 int
2584 wait_for_job (job)
2585      int job;
2586 {
2587   pid_t pid;
2588   int r;
2589   sigset_t set, oset;
2590
2591   BLOCK_CHILD(set, oset);
2592   if (JOBSTATE (job) == JSTOPPED)
2593     internal_warning (_("wait_for_job: job %d is stopped"), job+1);
2594
2595   pid = find_last_pid (job, 0);
2596   UNBLOCK_CHILD(oset);
2597   r = wait_for (pid);
2598
2599   /* POSIX.2: we can remove the job from the jobs table if we just waited
2600      for it. */
2601   BLOCK_CHILD (set, oset);
2602   if (job != NO_JOB && jobs[job] && DEADJOB (job))
2603     jobs[job]->flags |= J_NOTIFIED;
2604   UNBLOCK_CHILD (oset);
2605
2606   return r;
2607 }
2608
2609 /* Print info about dead jobs, and then delete them from the list
2610    of known jobs.  This does not actually delete jobs when the
2611    shell is not interactive, because the dead jobs are not marked
2612    as notified. */
2613 void
2614 notify_and_cleanup ()
2615 {
2616   if (jobs_list_frozen)
2617     return;
2618
2619   if (interactive || interactive_shell == 0 || sourcelevel)
2620     notify_of_job_status ();
2621
2622   cleanup_dead_jobs ();
2623 }
2624
2625 /* Make dead jobs disappear from the jobs array without notification.
2626    This is used when the shell is not interactive. */
2627 void
2628 reap_dead_jobs ()
2629 {
2630   mark_dead_jobs_as_notified (0);
2631   cleanup_dead_jobs ();
2632 }
2633
2634 /* Return the next closest (chronologically) job to JOB which is in
2635    STATE.  STATE can be JSTOPPED, JRUNNING.  NO_JOB is returned if
2636    there is no next recent job. */
2637 static int
2638 most_recent_job_in_state (job, state)
2639      int job;
2640      JOB_STATE state;
2641 {
2642   register int i, result;
2643   sigset_t set, oset;
2644
2645   BLOCK_CHILD (set, oset);
2646
2647   for (result = NO_JOB, i = job - 1; i >= 0; i--)
2648     {
2649       if (jobs[i] && (JOBSTATE (i) == state))
2650         {
2651           result = i;
2652           break;
2653         }
2654     }
2655
2656   UNBLOCK_CHILD (oset);
2657
2658   return (result);
2659 }
2660
2661 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
2662    found. */
2663 static int
2664 job_last_stopped (job)
2665      int job;
2666 {
2667   return (most_recent_job_in_state (job, JSTOPPED));
2668 }
2669
2670 /* Return the newest *running* job older than JOB, or NO_JOB if not
2671    found. */
2672 static int
2673 job_last_running (job)
2674      int job;
2675 {
2676   return (most_recent_job_in_state (job, JRUNNING));
2677 }
2678
2679 /* Make JOB be the current job, and make previous be useful.  Must be
2680    called with SIGCHLD blocked. */
2681 static void
2682 set_current_job (job)
2683      int job;
2684 {
2685   int candidate;
2686
2687   if (js.j_current != job)
2688     {
2689       js.j_previous = js.j_current;
2690       js.j_current = job;
2691     }
2692
2693   /* First choice for previous job is the old current job. */
2694   if (js.j_previous != js.j_current &&
2695       js.j_previous != NO_JOB &&
2696       jobs[js.j_previous] &&
2697       STOPPED (js.j_previous))
2698     return;
2699
2700   /* Second choice:  Newest stopped job that is older than
2701      the current job. */
2702   candidate = NO_JOB;
2703   if (STOPPED (js.j_current))
2704     {
2705       candidate = job_last_stopped (js.j_current);
2706
2707       if (candidate != NO_JOB)
2708         {
2709           js.j_previous = candidate;
2710           return;
2711         }
2712     }
2713
2714   /* If we get here, there is either only one stopped job, in which case it is
2715      the current job and the previous job should be set to the newest running
2716      job, or there are only running jobs and the previous job should be set to
2717      the newest running job older than the current job.  We decide on which
2718      alternative to use based on whether or not JOBSTATE(js.j_current) is
2719      JSTOPPED. */
2720
2721   candidate = RUNNING (js.j_current) ? job_last_running (js.j_current)
2722                                     : job_last_running (js.j_jobslots);
2723
2724   if (candidate != NO_JOB)
2725     {
2726       js.j_previous = candidate;
2727       return;
2728     }
2729
2730   /* There is only a single job, and it is both `+' and `-'. */
2731   js.j_previous = js.j_current;
2732 }
2733
2734 /* Make current_job be something useful, if it isn't already. */
2735
2736 /* Here's the deal:  The newest non-running job should be `+', and the
2737    next-newest non-running job should be `-'.  If there is only a single
2738    stopped job, the js.j_previous is the newest non-running job.  If there
2739    are only running jobs, the newest running job is `+' and the
2740    next-newest running job is `-'.  Must be called with SIGCHLD blocked. */
2741
2742 static void
2743 reset_current ()
2744 {
2745   int candidate;
2746
2747   if (js.j_jobslots && js.j_current != NO_JOB && jobs[js.j_current] && STOPPED (js.j_current))
2748     candidate = js.j_current;
2749   else
2750     {
2751       candidate = NO_JOB;
2752
2753       /* First choice: the previous job. */
2754       if (js.j_previous != NO_JOB && jobs[js.j_previous] && STOPPED (js.j_previous))
2755         candidate = js.j_previous;
2756
2757       /* Second choice: the most recently stopped job. */
2758       if (candidate == NO_JOB)
2759         candidate = job_last_stopped (js.j_jobslots);
2760
2761       /* Third choice: the newest running job. */
2762       if (candidate == NO_JOB)
2763         candidate = job_last_running (js.j_jobslots);
2764     }
2765
2766   /* If we found a job to use, then use it.  Otherwise, there
2767      are no jobs period. */
2768   if (candidate != NO_JOB)
2769     set_current_job (candidate);
2770   else
2771     js.j_current = js.j_previous = NO_JOB;
2772 }
2773
2774 /* Set up the job structures so we know the job and its processes are
2775    all running. */
2776 static void
2777 set_job_running (job)
2778      int job;
2779 {
2780   register PROCESS *p;
2781
2782   /* Each member of the pipeline is now running. */
2783   p = jobs[job]->pipe;
2784
2785   do
2786     {
2787       if (WIFSTOPPED (p->status))
2788         p->running = PS_RUNNING;        /* XXX - could be PS_STOPPED */
2789       p = p->next;
2790     }
2791   while (p != jobs[job]->pipe);
2792
2793   /* This means that the job is running. */
2794   JOBSTATE (job) = JRUNNING;
2795 }
2796
2797 /* Start a job.  FOREGROUND if non-zero says to do that.  Otherwise,
2798    start the job in the background.  JOB is a zero-based index into
2799    JOBS.  Returns -1 if it is unable to start a job, and the return
2800    status of the job otherwise. */
2801 int
2802 start_job (job, foreground)
2803      int job, foreground;
2804 {
2805   register PROCESS *p;
2806   int already_running;
2807   sigset_t set, oset;
2808   char *wd, *s;
2809   static TTYSTRUCT save_stty;
2810
2811   BLOCK_CHILD (set, oset);
2812
2813   if (DEADJOB (job))
2814     {
2815       internal_error (_("%s: job has terminated"), this_command_name);
2816       UNBLOCK_CHILD (oset);
2817       return (-1);
2818     }
2819
2820   already_running = RUNNING (job);
2821
2822   if (foreground == 0 && already_running)
2823     {
2824       internal_error (_("%s: job %d already in background"), this_command_name, job + 1);
2825       UNBLOCK_CHILD (oset);
2826       return (0);               /* XPG6/SUSv3 says this is not an error */
2827     }
2828
2829   wd = current_working_directory ();
2830
2831   /* You don't know about the state of this job.  Do you? */
2832   jobs[job]->flags &= ~J_NOTIFIED;
2833
2834   if (foreground)
2835     {
2836       set_current_job (job);
2837       jobs[job]->flags |= J_FOREGROUND;
2838     }
2839
2840   /* Tell the outside world what we're doing. */
2841   p = jobs[job]->pipe;
2842
2843   if (foreground == 0)
2844     {
2845       /* POSIX.2 says `bg' doesn't give any indication about current or
2846          previous job. */
2847       if (posixly_correct == 0)
2848         s = (job == js.j_current) ? "+ ": ((job == js.j_previous) ? "- " : " ");       
2849       else
2850         s = " ";
2851       printf ("[%d]%s", job + 1, s);
2852     }
2853
2854   do
2855     {
2856       printf ("%s%s",
2857                p->command ? p->command : "",
2858                p->next != jobs[job]->pipe? " | " : "");
2859       p = p->next;
2860     }
2861   while (p != jobs[job]->pipe);
2862
2863   if (foreground == 0)
2864     printf (" &");
2865
2866   if (strcmp (wd, jobs[job]->wd) != 0)
2867     printf ("   (wd: %s)", polite_directory_format (jobs[job]->wd));
2868
2869   printf ("\n");
2870
2871   /* Run the job. */
2872   if (already_running == 0)
2873     set_job_running (job);
2874
2875   /* Save the tty settings before we start the job in the foreground. */
2876   if (foreground)
2877     {
2878       get_tty_state ();
2879       save_stty = shell_tty_info;
2880       /* Give the terminal to this job. */
2881       if (IS_JOBCONTROL (job))
2882         give_terminal_to (jobs[job]->pgrp, 0);
2883     }
2884   else
2885     jobs[job]->flags &= ~J_FOREGROUND;
2886
2887   /* If the job is already running, then don't bother jump-starting it. */
2888   if (already_running == 0)
2889     {
2890       jobs[job]->flags |= J_NOTIFIED;
2891       killpg (jobs[job]->pgrp, SIGCONT);
2892     }
2893
2894   if (foreground)
2895     {
2896       pid_t pid;
2897       int st;
2898
2899       pid = find_last_pid (job, 0);
2900       UNBLOCK_CHILD (oset);
2901       st = wait_for (pid);
2902       shell_tty_info = save_stty;
2903       set_tty_state ();
2904       return (st);
2905     }
2906   else
2907     {
2908       reset_current ();
2909       UNBLOCK_CHILD (oset);
2910       return (0);
2911     }
2912 }
2913
2914 /* Give PID SIGNAL.  This determines what job the pid belongs to (if any).
2915    If PID does belong to a job, and the job is stopped, then CONTinue the
2916    job after giving it SIGNAL.  Returns -1 on failure.  If GROUP is non-null,
2917    then kill the process group associated with PID. */
2918 int
2919 kill_pid (pid, sig, group)
2920      pid_t pid;
2921      int sig, group;
2922 {
2923   register PROCESS *p;
2924   int job, result, negative;
2925   sigset_t set, oset;
2926
2927   if (pid < -1)
2928     {
2929       pid = -pid;
2930       group = negative = 1;
2931     }
2932   else
2933     negative = 0;
2934
2935   result = EXECUTION_SUCCESS;
2936   if (group)
2937     {
2938       BLOCK_CHILD (set, oset);
2939       p = find_pipeline (pid, 0, &job);
2940
2941       if (job != NO_JOB)
2942         {
2943           jobs[job]->flags &= ~J_NOTIFIED;
2944
2945           /* Kill process in backquotes or one started without job control? */
2946
2947           /* If we're passed a pid < -1, just call killpg and see what happens  */
2948           if (negative && jobs[job]->pgrp == shell_pgrp)
2949             result = killpg (pid, sig);
2950           /* If we're killing using job control notification, for example,
2951              without job control active, we have to do things ourselves. */
2952           else if (jobs[job]->pgrp == shell_pgrp)
2953             {
2954               p = jobs[job]->pipe;
2955               do
2956                 {
2957                   if (PALIVE (p) == 0)
2958                     continue;           /* avoid pid recycling problem */
2959                   kill (p->pid, sig);
2960                   if (PEXITED (p) && (sig == SIGTERM || sig == SIGHUP))
2961                     kill (p->pid, SIGCONT);
2962                   p = p->next;
2963                 }
2964               while  (p != jobs[job]->pipe);
2965             }
2966           else
2967             {
2968               result = killpg (jobs[job]->pgrp, sig);
2969               if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2970                 killpg (jobs[job]->pgrp, SIGCONT);
2971               /* If we're continuing a stopped job via kill rather than bg or
2972                  fg, emulate the `bg' behavior. */
2973               if (p && STOPPED (job) && (sig == SIGCONT))
2974                 {
2975                   set_job_running (job);
2976                   jobs[job]->flags &= ~J_FOREGROUND;
2977                   jobs[job]->flags |= J_NOTIFIED;
2978                 }
2979             }
2980         }
2981       else
2982         result = killpg (pid, sig);
2983
2984       UNBLOCK_CHILD (oset);
2985     }
2986   else
2987     result = kill (pid, sig);
2988
2989   return (result);
2990 }
2991
2992 /* sigchld_handler () flushes at least one of the children that we are
2993    waiting for.  It gets run when we have gotten a SIGCHLD signal. */
2994 static sighandler
2995 sigchld_handler (sig)
2996      int sig;
2997 {
2998   int n, oerrno;
2999
3000   oerrno = errno;
3001   REINSTALL_SIGCHLD_HANDLER;
3002   sigchld++;
3003   n = 0;
3004   if (queue_sigchld == 0)
3005     n = waitchld (-1, 0);
3006   errno = oerrno;
3007   SIGRETURN (n);
3008 }
3009
3010 /* waitchld() reaps dead or stopped children.  It's called by wait_for and
3011    sigchld_handler, and runs until there aren't any children terminating any
3012    more.
3013    If BLOCK is 1, this is to be a blocking wait for a single child, although
3014    an arriving SIGCHLD could cause the wait to be non-blocking.  It returns
3015    the number of children reaped, or -1 if there are no unwaited-for child
3016    processes. */
3017 static int
3018 waitchld (wpid, block)
3019      pid_t wpid;
3020      int block;
3021 {
3022   WAIT status;
3023   PROCESS *child;
3024   pid_t pid;
3025   int call_set_current, last_stopped_job, job, children_exited, waitpid_flags;
3026   static int wcontinued = WCONTINUED;   /* run-time fix for glibc problem */
3027
3028   call_set_current = children_exited = 0;
3029   last_stopped_job = NO_JOB;
3030
3031   do
3032     {
3033       /* We don't want to be notified about jobs stopping if job control
3034          is not active.  XXX - was interactive_shell instead of job_control */
3035       waitpid_flags = (job_control && subshell_environment == 0)
3036                         ? (WUNTRACED|wcontinued)
3037                         : 0;
3038       if (sigchld || block == 0)
3039         waitpid_flags |= WNOHANG;
3040       CHECK_TERMSIG;
3041
3042       pid = WAITPID (-1, &status, waitpid_flags);
3043
3044       /* WCONTINUED may be rejected by waitpid as invalid even when defined */
3045       if (wcontinued && pid < 0 && errno == EINVAL)
3046         {
3047           wcontinued = 0;
3048           continue;     /* jump back to the test and retry without WCONTINUED */
3049         }
3050
3051       /* The check for WNOHANG is to make sure we decrement sigchld only
3052          if it was non-zero before we called waitpid. */
3053       if (sigchld > 0 && (waitpid_flags & WNOHANG))
3054         sigchld--;
3055   
3056       /* If waitpid returns -1 with errno == ECHILD, there are no more
3057          unwaited-for child processes of this shell. */
3058       if (pid < 0 && errno == ECHILD)
3059         {
3060           if (children_exited == 0)
3061             return -1;
3062           else
3063             break;
3064         }
3065
3066       /* If waitpid returns 0, there are running children.  If it returns -1,
3067          the only other error POSIX says it can return is EINTR. */
3068       CHECK_TERMSIG;
3069       if (pid <= 0)
3070         continue;       /* jumps right to the test */
3071
3072       /* children_exited is used to run traps on SIGCHLD.  We don't want to
3073          run the trap if a process is just being continued. */
3074       if (WIFCONTINUED(status) == 0)
3075         {
3076           children_exited++;
3077           js.c_living--;
3078         }
3079
3080       /* Locate our PROCESS for this pid. */
3081       child = find_process (pid, 1, &job);      /* want living procs only */
3082
3083 #if defined (COPROCESS_SUPPORT)
3084       coproc_pidchk (pid);
3085 #endif
3086
3087       /* It is not an error to have a child terminate that we did
3088          not have a record of.  This child could have been part of
3089          a pipeline in backquote substitution.  Even so, I'm not
3090          sure child is ever non-zero. */
3091       if (child == 0)
3092         {
3093           if (WIFEXITED (status) || WIFSIGNALED (status))
3094             js.c_reaped++;
3095           continue;
3096         }
3097
3098       /* Remember status, and whether or not the process is running. */
3099       child->status = status;
3100       child->running = WIFCONTINUED(status) ? PS_RUNNING : PS_DONE;
3101
3102       if (PEXITED (child))
3103         {
3104           js.c_totreaped++;
3105           if (job != NO_JOB)
3106             js.c_reaped++;
3107         }
3108         
3109       if (job == NO_JOB)
3110         continue;
3111
3112       call_set_current += set_job_status_and_cleanup (job);
3113
3114       if (STOPPED (job))
3115         last_stopped_job = job;
3116       else if (DEADJOB (job) && last_stopped_job == job)
3117         last_stopped_job = NO_JOB;
3118     }
3119   while ((sigchld || block == 0) && pid > (pid_t)0);
3120
3121   /* If a job was running and became stopped, then set the current
3122      job.  Otherwise, don't change a thing. */
3123   if (call_set_current)
3124     {
3125       if (last_stopped_job != NO_JOB)
3126         set_current_job (last_stopped_job);
3127       else
3128         reset_current ();
3129     }
3130
3131   /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3132   if (job_control && signal_is_trapped (SIGCHLD) && children_exited &&
3133       trap_list[SIGCHLD] != (char *)IGNORE_SIG)
3134     {
3135       if (this_shell_builtin && this_shell_builtin == wait_builtin)
3136         {
3137           interrupt_immediately = 0;
3138           trap_handler (SIGCHLD);       /* set pending_traps[SIGCHLD] */
3139           wait_signal_received = SIGCHLD;
3140           longjmp (wait_intr_buf, 1);
3141         }
3142
3143       run_sigchld_trap (children_exited);
3144     }
3145
3146   /* We have successfully recorded the useful information about this process
3147      that has just changed state.  If we notify asynchronously, and the job
3148      that this process belongs to is no longer running, then notify the user
3149      of that fact now. */
3150   if (asynchronous_notification && interactive)
3151     notify_of_job_status ();
3152
3153   return (children_exited);
3154 }
3155
3156 /* Set the status of JOB and perform any necessary cleanup if the job is
3157    marked as JDEAD.
3158
3159    Currently, the cleanup activity is restricted to handling any SIGINT
3160    received while waiting for a foreground job to finish. */
3161 static int
3162 set_job_status_and_cleanup (job)
3163      int job;
3164 {
3165   PROCESS *child;
3166   int tstatus, job_state, any_stopped, any_tstped, call_set_current;
3167   SigHandler *temp_handler;
3168
3169   child = jobs[job]->pipe;
3170   jobs[job]->flags &= ~J_NOTIFIED;
3171
3172   call_set_current = 0;
3173
3174   /*
3175    * COMPUTE JOB STATUS
3176    */
3177
3178   /* If all children are not running, but any of them is  stopped, then
3179      the job is stopped, not dead. */
3180   job_state = any_stopped = any_tstped = 0;
3181   do
3182     {
3183       job_state |= PRUNNING (child);
3184 #if 0
3185       if (PEXITED (child) && (WIFSTOPPED (child->status)))
3186 #else
3187       /* Only checking for WIFSTOPPED now, not for PS_DONE */
3188       if (PSTOPPED (child))
3189 #endif
3190         {
3191           any_stopped = 1;
3192           any_tstped |= interactive && job_control &&
3193                             (WSTOPSIG (child->status) == SIGTSTP);
3194         }
3195       child = child->next;
3196     }
3197   while (child != jobs[job]->pipe);
3198
3199   /* If job_state != 0, the job is still running, so don't bother with
3200      setting the process exit status and job state unless we're
3201      transitioning from stopped to running. */
3202   if (job_state != 0 && JOBSTATE(job) != JSTOPPED)
3203     return 0;
3204
3205   /*
3206    * SET JOB STATUS
3207    */
3208
3209   /* The job is either stopped or dead.  Set the state of the job accordingly. */
3210   if (any_stopped)
3211     {
3212       jobs[job]->state = JSTOPPED;
3213       jobs[job]->flags &= ~J_FOREGROUND;
3214       call_set_current++;
3215       /* Suspending a job with SIGTSTP breaks all active loops. */
3216       if (any_tstped && loop_level)
3217         breaking = loop_level;
3218     }
3219   else if (job_state != 0)      /* was stopped, now running */
3220     {
3221       jobs[job]->state = JRUNNING;
3222       call_set_current++;
3223     }
3224   else
3225     {
3226       jobs[job]->state = JDEAD;
3227       js.j_ndead++;
3228
3229 #if 0
3230       if (IS_FOREGROUND (job))
3231         setjstatus (job);
3232 #endif
3233
3234       /* If this job has a cleanup function associated with it, call it
3235          with `cleanarg' as the single argument, then set the function
3236          pointer to NULL so it is not inadvertently called twice.  The
3237          cleanup function is responsible for deallocating cleanarg. */
3238       if (jobs[job]->j_cleanup)
3239         {
3240           (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
3241           jobs[job]->j_cleanup = (sh_vptrfunc_t *)NULL;
3242         }
3243     }
3244
3245   /*
3246    * CLEANUP
3247    *
3248    * Currently, we just do special things if we got a SIGINT while waiting
3249    * for a foreground job to complete
3250    */
3251
3252   if (JOBSTATE (job) == JDEAD)
3253     {
3254       /* If we're running a shell script and we get a SIGINT with a
3255          SIGINT trap handler, but the foreground job handles it and
3256          does not exit due to SIGINT, run the trap handler but do not
3257          otherwise act as if we got the interrupt. */
3258       if (wait_sigint_received && interactive_shell == 0 &&
3259           WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
3260           signal_is_trapped (SIGINT))
3261         {
3262           int old_frozen;
3263           wait_sigint_received = 0;
3264           last_command_exit_value = process_exit_status (child->status);
3265
3266           old_frozen = jobs_list_frozen;
3267           jobs_list_frozen = 1;
3268           tstatus = maybe_call_trap_handler (SIGINT);
3269           jobs_list_frozen = old_frozen;
3270         }
3271
3272       /* If the foreground job is killed by SIGINT when job control is not
3273          active, we need to perform some special handling.
3274
3275          The check of wait_sigint_received is a way to determine if the
3276          SIGINT came from the keyboard (in which case the shell has already
3277          seen it, and wait_sigint_received is non-zero, because keyboard
3278          signals are sent to process groups) or via kill(2) to the foreground
3279          process by another process (or itself).  If the shell did receive the
3280          SIGINT, it needs to perform normal SIGINT processing. */
3281       else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
3282               IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
3283         {
3284           int old_frozen;
3285
3286           wait_sigint_received = 0;
3287
3288           /* If SIGINT is trapped, set the exit status so that the trap
3289              handler can see it. */
3290           if (signal_is_trapped (SIGINT))
3291             last_command_exit_value = process_exit_status (child->status);
3292
3293           /* If the signal is trapped, let the trap handler get it no matter
3294              what and simply return if the trap handler returns.
3295             maybe_call_trap_handler() may cause dead jobs to be removed from
3296             the job table because of a call to execute_command.  We work
3297             around this by setting JOBS_LIST_FROZEN. */
3298           old_frozen = jobs_list_frozen;
3299           jobs_list_frozen = 1;
3300           tstatus = maybe_call_trap_handler (SIGINT);
3301           jobs_list_frozen = old_frozen;
3302           if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
3303             {
3304               /* wait_sigint_handler () has already seen SIGINT and
3305                  allowed the wait builtin to jump out.  We need to
3306                  call the original SIGINT handler, if necessary.  If
3307                  the original handler is SIG_DFL, we need to resend
3308                  the signal to ourselves. */
3309
3310               temp_handler = old_sigint_handler;
3311
3312               /* Bogus.  If we've reset the signal handler as the result
3313                  of a trap caught on SIGINT, then old_sigint_handler
3314                  will point to trap_handler, which now knows nothing about
3315                  SIGINT (if we reset the sighandler to the default).
3316                  In this case, we have to fix things up.  What a crock. */
3317               if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
3318                   temp_handler = trap_to_sighandler (SIGINT);
3319                 restore_sigint_handler ();
3320               if (temp_handler == SIG_DFL)
3321                 termsig_handler (SIGINT);
3322               else if (temp_handler != SIG_IGN)
3323                 (*temp_handler) (SIGINT);
3324             }
3325         }
3326     }
3327
3328   return call_set_current;
3329 }
3330
3331 /* Build the array of values for the $PIPESTATUS variable from the set of
3332    exit statuses of all processes in the job J. */
3333 static void
3334 setjstatus (j)
3335      int j;
3336 {
3337 #if defined (ARRAY_VARS)
3338   register int i;
3339   register PROCESS *p;
3340
3341   for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
3342     ;
3343   i++;
3344   if (statsize < i)
3345     {
3346       pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
3347       statsize = i;
3348     }
3349   i = 0;
3350   p = jobs[j]->pipe;
3351   do
3352     {
3353       pstatuses[i++] = process_exit_status (p->status);
3354       p = p->next;
3355     }
3356   while (p != jobs[j]->pipe);
3357
3358   pstatuses[i] = -1;    /* sentinel */
3359   set_pipestatus_array (pstatuses, i);
3360 #endif
3361 }
3362
3363 void
3364 run_sigchld_trap (nchild)
3365      int nchild;
3366 {
3367   char *trap_command;
3368   int i;
3369
3370   /* Turn off the trap list during the call to parse_and_execute ()
3371      to avoid potentially infinite recursive calls.  Preserve the
3372      values of last_command_exit_value, last_made_pid, and the_pipeline
3373      around the execution of the trap commands. */
3374   trap_command = savestring (trap_list[SIGCHLD]);
3375
3376   begin_unwind_frame ("SIGCHLD trap");
3377   unwind_protect_int (last_command_exit_value);
3378   unwind_protect_int (last_command_exit_signal);
3379   unwind_protect_var (last_made_pid);
3380   unwind_protect_int (interrupt_immediately);
3381   unwind_protect_int (jobs_list_frozen);
3382   unwind_protect_pointer (the_pipeline);
3383   unwind_protect_pointer (subst_assign_varlist);
3384
3385   /* We have to add the commands this way because they will be run
3386      in reverse order of adding.  We don't want maybe_set_sigchld_trap ()
3387      to reference freed memory. */
3388   add_unwind_protect (xfree, trap_command);
3389   add_unwind_protect (maybe_set_sigchld_trap, trap_command);
3390
3391   subst_assign_varlist = (WORD_LIST *)NULL;
3392   the_pipeline = (PROCESS *)NULL;
3393
3394   set_impossible_sigchld_trap ();
3395   jobs_list_frozen = 1;
3396   for (i = 0; i < nchild; i++)
3397     {
3398       interrupt_immediately = 1;
3399       parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST|SEVAL_RESETLINE);
3400     }
3401
3402   run_unwind_frame ("SIGCHLD trap");
3403 }
3404
3405 /* Function to call when you want to notify people of changes
3406    in job status.  This prints out all jobs which are pending
3407    notification to stderr, and marks those printed as already
3408    notified, thus making them candidates for cleanup. */
3409 static void
3410 notify_of_job_status ()
3411 {
3412   register int job, termsig;
3413   char *dir;
3414   sigset_t set, oset;
3415   WAIT s;
3416
3417   if (jobs == 0 || js.j_jobslots == 0)
3418     return;
3419
3420   if (old_ttou != 0)
3421     {
3422       sigemptyset (&set);
3423       sigaddset (&set, SIGCHLD);
3424       sigaddset (&set, SIGTTOU);
3425       sigemptyset (&oset);
3426       sigprocmask (SIG_BLOCK, &set, &oset);
3427     }
3428   else
3429     queue_sigchld++;
3430
3431   /* XXX could use js.j_firstj here */
3432   for (job = 0, dir = (char *)NULL; job < js.j_jobslots; job++)
3433     {
3434       if (jobs[job] && IS_NOTIFIED (job) == 0)
3435         {
3436           s = raw_job_exit_status (job);
3437           termsig = WTERMSIG (s);
3438
3439           /* POSIX.2 says we have to hang onto the statuses of at most the
3440              last CHILD_MAX background processes if the shell is running a
3441              script.  If the shell is running a script, either from a file
3442              or standard input, don't print anything unless the job was
3443              killed by a signal. */
3444           if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
3445                 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
3446             continue;
3447           
3448 #if 0
3449           /* If job control is disabled, don't print the status messages.
3450              Mark dead jobs as notified so that they get cleaned up.  If
3451              startup_state == 2, we were started to run `-c command', so
3452              don't print anything. */
3453           if ((job_control == 0 && interactive_shell) || startup_state == 2)
3454 #else
3455           /* If job control is disabled, don't print the status messages.
3456              Mark dead jobs as notified so that they get cleaned up.  If
3457              startup_state == 2 and subshell_environment has the
3458              SUBSHELL_COMSUB bit turned on, we were started to run a command
3459              substitution, so don't print anything. */
3460           if ((job_control == 0 && interactive_shell) ||
3461               (startup_state == 2 && (subshell_environment & SUBSHELL_COMSUB)))
3462 #endif
3463             {
3464               /* POSIX.2 compatibility:  if the shell is not interactive,
3465                  hang onto the job corresponding to the last asynchronous
3466                  pid until the user has been notified of its status or does
3467                  a `wait'. */
3468               if (DEADJOB (job) && (interactive_shell || (find_last_pid (job, 0) != last_asynchronous_pid)))
3469                 jobs[job]->flags |= J_NOTIFIED;
3470               continue;
3471             }
3472
3473           /* Print info on jobs that are running in the background,
3474              and on foreground jobs that were killed by anything
3475              except SIGINT (and possibly SIGPIPE). */
3476           switch (JOBSTATE (job))
3477             {
3478             case JDEAD:
3479               if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
3480                   termsig != SIGINT &&
3481 #if defined (DONT_REPORT_SIGPIPE)
3482                   termsig != SIGPIPE &&
3483 #endif
3484                   signal_is_trapped (termsig) == 0)
3485                 {
3486                   /* Don't print `0' for a line number. */
3487                   fprintf (stderr, _("%s: line %d: "), get_name_for_error (), (line_number == 0) ? 1 : line_number);
3488                   pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
3489                 }
3490               else if (IS_FOREGROUND (job))
3491                 {
3492 #if !defined (DONT_REPORT_SIGPIPE)
3493                   if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
3494 #else
3495                   if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
3496 #endif
3497                     {
3498                       fprintf (stderr, "%s", j_strsignal (termsig));
3499
3500                       if (WIFCORED (s))
3501                         fprintf (stderr, _(" (core dumped)"));
3502
3503                       fprintf (stderr, "\n");
3504                     }
3505                 }
3506               else if (job_control)     /* XXX job control test added */
3507                 {
3508                   if (dir == 0)
3509                     dir = current_working_directory ();
3510                   pretty_print_job (job, JLIST_STANDARD, stderr);
3511                   if (dir && strcmp (dir, jobs[job]->wd) != 0)
3512                     fprintf (stderr,
3513                              _("(wd now: %s)\n"), polite_directory_format (dir));
3514                 }
3515
3516               jobs[job]->flags |= J_NOTIFIED;
3517               break;
3518
3519             case JSTOPPED:
3520               fprintf (stderr, "\n");
3521               if (dir == 0)
3522                 dir = current_working_directory ();
3523               pretty_print_job (job, JLIST_STANDARD, stderr);
3524               if (dir && (strcmp (dir, jobs[job]->wd) != 0))
3525                 fprintf (stderr,
3526                          _("(wd now: %s)\n"), polite_directory_format (dir));
3527               jobs[job]->flags |= J_NOTIFIED;
3528               break;
3529
3530             case JRUNNING:
3531             case JMIXED:
3532               break;
3533
3534             default:
3535               programming_error ("notify_of_job_status");
3536             }
3537         }
3538     }
3539   if (old_ttou != 0)
3540     sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
3541   else
3542     queue_sigchld--;
3543 }
3544
3545 /* Initialize the job control mechanism, and set up the tty stuff. */
3546 int
3547 initialize_job_control (force)
3548      int force;
3549 {
3550   pid_t t;
3551   int t_errno;
3552
3553   t_errno = -1;
3554   shell_pgrp = getpgid (0);
3555
3556   if (shell_pgrp == -1)
3557     {
3558       sys_error (_("initialize_job_control: getpgrp failed"));
3559       exit (1);
3560     }
3561
3562   /* We can only have job control if we are interactive. */
3563   if (interactive == 0)
3564     {
3565       job_control = 0;
3566       original_pgrp = NO_PID;
3567       shell_tty = fileno (stderr);
3568     }
3569   else
3570     {
3571       shell_tty = -1;
3572
3573       /* If forced_interactive is set, we skip the normal check that stderr
3574          is attached to a tty, so we need to check here.  If it's not, we
3575          need to see whether we have a controlling tty by opening /dev/tty,
3576          since trying to use job control tty pgrp manipulations on a non-tty
3577          is going to fail. */
3578       if (forced_interactive && isatty (fileno (stderr)) == 0)
3579         shell_tty = open ("/dev/tty", O_RDWR|O_NONBLOCK);
3580
3581       /* Get our controlling terminal.  If job_control is set, or
3582          interactive is set, then this is an interactive shell no
3583          matter where fd 2 is directed. */
3584       if (shell_tty == -1)
3585         shell_tty = dup (fileno (stderr));      /* fd 2 */
3586
3587       shell_tty = move_to_high_fd (shell_tty, 1, -1);
3588
3589       /* Compensate for a bug in systems that compiled the BSD
3590          rlogind with DEBUG defined, like NeXT and Alliant. */
3591       if (shell_pgrp == 0)
3592         {
3593           shell_pgrp = getpid ();
3594           setpgid (0, shell_pgrp);
3595           tcsetpgrp (shell_tty, shell_pgrp);
3596         }
3597
3598       while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
3599         {
3600           if (shell_pgrp != terminal_pgrp)
3601             {
3602               SigHandler *ottin;
3603
3604               ottin = set_signal_handler(SIGTTIN, SIG_DFL);
3605               kill (0, SIGTTIN);
3606               set_signal_handler (SIGTTIN, ottin);
3607               continue;
3608             }
3609           break;
3610         }
3611
3612       if (terminal_pgrp == -1)
3613         t_errno = errno;
3614
3615       /* Make sure that we are using the new line discipline. */
3616       if (set_new_line_discipline (shell_tty) < 0)
3617         {
3618           sys_error (_("initialize_job_control: line discipline"));
3619           job_control = 0;
3620         }
3621       else
3622         {
3623           original_pgrp = shell_pgrp;
3624           shell_pgrp = getpid ();
3625
3626           if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
3627             {
3628               sys_error (_("initialize_job_control: setpgid"));
3629               shell_pgrp = original_pgrp;
3630             }
3631
3632           job_control = 1;
3633
3634           /* If (and only if) we just set our process group to our pid,
3635              thereby becoming a process group leader, and the terminal
3636              is not in the same process group as our (new) process group,
3637              then set the terminal's process group to our (new) process
3638              group.  If that fails, set our process group back to what it
3639              was originally (so we can still read from the terminal) and
3640              turn off job control.  */
3641           if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
3642             {
3643               if (give_terminal_to (shell_pgrp, 0) < 0)
3644                 {
3645                   t_errno = errno;
3646                   setpgid (0, original_pgrp);
3647                   shell_pgrp = original_pgrp;
3648                   job_control = 0;
3649                 }
3650             }
3651
3652           if (job_control && ((t = tcgetpgrp (shell_tty)) == -1 || t != shell_pgrp))
3653             {
3654               if (t_errno != -1)
3655                 errno = t_errno;
3656               sys_error (_("cannot set terminal process group (%d)"), t);
3657               job_control = 0;
3658             }
3659         }
3660       if (job_control == 0)
3661         internal_error (_("no job control in this shell"));
3662     }
3663
3664   if (shell_tty != fileno (stderr))
3665     SET_CLOSE_ON_EXEC (shell_tty);
3666
3667   set_signal_handler (SIGCHLD, sigchld_handler);
3668
3669   change_flag ('m', job_control ? '-' : '+');
3670
3671   if (interactive)
3672     get_tty_state ();
3673
3674   if (js.c_childmax < 0)
3675     js.c_childmax = getmaxchild ();
3676   if (js.c_childmax < 0)
3677     js.c_childmax = DEFAULT_CHILD_MAX;
3678
3679   return job_control;
3680 }
3681
3682 #ifdef DEBUG
3683 void
3684 debug_print_pgrps ()
3685 {
3686   itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
3687          (long)original_pgrp, (long)shell_pgrp, (long)terminal_pgrp);
3688   itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
3689          shell_tty, (long)tcgetpgrp (shell_tty), (long)getpgid(0));
3690 }
3691 #endif
3692
3693 /* Set the line discipline to the best this system has to offer.
3694    Return -1 if this is not possible. */
3695 static int
3696 set_new_line_discipline (tty)
3697      int tty;
3698 {
3699 #if defined (NEW_TTY_DRIVER)
3700   int ldisc;
3701
3702   if (ioctl (tty, TIOCGETD, &ldisc) < 0)
3703     return (-1);
3704
3705   if (ldisc != NTTYDISC)
3706     {
3707       ldisc = NTTYDISC;
3708
3709       if (ioctl (tty, TIOCSETD, &ldisc) < 0)
3710         return (-1);
3711     }
3712   return (0);
3713 #endif /* NEW_TTY_DRIVER */
3714
3715 #if defined (TERMIO_TTY_DRIVER)
3716 #  if defined (TERMIO_LDISC) && (NTTYDISC)
3717   if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
3718     return (-1);
3719
3720   if (shell_tty_info.c_line != NTTYDISC)
3721     {
3722       shell_tty_info.c_line = NTTYDISC;
3723       if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
3724         return (-1);
3725     }
3726 #  endif /* TERMIO_LDISC && NTTYDISC */
3727   return (0);
3728 #endif /* TERMIO_TTY_DRIVER */
3729
3730 #if defined (TERMIOS_TTY_DRIVER)
3731 #  if defined (TERMIOS_LDISC) && defined (NTTYDISC)
3732   if (tcgetattr (tty, &shell_tty_info) < 0)
3733     return (-1);
3734
3735   if (shell_tty_info.c_line != NTTYDISC)
3736     {
3737       shell_tty_info.c_line = NTTYDISC;
3738       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
3739         return (-1);
3740     }
3741 #  endif /* TERMIOS_LDISC && NTTYDISC */
3742   return (0);
3743 #endif /* TERMIOS_TTY_DRIVER */
3744
3745 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
3746   return (-1);
3747 #endif
3748 }
3749
3750 /* Setup this shell to handle C-C, etc. */
3751 void
3752 initialize_job_signals ()
3753 {
3754   if (interactive)
3755     {
3756       set_signal_handler (SIGINT, sigint_sighandler);
3757       set_signal_handler (SIGTSTP, SIG_IGN);
3758       set_signal_handler (SIGTTOU, SIG_IGN);
3759       set_signal_handler (SIGTTIN, SIG_IGN);
3760     }
3761   else if (job_control)
3762     {
3763       old_tstp = set_signal_handler (SIGTSTP, sigstop_sighandler);
3764       old_ttin = set_signal_handler (SIGTTIN, sigstop_sighandler);
3765       old_ttou = set_signal_handler (SIGTTOU, sigstop_sighandler);
3766     }
3767   /* Leave these things alone for non-interactive shells without job
3768      control. */
3769 }
3770
3771 /* Here we handle CONT signals. */
3772 static sighandler
3773 sigcont_sighandler (sig)
3774      int sig;
3775 {
3776   initialize_job_signals ();
3777   set_signal_handler (SIGCONT, old_cont);
3778   kill (getpid (), SIGCONT);
3779
3780   SIGRETURN (0);
3781 }
3782
3783 /* Here we handle stop signals while we are running not as a login shell. */
3784 static sighandler
3785 sigstop_sighandler (sig)
3786      int sig;
3787 {
3788   set_signal_handler (SIGTSTP, old_tstp);
3789   set_signal_handler (SIGTTOU, old_ttou);
3790   set_signal_handler (SIGTTIN, old_ttin);
3791
3792   old_cont = set_signal_handler (SIGCONT, sigcont_sighandler);
3793
3794   give_terminal_to (shell_pgrp, 0);
3795
3796   kill (getpid (), sig);
3797
3798   SIGRETURN (0);
3799 }
3800
3801 /* Give the terminal to PGRP.  */
3802 int
3803 give_terminal_to (pgrp, force)
3804      pid_t pgrp;
3805      int force;
3806 {
3807   sigset_t set, oset;
3808   int r, e;
3809
3810   r = 0;
3811   if (job_control || force)
3812     {
3813       sigemptyset (&set);
3814       sigaddset (&set, SIGTTOU);
3815       sigaddset (&set, SIGTTIN);
3816       sigaddset (&set, SIGTSTP);
3817       sigaddset (&set, SIGCHLD);
3818       sigemptyset (&oset);
3819       sigprocmask (SIG_BLOCK, &set, &oset);
3820
3821       if (tcsetpgrp (shell_tty, pgrp) < 0)
3822         {
3823           /* Maybe we should print an error message? */
3824 #if 0
3825           sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
3826             shell_tty, (long)getpid(), (long)pgrp);
3827 #endif
3828           r = -1;
3829           e = errno;
3830         }
3831       else
3832         terminal_pgrp = pgrp;
3833       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
3834     }
3835
3836   if (r == -1)
3837     errno = e;
3838
3839   return r;
3840 }
3841
3842 /* Give terminal to NPGRP iff it's currently owned by OPGRP.  FLAGS are the
3843    flags to pass to give_terminal_to(). */
3844 static int
3845 maybe_give_terminal_to (opgrp, npgrp, flags)
3846      pid_t opgrp, npgrp;
3847      int flags;
3848 {
3849   int tpgrp;
3850
3851   tpgrp = tcgetpgrp (shell_tty);
3852   if (tpgrp < 0 && errno == ENOTTY)
3853     return -1;
3854   if (tpgrp == npgrp)
3855     {
3856       terminal_pgrp = npgrp;
3857       return 0;
3858     }
3859   else if (tpgrp != opgrp)
3860     {
3861 #if defined (DEBUG)
3862       internal_warning ("maybe_give_terminal_to: terminal pgrp == %d shell pgrp = %d new pgrp = %d", tpgrp, opgrp, npgrp);
3863 #endif
3864       return -1;
3865     }
3866   else
3867     return (give_terminal_to (npgrp, flags));     
3868 }
3869
3870 /* Clear out any jobs in the job array.  This is intended to be used by
3871    children of the shell, who should not have any job structures as baggage
3872    when they start executing (forking subshells for parenthesized execution
3873    and functions with pipes are the two that spring to mind).  If RUNNING_ONLY
3874    is nonzero, only running jobs are removed from the table. */
3875 void
3876 delete_all_jobs (running_only)
3877      int running_only;
3878 {
3879   register int i;
3880   sigset_t set, oset;
3881
3882   BLOCK_CHILD (set, oset);
3883
3884   /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
3885   if (js.j_jobslots)
3886     {
3887       js.j_current = js.j_previous = NO_JOB;
3888
3889       /* XXX could use js.j_firstj here */
3890       for (i = 0; i < js.j_jobslots; i++)
3891         {
3892 #if defined (DEBUG)
3893           if (i < js.j_firstj && jobs[i])
3894             itrace("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
3895           if (i > js.j_lastj && jobs[i])
3896             itrace("delete_all_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
3897 #endif
3898           if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3899             delete_job (i, DEL_WARNSTOPPED);
3900         }
3901       if (running_only == 0)
3902         {
3903           free ((char *)jobs);
3904           js.j_jobslots = 0;
3905           js.j_firstj = js.j_lastj = js.j_njobs = 0;
3906         }
3907     }
3908
3909   if (running_only == 0)
3910     bgp_clear ();
3911
3912   UNBLOCK_CHILD (oset);
3913 }
3914
3915 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
3916    shell gets one.  If RUNNING_ONLY is nonzero, mark only running jobs. */
3917 void
3918 nohup_all_jobs (running_only)
3919      int running_only;
3920 {
3921   register int i;
3922   sigset_t set, oset;
3923
3924   BLOCK_CHILD (set, oset);
3925
3926   if (js.j_jobslots)
3927     {
3928       /* XXX could use js.j_firstj here */
3929       for (i = 0; i < js.j_jobslots; i++)
3930         if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3931           nohup_job (i);
3932     }
3933
3934   UNBLOCK_CHILD (oset);
3935 }
3936
3937 int
3938 count_all_jobs ()
3939 {
3940   int i, n;
3941   sigset_t set, oset;
3942
3943   /* This really counts all non-dead jobs. */
3944   BLOCK_CHILD (set, oset);
3945   /* XXX could use js.j_firstj here */
3946   for (i = n = 0; i < js.j_jobslots; i++)
3947     {
3948 #if defined (DEBUG)
3949       if (i < js.j_firstj && jobs[i])
3950         itrace("count_all_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
3951       if (i > js.j_lastj && jobs[i])
3952         itrace("count_all_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
3953 #endif
3954       if (jobs[i] && DEADJOB(i) == 0)
3955         n++;
3956     }
3957   UNBLOCK_CHILD (oset);
3958   return n;
3959 }
3960
3961 static void
3962 mark_all_jobs_as_dead ()
3963 {
3964   register int i;
3965   sigset_t set, oset;
3966
3967   if (js.j_jobslots == 0)
3968     return;
3969
3970   BLOCK_CHILD (set, oset);
3971
3972   /* XXX could use js.j_firstj here */
3973   for (i = 0; i < js.j_jobslots; i++)
3974     if (jobs[i])
3975       {
3976         jobs[i]->state = JDEAD;
3977         js.j_ndead++;
3978       }
3979
3980   UNBLOCK_CHILD (oset);
3981 }
3982
3983 /* Mark all dead jobs as notified, so delete_job () cleans them out
3984    of the job table properly.  POSIX.2 says we need to save the
3985    status of the last CHILD_MAX jobs, so we count the number of dead
3986    jobs and mark only enough as notified to save CHILD_MAX statuses. */
3987 static void
3988 mark_dead_jobs_as_notified (force)
3989      int force;
3990 {
3991   register int i, ndead, ndeadproc;
3992   sigset_t set, oset;
3993
3994   if (js.j_jobslots == 0)
3995     return;
3996
3997   BLOCK_CHILD (set, oset);
3998
3999   /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
4000      around; just run through the array. */
4001   if (force)
4002     {
4003     /* XXX could use js.j_firstj here */
4004       for (i = 0; i < js.j_jobslots; i++)
4005         {
4006           if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
4007             jobs[i]->flags |= J_NOTIFIED;
4008         }
4009       UNBLOCK_CHILD (oset);
4010       return;
4011     }
4012
4013   /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
4014      array with the corresponding not marked as notified.  This is a better
4015      way to avoid pid aliasing and reuse problems than keeping the POSIX-
4016      mandated CHILD_MAX jobs around.  delete_job() takes care of keeping the
4017      bgpids list regulated. */
4018           
4019   /* Count the number of dead jobs */
4020   /* XXX could use js.j_firstj here */
4021   for (i = ndead = ndeadproc = 0; i < js.j_jobslots; i++)
4022     {
4023 #if defined (DEBUG)
4024       if (i < js.j_firstj && jobs[i])
4025         itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
4026       if (i > js.j_lastj && jobs[i])
4027         itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
4028 #endif
4029       if (jobs[i] && DEADJOB (i))
4030         {
4031           ndead++;
4032           ndeadproc += processes_in_job (i);
4033         }
4034     }
4035
4036 #ifdef DEBUG
4037   if (ndeadproc != js.c_reaped)
4038     itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc, js.c_reaped);
4039   if (ndead != js.j_ndead)
4040     itrace("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead, js.j_ndead);
4041 #endif
4042
4043   if (js.c_childmax < 0)
4044     js.c_childmax = getmaxchild ();
4045   if (js.c_childmax < 0)
4046     js.c_childmax = DEFAULT_CHILD_MAX;
4047
4048   /* Don't do anything if the number of dead processes is less than CHILD_MAX
4049      and we're not forcing a cleanup. */
4050   if (ndeadproc <= js.c_childmax)
4051     {
4052       UNBLOCK_CHILD (oset);
4053       return;
4054     }
4055
4056 #if 0
4057 itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js.c_childmax, ndead, ndeadproc);
4058 #endif
4059
4060   /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
4061      the list.  This isn't exactly right yet; changes need to be made
4062      to stop_pipeline so we don't mark the newer jobs after we've
4063      created CHILD_MAX slots in the jobs array.  This needs to be
4064      integrated with a way to keep the jobs array from growing without
4065      bound.  Maybe we wrap back around to 0 after we reach some max
4066      limit, and there are sufficient job slots free (keep track of total
4067      size of jobs array (js.j_jobslots) and running count of number of jobs
4068      in jobs array.  Then keep a job index corresponding to the `oldest job'
4069      and start this loop there, wrapping around as necessary.  In effect,
4070      we turn the list into a circular buffer. */
4071   /* XXX could use js.j_firstj here */
4072   for (i = 0; i < js.j_jobslots; i++)
4073     {
4074       if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
4075         {
4076 #if defined (DEBUG)
4077           if (i < js.j_firstj && jobs[i])
4078             itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
4079           if (i > js.j_lastj && jobs[i])
4080             itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
4081 #endif
4082           /* If marking this job as notified would drop us down below
4083              child_max, don't mark it so we can keep at least child_max
4084              statuses.  XXX -- need to check what Posix actually says
4085              about keeping statuses. */
4086           if ((ndeadproc -= processes_in_job (i)) <= js.c_childmax)
4087             break;
4088           jobs[i]->flags |= J_NOTIFIED;
4089         }
4090     }
4091
4092   UNBLOCK_CHILD (oset);
4093 }
4094
4095 /* Here to allow other parts of the shell (like the trap stuff) to
4096    unfreeze the jobs list. */
4097 void
4098 unfreeze_jobs_list ()
4099 {
4100   jobs_list_frozen = 0;
4101 }
4102
4103 /* Allow or disallow job control to take place.  Returns the old value
4104    of job_control. */
4105 int
4106 set_job_control (arg)
4107      int arg;
4108 {
4109   int old;
4110
4111   old = job_control;
4112   job_control = arg;
4113
4114   /* If we're turning on job control, reset pipeline_pgrp so make_child will
4115      put new child processes into the right pgrp */
4116   if (job_control != old && job_control)
4117     pipeline_pgrp = 0;
4118
4119   return (old);
4120 }
4121
4122 /* Turn off all traces of job control.  This is run by children of the shell
4123    which are going to do shellsy things, like wait (), etc. */
4124 void
4125 without_job_control ()
4126 {
4127   stop_making_children ();
4128   start_pipeline ();
4129 #if defined (PGRP_PIPE)
4130   sh_closepipe (pgrp_pipe);
4131 #endif
4132   delete_all_jobs (0);
4133   set_job_control (0);
4134 }
4135
4136 /* If this shell is interactive, terminate all stopped jobs and
4137    restore the original terminal process group.  This is done
4138    before the `exec' builtin calls shell_execve. */
4139 void
4140 end_job_control ()
4141 {
4142   if (interactive_shell)                /* XXX - should it be interactive? */
4143     {
4144       terminate_stopped_jobs ();
4145
4146       if (original_pgrp >= 0)
4147         give_terminal_to (original_pgrp, 1);
4148     }
4149
4150   if (original_pgrp >= 0)
4151     setpgid (0, original_pgrp);
4152 }
4153
4154 /* Restart job control by closing shell tty and reinitializing.  This is
4155    called after an exec fails in an interactive shell and we do not exit. */
4156 void
4157 restart_job_control ()
4158 {
4159   if (shell_tty != -1)
4160     close (shell_tty);
4161   initialize_job_control (0);
4162 }
4163
4164 /* Set the handler to run when the shell receives a SIGCHLD signal. */
4165 void
4166 set_sigchld_handler ()
4167 {
4168   set_signal_handler (SIGCHLD, sigchld_handler);
4169 }
4170
4171 #if defined (PGRP_PIPE)
4172 /* Read from the read end of a pipe.  This is how the process group leader
4173    blocks until all of the processes in a pipeline have been made. */
4174 static void
4175 pipe_read (pp)
4176      int *pp;
4177 {
4178   char ch;
4179
4180   if (pp[1] >= 0)
4181     {
4182       close (pp[1]);
4183       pp[1] = -1;
4184     }
4185
4186   if (pp[0] >= 0)
4187     {
4188       while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
4189         ;
4190     }
4191 }
4192
4193 /* Functional interface closes our local-to-job-control pipes. */
4194 void
4195 close_pgrp_pipe ()
4196 {
4197   sh_closepipe (pgrp_pipe);
4198 }
4199
4200 #endif /* PGRP_PIPE */