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