1 /* The thing that makes children, remembers them, and contains wait loops. */
3 /* This file works under BSD, System V, minix, and Posix systems. It does
4 not implement job control. */
6 /* Copyright (C) 1987, 1989, 1992 Free Software Foundation, Inc.
8 This file is part of GNU Bash, the Bourne Again SHell.
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
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
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. */
26 #include "bashtypes.h"
29 #if defined (HAVE_UNISTD_H)
37 #if defined (BUFFERED_INPUT)
41 /* Need to include this up here for *_TTY_DRIVER definitions. */
44 #if !defined (STRUCT_WINSIZE_IN_SYS_IOCTL)
45 /* For struct winsize on SCO */
46 /* sys/ptem.h has winsize but needs mblk_t from sys/stream.h */
47 # if defined (HAVE_SYS_PTEM_H) && defined (TIOCGWINSZ) && defined (SIGWINCH)
48 # if defined (HAVE_SYS_STREAM_H)
49 # include <sys/stream.h>
51 # include <sys/ptem.h>
52 # endif /* HAVE_SYS_PTEM_H && TIOCGWINSZ && SIGWINCH */
53 #endif /* !STRUCT_WINSIZE_IN_SYS_IOCTL */
60 #include "builtins/builtext.h" /* for wait_builtin */
62 #define DEFAULT_CHILD_MAX 32
64 #if defined (_POSIX_VERSION) || !defined (HAVE_KILLPG)
65 # define killpg(pg, sig) kill(-(pg),(sig))
66 #endif /* USG || _POSIX_VERSION */
68 #if !defined (HAVE_SIGINTERRUPT) && !defined (HAVE_POSIX_SIGNALS)
69 # define siginterrupt(sig, code)
70 #endif /* !HAVE_SIGINTERRUPT && !HAVE_POSIX_SIGNALS */
72 #if defined (HAVE_WAITPID)
73 # define WAITPID(pid, statusp, options) waitpid (pid, statusp, options)
75 # define WAITPID(pid, statusp, options) wait (statusp)
76 #endif /* !HAVE_WAITPID */
78 /* Return the fd from which we are actually getting input. */
79 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
85 #if defined (READLINE)
86 extern void rl_set_screen_size __P((int, int));
89 extern int interactive, interactive_shell, login_shell;
90 extern int subshell_environment;
91 extern int last_command_exit_value, last_command_exit_signal;
92 extern int interrupt_immediately;
93 extern sh_builtin_func_t *this_shell_builtin;
94 #if defined (HAVE_POSIX_SIGNALS)
95 extern sigset_t top_level_mask;
97 extern procenv_t wait_intr_buf;
98 extern int wait_signal_received;
100 pid_t last_made_pid = NO_PID;
101 pid_t last_asynchronous_pid = NO_PID;
103 /* Call this when you start making children. */
104 int already_making_children = 0;
106 /* The controlling tty for this shell. */
109 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
110 exits from get_tty_state(). */
111 int check_window_size;
113 /* STATUS and FLAGS are only valid if pid != NO_PID
114 STATUS is only valid if (flags & PROC_RUNNING) == 0 */
117 int status; /* Exit status of PID or 128 + fatal signal number */
121 /* Values for proc_status.flags */
122 #define PROC_RUNNING 0x01
123 #define PROC_NOTIFIED 0x02
124 #define PROC_ASYNC 0x04
125 #define PROC_SIGNALED 0x10
127 /* Return values from find_status_by_pid */
129 #define PROC_STILL_ALIVE -2
131 static struct proc_status *pid_list = (struct proc_status *)NULL;
132 static int pid_list_size;
133 static int wait_sigint_received;
135 static long child_max = -1L;
137 static void alloc_pid_list __P((void));
138 static int find_proc_slot __P((void));
139 static int find_index_by_pid __P((pid_t));
140 static int find_status_by_pid __P((pid_t));
141 static int process_exit_status __P((WAIT));
142 static int find_termsig_by_pid __P((pid_t));
143 static int get_termsig __P((WAIT));
144 static void set_pid_status __P((pid_t, WAIT));
145 static void set_pid_flags __P((pid_t, int));
146 static void unset_pid_flags __P((pid_t, int));
147 static int get_pid_flags __P((pid_t));
148 static void add_pid __P((pid_t, int));
149 static void mark_dead_jobs_as_notified __P((int));
151 static void get_new_window_size __P((int));
152 static sighandler sigwinch_sighandler __P((int));
153 static sighandler wait_sigint_handler __P((int));
154 static char *j_strsignal __P((int));
156 #if defined (HAVE_WAITPID)
157 static void reap_zombie_children __P((void));
160 #if !defined (HAVE_SIGINTERRUPT) && defined (HAVE_POSIX_SIGNALS)
161 static int siginterrupt __P((int, int));
164 static void restore_sigint_handler __P((void));
166 /* Allocate new, or grow existing PID_LIST. */
171 int old = pid_list_size;
174 pid_list = (struct proc_status *)xrealloc (pid_list, pid_list_size * sizeof (struct proc_status));
176 /* None of the newly allocated slots have process id's yet. */
177 for (i = old; i < pid_list_size; i++)
178 pid_list[i].pid = NO_PID;
181 /* Return the offset within the PID_LIST array of an empty slot. This can
182 create new slots if all of the existing slots are taken. */
188 for (i = 0; i < pid_list_size; i++)
189 if (pid_list[i].pid == NO_PID)
192 if (i == pid_list_size)
198 /* Return the offset within the PID_LIST array of a slot containing PID,
199 or the value NO_PID if the pid wasn't found. */
201 find_index_by_pid (pid)
206 for (i = 0; i < pid_list_size; i++)
207 if (pid_list[i].pid == pid)
213 /* Return the status of PID as looked up in the PID_LIST array. A
214 return value of PROC_BAD indicates that PID wasn't found. */
216 find_status_by_pid (pid)
221 i = find_index_by_pid (pid);
224 if (pid_list[i].flags & PROC_RUNNING)
225 return (PROC_STILL_ALIVE);
226 return (pid_list[i].status);
230 process_exit_status (status)
233 if (WIFSIGNALED (status))
234 return (128 + WTERMSIG (status));
236 return (WEXITSTATUS (status));
239 /* Return the status of PID as looked up in the PID_LIST array. A
240 return value of PROC_BAD indicates that PID wasn't found. */
242 find_termsig_by_pid (pid)
247 i = find_index_by_pid (pid);
250 if (pid_list[i].flags & PROC_RUNNING)
252 return (get_termsig (pid_list[i].status));
255 /* Set LAST_COMMAND_EXIT_SIGNAL depending on STATUS. If STATUS is -1, look
256 up PID in the pid array and set LAST_COMMAND_EXIT_SIGNAL appropriately
257 depending on its flags and exit status. */
262 if (WIFSTOPPED (status) == 0 && WIFSIGNALED (status))
263 return (WTERMSIG (status));
268 /* Give PID the status value STATUS in the PID_LIST array. */
270 set_pid_status (pid, status)
276 slot = find_index_by_pid (pid);
280 pid_list[slot].status = process_exit_status (status);
281 pid_list[slot].flags &= ~PROC_RUNNING;
282 if (WIFSIGNALED (status))
283 pid_list[slot].flags |= PROC_SIGNALED;
284 /* If it's not a background process, mark it as notified so it gets
286 if ((pid_list[slot].flags & PROC_ASYNC) == 0)
287 pid_list[slot].flags |= PROC_NOTIFIED;
290 /* Give PID the flags FLAGS in the PID_LIST array. */
292 set_pid_flags (pid, flags)
298 slot = find_index_by_pid (pid);
302 pid_list[slot].flags |= flags;
305 /* Unset FLAGS for PID in the pid list */
307 unset_pid_flags (pid, flags)
313 slot = find_index_by_pid (pid);
317 pid_list[slot].flags &= ~flags;
320 /* Return the flags corresponding to PID in the PID_LIST array. */
327 slot = find_index_by_pid (pid);
331 return (pid_list[slot].flags);
341 slot = find_proc_slot ();
343 pid_list[slot].pid = pid;
344 pid_list[slot].status = -1;
345 pid_list[slot].flags = PROC_RUNNING;
347 pid_list[slot].flags |= PROC_ASYNC;
351 mark_dead_jobs_as_notified (force)
354 register int i, ndead;
356 /* first, count the number of non-running async jobs if FORCE == 0 */
357 for (i = ndead = 0; force == 0 && i < pid_list_size; i++)
359 if (pid_list[i].pid == NO_PID)
361 if (((pid_list[i].flags & PROC_RUNNING) == 0) &&
362 (pid_list[i].flags & PROC_ASYNC))
367 child_max = getmaxchild ();
369 child_max = DEFAULT_CHILD_MAX;
371 if (force == 0 && ndead <= child_max)
374 /* If FORCE == 0, we just mark as many non-running async jobs as notified
375 to bring us under the CHILD_MAX limit. */
376 for (i = 0; i < pid_list_size; i++)
378 if (pid_list[i].pid == NO_PID)
380 if (((pid_list[i].flags & PROC_RUNNING) == 0) &&
381 pid_list[i].pid != last_asynchronous_pid)
383 pid_list[i].flags |= PROC_NOTIFIED;
384 if (force == 0 && (pid_list[i].flags & PROC_ASYNC) && --ndead <= child_max)
390 /* Remove all dead, notified jobs from the pid_list. */
396 #if defined (HAVE_WAITPID)
397 reap_zombie_children ();
400 for (i = 0; i < pid_list_size; i++)
402 if ((pid_list[i].flags & PROC_RUNNING) == 0 &&
403 (pid_list[i].flags & PROC_NOTIFIED))
404 pid_list[i].pid = NO_PID;
413 mark_dead_jobs_as_notified (0);
414 cleanup_dead_jobs ();
417 /* Initialize the job control mechanism, and set up the tty stuff. */
418 initialize_job_control (force)
421 shell_tty = fileno (stderr);
427 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
428 static SigHandler *old_winch = (SigHandler *)SIG_DFL;
431 get_new_window_size (from_sig)
438 if (tty >= 0 && (ioctl (tty, TIOCGWINSZ, &win) == 0) &&
439 win.ws_row > 0 && win.ws_col > 0)
442 shell_tty_info.c_winsize = win; /* structure copying */
444 sh_set_lines_and_columns (win.ws_row, win.ws_col);
445 #if defined (READLINE)
446 rl_set_screen_size (win.ws_row, win.ws_col);
452 sigwinch_sighandler (sig)
455 #if defined (MUST_REINSTALL_SIGHANDLERS)
456 set_signal_handler (SIGWINCH, sigwinch_sighandler);
457 #endif /* MUST_REINSTALL_SIGHANDLERS */
458 get_new_window_size (1);
462 get_new_window_size (from_sig)
466 #endif /* TIOCGWINSZ && SIGWINCH */
469 set_sigwinch_handler ()
471 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
472 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
477 unset_sigwinch_handler ()
479 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
480 set_signal_handler (SIGWINCH, old_winch);
484 /* Setup this shell to handle C-C, etc. */
486 initialize_job_signals ()
488 set_signal_handler (SIGINT, sigint_sighandler);
489 set_sigwinch_handler ();
491 /* If this is a login shell we don't wish to be disturbed by
494 ignore_tty_job_signals ();
497 #if defined (HAVE_WAITPID)
498 /* Collect the status of all zombie children so that their system
499 resources can be deallocated. */
501 reap_zombie_children ()
503 # if defined (WNOHANG)
507 while ((pid = waitpid (-1, (int *)&status, WNOHANG)) > 0)
508 set_pid_status (pid, status);
509 # endif /* WNOHANG */
513 #if !defined (HAVE_SIGINTERRUPT) && defined (HAVE_POSIX_SIGNALS)
515 siginterrupt (sig, flag)
518 struct sigaction act;
520 sigaction (sig, (struct sigaction *)NULL, &act);
523 act.sa_flags &= ~SA_RESTART;
525 act.sa_flags |= SA_RESTART;
527 return (sigaction (sig, &act, (struct sigaction *)NULL));
529 #endif /* !HAVE_SIGINTERRUPT && HAVE_POSIX_SIGNALS */
531 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
532 COMMAND is just for remembering the name of the command; we don't do
533 anything else with it. ASYNC_P says what to do with the tty. If
534 non-zero, then don't give it away. */
536 make_child (command, async_p)
541 #if defined (HAVE_WAITPID)
543 #endif /* HAVE_WAITPID */
545 /* Discard saved memory. */
551 #if defined (BUFFERED_INPUT)
552 /* If default_buffered_input is active, we are reading a script. If
553 the command is asynchronous, we have already duplicated /dev/null
554 as fd 0, but have not changed the buffered stream corresponding to
555 the old fd 0. We don't want to sync the stream in this case. */
556 if (default_buffered_input != -1 && (!async_p || default_buffered_input > 0))
557 sync_buffered_stream (default_buffered_input);
558 #endif /* BUFFERED_INPUT */
560 /* Create the child, handle severe errors. */
561 #if defined (HAVE_WAITPID)
563 #endif /* HAVE_WAITPID */
565 if ((pid = fork ()) < 0)
567 #if defined (HAVE_WAITPID)
568 /* Posix systems with a non-blocking waitpid () system call available
569 get another chance after zombies are reaped. */
570 if (errno == EAGAIN && retry)
572 reap_zombie_children ();
576 #endif /* HAVE_WAITPID */
580 throw_to_top_level ();
585 #if defined (BUFFERED_INPUT)
586 unset_bash_input (0);
587 #endif /* BUFFERED_INPUT */
589 #if defined (HAVE_POSIX_SIGNALS)
590 /* Restore top-level signal mask. */
591 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
594 /* Ignore INT and QUIT in asynchronous children. */
596 last_asynchronous_pid = getpid ();
598 default_tty_job_signals ();
607 last_asynchronous_pid = pid;
609 add_pid (pid, async_p);
615 ignore_tty_job_signals ()
617 #if defined (SIGTSTP)
618 set_signal_handler (SIGTSTP, SIG_IGN);
619 set_signal_handler (SIGTTIN, SIG_IGN);
620 set_signal_handler (SIGTTOU, SIG_IGN);
625 default_tty_job_signals ()
627 #if defined (SIGTSTP)
628 set_signal_handler (SIGTSTP, SIG_DFL);
629 set_signal_handler (SIGTTIN, SIG_DFL);
630 set_signal_handler (SIGTTOU, SIG_DFL);
634 /* Wait for a single pid (PID) and return its exit status. Called by
637 wait_for_single_pid (pid)
644 pstatus = find_status_by_pid (pid);
646 if (pstatus == PROC_BAD)
648 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid);
652 if (pstatus != PROC_STILL_ALIVE)
655 last_command_exit_signal = find_termsig_by_pid (pid);
659 siginterrupt (SIGINT, 1);
660 while ((got_pid = WAITPID (pid, &status, 0)) != pid)
664 if (errno != EINTR && errno != ECHILD)
666 siginterrupt (SIGINT, 0);
671 else if (got_pid > 0)
672 set_pid_status (got_pid, status);
677 set_pid_status (got_pid, status);
678 set_pid_flags (got_pid, PROC_NOTIFIED);
681 siginterrupt (SIGINT, 0);
684 return (got_pid > 0 ? process_exit_status (status) : -1);
687 /* Wait for all of the shell's children to exit. Called by the `wait'
690 wait_for_background_pids ()
695 /* If we aren't using job control, we let the kernel take care of the
696 bookkeeping for us. wait () will return -1 and set errno to ECHILD
697 when there are no more unwaited-for child processes on both
698 4.2 BSD-based and System V-based systems. */
700 siginterrupt (SIGINT, 1);
702 /* Wait for ECHILD */
703 while ((got_pid = WAITPID (-1, &status, 0)) != -1)
704 set_pid_status (got_pid, status);
706 if (errno != EINTR && errno != ECHILD)
708 siginterrupt (SIGINT, 0);
712 siginterrupt (SIGINT, 0);
715 mark_dead_jobs_as_notified (1);
716 cleanup_dead_jobs ();
719 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
720 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
721 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
724 restore_sigint_handler ()
726 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
728 set_signal_handler (SIGINT, old_sigint_handler);
729 old_sigint_handler = INVALID_SIGNAL_HANDLER;
733 /* Handle SIGINT while we are waiting for children in a script to exit.
734 All interrupts are effectively ignored by the shell, but allowed to
735 kill a running job. */
737 wait_sigint_handler (sig)
740 SigHandler *sigint_handler;
742 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
743 what POSIX.2 says (see builtins/wait.def for more info). */
744 if (this_shell_builtin && this_shell_builtin == wait_builtin &&
745 signal_is_trapped (SIGINT) &&
746 ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
748 last_command_exit_value = EXECUTION_FAILURE;
749 restore_sigint_handler ();
750 interrupt_immediately = 0;
751 trap_handler (SIGINT); /* set pending_traps[SIGINT] */
752 wait_signal_received = SIGINT;
753 longjmp (wait_intr_buf, 1);
756 if (interrupt_immediately)
758 last_command_exit_value = EXECUTION_FAILURE;
759 restore_sigint_handler ();
764 wait_sigint_received = 1;
773 static char retcode_name_buffer[64] = { '\0' };
779 x = retcode_name_buffer;
780 sprintf (x, "Signal %d", s);
785 /* Wait for pid (one of our children) to terminate. This is called only
786 by the execution code in execute_cmd.c. */
791 int return_val, pstatus;
795 pstatus = find_status_by_pid (pid);
797 if (pstatus == PROC_BAD)
800 if (pstatus != PROC_STILL_ALIVE)
803 last_command_exit_signal = find_termsig_by_pid (pid);
807 /* If we are running a script, ignore SIGINT while we're waiting for
808 a child to exit. The loop below does some of this, but not all. */
809 wait_sigint_received = 0;
810 if (interactive_shell == 0)
811 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
813 while ((got_pid = WAITPID (-1, &status, 0)) != pid) /* XXX was pid now -1 */
815 if (got_pid < 0 && errno == ECHILD)
817 #if !defined (_POSIX_VERSION)
818 status.w_termsig = status.w_retcode = 0;
821 #endif /* _POSIX_VERSION */
824 else if (got_pid < 0 && errno != EINTR)
825 programming_error ("wait_for(%ld): %s", (long)pid, strerror(errno));
826 else if (got_pid > 0)
827 set_pid_status (got_pid, status);
831 set_pid_status (got_pid, status);
833 #if defined (HAVE_WAITPID)
835 reap_zombie_children ();
836 #endif /* HAVE_WAITPID */
838 if (interactive_shell == 0)
840 SigHandler *temp_handler;
842 temp_handler = old_sigint_handler;
843 restore_sigint_handler ();
845 /* If the job exited because of SIGINT, make sure the shell acts as if
846 it had received one also. */
847 if (WIFSIGNALED (status) && (WTERMSIG (status) == SIGINT))
850 if (maybe_call_trap_handler (SIGINT) == 0)
852 if (temp_handler == SIG_DFL)
853 termination_unwind_protect (SIGINT);
854 else if (temp_handler != INVALID_SIGNAL_HANDLER && temp_handler != SIG_IGN)
855 (*temp_handler) (SIGINT);
860 /* Default return value. */
861 /* ``a full 8 bits of status is returned'' */
862 return_val = process_exit_status (status);
863 last_command_exit_signal = get_termsig (status);
865 #if !defined (DONT_REPORT_SIGPIPE)
866 if ((WIFSTOPPED (status) == 0) && WIFSIGNALED (status) &&
867 (WTERMSIG (status) != SIGINT))
869 if ((WIFSTOPPED (status) == 0) && WIFSIGNALED (status) &&
870 (WTERMSIG (status) != SIGINT) && (WTERMSIG (status) != SIGPIPE))
873 fprintf (stderr, "%s", j_strsignal (WTERMSIG (status)));
874 if (WIFCORED (status))
875 fprintf (stderr, " (core dumped)");
876 fprintf (stderr, "\n");
879 if (interactive_shell && subshell_environment == 0)
881 if (WIFSIGNALED (status) || WIFSTOPPED (status))
890 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
891 If PID does belong to a job, and the job is stopped, then CONTinue the
892 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
893 then kill the process group associated with PID. */
895 kill_pid (pid, signal, group)
901 result = group ? killpg (pid, signal) : kill (pid, signal);
905 static TTYSTRUCT shell_tty_info;
906 static int got_tty_state;
908 /* Fill the contents of shell_tty_info with the current tty info. */
916 ttgetattr (tty, &shell_tty_info);
918 if (check_window_size)
919 get_new_window_size (0);
923 /* Make the current tty use the state in shell_tty_info. */
932 if (got_tty_state == 0)
934 ttsetattr (tty, &shell_tty_info);
939 /* Give the terminal to PGRP. */
940 give_terminal_to (pgrp, force)
946 /* Stop a pipeline. */
948 stop_pipeline (async, ignore)
952 already_making_children = 0;
959 already_making_children = 1;
963 stop_making_children ()
965 already_making_children = 0;
969 get_job_by_pid (pid, block)
975 i = find_index_by_pid (pid);
976 return ((i == NO_PID) ? PROC_BAD : i);
979 /* Print descriptive information about the job with leader pid PID. */
984 fprintf (stderr, "%ld\n", (long) pid);
988 unfreeze_jobs_list ()