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