1 /* The thing that makes children, remembers them, and contains wait loops. */
3 /* This file works with both POSIX and BSD systems. It implements job
6 /* Copyright (C) 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"
32 #if defined (HAVE_UNISTD_H)
36 #if defined (HAVE_SYS_TIME_H)
37 # include <sys/time.h>
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 */
46 #include <sys/ioctl.h>
47 #include <sys/param.h>
49 #if defined (BUFFERED_INPUT)
53 /* Need to include this up here for *_TTY_DRIVER definitions. */
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 */
60 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
61 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
63 #endif /* hpux && !TERMIOS_TTY_DRIVER */
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>
72 # include <sys/ptem.h>
73 # endif /* HAVE_SYS_PTEM_H && TIOCGWINSZ && SIGWINCH */
74 #endif /* !STRUCT_WINSIZE_IN_SYS_IOCTL */
81 #include "builtins/builtext.h"
82 #include "builtins/common.h"
88 #if !defined (CHILD_MAX)
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. */
96 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
97 # define WAITPID(pid, statusp, options) \
98 wait3 ((union wait *)statusp, options, (struct rusage *)0)
100 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
101 # define WAITPID(pid, statusp, options) \
102 waitpid ((pid_t)pid, statusp, options)
104 # if defined (HAVE_WAIT3)
105 # define WAITPID(pid, statusp, options) \
106 wait3 (statusp, options, (struct rusage *)0)
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) */
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 ()
119 # define getpgid(p) getpgrp (p)
120 #endif /* !GETPGRP_VOID */
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)
127 # define REINSTALL_SIGCHLD_HANDLER
128 #endif /* !MUST_REINSTALL_SIGHANDLERS */
130 /* The number of additional slots to allocate when we run out. */
133 #if defined (READLINE)
134 extern void _rl_set_screen_size ();
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 Function *this_shell_builtin;
144 extern char *shell_name, *this_command_name;
145 extern sigset_t top_level_mask;
146 extern procenv_t wait_intr_buf;
147 extern WORD_LIST *subst_assign_varlist;
149 #if defined (ARRAY_VARS)
150 static int *pstatuses; /* list of pipeline statuses */
153 static void setjstatus ();
154 static void get_new_window_size ();
156 /* The array of known jobs. */
157 JOB **jobs = (JOB **)NULL;
159 /* The number of slots currently allocated to JOBS. */
162 /* The controlling tty for this shell. */
165 /* The shell's process group. */
166 pid_t shell_pgrp = NO_PID;
168 /* The terminal's process group. */
169 pid_t terminal_pgrp = NO_PID;
171 /* The process group of the shell's parent. */
172 pid_t original_pgrp = NO_PID;
174 /* The process group of the pipeline currently being made. */
175 pid_t pipeline_pgrp = (pid_t)0;
177 #if defined (PGRP_PIPE)
178 /* Pipes which each shell uses to communicate with the process group leader
179 until all of the processes in a pipeline have been started. Then the
180 process leader is allowed to continue. */
181 int pgrp_pipe[2] = { -1, -1 };
184 /* The job which is current; i.e. the one that `%+' stands for. */
185 int current_job = NO_JOB;
187 /* The previous job; i.e. the one that `%-' stands for. */
188 int previous_job = NO_JOB;
190 /* Last child made by the shell. */
191 pid_t last_made_pid = NO_PID;
193 /* Pid of the last asynchronous child. */
194 pid_t last_asynchronous_pid = NO_PID;
196 /* The pipeline currently being built. */
197 PROCESS *the_pipeline = (PROCESS *)NULL;
199 /* If this is non-zero, do job control. */
202 /* Call this when you start making children. */
203 int already_making_children = 0;
205 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
206 exits from get_tty_state(). */
207 int check_window_size;
209 /* Functions local to this file. */
210 static sighandler sigchld_handler ();
211 static int waitchld ();
212 static PROCESS *find_pipeline ();
213 static char *current_working_directory ();
214 static char *job_working_directory ();
215 static pid_t find_last_pid (), last_pid ();
216 static int set_new_line_discipline (), map_over_jobs (), last_running_job ();
217 static int most_recent_job_in_state (), last_stopped_job (), find_job ();
218 static void notify_of_job_status (), cleanup_dead_jobs (), discard_pipeline ();
219 static void add_process (), set_current_job (), reset_current ();
220 static void print_pipeline ();
221 static void pretty_print_job ();
222 static void mark_all_jobs_as_dead ();
223 static void mark_dead_jobs_as_notified ();
224 #if defined (PGRP_PIPE)
225 static void pipe_read (), pipe_close ();
228 /* Used to synchronize between wait_for and the SIGCHLD signal handler. */
230 static int waiting_for_job;
232 /* A place to temporarily save the current pipeline. */
233 static PROCESS *saved_pipeline;
234 static int saved_already_making_children;
236 /* Set this to non-zero whenever you don't want the jobs list to change at
237 all: no jobs deleted and no status change notifications. This is used,
238 for example, when executing SIGCHLD traps, which may run arbitrary
240 static int jobs_list_frozen;
242 #if !defined (_POSIX_VERSION)
244 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
245 library functions and system calls. */
246 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
247 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
255 /* ioctl will handle setting errno correctly. */
256 if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
261 #endif /* !_POSIX_VERSION */
263 /* Return the working directory for the current process. Unlike
264 job_working_directory, this does not call malloc (), nor do any
265 of the functions it calls. This is so that it can safely be called
266 from a signal handler. */
268 current_working_directory ()
271 static char d[PATH_MAX];
273 dir = get_string_value ("PWD");
275 if (dir == 0 && the_current_working_directory && no_symbolic_links)
276 dir = the_current_working_directory;
280 dir = getcwd (d, sizeof(d));
285 return (dir == 0) ? "<unknown>" : dir;
288 /* Return the working directory for the current process. */
290 job_working_directory ()
294 dir = get_string_value ("PWD");
296 return (savestring (dir));
298 dir = get_working_directory ("job-working-directory");
302 return (savestring ("<unknown>"));
308 if (already_making_children)
311 already_making_children = 1;
316 stop_making_children ()
318 already_making_children = 0;
322 cleanup_the_pipeline ()
326 discard_pipeline (the_pipeline);
327 the_pipeline = (PROCESS *)NULL;
332 save_pipeline (clear)
335 saved_pipeline = the_pipeline;
336 saved_already_making_children = already_making_children;
338 the_pipeline = (PROCESS *)NULL;
342 restore_pipeline (discard)
345 PROCESS *old_pipeline;
347 old_pipeline = the_pipeline;
348 the_pipeline = saved_pipeline;
349 already_making_children = saved_already_making_children;
351 discard_pipeline (old_pipeline);
354 /* Start building a pipeline. */
360 cleanup_the_pipeline ();
362 #if defined (PGRP_PIPE)
363 pipe_close (pgrp_pipe);
367 #if defined (PGRP_PIPE)
370 if (pipe (pgrp_pipe) == -1)
371 sys_error ("start_pipeline: pgrp pipe");
376 /* Stop building a pipeline. Install the process list in the job array.
377 This returns the index of the newly installed job.
378 DEFERRED is a command structure to be executed upon satisfactory
379 execution exit of this pipeline. */
381 stop_pipeline (async, deferred)
389 BLOCK_CHILD (set, oset);
391 #if defined (PGRP_PIPE)
392 /* The parent closes the process group synchronization pipe. */
393 pipe_close (pgrp_pipe);
396 cleanup_dead_jobs ();
400 job_slots = JOB_SLOTS;
401 jobs = (JOB **)xmalloc (job_slots * sizeof (JOB *));
403 /* Now blank out these new entries. */
404 for (i = 0; i < job_slots; i++)
405 jobs[i] = (JOB *)NULL;
408 /* Scan from the last slot backward, looking for the next free one. */
411 for (i = job_slots; i; i--)
417 /* If we're not interactive, we don't need to monotonically increase
418 the job number (in fact, we don't care about the job number at all),
419 so we can simply scan for the first free slot. This helps to keep
420 us from continuously reallocating the jobs array when running
421 certain kinds of shell loops, and saves time spent searching. */
422 for (i = 0; i < job_slots; i++)
427 /* Do we need more room? */
430 job_slots += JOB_SLOTS;
431 jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
433 for (j = i; j < job_slots; j++)
434 jobs[j] = (JOB *)NULL;
437 /* Add the current pipeline to the job list. */
441 int any_alive, any_stopped;
443 newjob = (JOB *)xmalloc (sizeof (JOB));
445 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
447 p->next = (PROCESS *)NULL;
448 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
449 for (p = newjob->pipe; p->next; p = p->next)
451 p->next = newjob->pipe;
453 the_pipeline = (PROCESS *)NULL;
454 newjob->pgrp = pipeline_pgrp;
459 /* Flag to see if in another pgrp. */
461 newjob->flags |= J_JOBCONTROL;
463 /* Set the state of this pipeline. */
465 any_alive = any_stopped = 0;
468 any_alive |= p->running;
469 any_stopped |= WIFSTOPPED (p->status);
472 while (p != newjob->pipe);
474 newjob->state = any_alive ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
475 newjob->wd = job_working_directory ();
476 newjob->deferred = deferred;
478 newjob->j_cleanup = (VFunction *)NULL;
479 newjob->cleanarg = (PTR_T) NULL;
482 if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
486 newjob = (JOB *)NULL;
491 newjob->flags &= ~J_FOREGROUND;
498 newjob->flags |= J_FOREGROUND;
500 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
502 * The currently-accepted job control wisdom says to set the
503 * terminal's process group n+1 times in an n-step pipeline:
504 * once in the parent and once in each child. This is where
505 * the parent gives it away.
508 if (job_control && newjob->pgrp)
509 give_terminal_to (newjob->pgrp);
513 stop_making_children ();
514 UNBLOCK_CHILD (oset);
515 return (current_job);
518 /* Delete all DEAD jobs that the user had received notification about. */
525 if (job_slots == 0 || jobs_list_frozen)
528 BLOCK_CHILD (set, oset);
530 for (i = 0; i < job_slots; i++)
531 if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
534 UNBLOCK_CHILD (oset);
537 /* Delete the job at INDEX from the job list. Must be called
538 with SIGCHLD blocked. */
540 delete_job (job_index, warn_stopped)
541 int job_index, warn_stopped;
545 if (job_slots == 0 || jobs_list_frozen)
548 if (warn_stopped && subshell_environment == 0 && STOPPED (job_index))
549 internal_warning ("deleting stopped job %d with process group %d", job_index+1, jobs[job_index]->pgrp);
551 temp = jobs[job_index];
552 if (job_index == current_job || job_index == previous_job)
555 jobs[job_index] = (JOB *)NULL;
558 discard_pipeline (temp->pipe);
561 dispose_command (temp->deferred);
566 /* Must be called with SIGCHLD blocked. */
568 nohup_job (job_index)
576 if (temp = jobs[job_index])
577 temp->flags |= J_NOHUP;
580 /* Get rid of the data structure associated with a process chain. */
582 discard_pipeline (chain)
583 register PROCESS *chain;
585 register PROCESS *this, *next;
591 FREE (this->command);
595 while (this != chain);
598 /* Add this process to the chain being built in the_pipeline.
599 NAME is the command string that will be exec'ed later.
600 PID is the process id of the child. */
602 add_process (name, pid)
608 t = (PROCESS *)xmalloc (sizeof (PROCESS));
609 t->next = the_pipeline;
611 WSTATUS (t->status) = 0;
621 while (p->next != t->next)
628 /* Take the last job and make it the first job. Must be called with
631 rotate_the_pipeline ()
635 if (the_pipeline->next == the_pipeline)
637 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
642 /* Reverse the order of the processes in the_pipeline. Must be called with
645 reverse_the_pipeline ()
649 if (the_pipeline->next == the_pipeline)
652 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
654 p->next = (PROCESS *)NULL;
656 n = REVERSE_LIST (the_pipeline, PROCESS *);
659 for (p = the_pipeline; p->next; p = p->next)
661 p->next = the_pipeline;
665 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
666 then it is time to stop mapping, and that is the return value
667 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
670 map_over_jobs (func, arg1, arg2)
678 BLOCK_CHILD (set, oset);
680 for (i = result = 0; i < job_slots; i++)
684 result = (*func)(jobs[i], arg1, arg2, i);
690 UNBLOCK_CHILD (oset);
695 /* Cause all the jobs in the current pipeline to exit. */
697 terminate_current_pipeline ()
699 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
701 killpg (pipeline_pgrp, SIGTERM);
702 killpg (pipeline_pgrp, SIGCONT);
706 /* Cause all stopped jobs to exit. */
708 terminate_stopped_jobs ()
712 for (i = 0; i < job_slots; i++)
714 if (jobs[i] && STOPPED (i))
716 killpg (jobs[i]->pgrp, SIGTERM);
717 killpg (jobs[i]->pgrp, SIGCONT);
722 /* Cause all jobs, running or stopped, to receive a hangup signal. If
723 a job is marked J_NOHUP, don't send the SIGHUP. */
729 for (i = 0; i < job_slots; i++)
733 if ((jobs[i]->flags & J_NOHUP) == 0)
734 killpg (jobs[i]->pgrp, SIGHUP);
736 killpg (jobs[i]->pgrp, SIGCONT);
742 kill_current_pipeline ()
744 stop_making_children ();
748 /* Return the pipeline that PID belongs to. Note that the pipeline
749 doesn't have to belong to a job. Must be called with SIGCHLD blocked. */
757 /* See if this process is in the pipeline that we are building. */
763 /* Return it if we found it. */
769 while (p != the_pipeline);
772 job = find_job (pid);
774 return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
777 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
778 belong to any job. Must be called with SIGCHLD blocked. */
786 for (i = 0; i < job_slots; i++)
799 while (p != jobs[i]->pipe);
806 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
807 required by find_job. */
809 get_job_by_pid (pid, block)
817 BLOCK_CHILD (set, oset);
818 job = find_job (pid);
820 UNBLOCK_CHILD (oset);
825 /* Print descriptive information about the job with leader pid PID. */
833 BLOCK_CHILD (set, oset);
835 job = find_job (pid);
838 printf ("[%d] %d\n", job + 1, (int)pid);
840 programming_error ("describe_pid: %d: no such pid", (int)pid);
842 UNBLOCK_CHILD (oset);
845 /* This is the way to print out information on a job if you
846 know the index. FORMAT is:
848 JLIST_NORMAL) [1]+ Running emacs
849 JLIST_LONG ) [1]+ 2378 Running emacs
852 JLIST_NORMAL) [1]+ Stopped ls | more
853 JLIST_LONG ) [1]+ 2369 Stopped ls
856 Just list the pid of the process group leader (really
859 Use format JLIST_NORMAL, but list only jobs about which
860 the user has not been notified. */
862 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
863 the JOBS array corresponding to this pipeline. FORMAT is as described
864 above. Must be called with SIGCHLD blocked.
866 If you're printing a pipeline that's not in the jobs array, like the
867 current pipeline as it's being created, pass -1 for JOB_INDEX */
869 print_pipeline (p, job_index, format, stream)
871 int job_index, format;
874 PROCESS *first, *last, *show;
875 int es, name_padding;
876 char retcode_name_buffer[20], *temp;
882 while (last->next != first)
888 fprintf (stream, format ? " " : " |");
890 if (format != JLIST_STANDARD)
891 fprintf (stream, "%5d", (int)p->pid);
893 fprintf (stream, " ");
895 if (format > -1 && job_index >= 0)
897 show = format ? p : last;
900 if (STOPPED (job_index) && format == 0)
903 else if (RUNNING (job_index))
907 if (WIFSTOPPED (show->status))
908 temp = (char *)strsignal (WSTOPSIG (show->status));
909 else if (WIFSIGNALED (show->status))
910 temp = (char *)strsignal (WTERMSIG (show->status));
911 else if (WIFEXITED (show->status))
913 temp = retcode_name_buffer;
914 es = WEXITSTATUS (show->status);
917 strcpy (temp, "Done");
918 else if (posixly_correct)
919 sprintf (temp, "Done(%d)", es);
921 sprintf (temp, "Exit %d", es);
924 temp = "Unknown status";
931 if (show->running == first->running &&
932 WSTATUS (show->status) == WSTATUS (first->status))
941 fprintf (stream, "%s", temp);
945 es = 2; /* strlen ("| ") */
946 name_padding = LONGEST_SIGNAL_DESC - es;
948 fprintf (stream, "%*s", name_padding, "");
950 if ((WIFSTOPPED (show->status) == 0) && WIFCORED (show->status))
951 fprintf (stream, "(core dumped) ");
955 if (p != first && format)
956 fprintf (stream, "| ");
959 fprintf (stream, "%s", p->command);
961 if (p == last && job_index >= 0)
963 temp = current_working_directory ();
965 if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
966 fprintf (stream, " &");
968 if (strcmp (temp, jobs[job_index]->wd) != 0)
970 " (wd: %s)", polite_directory_format (jobs[job_index]->wd));
973 if (format || (p == last))
975 /* We need to add a CR only if this is an interactive shell, and
976 we're reporting the status of a completed job asynchronously.
977 We can't really check whether this particular job is being
978 reported asynchronously, so just add the CR if the shell is
979 currently interactive and asynchronous notification is enabled. */
980 if (asynchronous_notification && interactive)
981 fprintf (stream, "\r\n");
983 fprintf (stream, "\n");
994 pretty_print_job (job_index, format, stream)
995 int job_index, format;
1001 BLOCK_CHILD (set, oset);
1003 /* Format only pid information about the process group leader? */
1004 if (format == JLIST_PID_ONLY)
1006 fprintf (stream, "%d\n", (int)jobs[job_index]->pipe->pid);
1007 UNBLOCK_CHILD (oset);
1011 if (format == JLIST_CHANGED_ONLY)
1013 if (IS_NOTIFIED (job_index))
1015 UNBLOCK_CHILD (oset);
1018 format = JLIST_STANDARD;
1021 if (format != JLIST_NONINTERACTIVE)
1022 fprintf (stream, "[%d]%c ", job_index + 1,
1023 (job_index == current_job) ? '+':
1024 (job_index == previous_job) ? '-' : ' ');
1026 if (format == JLIST_NONINTERACTIVE)
1027 format = JLIST_LONG;
1029 p = jobs[job_index]->pipe;
1031 print_pipeline (p, job_index, format, stream);
1033 /* We have printed information about this job. When the job's
1034 status changes, waitchld () sets the notification flag to 0. */
1035 jobs[job_index]->flags |= J_NOTIFIED;
1037 UNBLOCK_CHILD (oset);
1041 print_job (job, format, state, job_index)
1043 int format, state, job_index;
1045 if (state == -1 || (JOB_STATE)state == job->state)
1046 pretty_print_job (job_index, format, stdout);
1051 list_one_job (job, format, ignore, job_index)
1053 int format, ignore, job_index;
1055 print_job (job, format, -1, job_index);
1059 list_stopped_jobs (format)
1062 cleanup_dead_jobs ();
1063 map_over_jobs (print_job, format, (int)JSTOPPED);
1067 list_running_jobs (format)
1070 cleanup_dead_jobs ();
1071 map_over_jobs (print_job, format, (int)JRUNNING);
1074 /* List jobs. If FORMAT is non-zero, then the long form of the information
1075 is printed, else just a short version. */
1077 list_all_jobs (format)
1080 cleanup_dead_jobs ();
1081 map_over_jobs (print_job, format, -1);
1084 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1085 COMMAND is just for remembering the name of the command; we don't do
1086 anything else with it. ASYNC_P says what to do with the tty. If
1087 non-zero, then don't give it away. */
1089 make_child (command, async_p)
1097 sigaddset (&set, SIGCHLD);
1098 sigaddset (&set, SIGINT);
1099 sigemptyset (&oset);
1100 sigprocmask (SIG_BLOCK, &set, &oset);
1104 #if defined (BUFFERED_INPUT)
1105 /* If default_buffered_input is active, we are reading a script. If
1106 the command is asynchronous, we have already duplicated /dev/null
1107 as fd 0, but have not changed the buffered stream corresponding to
1108 the old fd 0. We don't want to sync the stream in this case. */
1109 if (default_buffered_input != -1 &&
1110 (!async_p || default_buffered_input > 0))
1111 sync_buffered_stream (default_buffered_input);
1112 #endif /* BUFFERED_INPUT */
1114 /* Create the child, handle severe errors. */
1115 if ((pid = fork ()) < 0)
1119 /* Kill all of the processes in the current pipeline. */
1120 terminate_current_pipeline ();
1122 /* Discard the current pipeline, if any. */
1124 kill_current_pipeline ();
1126 throw_to_top_level (); /* Reset signals, etc. */
1131 /* In the child. Give this child the right process group, set the
1132 signals to the default state for a new process. */
1136 #if defined (BUFFERED_INPUT)
1137 /* Close default_buffered_input if it's > 0. We don't close it if it's
1138 0 because that's the file descriptor used when redirecting input,
1139 and it's wrong to close the file in that case. */
1140 unset_bash_input (0);
1141 #endif /* BUFFERED_INPUT */
1143 /* Restore top-level signal mask. */
1144 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1148 /* All processes in this pipeline belong in the same
1151 if (pipeline_pgrp == 0) /* This is the first child. */
1152 pipeline_pgrp = mypid;
1154 /* Check for running command in backquotes. */
1155 if (pipeline_pgrp == shell_pgrp)
1156 ignore_tty_job_signals ();
1158 default_tty_job_signals ();
1160 /* Set the process group before trying to mess with the terminal's
1161 process group. This is mandated by POSIX. */
1162 /* This is in accordance with the Posix 1003.1 standard,
1163 section B.7.2.4, which says that trying to set the terminal
1164 process group with tcsetpgrp() to an unused pgrp value (like
1165 this would have for the first child) is an error. Section
1166 B.4.3.3, p. 237 also covers this, in the context of job control
1168 if (setpgid (mypid, pipeline_pgrp) < 0)
1169 sys_error ("child setpgid (%d to %d)", mypid, pipeline_pgrp);
1170 #if defined (PGRP_PIPE)
1171 if (pipeline_pgrp == mypid)
1174 /* XXX - By convention (and assumption above), if
1175 pipeline_pgrp == shell_pgrp, we are making a child for
1176 command substitution.
1177 In this case, we don't want to give the terminal to the
1178 shell's process group (we could be in the middle of a
1179 pipeline, for example). */
1180 if (async_p == 0 && pipeline_pgrp != shell_pgrp)
1181 give_terminal_to (pipeline_pgrp);
1183 #if defined (PGRP_PIPE)
1184 pipe_read (pgrp_pipe);
1188 else /* Without job control... */
1190 if (pipeline_pgrp == 0)
1191 pipeline_pgrp = shell_pgrp;
1193 /* If these signals are set to SIG_DFL, we encounter the curious
1194 situation of an interactive ^Z to a running process *working*
1195 and stopping the process, but being unable to do anything with
1196 that process to change its state. On the other hand, if they
1197 are set to SIG_IGN, jobs started from scripts do not stop when
1198 the shell running the script gets a SIGTSTP and stops. */
1200 default_tty_job_signals ();
1203 #if defined (PGRP_PIPE)
1204 /* Release the process group pipe, since our call to setpgid ()
1205 is done. The last call to pipe_close is done in stop_pipeline. */
1206 pipe_close (pgrp_pipe);
1207 #endif /* PGRP_PIPE */
1210 last_asynchronous_pid = getpid ();
1214 /* In the parent. Remember the pid of the child just created
1215 as the proper pgrp if this is the first child. */
1219 if (pipeline_pgrp == 0)
1221 pipeline_pgrp = pid;
1222 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1223 not the good thing of twiddling them in the child! */
1224 /* give_terminal_to (pipeline_pgrp); */
1226 /* This is done on the recommendation of the Rationale section of
1227 the POSIX 1003.1 standard, where it discusses job control and
1228 shells. It is done to avoid possible race conditions. (Ref.
1229 1003.1 Rationale, section B.4.3.3, page 236). */
1230 setpgid (pid, pipeline_pgrp);
1234 if (pipeline_pgrp == 0)
1235 pipeline_pgrp = shell_pgrp;
1238 /* Place all processes into the jobs array regardless of the
1239 state of job_control. */
1240 add_process (command, pid);
1243 last_asynchronous_pid = pid;
1245 last_made_pid = pid;
1247 /* Unblock SIGINT and SIGCHLD. */
1248 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1255 ignore_tty_job_signals ()
1257 set_signal_handler (SIGTSTP, SIG_IGN);
1258 set_signal_handler (SIGTTIN, SIG_IGN);
1259 set_signal_handler (SIGTTOU, SIG_IGN);
1263 default_tty_job_signals ()
1265 set_signal_handler (SIGTSTP, SIG_DFL);
1266 set_signal_handler (SIGTTIN, SIG_DFL);
1267 set_signal_handler (SIGTTOU, SIG_DFL);
1270 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1271 state kept in here. When a job ends normally, we set the state in here
1272 to the state of the tty. */
1274 #if defined (NEW_TTY_DRIVER)
1275 static struct sgttyb shell_tty_info;
1276 static struct tchars shell_tchars;
1277 static struct ltchars shell_ltchars;
1278 #endif /* NEW_TTY_DRIVER */
1280 #if defined (TERMIO_TTY_DRIVER)
1281 static struct termio shell_tty_info;
1282 #endif /* TERMIO_TTY_DRIVER */
1284 #if defined (TERMIOS_TTY_DRIVER)
1285 static struct termios shell_tty_info;
1286 #endif /* TERMIOS_TTY_DRIVER */
1288 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1289 /* Since the BSD tty driver does not allow us to change the tty modes
1290 while simultaneously waiting for output to drain and preserving
1291 typeahead, we have to drain the output ourselves before calling
1292 ioctl. We cheat by finding the length of the output queue, and
1293 using select to wait for an appropriate length of time. This is
1294 a hack, and should be labeled as such (it's a hastily-adapted
1295 mutation of a `usleep' implementation). It's only reason for
1296 existing is the flaw in the BSD tty driver. */
1298 static int ttspeeds[] =
1300 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1301 1800, 2400, 4800, 9600, 19200, 38400
1308 register int delay = ttspeeds[ospeed];
1314 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1316 if (n > (delay / 100))
1320 n *= 10; /* 2 bits more for conservativeness. */
1321 tv.tv_sec = n / delay;
1322 tv.tv_usec = ((n % delay) * 1000000) / delay;
1323 select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1329 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1331 /* Return the fd from which we are actually getting input. */
1332 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1334 /* Fill the contents of shell_tty_info with the current tty info. */
1343 #if defined (NEW_TTY_DRIVER)
1344 ioctl (tty, TIOCGETP, &shell_tty_info);
1345 ioctl (tty, TIOCGETC, &shell_tchars);
1346 ioctl (tty, TIOCGLTC, &shell_ltchars);
1347 #endif /* NEW_TTY_DRIVER */
1349 #if defined (TERMIO_TTY_DRIVER)
1350 ioctl (tty, TCGETA, &shell_tty_info);
1351 #endif /* TERMIO_TTY_DRIVER */
1353 #if defined (TERMIOS_TTY_DRIVER)
1354 if (tcgetattr (tty, &shell_tty_info) < 0)
1357 /* Only print an error message if we're really interactive at
1360 sys_error ("[%d: %d] tcgetattr", getpid (), shell_level);
1364 #endif /* TERMIOS_TTY_DRIVER */
1365 if (check_window_size)
1366 get_new_window_size (0);
1371 /* Make the current tty use the state in shell_tty_info. */
1380 #if defined (NEW_TTY_DRIVER)
1381 # if defined (DRAIN_OUTPUT)
1382 draino (tty, shell_tty_info.sg_ospeed);
1383 # endif /* DRAIN_OUTPUT */
1384 ioctl (tty, TIOCSETN, &shell_tty_info);
1385 ioctl (tty, TIOCSETC, &shell_tchars);
1386 ioctl (tty, TIOCSLTC, &shell_ltchars);
1387 #endif /* NEW_TTY_DRIVER */
1389 #if defined (TERMIO_TTY_DRIVER)
1390 ioctl (tty, TCSETAW, &shell_tty_info);
1391 #endif /* TERMIO_TTY_DRIVER */
1393 #if defined (TERMIOS_TTY_DRIVER)
1394 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1396 /* Only print an error message if we're really interactive at
1399 sys_error ("[%d: %d] tcsetattr", getpid (), shell_level);
1402 #endif /* TERMIOS_TTY_DRIVER */
1407 /* Given an index into the jobs array JOB, return the pid of the last
1408 process in that job's pipeline. This is the one whose exit status
1414 register PROCESS *p;
1416 p = jobs[job]->pipe;
1417 while (p->next != jobs[job]->pipe)
1430 BLOCK_CHILD (set, oset);
1431 pid = find_last_pid (job);
1432 UNBLOCK_CHILD (oset);
1437 /* Wait for a particular child of the shell to finish executing.
1438 This low-level function prints an error message if PID is not
1439 a child of this shell. It returns -1 if it fails, or 0 if not
1440 (whatever wait_for returns). If the child is not found in the
1441 jobs table, it returns 127. */
1443 wait_for_single_pid (pid)
1446 register PROCESS *child;
1450 BLOCK_CHILD (set, oset);
1451 child = find_pipeline (pid);
1452 UNBLOCK_CHILD (oset);
1456 internal_error ("wait: pid %d is not a child of this shell", pid);
1462 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
1464 BLOCK_CHILD (set, oset);
1465 job = find_job (pid);
1466 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1467 jobs[job]->flags |= J_NOTIFIED;
1468 UNBLOCK_CHILD (oset);
1473 /* Wait for all of the backgrounds of this shell to finish. */
1475 wait_for_background_pids ()
1477 register int i, count, r, waited_for;
1481 for (waited_for = 0;;)
1483 BLOCK_CHILD (set, oset);
1486 for (i = 0; i < job_slots; i++)
1487 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1495 UNBLOCK_CHILD (oset);
1499 for (i = 0; i < job_slots; i++)
1500 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1503 UNBLOCK_CHILD (oset);
1505 errno = 0; /* XXX */
1506 r = wait_for_single_pid (pid);
1509 if (errno == ECHILD)
1510 mark_all_jobs_as_dead ();
1518 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
1519 `wait' is called with no arguments. */
1520 mark_dead_jobs_as_notified (1);
1521 cleanup_dead_jobs ();
1524 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
1525 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
1526 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
1529 restore_sigint_handler ()
1531 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1533 set_signal_handler (SIGINT, old_sigint_handler);
1534 old_sigint_handler = INVALID_SIGNAL_HANDLER;
1538 static int wait_sigint_received;
1540 /* Handle SIGINT while we are waiting for children in a script to exit.
1541 The `wait' builtin should be interruptible, but all others should be
1542 effectively ignored (i.e. not cause the shell to exit). */
1544 wait_sigint_handler (sig)
1547 SigHandler *sigint_handler;
1549 if (interrupt_immediately ||
1550 (this_shell_builtin && this_shell_builtin == wait_builtin))
1552 last_command_exit_value = EXECUTION_FAILURE;
1553 restore_sigint_handler ();
1554 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
1555 what POSIX.2 says (see builtins/wait.def for more info). */
1556 if (this_shell_builtin && this_shell_builtin == wait_builtin &&
1557 signal_is_trapped (SIGINT) &&
1558 ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
1560 interrupt_immediately = 0;
1561 trap_handler (SIGINT); /* set pending_traps[SIGINT] */
1562 longjmp (wait_intr_buf, 1);
1569 /* XXX - should this be interrupt_state? If it is, the shell will act
1570 as if it got the SIGINT interrupt. */
1571 wait_sigint_received = 1;
1573 /* Otherwise effectively ignore the SIGINT and allow the running job to
1579 process_exit_status (status)
1582 if (WIFSIGNALED (status))
1583 return (128 + WTERMSIG (status));
1584 else if (WIFSTOPPED (status) == 0)
1585 return (WEXITSTATUS (status));
1587 return (EXECUTION_SUCCESS);
1591 raw_job_exit_status (job)
1593 register PROCESS *p;
1594 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
1600 job_exit_status (job)
1603 return (process_exit_status (raw_job_exit_status (job)));
1606 #define FIND_CHILD(pid, child) \
1609 child = find_pipeline (pid); \
1612 give_terminal_to (shell_pgrp); \
1613 UNBLOCK_CHILD (oset); \
1614 internal_error ("wait_for: No record of process %d", pid); \
1615 restore_sigint_handler (); \
1616 return (termination_state = 127); \
1621 /* Wait for pid (one of our children) to terminate, then
1622 return the termination state. Returns 127 if PID is not found in
1623 the jobs table. Returns -1 if waitchld() returns -1, indicating
1624 that there are no unwaited-for child processes. */
1629 int job, termination_state, r, s;
1630 register PROCESS *child;
1632 register PROCESS *p;
1634 int job_state, any_stopped;
1637 /* In the case that this code is interrupted, and we longjmp () out of it,
1638 we are relying on the code in throw_to_top_level () to restore the
1639 top-level signal mask. */
1640 BLOCK_CHILD (set, oset);
1642 /* Ignore interrupts while waiting for a job run without job control
1643 to finish. We don't want the shell to exit if an interrupt is
1644 received, only if one of the jobs run is killed via SIGINT. If
1645 job control is not set, the job will be run in the same pgrp as
1646 the shell, and the shell will see any signals the job gets. */
1648 /* This is possibly a race condition -- should it go in stop_pipeline? */
1649 wait_sigint_received = 0;
1650 if (job_control == 0)
1651 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
1653 termination_state = last_command_exit_value;
1655 if (interactive && job_control == 0)
1658 /* If we say wait_for (), then we have a record of this child somewhere.
1659 If it and none of its peers are running, don't call waitchld(). */
1664 FIND_CHILD (pid, child);
1666 /* If this child is part of a job, then we are really waiting for the
1667 job to finish. Otherwise, we are waiting for the child to finish.
1668 We check for JDEAD in case the job state has been set by waitchld
1669 after receipt of a SIGCHLD. */
1671 job = find_job (pid);
1674 /* XXX - let waitchld take care of setting this. If the job has
1675 already exited before this is called, sigchld_handler will have
1676 called waitchld and this will be set to JDEAD. */
1677 if (job != NO_JOB && JOBSTATE (job) != JDEAD)
1679 job_state = any_stopped = 0;
1680 p = jobs[job]->pipe;
1683 job_state |= p->running;
1684 if (p->running == 0)
1685 any_stopped |= WIFSTOPPED (p->status);
1688 while (p != jobs[job]->pipe);
1691 jobs[job]->state = any_stopped ? JSTOPPED : JDEAD;
1695 if (child->running || (job != NO_JOB && RUNNING (job)))
1697 #if defined (WAITPID_BROKEN) /* SCOv4 */
1698 sigset_t suspend_set;
1699 sigemptyset (&suspend_set);
1700 sigsuspend (&suspend_set);
1701 #else /* !WAITPID_BROKEN */
1702 # if defined (MUST_UNBLOCK_CHLD)
1703 struct sigaction act, oact;
1704 sigset_t nullset, chldset;
1706 sigemptyset (&nullset);
1707 sigemptyset (&chldset);
1708 sigprocmask (SIG_SETMASK, &nullset, &chldset);
1709 act.sa_handler = SIG_DFL;
1710 sigemptyset (&act.sa_mask);
1711 sigemptyset (&oact.sa_mask);
1713 sigaction (SIGCHLD, &act, &oact);
1715 waiting_for_job = 1;
1716 r = waitchld (pid, 1);
1717 # if defined (MUST_UNBLOCK_CHLD)
1718 sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
1719 sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
1721 waiting_for_job = 0;
1722 if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
1724 termination_state = -1;
1725 goto wait_for_return;
1727 #endif /* WAITPID_BROKEN */
1730 /* If the shell is interactive, and job control is disabled, see
1731 if the foreground process has died due to SIGINT and jump out
1732 of the wait loop if it has. waitchld has already restored the
1733 old SIGINT signal handler. */
1734 if (interactive && job_control == 0)
1737 while (child->running || (job != NO_JOB && RUNNING (job)));
1739 /* The exit state of the command is either the termination state of the
1740 child, or the termination state of the job. If a job, the status
1741 of the last child in the pipeline is the significant one. */
1743 termination_state = job_exit_status (job);
1745 termination_state = process_exit_status (child->status);
1747 if (job == NO_JOB || IS_JOBCONTROL (job))
1749 /* XXX - under what circumstances is a job not present in the jobs
1750 table (job == NO_JOB)?
1751 1. command substitution
1753 In the case of command substitution, at least, it's probably not
1754 the right thing to give the terminal to the shell's process group,
1755 even though there is code in subst.c:command_substitute to work
1759 $PROMPT_COMMAND execution
1760 process substitution
1764 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%d)", shell_pgrp);
1767 give_terminal_to (shell_pgrp);
1770 /* If the command did not exit cleanly, or the job is just
1771 being stopped, then reset the tty state back to what it
1772 was before this command. Reset the tty state and notify
1773 the user of the job termination only if the shell is
1774 interactive. Clean up any dead jobs in either case. */
1777 if (interactive_shell && subshell_environment == 0)
1779 /* This used to use `child->status'. That's wrong, however, for
1780 pipelines. `child' is the first process in the pipeline. It's
1781 likely that the process we want to check for abnormal termination
1782 or stopping is the last process in the pipeline, especially if
1783 it's long-lived and the first process is short-lived. Since we
1784 know we have a job here, we can check all the processes in this
1785 job's pipeline and see if one of them stopped or terminated due
1786 to a signal. We might want to change this later to just check
1787 the last process in the pipeline. If no process exits due to a
1788 signal, S is left as the status of the last job in the pipeline. */
1789 p = jobs[job]->pipe;
1793 if (WIFSIGNALED(s) || WIFSTOPPED(s))
1797 while (p != jobs[job]->pipe);
1799 if (WIFSIGNALED (s) || WIFSTOPPED (s))
1803 /* If the foreground job was suspended with ^Z (SIGTSTP), and
1804 the user has requested it, get a possibly new window size. */
1805 if (check_window_size && WIFSTOPPED (s) &&
1806 (WSTOPSIG (s) == SIGTSTP) &&
1809 /* If the current job was stopped or killed by a signal, and
1810 the user has requested it, get a possibly new window size */
1811 if (check_window_size && job == current_job)
1813 get_new_window_size (0);
1818 /* If job control is enabled, the job was started with job
1819 control, the job was the foreground job, and it was killed
1820 by SIGINT, then print a newline to compensate for the kernel
1821 printing the ^C without a trailing newline. */
1822 if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
1823 WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
1825 /* If SIGINT is not trapped and the shell is in a for, while,
1826 or until loop, act as if the shell received SIGINT as
1827 well, so the loop can be broken. This doesn't call the
1828 SIGINT signal handler; maybe it should. */
1829 if (signal_is_trapped (SIGINT) == 0 && loop_level)
1838 notify_and_cleanup ();
1842 /* If this job is dead, and the shell is not interactive, make
1843 sure we turn on the notify bit so we don't get an unwanted
1844 message about the job's termination, and so delete_job really
1845 clears the slot in the jobs table. */
1846 notify_and_cleanup ();
1852 UNBLOCK_CHILD (oset);
1854 /* Restore the original SIGINT signal handler before we return. */
1855 restore_sigint_handler ();
1857 return (termination_state);
1860 /* Wait for the last process in the pipeline for JOB. Returns whatever
1861 wait_for returns: the last process's termination state or -1 if there
1862 are no unwaited-for child processes or an error occurs. */
1871 BLOCK_CHILD(set, oset);
1872 if (JOBSTATE (job) == JSTOPPED)
1873 internal_warning ("wait_for_job: job %d is stopped", job+1);
1874 UNBLOCK_CHILD(oset);
1876 pid = last_pid (job);
1879 /* POSIX.2: we can remove the job from the jobs table if we just waited
1881 BLOCK_CHILD (set, oset);
1882 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1883 jobs[job]->flags |= J_NOTIFIED;
1884 UNBLOCK_CHILD (oset);
1889 /* Print info about dead jobs, and then delete them from the list
1890 of known jobs. This does not actually delete jobs when the
1891 shell is not interactive, because the dead jobs are not marked
1894 notify_and_cleanup ()
1896 if (jobs_list_frozen)
1899 if (interactive || interactive_shell == 0)
1900 notify_of_job_status ();
1902 cleanup_dead_jobs ();
1905 /* Make dead jobs disappear from the jobs array without notification.
1906 This is used when the shell is not interactive. */
1910 mark_dead_jobs_as_notified (0);
1911 cleanup_dead_jobs ();
1914 /* Return the next closest (chronologically) job to JOB which is in
1915 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
1916 there is no next recent job. */
1918 most_recent_job_in_state (job, state)
1922 register int i, result;
1925 BLOCK_CHILD (set, oset);
1926 for (result = NO_JOB, i = job - 1; i >= 0; i--)
1928 if (jobs[i] && (JOBSTATE (i) == state))
1934 UNBLOCK_CHILD (oset);
1939 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
1942 last_stopped_job (job)
1945 return (most_recent_job_in_state (job, JSTOPPED));
1948 /* Return the newest *running* job older than JOB, or NO_JOB if not
1951 last_running_job (job)
1954 return (most_recent_job_in_state (job, JRUNNING));
1957 /* Make JOB be the current job, and make previous be useful. Must be
1958 called with SIGCHLD blocked. */
1960 set_current_job (job)
1965 if (current_job != job)
1967 previous_job = current_job;
1971 /* First choice for previous_job is the old current_job. */
1972 if (previous_job != current_job &&
1973 previous_job != NO_JOB &&
1974 jobs[previous_job] &&
1975 STOPPED (previous_job))
1978 /* Second choice: Newest stopped job that is older than
1981 if (STOPPED (current_job))
1983 candidate = last_stopped_job (current_job);
1985 if (candidate != NO_JOB)
1987 previous_job = candidate;
1992 /* If we get here, there is either only one stopped job, in which case it is
1993 the current job and the previous job should be set to the newest running
1994 job, or there are only running jobs and the previous job should be set to
1995 the newest running job older than the current job. We decide on which
1996 alternative to use based on whether or not JOBSTATE(current_job) is
1999 candidate = RUNNING (current_job) ? last_running_job (current_job)
2000 : last_running_job (job_slots);
2002 if (candidate != NO_JOB)
2004 previous_job = candidate;
2008 /* There is only a single job, and it is both `+' and `-'. */
2009 previous_job = current_job;
2012 /* Make current_job be something useful, if it isn't already. */
2014 /* Here's the deal: The newest non-running job should be `+', and the
2015 next-newest non-running job should be `-'. If there is only a single
2016 stopped job, the previous_job is the newest non-running job. If there
2017 are only running jobs, the newest running job is `+' and the
2018 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
2025 if (job_slots && current_job != NO_JOB && jobs[current_job] && STOPPED (current_job))
2026 candidate = current_job;
2031 /* First choice: the previous job. */
2032 if (previous_job != NO_JOB && jobs[previous_job] && STOPPED (previous_job))
2033 candidate = previous_job;
2035 /* Second choice: the most recently stopped job. */
2036 if (candidate == NO_JOB)
2037 candidate = last_stopped_job (job_slots);
2039 /* Third choice: the newest running job. */
2040 if (candidate == NO_JOB)
2041 candidate = last_running_job (job_slots);
2044 /* If we found a job to use, then use it. Otherwise, there
2045 are no jobs period. */
2046 if (candidate != NO_JOB)
2047 set_current_job (candidate);
2049 current_job = previous_job = NO_JOB;
2052 /* Set up the job structures so we know the job and its processes are
2055 set_job_running (job)
2058 register PROCESS *p;
2060 /* Each member of the pipeline is now running. */
2061 p = jobs[job]->pipe;
2065 if (WIFSTOPPED (p->status))
2069 while (p != jobs[job]->pipe);
2071 /* This means that the job is running. */
2072 JOBSTATE (job) = JRUNNING;
2075 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2076 start the job in the background. JOB is a zero-based index into
2077 JOBS. Returns -1 if it is unable to start a job, and the return
2078 status of the job otherwise. */
2080 start_job (job, foreground)
2081 int job, foreground;
2083 register PROCESS *p;
2084 int already_running;
2087 #if defined (NEW_TTY_DRIVER)
2088 static struct sgttyb save_stty;
2090 #if defined (TERMIO_TTY_DRIVER)
2091 static struct termio save_stty;
2093 #if defined (TERMIOS_TTY_DRIVER)
2094 static struct termios save_stty;
2097 BLOCK_CHILD (set, oset);
2101 internal_error ("%s: job has terminated", this_command_name);
2102 UNBLOCK_CHILD (oset);
2106 already_running = RUNNING (job);
2108 if (foreground == 0 && already_running)
2110 internal_error ("%s: bg background job?", this_command_name);
2111 UNBLOCK_CHILD (oset);
2115 wd = current_working_directory ();
2117 /* You don't know about the state of this job. Do you? */
2118 jobs[job]->flags &= ~J_NOTIFIED;
2122 set_current_job (job);
2123 jobs[job]->flags |= J_FOREGROUND;
2126 /* Tell the outside world what we're doing. */
2127 p = jobs[job]->pipe;
2129 if (foreground == 0)
2130 fprintf (stderr, "[%d]%c ", job + 1,
2131 (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
2135 fprintf (stderr, "%s%s",
2136 p->command ? p->command : "",
2137 p->next != jobs[job]->pipe? " | " : "");
2140 while (p != jobs[job]->pipe);
2142 if (foreground == 0)
2143 fprintf (stderr, " &");
2145 if (strcmp (wd, jobs[job]->wd) != 0)
2146 fprintf (stderr, " (wd: %s)", polite_directory_format (jobs[job]->wd));
2148 fprintf (stderr, "\n");
2151 if (already_running == 0)
2152 set_job_running (job);
2154 /* Save the tty settings before we start the job in the foreground. */
2158 save_stty = shell_tty_info;
2159 /* Give the terminal to this job. */
2160 if (IS_JOBCONTROL (job))
2161 give_terminal_to (jobs[job]->pgrp);
2164 jobs[job]->flags &= ~J_FOREGROUND;
2166 /* If the job is already running, then don't bother jump-starting it. */
2167 if (already_running == 0)
2169 jobs[job]->flags |= J_NOTIFIED;
2170 killpg (jobs[job]->pgrp, SIGCONT);
2173 UNBLOCK_CHILD (oset);
2180 pid = last_pid (job);
2182 shell_tty_info = save_stty;
2188 BLOCK_CHILD (set, oset);
2190 UNBLOCK_CHILD (oset);
2195 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2196 If PID does belong to a job, and the job is stopped, then CONTinue the
2197 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2198 then kill the process group associated with PID. */
2200 kill_pid (pid, sig, group)
2204 register PROCESS *p;
2208 BLOCK_CHILD (set, oset);
2209 p = find_pipeline (pid);
2210 job = find_job (pid);
2212 result = EXECUTION_SUCCESS;
2217 jobs[job]->flags &= ~J_NOTIFIED;
2219 /* Kill process in backquotes or one started without job control? */
2220 if (jobs[job]->pgrp == shell_pgrp)
2222 p = jobs[job]->pipe;
2227 if (p->running == 0 && (sig == SIGTERM || sig == SIGHUP))
2228 kill (p->pid, SIGCONT);
2231 while (p != jobs[job]->pipe);
2235 result = killpg (jobs[job]->pgrp, sig);
2236 if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2237 killpg (jobs[job]->pgrp, SIGCONT);
2238 /* If we're continuing a stopped job via kill rather than bg or
2239 fg, emulate the `bg' behavior. */
2240 if (p && STOPPED (job) && (sig == SIGCONT))
2242 set_job_running (job);
2243 jobs[job]->flags &= ~J_FOREGROUND;
2244 jobs[job]->flags |= J_NOTIFIED;
2249 result = killpg (pid, sig);
2252 result = kill (pid, sig);
2254 UNBLOCK_CHILD (oset);
2258 /* sigchld_handler () flushes at least one of the children that we are
2259 waiting for. It gets run when we have gotten a SIGCHLD signal. */
2261 sigchld_handler (sig)
2267 REINSTALL_SIGCHLD_HANDLER;
2270 if (waiting_for_job == 0)
2271 n = waitchld (-1, 0);
2276 /* waitchld() reaps dead or stopped children. It's called by wait_for and
2277 sigchld_handler, and runs until there aren't any children terminating any
2279 If BLOCK is 1, this is to be a blocking wait for a single child, although
2280 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
2281 the number of children reaped, or -1 if there are no unwaited-for child
2284 waitchld (wpid, block)
2291 int call_set_current, last_stopped_job, job, children_exited;
2292 int job_state, any_stopped, any_tstped, waitpid_flags, tstatus;
2294 call_set_current = children_exited = 0;
2295 last_stopped_job = NO_JOB;
2299 /* We don't want to be notified about jobs stopping if job control
2300 is not active. XXX - was interactive_shell instead of job_control */
2301 waitpid_flags = (job_control && subshell_environment == 0)
2304 if (sigchld || block == 0)
2305 waitpid_flags |= WNOHANG;
2306 pid = WAITPID (-1, &status, waitpid_flags);
2307 /* The check for WNOHANG is to make sure we decrement sigchld only
2308 if it was non-zero before we called waitpid. */
2309 if (sigchld > 0 && (waitpid_flags & WNOHANG))
2312 /* If waitpid returns -1 with errno == ECHILD, there are no more
2313 unwaited-for child processes of this shell. */
2314 if (pid < 0 && errno == ECHILD)
2316 if (children_exited == 0)
2322 /* If waitpid returns 0, there are running children. If it returns -1,
2323 the only other error POSIX says it can return is EINTR. */
2325 continue; /* jumps right to the test */
2329 /* Locate our PROCESS for this pid. */
2330 child = find_pipeline (pid);
2332 /* It is not an error to have a child terminate that we did
2333 not have a record of. This child could have been part of
2334 a pipeline in backquote substitution. Even so, I'm not
2335 sure child is ever non-zero. */
2339 while (child->pid != pid)
2340 child = child->next;
2342 /* Remember status, and fact that process is not running. */
2343 child->status = status;
2346 job = find_job (pid);
2351 /* Note that we're resetting `child' here because we now want to
2352 deal with the job. */
2353 child = jobs[job]->pipe;
2354 jobs[job]->flags &= ~J_NOTIFIED;
2356 /* If all children are not running, but any of them is
2357 stopped, then the job is stopped, not dead. */
2358 job_state = any_stopped = any_tstped = 0;
2361 job_state |= child->running;
2362 if (child->running == 0 && (WIFSTOPPED (child->status)))
2365 any_tstped |= interactive && job_control &&
2366 (WSTOPSIG (child->status) == SIGTSTP);
2368 child = child->next;
2370 while (child != jobs[job]->pipe);
2372 /* If job_state != 0, the job is still running, so don't bother with
2373 setting the process exit status and job state. */
2377 /* The job is either stopped or dead. Set the state of the job
2381 jobs[job]->state = JSTOPPED;
2382 jobs[job]->flags &= ~J_FOREGROUND;
2384 last_stopped_job = job;
2385 /* Suspending a job with SIGTSTP breaks all active loops. */
2386 if (any_tstped && loop_level)
2387 breaking = loop_level;
2391 /* ASSERT(child == jobs[job]->pipe); */
2392 jobs[job]->state = JDEAD;
2393 if (job == last_stopped_job)
2394 last_stopped_job = NO_JOB;
2396 if (IS_FOREGROUND (job))
2397 setjstatus (job); /* XXX */
2399 /* If this job has a cleanup function associated with it, call it
2400 with `cleanarg' as the single argument, then set the function
2401 pointer to NULL so it is not inadvertently called twice. The
2402 cleanup function is responsible for deallocating cleanarg. */
2403 if (jobs[job]->j_cleanup)
2405 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
2406 jobs[job]->j_cleanup = (VFunction *)NULL;
2410 If we're running a shell script and we get a SIGINT with a
2411 SIGINT trap handler, but the foreground job handles it and
2412 does not exit due to SIGINT, run the trap handler but do not
2413 otherwise act as if we got the interrupt. */
2414 if (wait_sigint_received && interactive_shell == 0 &&
2415 WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
2416 signal_is_trapped (SIGINT))
2418 wait_sigint_received = 0;
2419 last_command_exit_value = process_exit_status (child->status);
2421 jobs_list_frozen = 1;
2422 tstatus = maybe_call_trap_handler (SIGINT);
2423 jobs_list_frozen = 0;
2426 /* If the foreground job is killed by SIGINT when
2427 job control is not active, we need to perform
2428 some special handling.
2430 The check of wait_sigint_received is a way to
2431 determine if the SIGINT came from the keyboard
2432 (in which case the shell has already seen it,
2433 and wait_sigint_received is non-zero, because
2434 keyboard signals are sent to process groups)
2435 or via kill(2) to the foreground process by
2436 another process (or itself). If the shell did
2437 receive the SIGINT, it needs to perform normal
2438 SIGINT processing. */
2439 else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
2440 IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
2442 wait_sigint_received = 0;
2444 /* If SIGINT is trapped, set the exit status so
2445 that the trap handler can see it. */
2446 if (signal_is_trapped (SIGINT))
2447 last_command_exit_value = process_exit_status (child->status);
2449 /* If the signal is trapped, let the trap handler
2450 get it no matter what and simply return if
2451 the trap handler returns.
2452 maybe_call_trap_handler() may cause dead jobs
2453 to be removed from the job table because of
2454 a call to execute_command. Watch out for this. */
2455 jobs_list_frozen = 1;
2456 tstatus = maybe_call_trap_handler (SIGINT);
2457 jobs_list_frozen = 0;
2458 if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
2460 /* wait_sigint_handler () has already seen SIGINT and
2461 allowed the wait builtin to jump out. We need to
2462 call the original SIGINT handler, if necessary. If
2463 the original handler is SIG_DFL, we need to resend
2464 the signal to ourselves. */
2465 SigHandler *temp_handler;
2467 temp_handler = old_sigint_handler;
2468 /* Bogus. If we've reset the signal handler as the result
2469 of a trap caught on SIGINT, then old_sigint_handler
2470 will point to trap_handler, which now knows nothing about
2471 SIGINT (if we reset the sighandler to the default).
2472 In this case, we have to fix things up. What a crock. */
2473 if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
2474 temp_handler = trap_to_sighandler (SIGINT);
2475 restore_sigint_handler ();
2476 if (temp_handler == SIG_DFL)
2477 termination_unwind_protect (SIGINT);
2478 else if (temp_handler != SIG_IGN)
2479 (*temp_handler) (SIGINT);
2484 while ((sigchld || block == 0) && pid > (pid_t)0);
2486 /* If a job was running and became stopped, then set the current
2487 job. Otherwise, don't change a thing. */
2488 if (call_set_current)
2490 if (last_stopped_job != NO_JOB)
2491 set_current_job (last_stopped_job);
2496 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
2497 if (job_control && signal_is_trapped (SIGCHLD) && children_exited &&
2498 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
2503 /* Turn off the trap list during the call to parse_and_execute ()
2504 to avoid potentially infinite recursive calls. Preserve the
2505 values of last_command_exit_value, last_made_pid, and the_pipeline
2506 around the execution of the trap commands. */
2507 trap_command = savestring (trap_list[SIGCHLD]);
2509 begin_unwind_frame ("SIGCHLD trap");
2510 unwind_protect_int (last_command_exit_value);
2511 if (sizeof (pid_t) == sizeof (short))
2512 unwind_protect_short (last_made_pid);
2514 unwind_protect_int (last_made_pid);
2515 unwind_protect_int (interrupt_immediately);
2516 unwind_protect_int (jobs_list_frozen);
2517 unwind_protect_pointer (the_pipeline);
2518 unwind_protect_pointer (subst_assign_varlist);
2520 /* We have to add the commands this way because they will be run
2521 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
2522 to reference freed memory. */
2523 add_unwind_protect ((Function *)xfree, trap_command);
2524 add_unwind_protect ((Function *)maybe_set_sigchld_trap, trap_command);
2526 subst_assign_varlist = (WORD_LIST *)NULL;
2527 the_pipeline = (PROCESS *)NULL;
2528 restore_default_signal (SIGCHLD);
2529 jobs_list_frozen = 1;
2530 for (i = 0; i < children_exited; i++)
2532 interrupt_immediately = 1;
2533 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST);
2536 run_unwind_frame ("SIGCHLD trap");
2539 /* We have successfully recorded the useful information about this process
2540 that has just changed state. If we notify asynchronously, and the job
2541 that this process belongs to is no longer running, then notify the user
2542 of that fact now. */
2543 if (asynchronous_notification && interactive)
2544 notify_of_job_status ();
2546 return (children_exited);
2549 /* Function to call when you want to notify people of changes
2550 in job status. This prints out all jobs which are pending
2551 notification to stderr, and marks those printed as already
2552 notified, thus making them candidates for cleanup. */
2554 notify_of_job_status ()
2556 register int job, termsig;
2562 sigaddset (&set, SIGCHLD);
2563 sigaddset (&set, SIGTTOU);
2564 sigemptyset (&oset);
2565 sigprocmask (SIG_BLOCK, &set, &oset);
2567 for (job = 0, dir = (char *)NULL; job < job_slots; job++)
2569 if (jobs[job] && IS_NOTIFIED (job) == 0)
2572 s = jobs[job]->pipe->status;
2574 s = raw_job_exit_status (job);
2576 termsig = WTERMSIG (s);
2578 /* POSIX.2 says we have to hang onto the statuses of at most the
2579 last CHILD_MAX background processes if the shell is running a
2580 script. If the shell is not interactive, don't print anything
2581 unless the job was killed by a signal. */
2582 if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
2583 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
2586 /* If job control is disabled, don't print the status messages.
2587 Mark dead jobs as notified so that they get cleaned up. If
2588 startup_state == 2, we were started to run `-c command', so
2589 don't print anything. */
2590 if ((job_control == 0 && interactive_shell) || startup_state == 2)
2592 /* POSIX.2 compatibility: if the shell is not interactive,
2593 hang onto the job corresponding to the last asynchronous
2594 pid until the user has been notified of its status or does
2596 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job) != last_asynchronous_pid)))
2597 jobs[job]->flags |= J_NOTIFIED;
2601 /* Print info on jobs that are running in the background,
2602 and on foreground jobs that were killed by anything
2603 except SIGINT (and possibly SIGPIPE). */
2604 switch (JOBSTATE (job))
2607 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
2608 termsig != SIGINT &&
2609 #if defined (DONT_REPORT_SIGPIPE)
2610 termsig != SIGPIPE &&
2612 signal_is_trapped (termsig) == 0)
2614 fprintf (stderr, "%s: line %d: ", get_name_for_error (), line_number);
2615 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
2617 else if (IS_FOREGROUND (job))
2619 #if !defined (DONT_REPORT_SIGPIPE)
2620 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2622 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
2625 fprintf (stderr, "%s", strsignal (termsig));
2628 fprintf (stderr, " (core dumped)");
2630 fprintf (stderr, "\n");
2636 dir = current_working_directory ();
2637 pretty_print_job (job, JLIST_STANDARD, stderr);
2638 if (dir && strcmp (dir, jobs[job]->wd) != 0)
2640 "(wd now: %s)\n", polite_directory_format (dir));
2643 jobs[job]->flags |= J_NOTIFIED;
2647 fprintf (stderr, "\n");
2649 dir = current_working_directory ();
2650 pretty_print_job (job, JLIST_STANDARD, stderr);
2651 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2653 "(wd now: %s)\n", polite_directory_format (dir));
2654 jobs[job]->flags |= J_NOTIFIED;
2662 programming_error ("notify_of_job_status");
2666 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2669 /* Initialize the job control mechanism, and set up the tty stuff. */
2671 initialize_job_control (force)
2674 shell_pgrp = getpgid (0);
2676 if (shell_pgrp == -1)
2678 sys_error ("initialize_job_control: getpgrp failed");
2682 /* We can only have job control if we are interactive. */
2683 if (interactive == 0)
2686 original_pgrp = NO_PID;
2687 shell_tty = fileno (stderr);
2691 /* Get our controlling terminal. If job_control is set, or
2692 interactive is set, then this is an interactive shell no
2693 matter where fd 2 is directed. */
2694 shell_tty = dup (fileno (stderr)); /* fd 2 */
2696 shell_tty = move_to_high_fd (shell_tty, 1, -1);
2698 /* Compensate for a bug in systems that compiled the BSD
2699 rlogind with DEBUG defined, like NeXT and Alliant. */
2700 if (shell_pgrp == 0)
2702 shell_pgrp = getpid ();
2703 setpgid (0, shell_pgrp);
2704 tcsetpgrp (shell_tty, shell_pgrp);
2707 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2709 if (shell_pgrp != terminal_pgrp)
2711 SigHandler *old_ttin;
2713 old_ttin = set_signal_handler(SIGTTIN, SIG_DFL);
2715 set_signal_handler (SIGTTIN, old_ttin);
2721 /* Make sure that we are using the new line discipline. */
2722 if (set_new_line_discipline (shell_tty) < 0)
2724 sys_error ("initialize_job_control: line discipline");
2729 original_pgrp = shell_pgrp;
2730 shell_pgrp = getpid ();
2732 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
2734 sys_error ("initialize_job_control: setpgid");
2735 shell_pgrp = original_pgrp;
2740 /* If (and only if) we just set our process group to our pid,
2741 thereby becoming a process group leader, and the terminal
2742 is not in the same process group as our (new) process group,
2743 then set the terminal's process group to our (new) process
2744 group. If that fails, set our process group back to what it
2745 was originally (so we can still read from the terminal) and
2746 turn off job control. */
2747 if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
2749 if (give_terminal_to (shell_pgrp) < 0) /* XXX */
2751 setpgid (0, original_pgrp); /* XXX */
2752 shell_pgrp = original_pgrp; /* XXX */
2753 job_control = 0; /* XXX */
2757 if (job_control == 0)
2758 internal_error ("no job control in this shell"); /* XXX */
2761 if (shell_tty != fileno (stderr))
2762 SET_CLOSE_ON_EXEC (shell_tty);
2764 set_signal_handler (SIGCHLD, sigchld_handler);
2766 change_flag ('m', job_control ? '-' : '+');
2774 /* Set the line discipline to the best this system has to offer.
2775 Return -1 if this is not possible. */
2777 set_new_line_discipline (tty)
2780 #if defined (NEW_TTY_DRIVER)
2783 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
2786 if (ldisc != NTTYDISC)
2790 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
2794 #endif /* NEW_TTY_DRIVER */
2796 #if defined (TERMIO_TTY_DRIVER)
2797 # if defined (TERMIO_LDISC) && (NTTYDISC)
2798 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
2801 if (shell_tty_info.c_line != NTTYDISC)
2803 shell_tty_info.c_line = NTTYDISC;
2804 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
2807 # endif /* TERMIO_LDISC && NTTYDISC */
2809 #endif /* TERMIO_TTY_DRIVER */
2811 #if defined (TERMIOS_TTY_DRIVER)
2812 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
2813 if (tcgetattr (tty, &shell_tty_info) < 0)
2816 if (shell_tty_info.c_line != NTTYDISC)
2818 shell_tty_info.c_line = NTTYDISC;
2819 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2822 # endif /* TERMIOS_LDISC && NTTYDISC */
2824 #endif /* TERMIOS_TTY_DRIVER */
2826 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
2831 static SigHandler *old_tstp, *old_ttou, *old_ttin;
2832 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
2833 static sighandler stop_signal_handler (), cont_signal_handler ();
2835 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2836 static SigHandler *old_winch = (SigHandler *)SIG_DFL;
2839 get_new_window_size (from_sig)
2844 if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
2845 win.ws_row > 0 && win.ws_col > 0)
2848 shell_tty_info.c_winsize = win; /* structure copying */
2850 set_lines_and_columns (win.ws_row, win.ws_col);
2851 #if defined (READLINE)
2852 _rl_set_screen_size (win.ws_row, win.ws_col);
2858 sigwinch_sighandler (sig)
2861 #if defined (MUST_REINSTALL_SIGHANDLERS)
2862 set_signal_handler (SIGWINCH, sigwinch_sighandler);
2863 #endif /* MUST_REINSTALL_SIGHANDLERS */
2864 get_new_window_size (1);
2869 get_new_window_size (from_sig)
2873 #endif /* TIOCGWINSZ && SIGWINCH */
2876 set_sigwinch_handler ()
2878 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2879 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
2884 unset_sigwinch_handler ()
2886 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2887 set_signal_handler (SIGWINCH, old_winch);
2891 /* Setup this shell to handle C-C, etc. */
2893 initialize_job_signals ()
2897 set_signal_handler (SIGINT, sigint_sighandler);
2898 set_signal_handler (SIGTSTP, SIG_IGN);
2899 set_signal_handler (SIGTTOU, SIG_IGN);
2900 set_signal_handler (SIGTTIN, SIG_IGN);
2901 set_sigwinch_handler ();
2903 else if (job_control)
2905 old_tstp = set_signal_handler (SIGTSTP, stop_signal_handler);
2906 old_ttou = set_signal_handler (SIGTTOU, stop_signal_handler);
2907 old_ttin = set_signal_handler (SIGTTIN, stop_signal_handler);
2909 /* Leave these things alone for non-interactive shells without job
2913 /* Here we handle CONT signals. */
2915 cont_signal_handler (sig)
2918 initialize_job_signals ();
2919 set_signal_handler (SIGCONT, old_cont);
2920 kill (getpid (), SIGCONT);
2925 /* Here we handle stop signals while we are running not as a login shell. */
2927 stop_signal_handler (sig)
2930 set_signal_handler (SIGTSTP, old_tstp);
2931 set_signal_handler (SIGTTOU, old_ttou);
2932 set_signal_handler (SIGTTIN, old_ttin);
2934 old_cont = set_signal_handler (SIGCONT, cont_signal_handler);
2936 give_terminal_to (shell_pgrp);
2938 kill (getpid (), sig);
2943 /* Give the terminal to PGRP. */
2945 give_terminal_to (pgrp)
2955 sigaddset (&set, SIGTTOU);
2956 sigaddset (&set, SIGTTIN);
2957 sigaddset (&set, SIGTSTP);
2958 sigaddset (&set, SIGCHLD);
2959 sigemptyset (&oset);
2960 sigprocmask (SIG_BLOCK, &set, &oset);
2962 if (tcsetpgrp (shell_tty, pgrp) < 0)
2964 /* Maybe we should print an error message? */
2966 sys_error ("tcsetpgrp(%d) failed: pid %d to pgrp %d",
2967 shell_tty, getpid(), pgrp);
2972 terminal_pgrp = pgrp;
2973 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2979 /* Clear out any jobs in the job array. This is intended to be used by
2980 children of the shell, who should not have any job structures as baggage
2981 when they start executing (forking subshells for parenthesized execution
2982 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
2983 is nonzero, only running jobs are removed from the table. */
2985 delete_all_jobs (running_only)
2991 BLOCK_CHILD (set, oset);
2995 current_job = previous_job = NO_JOB;
2997 for (i = 0; i < job_slots; i++)
2998 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3001 if (running_only == 0)
3003 free ((char *)jobs);
3008 UNBLOCK_CHILD (oset);
3011 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
3012 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
3014 nohup_all_jobs (running_only)
3020 BLOCK_CHILD (set, oset);
3024 for (i = 0; i < job_slots; i++)
3025 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3029 UNBLOCK_CHILD (oset);
3038 BLOCK_CHILD (set, oset);
3039 for (i = n = 0; i < job_slots; i++)
3040 if (jobs[i] && DEADJOB(i) == 0)
3042 UNBLOCK_CHILD (oset);
3047 mark_all_jobs_as_dead ()
3054 BLOCK_CHILD (set, oset);
3056 for (i = 0; i < job_slots; i++)
3058 jobs[i]->state = JDEAD;
3060 UNBLOCK_CHILD (oset);
3064 /* Mark all dead jobs as notified, so delete_job () cleans them out
3065 of the job table properly. POSIX.2 says we need to save the
3066 status of the last CHILD_MAX jobs, so we count the number of dead
3067 jobs and mark only enough as notified to save CHILD_MAX statuses. */
3069 mark_dead_jobs_as_notified (force)
3072 register int i, ndead;
3077 BLOCK_CHILD (set, oset);
3079 /* Count the number of dead jobs */
3080 for (i = ndead = 0; force == 0 && i < job_slots; i++)
3082 if (jobs[i] && DEADJOB (i))
3086 /* Don't do anything if the number of jobs is less than CHILD_MAX and
3087 we're not forcing a cleanup. */
3088 if (force == 0 && ndead <= CHILD_MAX)
3090 UNBLOCK_CHILD (oset);
3094 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
3095 the list. This isn't exactly right yet; changes need to be made
3096 to stop_pipeline so we don't mark the newer jobs after we've
3097 created CHILD_MAX slots in the jobs array. */
3098 for (i = 0; i < job_slots; i++)
3100 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i) != last_asynchronous_pid)))
3102 jobs[i]->flags |= J_NOTIFIED;
3103 if (force == 0 && --ndead <= CHILD_MAX)
3108 UNBLOCK_CHILD (oset);
3112 /* Here to allow other parts of the shell (like the trap stuff) to
3113 unfreeze the jobs list. */
3115 unfreeze_jobs_list ()
3117 jobs_list_frozen = 0;
3120 /* Allow or disallow job control to take place. Returns the old value
3123 set_job_control (arg)
3133 /* Turn off all traces of job control. This is run by children of the shell
3134 which are going to do shellsy things, like wait (), etc. */
3136 without_job_control ()
3138 stop_making_children ();
3140 delete_all_jobs (0);
3141 set_job_control (0);
3144 /* If this shell is interactive, terminate all stopped jobs and
3145 restore the original terminal process group. This is done
3146 before the `exec' builtin calls shell_execve. */
3150 if (interactive_shell) /* XXX - should it be interactive? */
3152 terminate_stopped_jobs ();
3154 if (original_pgrp >= 0)
3155 give_terminal_to (original_pgrp);
3158 if (original_pgrp >= 0)
3159 setpgid (0, original_pgrp);
3162 /* Restart job control by closing shell tty and reinitializing. This is
3163 called after an exec fails in an interactive shell and we do not exit. */
3165 restart_job_control ()
3167 if (shell_tty != -1)
3169 initialize_job_control (0);
3172 /* Set the handler to run when the shell receives a SIGCHLD signal. */
3174 set_sigchld_handler ()
3176 set_signal_handler (SIGCHLD, sigchld_handler);
3179 #if defined (PGRP_PIPE)
3180 /* Read from the read end of a pipe. This is how the process group leader
3181 blocks until all of the processes in a pipeline have been made. */
3196 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
3201 /* Close the read and write ends of PP, an array of file descriptors. */
3215 /* Functional interface closes our local-to-job-control pipes. */
3219 pipe_close (pgrp_pipe);
3222 #endif /* PGRP_PIPE */
3228 #if defined (ARRAY_VARS)
3230 register PROCESS *p;
3232 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
3237 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
3244 pstatuses[i++] = process_exit_status (p->status);
3247 while (p != jobs[j]->pipe);
3249 pstatuses[i] = -1; /* sentinel */
3250 set_pipestatus_array (pstatuses);