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