Imported from ../bash-3.2.48.tar.gz.
[platform/upstream/bash.git] / jobs.c
1 /* The thing that makes children, remembers them, and contains wait loops. */
2
3 /* This file works with both POSIX and BSD systems.  It implements job
4    control. */
5
6 /* Copyright (C) 1989-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)
76 extern 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
140 typedef int sh_job_map_func_t __P((JOB *, int, int, int));
141
142 /* Variables used here but defined in other files. */
143 extern int subshell_environment, line_number;
144 extern int posixly_correct, shell_level;
145 extern int last_command_exit_value, last_command_exit_signal;
146 extern int loop_level, breaking;
147 extern int sourcelevel;
148 extern int running_trap;
149 extern sh_builtin_func_t *this_shell_builtin;
150 extern char *shell_name, *this_command_name;
151 extern sigset_t top_level_mask;
152 extern procenv_t wait_intr_buf;
153 extern int wait_signal_received;
154 extern WORD_LIST *subst_assign_varlist;
155
156 static struct jobstats zerojs = { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB, NO_JOB, 0, 0 };
157 struct jobstats js = { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB, NO_JOB, 0, 0 };
158
159 struct bgpids bgpids = { 0, 0, 0 };
160
161 /* The array of known jobs. */
162 JOB **jobs = (JOB **)NULL;
163
164 #if 0
165 /* The number of slots currently allocated to JOBS. */
166 int job_slots = 0;
167 #endif
168
169 /* The controlling tty for this shell. */
170 int shell_tty = -1;
171
172 /* The shell's process group. */
173 pid_t shell_pgrp = NO_PID;
174
175 /* The terminal's process group. */
176 pid_t terminal_pgrp = NO_PID;
177
178 /* The process group of the shell's parent. */
179 pid_t original_pgrp = NO_PID;
180
181 /* The process group of the pipeline currently being made. */
182 pid_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. */
188 int pgrp_pipe[2] = { -1, -1 };
189 #endif
190
191 #if 0
192 /* The job which is current; i.e. the one that `%+' stands for. */
193 int current_job = NO_JOB;
194
195 /* The previous job; i.e. the one that `%-' stands for. */
196 int previous_job = NO_JOB;
197 #endif
198
199 /* Last child made by the shell.  */
200 pid_t last_made_pid = NO_PID;
201
202 /* Pid of the last asynchronous child. */
203 pid_t last_asynchronous_pid = NO_PID;
204
205 /* The pipeline currently being built. */
206 PROCESS *the_pipeline = (PROCESS *)NULL;
207
208 /* If this is non-zero, do job control. */
209 int job_control = 1;
210
211 /* Call this when you start making children. */
212 int 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(). */
216 int check_window_size;
217
218 /* Functions local to this file. */
219
220 static void run_sigchld_trap __P((int));
221
222 static sighandler wait_sigint_handler __P((int));
223 static sighandler sigchld_handler __P((int));
224 static sighandler sigcont_sighandler __P((int));
225 static sighandler sigstop_sighandler __P((int));
226
227 static int waitchld __P((pid_t, int));
228
229 static PROCESS *find_pipeline __P((pid_t, int, int *));
230 static PROCESS *find_process __P((pid_t, int, int *));
231
232 static char *current_working_directory __P((void));
233 static char *job_working_directory __P((void));
234 static char *j_strsignal __P((int));
235 static char *printable_job_status __P((int, PROCESS *, int));
236
237 static PROCESS *find_last_proc __P((int, int));
238 static pid_t find_last_pid __P((int, int));
239
240 static int set_new_line_discipline __P((int));
241 static int map_over_jobs __P((sh_job_map_func_t *, int, int));
242 static int job_last_stopped __P((int));
243 static int job_last_running __P((int));
244 static int most_recent_job_in_state __P((int, JOB_STATE));
245 static int find_job __P((pid_t, int, PROCESS **));
246 static int print_job __P((JOB *, int, int, int));
247 static int process_exit_status __P((WAIT));
248 static int process_exit_signal __P((WAIT));
249 static int job_exit_status __P((int));
250 static int job_exit_signal __P((int));
251 static int set_job_status_and_cleanup __P((int));
252
253 static WAIT job_signal_status __P((int));
254 static WAIT raw_job_exit_status __P((int));
255
256 static void notify_of_job_status __P((void));
257 static void reset_job_indices __P((void));
258 static void cleanup_dead_jobs __P((void));
259 static int processes_in_job __P((int));
260 static void realloc_jobs_list __P((void));
261 static int compact_jobs_list __P((int));
262 static int discard_pipeline __P((PROCESS *));
263 static void add_process __P((char *, pid_t));
264 static void print_pipeline __P((PROCESS *, int, int, FILE *));
265 static void pretty_print_job __P((int, int, FILE *));
266 static void set_current_job __P((int));
267 static void reset_current __P((void));
268 static void set_job_running __P((int));
269 static void setjstatus __P((int));
270 static void mark_all_jobs_as_dead __P((void));
271 static void mark_dead_jobs_as_notified __P((int));
272 static void restore_sigint_handler __P((void));
273 #if defined (PGRP_PIPE)
274 static void pipe_read __P((int *));
275 static void pipe_close __P((int *));
276 #endif
277
278 static struct pidstat *bgp_alloc __P((pid_t, int));
279 static struct pidstat *bgp_add __P((pid_t, int));
280 static int bgp_delete __P((pid_t));
281 static void bgp_clear __P((void));
282 static int bgp_search __P((pid_t));
283 static void bgp_prune __P((void));
284
285 #if defined (ARRAY_VARS)
286 static int *pstatuses;          /* list of pipeline statuses */
287 static int statsize;
288 #endif
289
290 /* Used to synchronize between wait_for and other functions and the SIGCHLD
291    signal handler. */
292 static int sigchld;
293 static int queue_sigchld;
294
295 #define QUEUE_SIGCHLD(os)       (os) = sigchld, queue_sigchld++
296
297 #define UNQUEUE_SIGCHLD(os) \
298         do { \
299           queue_sigchld--; \
300           if (queue_sigchld == 0 && os != sigchld) \
301             waitchld (-1, 0); \
302         } while (0)
303
304 static SigHandler *old_tstp, *old_ttou, *old_ttin;
305 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
306
307 /* A place to temporarily save the current pipeline. */
308 static PROCESS *saved_pipeline;
309 static int saved_already_making_children;
310
311 /* Set this to non-zero whenever you don't want the jobs list to change at
312    all: no jobs deleted and no status change notifications.  This is used,
313    for example, when executing SIGCHLD traps, which may run arbitrary
314    commands. */
315 static int jobs_list_frozen;
316
317 static char retcode_name_buffer[64];
318
319 /* flags to detect pid wraparound */
320 static pid_t first_pid = NO_PID;
321 static int pid_wrap = -1;
322
323 #if !defined (_POSIX_VERSION)
324
325 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
326    library functions and system calls. */
327 #define setpgid(pid, pgrp)      setpgrp (pid, pgrp)
328 #define tcsetpgrp(fd, pgrp)     ioctl ((fd), TIOCSPGRP, &(pgrp))
329
330 pid_t
331 tcgetpgrp (fd)
332      int fd;
333 {
334   pid_t pgrp;
335
336   /* ioctl will handle setting errno correctly. */
337   if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
338     return (-1);
339   return (pgrp);
340 }
341
342 #endif /* !_POSIX_VERSION */
343
344 /* Initialize the global job stats structure and other bookkeeping variables */
345 void
346 init_job_stats ()
347 {
348   js = zerojs;
349   first_pid = NO_PID;
350   pid_wrap = -1;
351 }
352
353 /* Return the working directory for the current process.  Unlike
354    job_working_directory, this does not call malloc (), nor do any
355    of the functions it calls.  This is so that it can safely be called
356    from a signal handler. */
357 static char *
358 current_working_directory ()
359 {
360   char *dir;
361   static char d[PATH_MAX];
362
363   dir = get_string_value ("PWD");
364
365   if (dir == 0 && the_current_working_directory && no_symbolic_links)
366     dir = the_current_working_directory;
367
368   if (dir == 0)
369     {
370       dir = getcwd (d, sizeof(d));
371       if (dir)
372         dir = d;
373     }
374
375   return (dir == 0) ? "<unknown>" : dir;
376 }
377
378 /* Return the working directory for the current process. */
379 static char *
380 job_working_directory ()
381 {
382   char *dir;
383
384   dir = get_string_value ("PWD");
385   if (dir)
386     return (savestring (dir));
387
388   dir = get_working_directory ("job-working-directory");
389   if (dir)
390     return (dir);
391
392   return (savestring ("<unknown>"));
393 }
394
395 void
396 making_children ()
397 {
398   if (already_making_children)
399     return;
400
401   already_making_children = 1;
402   start_pipeline ();
403 }
404
405 void
406 stop_making_children ()
407 {
408   already_making_children = 0;
409 }
410
411 void
412 cleanup_the_pipeline ()
413 {
414   PROCESS *disposer;
415   sigset_t set, oset;
416
417   BLOCK_CHILD (set, oset);
418   disposer = the_pipeline;
419   the_pipeline = (PROCESS *)NULL;
420   UNBLOCK_CHILD (oset);
421
422   if (disposer)
423     discard_pipeline (disposer);
424 }
425
426 void
427 save_pipeline (clear)
428      int clear;
429 {
430   saved_pipeline = the_pipeline;
431   if (clear)
432     the_pipeline = (PROCESS *)NULL;
433   saved_already_making_children = already_making_children;
434 }
435
436 void
437 restore_pipeline (discard)
438      int discard;
439 {
440   PROCESS *old_pipeline;
441
442   old_pipeline = the_pipeline;
443   the_pipeline = saved_pipeline;
444   already_making_children = saved_already_making_children;
445   if (discard)
446     discard_pipeline (old_pipeline);
447 }
448
449 /* Start building a pipeline.  */
450 void
451 start_pipeline ()
452 {
453   if (the_pipeline)
454     {
455       cleanup_the_pipeline ();
456       pipeline_pgrp = 0;
457 #if defined (PGRP_PIPE)
458       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. */
475 int
476 stop_pipeline (async, deferred)
477      int async;
478      COMMAND *deferred;
479 {
480   register int i, j;
481   JOB *newjob;
482   sigset_t set, oset;
483
484   BLOCK_CHILD (set, oset);
485
486 #if defined (PGRP_PIPE)
487   /* The parent closes the process group synchronization pipe. */
488   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
654 static struct pidstat *
655 bgp_alloc (pid, status)
656      pid_t pid;
657      int status;
658 {
659   struct pidstat *ps;
660
661   ps = (struct pidstat *)xmalloc (sizeof (struct pidstat));
662   ps->pid = pid;
663   ps->status = status;
664   ps->next = (struct pidstat *)0;
665   return ps;
666 }
667
668 static struct pidstat *
669 bgp_add (pid, status)
670      pid_t pid;
671      int status;
672 {
673   struct pidstat *ps;
674
675   ps = bgp_alloc (pid, status);
676
677   if (bgpids.list == 0)
678     {
679       bgpids.list = bgpids.end = ps;
680       bgpids.npid = 0;                  /* just to make sure */
681     }
682   else
683     {
684       bgpids.end->next = ps;
685       bgpids.end = ps;
686     }
687   bgpids.npid++;
688
689   if (bgpids.npid > js.c_childmax)
690     bgp_prune ();
691
692   return ps;
693 }
694
695 static int
696 bgp_delete (pid)
697      pid_t pid;
698 {
699   struct pidstat *prev, *p;
700
701   for (prev = p = bgpids.list; p; prev = p, p = p->next)
702     if (p->pid == pid)
703       {
704         prev->next = p->next;   /* remove from list */
705         break;
706       }
707
708   if (p == 0)
709     return 0;           /* not found */
710
711 #if defined (DEBUG)
712   itrace("bgp_delete: deleting %d", pid);
713 #endif
714
715   /* Housekeeping in the border cases. */
716   if (p == bgpids.list)
717     bgpids.list = bgpids.list->next;
718   else if (p == bgpids.end)
719     bgpids.end = prev;
720
721   bgpids.npid--;
722   if (bgpids.npid == 0)
723     bgpids.list = bgpids.end = 0;
724   else if (bgpids.npid == 1)
725     bgpids.end = bgpids.list;           /* just to make sure */
726
727   free (p);
728   return 1;
729 }
730
731 /* Clear out the list of saved statuses */
732 static void
733 bgp_clear ()
734 {
735   struct pidstat *ps, *p;
736
737   for (ps = bgpids.list; ps; )
738     {
739       p = ps;
740       ps = ps->next;
741       free (p);
742     }
743   bgpids.list = bgpids.end = 0;
744   bgpids.npid = 0;
745 }
746
747 /* Search for PID in the list of saved background pids; return its status if
748    found.  If not found, return -1. */
749 static int
750 bgp_search (pid)
751      pid_t pid;
752 {
753   struct pidstat *ps;
754
755   for (ps = bgpids.list ; ps; ps = ps->next)
756     if (ps->pid == pid)
757       return ps->status;
758   return -1;
759 }
760
761 static void
762 bgp_prune ()
763 {
764   struct pidstat *ps;
765
766   while (bgpids.npid > js.c_childmax)
767     {
768       ps = bgpids.list;
769       bgpids.list = bgpids.list->next;
770       free (ps);
771       bgpids.npid--;
772     }
773 }
774     
775 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
776    been deleted.  The caller should check whether js.j_njobs is 0 before
777    calling this.  This wraps around, but the rest of the code does not.  At
778    this point, it should not matter. */
779 static void
780 reset_job_indices ()
781 {
782   int old;
783
784   if (jobs[js.j_firstj] == 0)
785     {
786       old = js.j_firstj++;
787       if (old >= js.j_jobslots)
788         old = js.j_jobslots - 1;
789       while (js.j_firstj != old)
790         {
791           if (js.j_firstj >= js.j_jobslots)
792             js.j_firstj = 0;
793           if (jobs[js.j_firstj] || js.j_firstj == old)  /* needed if old == 0 */
794             break;
795           js.j_firstj++;
796         }
797       if (js.j_firstj == old)
798         js.j_firstj = js.j_lastj = js.j_njobs = 0;
799     }
800   if (jobs[js.j_lastj] == 0)
801     {
802       old = js.j_lastj--;
803       if (old < 0)
804         old = 0;
805       while (js.j_lastj != old)
806         {
807           if (js.j_lastj < 0)
808             js.j_lastj = js.j_jobslots - 1;
809           if (jobs[js.j_lastj] || js.j_lastj == old)    /* needed if old == js.j_jobslots */
810             break;
811           js.j_lastj--;
812         }
813       if (js.j_lastj == old)
814         js.j_firstj = js.j_lastj = js.j_njobs = 0;
815     }
816 }
817       
818 /* Delete all DEAD jobs that the user had received notification about. */
819 static void
820 cleanup_dead_jobs ()
821 {
822   register int i;
823   int os;
824
825   if (js.j_jobslots == 0 || jobs_list_frozen)
826     return;
827
828   QUEUE_SIGCHLD(os);
829
830   /* XXX could use js.j_firstj and js.j_lastj here */
831   for (i = 0; i < js.j_jobslots; i++)
832     {
833 #if defined (DEBUG)
834       if (i < js.j_firstj && jobs[i])
835         itrace("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
836       if (i > js.j_lastj && jobs[i])
837         itrace("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
838 #endif
839
840       if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
841         delete_job (i, 0);
842     }
843   UNQUEUE_SIGCHLD(os);
844 }
845
846 static int
847 processes_in_job (job)
848 {
849   int nproc;
850   register PROCESS *p;
851
852   nproc = 0;
853   p = jobs[job]->pipe;
854   do
855     {
856       p = p->next;
857       nproc++;
858     }
859   while (p != jobs[job]->pipe);
860
861   return nproc;
862 }
863
864 static void
865 delete_old_job (pid)
866      pid_t pid;
867 {
868   PROCESS *p;
869   int job;
870
871   job = find_job (pid, 0, &p);
872   if (job != NO_JOB)
873     {
874 #ifdef DEBUG
875       itrace ("delete_old_job: found pid %d in job %d with state %d", pid, job, jobs[job]->state);
876 #endif
877       if (JOBSTATE (job) == JDEAD)
878         delete_job (job, DEL_NOBGPID);
879       else
880         {
881           internal_warning (_("forked pid %d appears in running job %d"), pid, job);
882           if (p)
883             p->pid = 0;
884         }
885     }
886 }
887
888 /* Reallocate and compress the jobs list.  This returns with a jobs array
889    whose size is a multiple of JOB_SLOTS and can hold the current number of
890    jobs.  Heuristics are used to minimize the number of new reallocs. */
891 static void
892 realloc_jobs_list ()
893 {
894   sigset_t set, oset;
895   int nsize, i, j, ncur, nprev;
896   JOB **nlist;
897
898   ncur = nprev = NO_JOB;
899   nsize = ((js.j_njobs + JOB_SLOTS - 1) / JOB_SLOTS);
900   nsize *= JOB_SLOTS;
901   i = js.j_njobs % JOB_SLOTS;
902   if (i == 0 || i > (JOB_SLOTS >> 1))
903     nsize += JOB_SLOTS;
904
905   BLOCK_CHILD (set, oset);
906   nlist = (js.j_jobslots == nsize) ? jobs : (JOB **) xmalloc (nsize * sizeof (JOB *));
907
908   for (i = j = 0; i < js.j_jobslots; i++)
909     if (jobs[i])
910       {
911         if (i == js.j_current)
912           ncur = j;
913         if (i == js.j_previous)
914           nprev = j;
915         nlist[j++] = jobs[i];
916       }
917
918 #if defined (DEBUG)
919   itrace ("realloc_jobs_list: resize jobs list from %d to %d", js.j_jobslots, nsize);
920   itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js.j_lastj, (j > 0) ? j - 1 : 0);
921   itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js.j_njobs, (j > 0) ? j - 1 : 0);
922 #endif
923
924   js.j_firstj = 0;
925   js.j_lastj = (j > 0) ? j - 1 : 0;
926   js.j_njobs = j;
927   js.j_jobslots = nsize;
928
929   /* Zero out remaining slots in new jobs list */
930   for ( ; j < nsize; j++)
931     nlist[j] = (JOB *)NULL;
932
933   if (jobs != nlist)
934     {
935       free (jobs);
936       jobs = nlist;
937     }
938
939   if (ncur != NO_JOB)
940     js.j_current = ncur;
941   if (nprev != NO_JOB)
942     js.j_previous = nprev;
943
944   /* Need to reset these */
945   if (js.j_current == NO_JOB || js.j_previous == NO_JOB || js.j_current > js.j_lastj || js.j_previous > js.j_lastj)
946     reset_current ();
947
948 #ifdef DEBUG
949   itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js.j_current, js.j_previous);
950 #endif
951
952   UNBLOCK_CHILD (oset);
953 }
954
955 /* Compact the jobs list by removing dead jobs.  Assumed that we have filled
956    the jobs array to some predefined maximum.  Called when the shell is not
957    the foreground process (subshell_environment != 0).  Returns the first
958    available slot in the compacted list.  If that value is js.j_jobslots, then
959    the list needs to be reallocated.  The jobs array may be in new memory if
960    this returns > 0 and < js.j_jobslots.  FLAGS is reserved for future use. */
961 static int
962 compact_jobs_list (flags)
963      int flags;
964 {
965   if (js.j_jobslots == 0 || jobs_list_frozen)
966     return js.j_jobslots;
967
968   reap_dead_jobs ();
969   realloc_jobs_list ();
970
971 #ifdef DEBUG
972   itrace("compact_jobs_list: returning %d", (js.j_lastj || jobs[js.j_lastj]) ? js.j_lastj + 1 : 0);
973 #endif
974
975   return ((js.j_lastj || jobs[js.j_lastj]) ? js.j_lastj + 1 : 0);
976 }
977
978 /* Delete the job at INDEX from the job list.  Must be called
979    with SIGCHLD blocked. */
980 void
981 delete_job (job_index, dflags)
982      int job_index, dflags;
983 {
984   register JOB *temp;
985   PROCESS *proc;
986   int ndel;
987
988   if (js.j_jobslots == 0 || jobs_list_frozen)
989     return;
990
991   if ((dflags & DEL_WARNSTOPPED) && subshell_environment == 0 && STOPPED (job_index))
992     internal_warning (_("deleting stopped job %d with process group %ld"), job_index+1, (long)jobs[job_index]->pgrp);
993   temp = jobs[job_index];
994   if (temp == 0)
995     return;
996
997   if ((dflags & DEL_NOBGPID) == 0)
998     {
999       proc = find_last_proc (job_index, 0);
1000       /* Could do this just for J_ASYNC jobs, but we save all. */
1001       if (proc)
1002         bgp_add (proc->pid, process_exit_status (proc->status));
1003     }
1004
1005   jobs[job_index] = (JOB *)NULL;
1006   if (temp == js.j_lastmade)
1007     js.j_lastmade = 0;
1008   else if (temp == js.j_lastasync)
1009     js.j_lastasync = 0;
1010
1011   free (temp->wd);
1012   ndel = discard_pipeline (temp->pipe);
1013
1014   js.c_injobs -= ndel;
1015   if (temp->state == JDEAD)
1016     {
1017       js.c_reaped -= ndel;
1018       js.j_ndead--;
1019       if (js.c_reaped < 0)
1020         {
1021 #ifdef DEBUG
1022           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);
1023 #endif
1024           js.c_reaped = 0;
1025         }
1026     }
1027
1028   if (temp->deferred)
1029     dispose_command (temp->deferred);
1030
1031   free (temp);
1032
1033   js.j_njobs--;
1034   if (js.j_njobs == 0)
1035     js.j_firstj = js.j_lastj = 0;
1036   else if (jobs[js.j_firstj] == 0 || jobs[js.j_lastj] == 0)
1037     reset_job_indices ();
1038
1039   if (job_index == js.j_current || job_index == js.j_previous)
1040     reset_current ();
1041 }
1042
1043 /* Must be called with SIGCHLD blocked. */
1044 void
1045 nohup_job (job_index)
1046      int job_index;
1047 {
1048   register JOB *temp;
1049
1050   if (js.j_jobslots == 0)
1051     return;
1052
1053   if (temp = jobs[job_index])
1054     temp->flags |= J_NOHUP;
1055 }
1056
1057 /* Get rid of the data structure associated with a process chain. */
1058 static int
1059 discard_pipeline (chain)
1060      register PROCESS *chain;
1061 {
1062   register PROCESS *this, *next;
1063   int n;
1064
1065   this = chain;
1066   n = 0;
1067   do
1068     {
1069       next = this->next;
1070       FREE (this->command);
1071       free (this);
1072       n++;
1073       this = next;
1074     }
1075   while (this != chain);
1076
1077   return n;
1078 }
1079
1080 /* Add this process to the chain being built in the_pipeline.
1081    NAME is the command string that will be exec'ed later.
1082    PID is the process id of the child. */
1083 static void
1084 add_process (name, pid)
1085      char *name;
1086      pid_t pid;
1087 {
1088   PROCESS *t, *p;
1089
1090 #if defined (RECYCLES_PIDS)
1091   int j;
1092   p = find_process (pid, 0, &j);
1093   if (p)
1094     {
1095 #  ifdef DEBUG
1096       if (j == NO_JOB)
1097         internal_warning ("add_process: process %5ld (%s) in the_pipeline", (long)p->pid, p->command);
1098 #  endif
1099       if (PALIVE (p))
1100         internal_warning ("add_process: pid %5ld (%s) marked as still alive", (long)p->pid, p->command);
1101       p->running = PS_RECYCLED;         /* mark as recycled */
1102     }
1103 #endif
1104
1105   t = (PROCESS *)xmalloc (sizeof (PROCESS));
1106   t->next = the_pipeline;
1107   t->pid = pid;
1108   WSTATUS (t->status) = 0;
1109   t->running = PS_RUNNING;
1110   t->command = name;
1111   the_pipeline = t;
1112
1113   if (t->next == 0)
1114     t->next = t;
1115   else
1116     {
1117       p = t->next;
1118       while (p->next != t->next)
1119         p = p->next;
1120       p->next = t;
1121     }
1122 }
1123
1124 #if 0
1125 /* Take the last job and make it the first job.  Must be called with
1126    SIGCHLD blocked. */
1127 int
1128 rotate_the_pipeline ()
1129 {
1130   PROCESS *p;
1131
1132   if (the_pipeline->next == the_pipeline)
1133     return;
1134   for (p = the_pipeline; p->next != the_pipeline; p = p->next)
1135     ;
1136   the_pipeline = p;
1137 }
1138
1139 /* Reverse the order of the processes in the_pipeline.  Must be called with
1140    SIGCHLD blocked. */
1141 int
1142 reverse_the_pipeline ()
1143 {
1144   PROCESS *p, *n;
1145
1146   if (the_pipeline->next == the_pipeline)
1147     return;
1148
1149   for (p = the_pipeline; p->next != the_pipeline; p = p->next)
1150     ;
1151   p->next = (PROCESS *)NULL;
1152
1153   n = REVERSE_LIST (the_pipeline, PROCESS *);
1154
1155   the_pipeline = n;
1156   for (p = the_pipeline; p->next; p = p->next)
1157     ;
1158   p->next = the_pipeline;
1159 }
1160 #endif
1161
1162 /* Map FUNC over the list of jobs.  If FUNC returns non-zero,
1163    then it is time to stop mapping, and that is the return value
1164    for map_over_jobs.  FUNC is called with a JOB, arg1, arg2,
1165    and INDEX. */
1166 static int
1167 map_over_jobs (func, arg1, arg2)
1168      sh_job_map_func_t *func;
1169      int arg1, arg2;
1170 {
1171   register int i;
1172   int result;
1173   sigset_t set, oset;
1174
1175   if (js.j_jobslots == 0)
1176     return 0;
1177
1178   BLOCK_CHILD (set, oset);
1179
1180   /* XXX could use js.j_firstj here */
1181   for (i = result = 0; i < js.j_jobslots; i++)
1182     {
1183 #if defined (DEBUG)
1184       if (i < js.j_firstj && jobs[i])
1185         itrace("map_over_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
1186       if (i > js.j_lastj && jobs[i])
1187         itrace("map_over_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
1188 #endif
1189       if (jobs[i])
1190         {
1191           result = (*func)(jobs[i], arg1, arg2, i);
1192           if (result)
1193             break;
1194         }
1195     }
1196
1197   UNBLOCK_CHILD (oset);
1198
1199   return (result);
1200 }
1201
1202 /* Cause all the jobs in the current pipeline to exit. */
1203 void
1204 terminate_current_pipeline ()
1205 {
1206   if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
1207     {
1208       killpg (pipeline_pgrp, SIGTERM);
1209       killpg (pipeline_pgrp, SIGCONT);
1210     }
1211 }
1212
1213 /* Cause all stopped jobs to exit. */
1214 void
1215 terminate_stopped_jobs ()
1216 {
1217   register int i;
1218
1219   /* XXX could use js.j_firstj here */
1220   for (i = 0; i < js.j_jobslots; i++)
1221     {
1222       if (jobs[i] && STOPPED (i))
1223         {
1224           killpg (jobs[i]->pgrp, SIGTERM);
1225           killpg (jobs[i]->pgrp, SIGCONT);
1226         }
1227     }
1228 }
1229
1230 /* Cause all jobs, running or stopped, to receive a hangup signal.  If
1231    a job is marked J_NOHUP, don't send the SIGHUP. */
1232 void
1233 hangup_all_jobs ()
1234 {
1235   register int i;
1236
1237   /* XXX could use js.j_firstj here */
1238   for (i = 0; i < js.j_jobslots; i++)
1239     {
1240       if (jobs[i])
1241         {
1242           if  (jobs[i]->flags & J_NOHUP)
1243             continue;
1244           killpg (jobs[i]->pgrp, SIGHUP);
1245           if (STOPPED (i))
1246             killpg (jobs[i]->pgrp, SIGCONT);
1247         }
1248     }
1249 }
1250
1251 void
1252 kill_current_pipeline ()
1253 {
1254   stop_making_children ();
1255   start_pipeline ();
1256 }
1257
1258 /* Return the pipeline that PID belongs to.  Note that the pipeline
1259    doesn't have to belong to a job.  Must be called with SIGCHLD blocked.
1260    If JOBP is non-null, return the index of the job containing PID.  */
1261 static PROCESS *
1262 find_pipeline (pid, alive_only, jobp)
1263      pid_t pid;
1264      int alive_only;
1265      int *jobp;         /* index into jobs list or NO_JOB */
1266 {
1267   int job;
1268   PROCESS *p;
1269
1270   /* See if this process is in the pipeline that we are building. */
1271   if (jobp)
1272     *jobp = NO_JOB;
1273   if (the_pipeline)
1274     {
1275       p = the_pipeline;
1276       do
1277         {
1278           /* Return it if we found it.  Don't ever return a recycled pid. */
1279           if (p->pid == pid && ((alive_only == 0 && PRECYCLED(p) == 0) || PALIVE(p)))
1280             return (p);
1281
1282           p = p->next;
1283         }
1284       while (p != the_pipeline);
1285     }
1286
1287   job = find_job (pid, alive_only, &p);
1288   if (jobp)
1289     *jobp = job;
1290   return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
1291 }
1292
1293 /* Return the PROCESS * describing PID.  If JOBP is non-null return the index
1294    into the jobs array of the job containing PID.  Must be called with
1295    SIGCHLD blocked. */
1296 static PROCESS *
1297 find_process (pid, alive_only, jobp)
1298      pid_t pid;
1299      int alive_only;
1300      int *jobp;         /* index into jobs list or NO_JOB */
1301 {
1302   PROCESS *p;
1303
1304   p = find_pipeline (pid, alive_only, jobp);
1305   while (p && p->pid != pid)
1306     p = p->next;
1307   return p;
1308 }
1309
1310 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1311    belong to any job.  Must be called with SIGCHLD blocked. */
1312 static int
1313 find_job (pid, alive_only, procp)
1314      pid_t pid;
1315      int alive_only;
1316      PROCESS **procp;
1317 {
1318   register int i;
1319   PROCESS *p;
1320
1321   /* XXX could use js.j_firstj here, and should check js.j_lastj */
1322   for (i = 0; i < js.j_jobslots; i++)
1323     {
1324 #if defined (DEBUG)
1325       if (i < js.j_firstj && jobs[i])
1326         itrace("find_job: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
1327       if (i > js.j_lastj && jobs[i])
1328         itrace("find_job: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
1329 #endif
1330       if (jobs[i])
1331         {
1332           p = jobs[i]->pipe;
1333
1334           do
1335             {
1336               if (p->pid == pid && ((alive_only == 0 && PRECYCLED(p) == 0) || PALIVE(p)))
1337                 {
1338                   if (procp)
1339                     *procp = p;
1340                   return (i);
1341                 }
1342
1343               p = p->next;
1344             }
1345           while (p != jobs[i]->pipe);
1346         }
1347     }
1348
1349   return (NO_JOB);
1350 }
1351
1352 /* Find a job given a PID.  If BLOCK is non-zero, block SIGCHLD as
1353    required by find_job. */
1354 int
1355 get_job_by_pid (pid, block)
1356      pid_t pid;
1357      int block;
1358 {
1359   int job;
1360   sigset_t set, oset;
1361
1362   if (block)
1363     BLOCK_CHILD (set, oset);
1364
1365   job = find_job (pid, 0, NULL);
1366
1367   if (block)
1368     UNBLOCK_CHILD (oset);
1369
1370   return job;
1371 }
1372
1373 /* Print descriptive information about the job with leader pid PID. */
1374 void
1375 describe_pid (pid)
1376      pid_t pid;
1377 {
1378   int job;
1379   sigset_t set, oset;
1380
1381   BLOCK_CHILD (set, oset);
1382
1383   job = find_job (pid, 0, NULL);
1384
1385   if (job != NO_JOB)
1386     fprintf (stderr, "[%d] %ld\n", job + 1, (long)pid);
1387   else
1388     programming_error (_("describe_pid: %ld: no such pid"), (long)pid);
1389
1390   UNBLOCK_CHILD (oset);
1391 }
1392
1393 static char *
1394 j_strsignal (s)
1395      int s;
1396 {
1397   char *x;
1398
1399   x = strsignal (s);
1400   if (x == 0)
1401     {
1402       x = retcode_name_buffer;
1403       sprintf (x, "Signal %d", s);
1404     }
1405   return x;
1406 }
1407
1408 static char *
1409 printable_job_status (j, p, format)
1410      int j;
1411      PROCESS *p;
1412      int format;
1413 {
1414   static char *temp;
1415   int es;
1416
1417   temp = "Done";
1418
1419   if (STOPPED (j) && format == 0)
1420     {
1421       if (posixly_correct == 0 || p == 0 || (WIFSTOPPED (p->status) == 0))
1422         temp = "Stopped";
1423       else
1424         {
1425           temp = retcode_name_buffer;
1426           sprintf (temp, "Stopped(%s)", signal_name (WSTOPSIG (p->status)));
1427         }
1428     }
1429   else if (RUNNING (j))
1430     temp = "Running";
1431   else
1432     {
1433       if (WIFSTOPPED (p->status))
1434         temp = j_strsignal (WSTOPSIG (p->status));
1435       else if (WIFSIGNALED (p->status))
1436         temp = j_strsignal (WTERMSIG (p->status));
1437       else if (WIFEXITED (p->status))
1438         {
1439           temp = retcode_name_buffer;
1440           es = WEXITSTATUS (p->status);
1441           if (es == 0)
1442             strcpy (temp, "Done");
1443           else if (posixly_correct)
1444             sprintf (temp, "Done(%d)", es);
1445           else
1446             sprintf (temp, "Exit %d", es);
1447         }
1448       else
1449         temp = "Unknown status";
1450     }
1451
1452   return temp;
1453 }
1454
1455 /* This is the way to print out information on a job if you
1456    know the index.  FORMAT is:
1457
1458     JLIST_NORMAL)   [1]+ Running           emacs
1459     JLIST_LONG  )   [1]+ 2378 Running      emacs
1460     -1    )   [1]+ 2378       emacs
1461
1462     JLIST_NORMAL)   [1]+ Stopped           ls | more
1463     JLIST_LONG  )   [1]+ 2369 Stopped      ls
1464                          2367       | more
1465     JLIST_PID_ONLY)
1466         Just list the pid of the process group leader (really
1467         the process group).
1468     JLIST_CHANGED_ONLY)
1469         Use format JLIST_NORMAL, but list only jobs about which
1470         the user has not been notified. */
1471
1472 /* Print status for pipeline P.  If JOB_INDEX is >= 0, it is the index into
1473    the JOBS array corresponding to this pipeline.  FORMAT is as described
1474    above.  Must be called with SIGCHLD blocked.
1475
1476    If you're printing a pipeline that's not in the jobs array, like the
1477    current pipeline as it's being created, pass -1 for JOB_INDEX */
1478 static void
1479 print_pipeline (p, job_index, format, stream)
1480      PROCESS *p;
1481      int job_index, format;
1482      FILE *stream;
1483 {
1484   PROCESS *first, *last, *show;
1485   int es, name_padding;
1486   char *temp;
1487
1488   if (p == 0)
1489     return;
1490
1491   first = last = p;
1492   while (last->next != first)
1493     last = last->next;
1494
1495   for (;;)
1496     {
1497       if (p != first)
1498         fprintf (stream, format ? "     " : " |");
1499
1500       if (format != JLIST_STANDARD)
1501         fprintf (stream, "%5ld", (long)p->pid);
1502
1503       fprintf (stream, " ");
1504
1505       if (format > -1 && job_index >= 0)
1506         {
1507           show = format ? p : last;
1508           temp = printable_job_status (job_index, show, format);
1509
1510           if (p != first)
1511             {
1512               if (format)
1513                 {
1514                   if (show->running == first->running &&
1515                       WSTATUS (show->status) == WSTATUS (first->status))
1516                     temp = "";
1517                 }
1518               else
1519                 temp = (char *)NULL;
1520             }
1521
1522           if (temp)
1523             {
1524               fprintf (stream, "%s", temp);
1525
1526               es = STRLEN (temp);
1527               if (es == 0)
1528                 es = 2; /* strlen ("| ") */
1529               name_padding = LONGEST_SIGNAL_DESC - es;
1530
1531               fprintf (stream, "%*s", name_padding, "");
1532
1533               if ((WIFSTOPPED (show->status) == 0) &&
1534                   (WIFCONTINUED (show->status) == 0) &&
1535                   WIFCORED (show->status))
1536                 fprintf (stream, "(core dumped) ");
1537             }
1538         }
1539
1540       if (p != first && format)
1541         fprintf (stream, "| ");
1542
1543       if (p->command)
1544         fprintf (stream, "%s", p->command);
1545
1546       if (p == last && job_index >= 0)
1547         {
1548           temp = current_working_directory ();
1549
1550           if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
1551             fprintf (stream, " &");
1552
1553           if (strcmp (temp, jobs[job_index]->wd) != 0)
1554             fprintf (stream,
1555               "  (wd: %s)", polite_directory_format (jobs[job_index]->wd));
1556         }
1557
1558       if (format || (p == last))
1559         {
1560           /* We need to add a CR only if this is an interactive shell, and
1561              we're reporting the status of a completed job asynchronously.
1562              We can't really check whether this particular job is being
1563              reported asynchronously, so just add the CR if the shell is
1564              currently interactive and asynchronous notification is enabled. */
1565           if (asynchronous_notification && interactive)
1566             fprintf (stream, "\r\n");
1567           else
1568             fprintf (stream, "\n");
1569         }
1570
1571       if (p == last)
1572         break;
1573       p = p->next;
1574     }
1575   fflush (stream);
1576 }
1577
1578 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1579    Must be called with SIGCHLD blocked or queued with queue_sigchld */
1580 static void
1581 pretty_print_job (job_index, format, stream)
1582      int job_index, format;
1583      FILE *stream;
1584 {
1585   register PROCESS *p;
1586
1587   /* Format only pid information about the process group leader? */
1588   if (format == JLIST_PID_ONLY)
1589     {
1590       fprintf (stream, "%ld\n", (long)jobs[job_index]->pipe->pid);
1591       return;
1592     }
1593
1594   if (format == JLIST_CHANGED_ONLY)
1595     {
1596       if (IS_NOTIFIED (job_index))
1597         return;
1598       format = JLIST_STANDARD;
1599     }
1600
1601   if (format != JLIST_NONINTERACTIVE)
1602     fprintf (stream, "[%d]%c ", job_index + 1,
1603               (job_index == js.j_current) ? '+':
1604                 (job_index == js.j_previous) ? '-' : ' ');
1605
1606   if (format == JLIST_NONINTERACTIVE)
1607     format = JLIST_LONG;
1608
1609   p = jobs[job_index]->pipe;
1610
1611   print_pipeline (p, job_index, format, stream);
1612
1613   /* We have printed information about this job.  When the job's
1614      status changes, waitchld () sets the notification flag to 0. */
1615   jobs[job_index]->flags |= J_NOTIFIED;
1616 }
1617
1618 static int
1619 print_job (job, format, state, job_index)
1620      JOB *job;
1621      int format, state, job_index;
1622 {
1623   if (state == -1 || (JOB_STATE)state == job->state)
1624     pretty_print_job (job_index, format, stdout);
1625   return (0);
1626 }
1627
1628 void
1629 list_one_job (job, format, ignore, job_index)
1630      JOB *job;
1631      int format, ignore, job_index;
1632 {
1633   pretty_print_job (job_index, format, stdout);
1634 }
1635
1636 void
1637 list_stopped_jobs (format)
1638      int format;
1639 {
1640   cleanup_dead_jobs ();
1641   map_over_jobs (print_job, format, (int)JSTOPPED);
1642 }
1643
1644 void
1645 list_running_jobs (format)
1646      int format;
1647 {
1648   cleanup_dead_jobs ();
1649   map_over_jobs (print_job, format, (int)JRUNNING);
1650 }
1651
1652 /* List jobs.  If FORMAT is non-zero, then the long form of the information
1653    is printed, else just a short version. */
1654 void
1655 list_all_jobs (format)
1656      int format;
1657 {
1658   cleanup_dead_jobs ();
1659   map_over_jobs (print_job, format, -1);
1660 }
1661
1662 /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
1663    COMMAND is just for remembering the name of the command; we don't do
1664    anything else with it.  ASYNC_P says what to do with the tty.  If
1665    non-zero, then don't give it away. */
1666 pid_t
1667 make_child (command, async_p)
1668      char *command;
1669      int async_p;
1670 {
1671   sigset_t set, oset;
1672   pid_t pid;
1673
1674   sigemptyset (&set);
1675   sigaddset (&set, SIGCHLD);
1676   sigaddset (&set, SIGINT);
1677   sigemptyset (&oset);
1678   sigprocmask (SIG_BLOCK, &set, &oset);
1679
1680   making_children ();
1681
1682 #if defined (BUFFERED_INPUT)
1683   /* If default_buffered_input is active, we are reading a script.  If
1684      the command is asynchronous, we have already duplicated /dev/null
1685      as fd 0, but have not changed the buffered stream corresponding to
1686      the old fd 0.  We don't want to sync the stream in this case. */
1687   if (default_buffered_input != -1 &&
1688       (!async_p || default_buffered_input > 0))
1689     sync_buffered_stream (default_buffered_input);
1690 #endif /* BUFFERED_INPUT */
1691
1692   /* Create the child, handle severe errors. */
1693   if ((pid = fork ()) < 0)
1694     {
1695       sys_error ("fork");
1696
1697       /* Kill all of the processes in the current pipeline. */
1698       terminate_current_pipeline ();
1699
1700       /* Discard the current pipeline, if any. */
1701       if (the_pipeline)
1702         kill_current_pipeline ();
1703
1704       throw_to_top_level ();    /* Reset signals, etc. */
1705     }
1706
1707   if (pid == 0)
1708     {
1709       /* In the child.  Give this child the right process group, set the
1710          signals to the default state for a new process. */
1711       pid_t mypid;
1712
1713       mypid = getpid ();
1714 #if defined (BUFFERED_INPUT)
1715       /* Close default_buffered_input if it's > 0.  We don't close it if it's
1716          0 because that's the file descriptor used when redirecting input,
1717          and it's wrong to close the file in that case. */
1718       unset_bash_input (0);
1719 #endif /* BUFFERED_INPUT */
1720
1721       /* Restore top-level signal mask. */
1722       sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1723
1724       if (job_control)
1725         {
1726           /* All processes in this pipeline belong in the same
1727              process group. */
1728
1729           if (pipeline_pgrp == 0)       /* This is the first child. */
1730             pipeline_pgrp = mypid;
1731
1732           /* Check for running command in backquotes. */
1733           if (pipeline_pgrp == shell_pgrp)
1734             ignore_tty_job_signals ();
1735           else
1736             default_tty_job_signals ();
1737
1738           /* Set the process group before trying to mess with the terminal's
1739              process group.  This is mandated by POSIX. */
1740           /* This is in accordance with the Posix 1003.1 standard,
1741              section B.7.2.4, which says that trying to set the terminal
1742              process group with tcsetpgrp() to an unused pgrp value (like
1743              this would have for the first child) is an error.  Section
1744              B.4.3.3, p. 237 also covers this, in the context of job control
1745              shells. */
1746           if (setpgid (mypid, pipeline_pgrp) < 0)
1747             sys_error ("child setpgid (%ld to %ld)", (long)mypid, (long)pipeline_pgrp);
1748
1749           /* By convention (and assumption above), if
1750              pipeline_pgrp == shell_pgrp, we are making a child for
1751              command substitution.
1752              In this case, we don't want to give the terminal to the
1753              shell's process group (we could be in the middle of a
1754              pipeline, for example). */
1755           if (async_p == 0 && pipeline_pgrp != shell_pgrp && ((subshell_environment&SUBSHELL_ASYNC) == 0))
1756             give_terminal_to (pipeline_pgrp, 0);
1757
1758 #if defined (PGRP_PIPE)
1759           if (pipeline_pgrp == mypid)
1760             pipe_read (pgrp_pipe);
1761 #endif
1762         }
1763       else                      /* Without job control... */
1764         {
1765           if (pipeline_pgrp == 0)
1766             pipeline_pgrp = shell_pgrp;
1767
1768           /* If these signals are set to SIG_DFL, we encounter the curious
1769              situation of an interactive ^Z to a running process *working*
1770              and stopping the process, but being unable to do anything with
1771              that process to change its state.  On the other hand, if they
1772              are set to SIG_IGN, jobs started from scripts do not stop when
1773              the shell running the script gets a SIGTSTP and stops. */
1774
1775           default_tty_job_signals ();
1776         }
1777
1778 #if defined (PGRP_PIPE)
1779       /* Release the process group pipe, since our call to setpgid ()
1780          is done.  The last call to pipe_close is done in stop_pipeline. */
1781       pipe_close (pgrp_pipe);
1782 #endif /* PGRP_PIPE */
1783
1784       if (async_p)
1785         last_asynchronous_pid = mypid;
1786 #if defined (RECYCLES_PIDS)
1787       else if (last_asynchronous_pid == mypid)
1788         /* Avoid pid aliasing.  1 seems like a safe, unusual pid value. */
1789         last_asynchronous_pid = 1;
1790 #endif
1791     }
1792   else
1793     {
1794       /* In the parent.  Remember the pid of the child just created
1795          as the proper pgrp if this is the first child. */
1796
1797       if (first_pid == NO_PID)
1798         first_pid = pid;
1799       else if (pid_wrap == -1 && pid < first_pid)
1800         pid_wrap = 0;
1801       else if (pid_wrap == 0 && pid >= first_pid)
1802         pid_wrap = 1;
1803
1804       if (job_control)
1805         {
1806           if (pipeline_pgrp == 0)
1807             {
1808               pipeline_pgrp = pid;
1809               /* Don't twiddle terminal pgrps in the parent!  This is the bug,
1810                  not the good thing of twiddling them in the child! */
1811               /* give_terminal_to (pipeline_pgrp, 0); */
1812             }
1813           /* This is done on the recommendation of the Rationale section of
1814              the POSIX 1003.1 standard, where it discusses job control and
1815              shells.  It is done to avoid possible race conditions. (Ref.
1816              1003.1 Rationale, section B.4.3.3, page 236). */
1817           setpgid (pid, pipeline_pgrp);
1818         }
1819       else
1820         {
1821           if (pipeline_pgrp == 0)
1822             pipeline_pgrp = shell_pgrp;
1823         }
1824
1825       /* Place all processes into the jobs array regardless of the
1826          state of job_control. */
1827       add_process (command, pid);
1828
1829       if (async_p)
1830         last_asynchronous_pid = pid;
1831 #if defined (RECYCLES_PIDS)
1832       else if (last_asynchronous_pid == pid)
1833         /* Avoid pid aliasing.  1 seems like a safe, unusual pid value. */
1834         last_asynchronous_pid = 1;
1835 #endif
1836
1837       if (pid_wrap > 0)
1838         delete_old_job (pid);
1839
1840 #if !defined (RECYCLES_PIDS)
1841       /* Only check for saved status if we've saved more than CHILD_MAX
1842          statuses, unless the system recycles pids. */
1843       if ((js.c_reaped + bgpids.npid) >= js.c_childmax)
1844 #endif
1845         bgp_delete (pid);               /* new process, discard any saved status */
1846
1847       last_made_pid = pid;
1848
1849       /* keep stats */
1850       js.c_totforked++;
1851       js.c_living++;
1852
1853       /* Unblock SIGINT and SIGCHLD unless creating a pipeline, in which case
1854          SIGCHLD remains blocked until all commands in the pipeline have been
1855          created. */
1856       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1857     }
1858
1859   return (pid);
1860 }
1861
1862 /* These two functions are called only in child processes. */
1863 void
1864 ignore_tty_job_signals ()
1865 {
1866   set_signal_handler (SIGTSTP, SIG_IGN);
1867   set_signal_handler (SIGTTIN, SIG_IGN);
1868   set_signal_handler (SIGTTOU, SIG_IGN);
1869 }
1870
1871 void
1872 default_tty_job_signals ()
1873 {
1874   set_signal_handler (SIGTSTP, SIG_DFL);
1875   set_signal_handler (SIGTTIN, SIG_DFL);
1876   set_signal_handler (SIGTTOU, SIG_DFL);
1877 }
1878
1879 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1880    state kept in here.  When a job ends normally, we set the state in here
1881    to the state of the tty. */
1882
1883 static TTYSTRUCT shell_tty_info;
1884
1885 #if defined (NEW_TTY_DRIVER)
1886 static struct tchars shell_tchars;
1887 static struct ltchars shell_ltchars;
1888 #endif /* NEW_TTY_DRIVER */
1889
1890 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1891 /* Since the BSD tty driver does not allow us to change the tty modes
1892    while simultaneously waiting for output to drain and preserving
1893    typeahead, we have to drain the output ourselves before calling
1894    ioctl.  We cheat by finding the length of the output queue, and
1895    using select to wait for an appropriate length of time.  This is
1896    a hack, and should be labeled as such (it's a hastily-adapted
1897    mutation of a `usleep' implementation).  It's only reason for
1898    existing is the flaw in the BSD tty driver. */
1899
1900 static int ttspeeds[] =
1901 {
1902   0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1903   1800, 2400, 4800, 9600, 19200, 38400
1904 };
1905
1906 static void
1907 draino (fd, ospeed)
1908      int fd, ospeed;
1909 {
1910   register int delay = ttspeeds[ospeed];
1911   int n;
1912
1913   if (!delay)
1914     return;
1915
1916   while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1917     {
1918       if (n > (delay / 100))
1919         {
1920           struct timeval tv;
1921
1922           n *= 10;              /* 2 bits more for conservativeness. */
1923           tv.tv_sec = n / delay;
1924           tv.tv_usec = ((n % delay) * 1000000) / delay;
1925           select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1926         }
1927       else
1928         break;
1929     }
1930 }
1931 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1932
1933 /* Return the fd from which we are actually getting input. */
1934 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1935
1936 /* Fill the contents of shell_tty_info with the current tty info. */
1937 int
1938 get_tty_state ()
1939 {
1940   int tty;
1941
1942   tty = input_tty ();
1943   if (tty != -1)
1944     {
1945 #if defined (NEW_TTY_DRIVER)
1946       ioctl (tty, TIOCGETP, &shell_tty_info);
1947       ioctl (tty, TIOCGETC, &shell_tchars);
1948       ioctl (tty, TIOCGLTC, &shell_ltchars);
1949 #endif /* NEW_TTY_DRIVER */
1950
1951 #if defined (TERMIO_TTY_DRIVER)
1952       ioctl (tty, TCGETA, &shell_tty_info);
1953 #endif /* TERMIO_TTY_DRIVER */
1954
1955 #if defined (TERMIOS_TTY_DRIVER)
1956       if (tcgetattr (tty, &shell_tty_info) < 0)
1957         {
1958 #if 0
1959           /* Only print an error message if we're really interactive at
1960              this time. */
1961           if (interactive)
1962             sys_error ("[%ld: %d] tcgetattr", (long)getpid (), shell_level);
1963 #endif
1964           return -1;
1965         }
1966 #endif /* TERMIOS_TTY_DRIVER */
1967       if (check_window_size)
1968         get_new_window_size (0, (int *)0, (int *)0);
1969     }
1970   return 0;
1971 }
1972
1973 /* Make the current tty use the state in shell_tty_info. */
1974 int
1975 set_tty_state ()
1976 {
1977   int tty;
1978
1979   tty = input_tty ();
1980   if (tty != -1)
1981     {
1982 #if defined (NEW_TTY_DRIVER)
1983 #  if defined (DRAIN_OUTPUT)
1984       draino (tty, shell_tty_info.sg_ospeed);
1985 #  endif /* DRAIN_OUTPUT */
1986       ioctl (tty, TIOCSETN, &shell_tty_info);
1987       ioctl (tty, TIOCSETC, &shell_tchars);
1988       ioctl (tty, TIOCSLTC, &shell_ltchars);
1989 #endif /* NEW_TTY_DRIVER */
1990
1991 #if defined (TERMIO_TTY_DRIVER)
1992       ioctl (tty, TCSETAW, &shell_tty_info);
1993 #endif /* TERMIO_TTY_DRIVER */
1994
1995 #if defined (TERMIOS_TTY_DRIVER)
1996       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1997         {
1998           /* Only print an error message if we're really interactive at
1999              this time. */
2000           if (interactive)
2001             sys_error ("[%ld: %d] tcsetattr", (long)getpid (), shell_level);
2002           return -1;
2003         }
2004 #endif /* TERMIOS_TTY_DRIVER */
2005     }
2006   return 0;
2007 }
2008
2009 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2010    process in that job's pipeline.  This is the one whose exit status
2011    counts.  Must be called with SIGCHLD blocked or queued. */
2012 static PROCESS *
2013 find_last_proc (job, block)
2014      int job;
2015      int block;
2016 {
2017   register PROCESS *p;
2018   sigset_t set, oset;
2019
2020   if (block)
2021     BLOCK_CHILD (set, oset);
2022
2023   p = jobs[job]->pipe;
2024   while (p && p->next != jobs[job]->pipe)
2025     p = p->next;
2026
2027   if (block)
2028     UNBLOCK_CHILD (oset);
2029
2030   return (p);
2031 }
2032
2033 static pid_t
2034 find_last_pid (job, block)
2035      int job;
2036      int block;
2037 {
2038   PROCESS *p;
2039
2040   p = find_last_proc (job, block);
2041   /* Possible race condition here. */
2042   return p->pid;
2043 }     
2044
2045 /* Wait for a particular child of the shell to finish executing.
2046    This low-level function prints an error message if PID is not
2047    a child of this shell.  It returns -1 if it fails, or whatever
2048    wait_for returns otherwise.  If the child is not found in the
2049    jobs table, it returns 127. */
2050 int
2051 wait_for_single_pid (pid)
2052      pid_t pid;
2053 {
2054   register PROCESS *child;
2055   sigset_t set, oset;
2056   int r, job;
2057
2058   BLOCK_CHILD (set, oset);
2059   child = find_pipeline (pid, 0, (int *)NULL);
2060   UNBLOCK_CHILD (oset);
2061
2062   if (child == 0)
2063     {
2064       r = bgp_search (pid);
2065       if (r >= 0)
2066         return r;
2067     }
2068
2069   if (child == 0)
2070     {
2071       internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid);
2072       return (127);
2073     }
2074
2075   r = wait_for (pid);
2076
2077   /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2078      table. */
2079   BLOCK_CHILD (set, oset);
2080   job = find_job (pid, 0, NULL);
2081   if (job != NO_JOB && jobs[job] && DEADJOB (job))
2082     jobs[job]->flags |= J_NOTIFIED;
2083   UNBLOCK_CHILD (oset);
2084
2085   /* If running in posix mode, remove the job from the jobs table immediately */
2086   if (posixly_correct)
2087     {
2088       cleanup_dead_jobs ();
2089       bgp_delete (pid);
2090     }
2091
2092   return r;
2093 }
2094
2095 /* Wait for all of the backgrounds of this shell to finish. */
2096 void
2097 wait_for_background_pids ()
2098 {
2099   register int i, r, waited_for;
2100   sigset_t set, oset;
2101   pid_t pid;
2102
2103   for (waited_for = 0;;)
2104     {
2105       BLOCK_CHILD (set, oset);
2106
2107       /* find first running job; if none running in foreground, break */
2108       /* XXX could use js.j_firstj and js.j_lastj here */
2109       for (i = 0; i < js.j_jobslots; i++)
2110         {
2111 #if defined (DEBUG)
2112           if (i < js.j_firstj && jobs[i])
2113             itrace("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
2114           if (i > js.j_lastj && jobs[i])
2115             itrace("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i, js.j_lastj);
2116 #endif
2117           if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
2118             break;
2119         }
2120       if (i == js.j_jobslots)
2121         {
2122           UNBLOCK_CHILD (oset);
2123           break;
2124         }
2125
2126       /* now wait for the last pid in that job. */
2127       pid = find_last_pid (i, 0);
2128       UNBLOCK_CHILD (oset);
2129       QUIT;
2130       errno = 0;                /* XXX */
2131       r = wait_for_single_pid (pid);
2132       if (r == -1)
2133         {
2134           /* If we're mistaken about job state, compensate. */
2135           if (errno == ECHILD)
2136             mark_all_jobs_as_dead ();
2137         }
2138       else
2139         waited_for++;
2140     }
2141
2142   /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2143      `wait' is called with no arguments. */
2144   mark_dead_jobs_as_notified (1);
2145   cleanup_dead_jobs ();
2146   bgp_clear ();
2147 }
2148
2149 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2150 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2151 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
2152
2153 static void
2154 restore_sigint_handler ()
2155 {
2156   if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
2157     {
2158       set_signal_handler (SIGINT, old_sigint_handler);
2159       old_sigint_handler = INVALID_SIGNAL_HANDLER;
2160     }
2161 }
2162
2163 static int wait_sigint_received;
2164
2165 /* Handle SIGINT while we are waiting for children in a script to exit.
2166    The `wait' builtin should be interruptible, but all others should be
2167    effectively ignored (i.e. not cause the shell to exit). */
2168 static sighandler
2169 wait_sigint_handler (sig)
2170      int sig;
2171 {
2172   SigHandler *sigint_handler;
2173
2174   if (interrupt_immediately ||
2175       (this_shell_builtin && this_shell_builtin == wait_builtin))
2176     {
2177       last_command_exit_value = EXECUTION_FAILURE;
2178       restore_sigint_handler ();
2179       /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2180          what POSIX.2 says (see builtins/wait.def for more info). */
2181       if (this_shell_builtin && this_shell_builtin == wait_builtin &&
2182           signal_is_trapped (SIGINT) &&
2183           ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
2184         {
2185           interrupt_immediately = 0;
2186           trap_handler (SIGINT);        /* set pending_traps[SIGINT] */
2187           wait_signal_received = SIGINT;
2188           longjmp (wait_intr_buf, 1);
2189         }
2190       
2191       ADDINTERRUPT;
2192       QUIT;
2193     }
2194
2195   /* XXX - should this be interrupt_state?  If it is, the shell will act
2196      as if it got the SIGINT interrupt. */
2197   wait_sigint_received = 1;
2198
2199   /* Otherwise effectively ignore the SIGINT and allow the running job to
2200      be killed. */
2201   SIGRETURN (0);
2202 }
2203
2204 static int
2205 process_exit_signal (status)
2206      WAIT status;
2207 {
2208   return (WIFSIGNALED (status) ? WTERMSIG (status) : 0);
2209 }
2210
2211 static int
2212 process_exit_status (status)
2213      WAIT status;
2214 {
2215   if (WIFSIGNALED (status))
2216     return (128 + WTERMSIG (status));
2217   else if (WIFSTOPPED (status) == 0)
2218     return (WEXITSTATUS (status));
2219   else
2220     return (EXECUTION_SUCCESS);
2221 }
2222
2223 static WAIT
2224 job_signal_status (job)
2225      int job;
2226 {
2227   register PROCESS *p;
2228   WAIT s;
2229
2230   p = jobs[job]->pipe;
2231   do
2232     {
2233       s = p->status;
2234       if (WIFSIGNALED(s) || WIFSTOPPED(s))
2235         break;
2236       p = p->next;
2237     }
2238   while (p != jobs[job]->pipe);
2239
2240   return s;
2241 }
2242   
2243 /* Return the exit status of the last process in the pipeline for job JOB.
2244    This is the exit status of the entire job. */
2245 static WAIT
2246 raw_job_exit_status (job)
2247      int job;
2248 {
2249   register PROCESS *p;
2250   int fail;
2251
2252   if (pipefail_opt)
2253     {
2254       fail = 0;
2255       p = jobs[job]->pipe;
2256       do
2257         {
2258           if (p->status != EXECUTION_SUCCESS) fail = p->status;
2259           p = p->next;
2260         }
2261       while (p != jobs[job]->pipe);
2262       return fail;
2263     }
2264
2265   for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
2266     ;
2267   return (p->status);
2268 }
2269
2270 /* Return the exit status of job JOB.  This is the exit status of the last
2271    (rightmost) process in the job's pipeline, modified if the job was killed
2272    by a signal or stopped. */
2273 static int
2274 job_exit_status (job)
2275      int job;
2276 {
2277   return (process_exit_status (raw_job_exit_status (job)));
2278 }
2279
2280 static int
2281 job_exit_signal (job)
2282      int job;
2283 {
2284   return (process_exit_signal (raw_job_exit_status (job)));
2285 }
2286
2287 #define FIND_CHILD(pid, child) \
2288   do \
2289     { \
2290       child = find_pipeline (pid, 0, (int *)NULL); \
2291       if (child == 0) \
2292         { \
2293           give_terminal_to (shell_pgrp, 0); \
2294           UNBLOCK_CHILD (oset); \
2295           internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2296           restore_sigint_handler (); \
2297           return (termination_state = 127); \
2298         } \
2299     } \
2300   while (0)
2301
2302 /* Wait for pid (one of our children) to terminate, then
2303    return the termination state.  Returns 127 if PID is not found in
2304    the jobs table.  Returns -1 if waitchld() returns -1, indicating
2305    that there are no unwaited-for child processes. */
2306 int
2307 wait_for (pid)
2308      pid_t pid;
2309 {
2310   int job, termination_state, r;
2311   WAIT s;
2312   register PROCESS *child;
2313   sigset_t set, oset;
2314   register PROCESS *p;
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
2453 if (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
2544 wait_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. */
2557 int
2558 wait_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. */
2587 void
2588 notify_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. */
2601 void
2602 reap_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. */
2611 static int
2612 most_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. */
2637 static int
2638 job_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. */
2646 static int
2647 job_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. */
2655 static void
2656 set_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
2716 static void
2717 reset_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. */
2750 static void
2751 set_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. */
2775 int
2776 start_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. */
2892 int
2893 kill_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. */
2968 static sighandler
2969 sigchld_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. */
2991 static int
2992 waitchld (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. */
3116 static int
3117 set_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. */
3288 static void
3289 setjstatus (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
3318 static void
3319 run_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. */
3364 static void
3365 notify_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. */
3501 int
3502 initialize_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
3611 void
3612 debug_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. */
3623 static int
3624 set_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. */
3679 void
3680 initialize_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. */
3700 static sighandler
3701 sigcont_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. */
3712 static sighandler
3713 sigstop_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.  */
3730 int
3731 give_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. */
3771 void
3772 delete_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. */
3813 void
3814 nohup_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
3833 int
3834 count_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
3857 static void
3858 mark_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. */
3883 static void
3884 mark_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
3953 itrace("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. */
3993 void
3994 unfreeze_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. */
4001 int
4002 set_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. */
4020 void
4021 without_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. */
4035 void
4036 end_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. */
4052 void
4053 restart_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. */
4061 void
4062 set_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. */
4070 static void
4071 pipe_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. */
4090 static void
4091 pipe_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. */
4104 void
4105 close_pgrp_pipe ()
4106 {
4107   pipe_close (pgrp_pipe);
4108 }
4109
4110 #endif /* PGRP_PIPE */