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