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 __P((int, int));
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;
150 #if defined (ARRAY_VARS)
151 static int *pstatuses; /* list of pipeline statuses */
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 ();
159 /* The array of known jobs. */
160 JOB **jobs = (JOB **)NULL;
162 /* The number of slots currently allocated to JOBS. */
165 /* The controlling tty for this shell. */
168 /* The shell's process group. */
169 pid_t shell_pgrp = NO_PID;
171 /* The terminal's process group. */
172 pid_t terminal_pgrp = NO_PID;
174 /* The process group of the shell's parent. */
175 pid_t original_pgrp = NO_PID;
177 /* The process group of the pipeline currently being made. */
178 pid_t pipeline_pgrp = (pid_t)0;
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 };
187 /* The job which is current; i.e. the one that `%+' stands for. */
188 int current_job = NO_JOB;
190 /* The previous job; i.e. the one that `%-' stands for. */
191 int previous_job = NO_JOB;
193 /* Last child made by the shell. */
194 pid_t last_made_pid = NO_PID;
196 /* Pid of the last asynchronous child. */
197 pid_t last_asynchronous_pid = NO_PID;
199 /* The pipeline currently being built. */
200 PROCESS *the_pipeline = (PROCESS *)NULL;
202 /* If this is non-zero, do job control. */
205 /* Call this when you start making children. */
206 int already_making_children = 0;
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;
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 ();
232 /* Used to synchronize between wait_for and the SIGCHLD signal handler. */
234 static int waiting_for_job;
236 /* A place to temporarily save the current pipeline. */
237 static PROCESS *saved_pipeline;
238 static int saved_already_making_children;
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
244 static int jobs_list_frozen;
246 static sigset_t empty_sigset;
247 static sigset_t sigchld_sigset;
249 static char retcode_name_buffer[64];
251 #if !defined (_POSIX_VERSION)
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))
264 /* ioctl will handle setting errno correctly. */
265 if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
270 #endif /* !_POSIX_VERSION */
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. */
277 current_working_directory ()
280 static char d[PATH_MAX];
282 dir = get_string_value ("PWD");
284 if (dir == 0 && the_current_working_directory && no_symbolic_links)
285 dir = the_current_working_directory;
289 dir = getcwd (d, sizeof(d));
294 return (dir == 0) ? "<unknown>" : dir;
297 /* Return the working directory for the current process. */
299 job_working_directory ()
303 dir = get_string_value ("PWD");
305 return (savestring (dir));
307 dir = get_working_directory ("job-working-directory");
311 return (savestring ("<unknown>"));
317 if (already_making_children)
320 already_making_children = 1;
325 stop_making_children ()
327 already_making_children = 0;
331 cleanup_the_pipeline ()
335 discard_pipeline (the_pipeline);
336 the_pipeline = (PROCESS *)NULL;
341 save_pipeline (clear)
344 saved_pipeline = the_pipeline;
345 saved_already_making_children = already_making_children;
347 the_pipeline = (PROCESS *)NULL;
351 restore_pipeline (discard)
354 PROCESS *old_pipeline;
356 old_pipeline = the_pipeline;
357 the_pipeline = saved_pipeline;
358 already_making_children = saved_already_making_children;
360 discard_pipeline (old_pipeline);
363 /* Start building a pipeline. */
369 cleanup_the_pipeline ();
371 #if defined (PGRP_PIPE)
372 pipe_close (pgrp_pipe);
376 #if defined (PGRP_PIPE)
379 if (pipe (pgrp_pipe) == -1)
380 sys_error ("start_pipeline: pgrp pipe");
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. */
390 stop_pipeline (async, deferred)
398 BLOCK_CHILD (set, oset);
400 #if defined (PGRP_PIPE)
401 /* The parent closes the process group synchronization pipe. */
402 pipe_close (pgrp_pipe);
405 cleanup_dead_jobs ();
409 job_slots = JOB_SLOTS;
410 jobs = (JOB **)xmalloc (job_slots * sizeof (JOB *));
412 /* Now blank out these new entries. */
413 for (i = 0; i < job_slots; i++)
414 jobs[i] = (JOB *)NULL;
417 /* Scan from the last slot backward, looking for the next free one. */
420 for (i = job_slots; i; i--)
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++)
436 /* Do we need more room? */
439 job_slots += JOB_SLOTS;
440 jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
442 for (j = i; j < job_slots; j++)
443 jobs[j] = (JOB *)NULL;
446 /* Add the current pipeline to the job list. */
450 int any_alive, any_stopped;
452 newjob = (JOB *)xmalloc (sizeof (JOB));
454 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
456 p->next = (PROCESS *)NULL;
457 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
458 for (p = newjob->pipe; p->next; p = p->next)
460 p->next = newjob->pipe;
462 the_pipeline = (PROCESS *)NULL;
463 newjob->pgrp = pipeline_pgrp;
468 /* Flag to see if in another pgrp. */
470 newjob->flags |= J_JOBCONTROL;
472 /* Set the state of this pipeline. */
474 any_alive = any_stopped = 0;
477 any_alive |= p->running;
478 any_stopped |= WIFSTOPPED (p->status);
481 while (p != newjob->pipe);
483 newjob->state = any_alive ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
484 newjob->wd = job_working_directory ();
485 newjob->deferred = deferred;
487 newjob->j_cleanup = (VFunction *)NULL;
488 newjob->cleanarg = (PTR_T) NULL;
491 if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
495 newjob = (JOB *)NULL;
500 newjob->flags &= ~J_FOREGROUND;
507 newjob->flags |= J_FOREGROUND;
509 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
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.
517 if (job_control && newjob->pgrp)
518 give_terminal_to (newjob->pgrp, 0);
522 stop_making_children ();
523 UNBLOCK_CHILD (oset);
524 return (current_job);
527 /* Delete all DEAD jobs that the user had received notification about. */
534 if (job_slots == 0 || jobs_list_frozen)
537 BLOCK_CHILD (set, oset);
539 for (i = 0; i < job_slots; i++)
540 if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
543 UNBLOCK_CHILD (oset);
546 /* Delete the job at INDEX from the job list. Must be called
547 with SIGCHLD blocked. */
549 delete_job (job_index, warn_stopped)
550 int job_index, warn_stopped;
554 if (job_slots == 0 || jobs_list_frozen)
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);
560 temp = jobs[job_index];
561 if (job_index == current_job || job_index == previous_job)
564 jobs[job_index] = (JOB *)NULL;
567 discard_pipeline (temp->pipe);
570 dispose_command (temp->deferred);
575 /* Must be called with SIGCHLD blocked. */
577 nohup_job (job_index)
585 if (temp = jobs[job_index])
586 temp->flags |= J_NOHUP;
589 /* Get rid of the data structure associated with a process chain. */
591 discard_pipeline (chain)
592 register PROCESS *chain;
594 register PROCESS *this, *next;
600 FREE (this->command);
604 while (this != chain);
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. */
611 add_process (name, pid)
617 t = (PROCESS *)xmalloc (sizeof (PROCESS));
618 t->next = the_pipeline;
620 WSTATUS (t->status) = 0;
630 while (p->next != t->next)
637 /* Take the last job and make it the first job. Must be called with
640 rotate_the_pipeline ()
644 if (the_pipeline->next == the_pipeline)
646 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
651 /* Reverse the order of the processes in the_pipeline. Must be called with
654 reverse_the_pipeline ()
658 if (the_pipeline->next == the_pipeline)
661 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
663 p->next = (PROCESS *)NULL;
665 n = REVERSE_LIST (the_pipeline, PROCESS *);
668 for (p = the_pipeline; p->next; p = p->next)
670 p->next = the_pipeline;
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,
679 map_over_jobs (func, arg1, arg2)
690 BLOCK_CHILD (set, oset);
692 for (i = result = 0; i < job_slots; i++)
696 result = (*func)(jobs[i], arg1, arg2, i);
702 UNBLOCK_CHILD (oset);
707 /* Cause all the jobs in the current pipeline to exit. */
709 terminate_current_pipeline ()
711 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
713 killpg (pipeline_pgrp, SIGTERM);
714 killpg (pipeline_pgrp, SIGCONT);
718 /* Cause all stopped jobs to exit. */
720 terminate_stopped_jobs ()
724 for (i = 0; i < job_slots; i++)
726 if (jobs[i] && STOPPED (i))
728 killpg (jobs[i]->pgrp, SIGTERM);
729 killpg (jobs[i]->pgrp, SIGCONT);
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. */
741 for (i = 0; i < job_slots; i++)
745 if ((jobs[i]->flags & J_NOHUP) == 0)
746 killpg (jobs[i]->pgrp, SIGHUP);
748 killpg (jobs[i]->pgrp, SIGCONT);
754 kill_current_pipeline ()
756 stop_making_children ();
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. */
769 /* See if this process is in the pipeline that we are building. */
775 /* Return it if we found it. */
781 while (p != the_pipeline);
784 job = find_job (pid);
786 return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
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. */
798 for (i = 0; i < job_slots; i++)
811 while (p != jobs[i]->pipe);
818 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
819 required by find_job. */
821 get_job_by_pid (pid, block)
829 BLOCK_CHILD (set, oset);
830 job = find_job (pid);
832 UNBLOCK_CHILD (oset);
837 /* Print descriptive information about the job with leader pid PID. */
845 BLOCK_CHILD (set, oset);
847 job = find_job (pid);
850 printf ("[%d] %d\n", job + 1, (int)pid);
852 programming_error ("describe_pid: %d: no such pid", (int)pid);
854 UNBLOCK_CHILD (oset);
858 printable_job_status (j, p, format)
868 if (STOPPED (j) && format == 0)
870 if (posixly_correct == 0 || p == 0 || (WIFSTOPPED (p->status) == 0))
874 temp = retcode_name_buffer;
875 sprintf (temp, "Stopped(%s)", signal_name (WSTOPSIG (p->status)));
878 else if (RUNNING (j))
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))
888 temp = retcode_name_buffer;
889 es = WEXITSTATUS (p->status);
891 strcpy (temp, "Done");
892 else if (posixly_correct)
893 sprintf (temp, "Done(%d)", es);
895 sprintf (temp, "Exit %d", es);
898 temp = "Unknown status";
904 /* This is the way to print out information on a job if you
905 know the index. FORMAT is:
907 JLIST_NORMAL) [1]+ Running emacs
908 JLIST_LONG ) [1]+ 2378 Running emacs
911 JLIST_NORMAL) [1]+ Stopped ls | more
912 JLIST_LONG ) [1]+ 2369 Stopped ls
915 Just list the pid of the process group leader (really
918 Use format JLIST_NORMAL, but list only jobs about which
919 the user has not been notified. */
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.
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 */
928 print_pipeline (p, job_index, format, stream)
930 int job_index, format;
933 PROCESS *first, *last, *show;
934 int es, name_padding;
941 while (last->next != first)
947 fprintf (stream, format ? " " : " |");
949 if (format != JLIST_STANDARD)
950 fprintf (stream, "%5d", (int)p->pid);
952 fprintf (stream, " ");
954 if (format > -1 && job_index >= 0)
956 show = format ? p : last;
957 temp = printable_job_status (job_index, show, format);
963 if (show->running == first->running &&
964 WSTATUS (show->status) == WSTATUS (first->status))
973 fprintf (stream, "%s", temp);
977 es = 2; /* strlen ("| ") */
978 name_padding = LONGEST_SIGNAL_DESC - es;
980 fprintf (stream, "%*s", name_padding, "");
982 if ((WIFSTOPPED (show->status) == 0) && WIFCORED (show->status))
983 fprintf (stream, "(core dumped) ");
987 if (p != first && format)
988 fprintf (stream, "| ");
991 fprintf (stream, "%s", p->command);
993 if (p == last && job_index >= 0)
995 temp = current_working_directory ();
997 if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
998 fprintf (stream, " &");
1000 if (strcmp (temp, jobs[job_index]->wd) != 0)
1002 " (wd: %s)", polite_directory_format (jobs[job_index]->wd));
1005 if (format || (p == last))
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");
1015 fprintf (stream, "\n");
1026 pretty_print_job (job_index, format, stream)
1027 int job_index, format;
1030 register PROCESS *p;
1033 BLOCK_CHILD (set, oset);
1035 /* Format only pid information about the process group leader? */
1036 if (format == JLIST_PID_ONLY)
1038 fprintf (stream, "%d\n", (int)jobs[job_index]->pipe->pid);
1039 UNBLOCK_CHILD (oset);
1043 if (format == JLIST_CHANGED_ONLY)
1045 if (IS_NOTIFIED (job_index))
1047 UNBLOCK_CHILD (oset);
1050 format = JLIST_STANDARD;
1053 if (format != JLIST_NONINTERACTIVE)
1054 fprintf (stream, "[%d]%c ", job_index + 1,
1055 (job_index == current_job) ? '+':
1056 (job_index == previous_job) ? '-' : ' ');
1058 if (format == JLIST_NONINTERACTIVE)
1059 format = JLIST_LONG;
1061 p = jobs[job_index]->pipe;
1063 print_pipeline (p, job_index, format, stream);
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;
1069 UNBLOCK_CHILD (oset);
1073 print_job (job, format, state, job_index)
1075 int format, state, job_index;
1077 if (state == -1 || (JOB_STATE)state == job->state)
1078 pretty_print_job (job_index, format, stdout);
1083 list_one_job (job, format, ignore, job_index)
1085 int format, ignore, job_index;
1087 print_job (job, format, -1, job_index);
1091 list_stopped_jobs (format)
1094 cleanup_dead_jobs ();
1095 map_over_jobs (print_job, format, (int)JSTOPPED);
1099 list_running_jobs (format)
1102 cleanup_dead_jobs ();
1103 map_over_jobs (print_job, format, (int)JRUNNING);
1106 /* List jobs. If FORMAT is non-zero, then the long form of the information
1107 is printed, else just a short version. */
1109 list_all_jobs (format)
1112 cleanup_dead_jobs ();
1113 map_over_jobs (print_job, format, -1);
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. */
1121 make_child (command, async_p)
1129 sigaddset (&set, SIGCHLD);
1130 sigaddset (&set, SIGINT);
1131 sigemptyset (&oset);
1132 sigprocmask (SIG_BLOCK, &set, &oset);
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 */
1146 /* Create the child, handle severe errors. */
1147 if ((pid = fork ()) < 0)
1151 /* Kill all of the processes in the current pipeline. */
1152 terminate_current_pipeline ();
1154 /* Discard the current pipeline, if any. */
1156 kill_current_pipeline ();
1158 throw_to_top_level (); /* Reset signals, etc. */
1163 /* In the child. Give this child the right process group, set the
1164 signals to the default state for a new process. */
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 */
1175 /* Restore top-level signal mask. */
1176 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1180 /* All processes in this pipeline belong in the same
1183 if (pipeline_pgrp == 0) /* This is the first child. */
1184 pipeline_pgrp = mypid;
1186 /* Check for running command in backquotes. */
1187 if (pipeline_pgrp == shell_pgrp)
1188 ignore_tty_job_signals ();
1190 default_tty_job_signals ();
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
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)
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);
1215 #if defined (PGRP_PIPE)
1216 pipe_read (pgrp_pipe);
1220 else /* Without job control... */
1222 if (pipeline_pgrp == 0)
1223 pipeline_pgrp = shell_pgrp;
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. */
1232 default_tty_job_signals ();
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 */
1242 last_asynchronous_pid = getpid ();
1246 /* In the parent. Remember the pid of the child just created
1247 as the proper pgrp if this is the first child. */
1251 if (pipeline_pgrp == 0)
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); */
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);
1266 if (pipeline_pgrp == 0)
1267 pipeline_pgrp = shell_pgrp;
1270 /* Place all processes into the jobs array regardless of the
1271 state of job_control. */
1272 add_process (command, pid);
1275 last_asynchronous_pid = pid;
1277 last_made_pid = pid;
1279 /* Unblock SIGINT and SIGCHLD. */
1280 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1287 ignore_tty_job_signals ()
1289 set_signal_handler (SIGTSTP, SIG_IGN);
1290 set_signal_handler (SIGTTIN, SIG_IGN);
1291 set_signal_handler (SIGTTOU, SIG_IGN);
1295 default_tty_job_signals ()
1297 set_signal_handler (SIGTSTP, SIG_DFL);
1298 set_signal_handler (SIGTTIN, SIG_DFL);
1299 set_signal_handler (SIGTTOU, SIG_DFL);
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. */
1306 static TTYSTRUCT shell_tty_info;
1308 #if defined (NEW_TTY_DRIVER)
1309 static struct tchars shell_tchars;
1310 static struct ltchars shell_ltchars;
1311 #endif /* NEW_TTY_DRIVER */
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. */
1323 static int ttspeeds[] =
1325 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1326 1800, 2400, 4800, 9600, 19200, 38400
1333 register int delay = ttspeeds[ospeed];
1339 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1341 if (n > (delay / 100))
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);
1354 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1356 /* Return the fd from which we are actually getting input. */
1357 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1359 /* Fill the contents of shell_tty_info with the current tty info. */
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 */
1374 #if defined (TERMIO_TTY_DRIVER)
1375 ioctl (tty, TCGETA, &shell_tty_info);
1376 #endif /* TERMIO_TTY_DRIVER */
1378 #if defined (TERMIOS_TTY_DRIVER)
1379 if (tcgetattr (tty, &shell_tty_info) < 0)
1382 /* Only print an error message if we're really interactive at
1385 sys_error ("[%d: %d] tcgetattr", getpid (), shell_level);
1389 #endif /* TERMIOS_TTY_DRIVER */
1390 if (check_window_size)
1391 get_new_window_size (0);
1396 /* Make the current tty use the state in shell_tty_info. */
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 */
1414 #if defined (TERMIO_TTY_DRIVER)
1415 ioctl (tty, TCSETAW, &shell_tty_info);
1416 #endif /* TERMIO_TTY_DRIVER */
1418 #if defined (TERMIOS_TTY_DRIVER)
1419 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1421 /* Only print an error message if we're really interactive at
1424 sys_error ("[%d: %d] tcsetattr", getpid (), shell_level);
1427 #endif /* TERMIOS_TTY_DRIVER */
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
1439 register PROCESS *p;
1441 p = jobs[job]->pipe;
1442 while (p->next != jobs[job]->pipe)
1455 BLOCK_CHILD (set, oset);
1456 pid = find_last_pid (job);
1457 UNBLOCK_CHILD (oset);
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. */
1468 wait_for_single_pid (pid)
1471 register PROCESS *child;
1475 BLOCK_CHILD (set, oset);
1476 child = find_pipeline (pid);
1477 UNBLOCK_CHILD (oset);
1481 internal_error ("wait: pid %d is not a child of this shell", pid);
1487 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
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);
1498 /* Wait for all of the backgrounds of this shell to finish. */
1500 wait_for_background_pids ()
1502 register int i, count, r, waited_for;
1506 for (waited_for = 0;;)
1508 BLOCK_CHILD (set, oset);
1511 for (i = 0; i < job_slots; i++)
1512 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1520 UNBLOCK_CHILD (oset);
1524 for (i = 0; i < job_slots; i++)
1525 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1528 UNBLOCK_CHILD (oset);
1530 errno = 0; /* XXX */
1531 r = wait_for_single_pid (pid);
1534 if (errno == ECHILD)
1535 mark_all_jobs_as_dead ();
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 ();
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;
1554 restore_sigint_handler ()
1556 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1558 set_signal_handler (SIGINT, old_sigint_handler);
1559 old_sigint_handler = INVALID_SIGNAL_HANDLER;
1563 static int wait_sigint_received;
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). */
1569 wait_sigint_handler (sig)
1572 SigHandler *sigint_handler;
1574 if (interrupt_immediately ||
1575 (this_shell_builtin && this_shell_builtin == wait_builtin))
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))
1585 interrupt_immediately = 0;
1586 trap_handler (SIGINT); /* set pending_traps[SIGINT] */
1587 longjmp (wait_intr_buf, 1);
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;
1598 /* Otherwise effectively ignore the SIGINT and allow the running job to
1604 process_exit_status (status)
1607 if (WIFSIGNALED (status))
1608 return (128 + WTERMSIG (status));
1609 else if (WIFSTOPPED (status) == 0)
1610 return (WEXITSTATUS (status));
1612 return (EXECUTION_SUCCESS);
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. */
1618 raw_job_exit_status (job)
1620 register PROCESS *p;
1621 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
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. */
1630 job_exit_status (job)
1633 return (process_exit_status (raw_job_exit_status (job)));
1636 #define FIND_CHILD(pid, child) \
1639 child = find_pipeline (pid); \
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); \
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. */
1659 int job, termination_state, r;
1661 register PROCESS *child;
1663 register PROCESS *p;
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);
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. */
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);
1681 termination_state = last_command_exit_value;
1683 if (interactive && job_control == 0)
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(). */
1692 FIND_CHILD (pid, child);
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. */
1699 job = find_job (pid);
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. */
1705 if (child->running || (job != NO_JOB && RUNNING (job)))
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;
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);
1723 sigaction (SIGCHLD, &act, &oact);
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);
1731 waiting_for_job = 0;
1732 if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
1734 termination_state = -1;
1735 goto wait_for_return;
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)
1745 child->status = 0; /* XXX */
1747 jobs[job]->state = JDEAD;
1749 #endif /* WAITPID_BROKEN */
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)
1759 while (child->running || (job != NO_JOB && RUNNING (job)));
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. */
1765 termination_state = job_exit_status (job);
1767 termination_state = process_exit_status (child->status);
1769 if (job == NO_JOB || IS_JOBCONTROL (job))
1771 /* XXX - under what circumstances is a job not present in the jobs
1772 table (job == NO_JOB)?
1773 1. command substitution
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
1781 $PROMPT_COMMAND execution
1782 process substitution
1786 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%d)", shell_pgrp);
1789 give_terminal_to (shell_pgrp, 0);
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. */
1799 if (interactive_shell && subshell_environment == 0)
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;
1815 if (WIFSIGNALED(s) || WIFSTOPPED(s))
1819 while (p != jobs[job]->pipe);
1821 if (WIFSIGNALED (s) || WIFSTOPPED (s))
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);
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)
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)
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 ();
1864 UNBLOCK_CHILD (oset);
1866 /* Restore the original SIGINT signal handler before we return. */
1867 restore_sigint_handler ();
1869 return (termination_state);
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. */
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);
1888 pid = last_pid (job);
1891 /* POSIX.2: we can remove the job from the jobs table if we just waited
1893 BLOCK_CHILD (set, oset);
1894 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1895 jobs[job]->flags |= J_NOTIFIED;
1896 UNBLOCK_CHILD (oset);
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
1906 notify_and_cleanup ()
1908 if (jobs_list_frozen)
1911 if (interactive || interactive_shell == 0 || sourcelevel)
1912 notify_of_job_status ();
1914 cleanup_dead_jobs ();
1917 /* Make dead jobs disappear from the jobs array without notification.
1918 This is used when the shell is not interactive. */
1922 mark_dead_jobs_as_notified (0);
1923 cleanup_dead_jobs ();
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. */
1930 most_recent_job_in_state (job, state)
1934 register int i, result;
1937 BLOCK_CHILD (set, oset);
1938 for (result = NO_JOB, i = job - 1; i >= 0; i--)
1940 if (jobs[i] && (JOBSTATE (i) == state))
1946 UNBLOCK_CHILD (oset);
1951 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
1954 job_last_stopped (job)
1957 return (most_recent_job_in_state (job, JSTOPPED));
1960 /* Return the newest *running* job older than JOB, or NO_JOB if not
1963 job_last_running (job)
1966 return (most_recent_job_in_state (job, JRUNNING));
1969 /* Make JOB be the current job, and make previous be useful. Must be
1970 called with SIGCHLD blocked. */
1972 set_current_job (job)
1977 if (current_job != job)
1979 previous_job = current_job;
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))
1990 /* Second choice: Newest stopped job that is older than
1993 if (STOPPED (current_job))
1995 candidate = job_last_stopped (current_job);
1997 if (candidate != NO_JOB)
1999 previous_job = candidate;
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
2011 candidate = RUNNING (current_job) ? job_last_running (current_job)
2012 : job_last_running (job_slots);
2014 if (candidate != NO_JOB)
2016 previous_job = candidate;
2020 /* There is only a single job, and it is both `+' and `-'. */
2021 previous_job = current_job;
2024 /* Make current_job be something useful, if it isn't already. */
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. */
2037 if (job_slots && current_job != NO_JOB && jobs[current_job] && STOPPED (current_job))
2038 candidate = current_job;
2043 /* First choice: the previous job. */
2044 if (previous_job != NO_JOB && jobs[previous_job] && STOPPED (previous_job))
2045 candidate = previous_job;
2047 /* Second choice: the most recently stopped job. */
2048 if (candidate == NO_JOB)
2049 candidate = job_last_stopped (job_slots);
2051 /* Third choice: the newest running job. */
2052 if (candidate == NO_JOB)
2053 candidate = job_last_running (job_slots);
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);
2061 current_job = previous_job = NO_JOB;
2064 /* Set up the job structures so we know the job and its processes are
2067 set_job_running (job)
2070 register PROCESS *p;
2072 /* Each member of the pipeline is now running. */
2073 p = jobs[job]->pipe;
2077 if (WIFSTOPPED (p->status))
2081 while (p != jobs[job]->pipe);
2083 /* This means that the job is running. */
2084 JOBSTATE (job) = JRUNNING;
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. */
2092 start_job (job, foreground)
2093 int job, foreground;
2095 register PROCESS *p;
2096 int already_running;
2099 static TTYSTRUCT save_stty;
2101 BLOCK_CHILD (set, oset);
2105 internal_error ("%s: job has terminated", this_command_name);
2106 UNBLOCK_CHILD (oset);
2110 already_running = RUNNING (job);
2112 if (foreground == 0 && already_running)
2114 internal_error ("%s: bg background job?", this_command_name);
2115 UNBLOCK_CHILD (oset);
2119 wd = current_working_directory ();
2121 /* You don't know about the state of this job. Do you? */
2122 jobs[job]->flags &= ~J_NOTIFIED;
2126 set_current_job (job);
2127 jobs[job]->flags |= J_FOREGROUND;
2130 /* Tell the outside world what we're doing. */
2131 p = jobs[job]->pipe;
2133 if (foreground == 0)
2134 fprintf (stderr, "[%d]%c ", job + 1,
2135 (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
2139 fprintf (stderr, "%s%s",
2140 p->command ? p->command : "",
2141 p->next != jobs[job]->pipe? " | " : "");
2144 while (p != jobs[job]->pipe);
2146 if (foreground == 0)
2147 fprintf (stderr, " &");
2149 if (strcmp (wd, jobs[job]->wd) != 0)
2150 fprintf (stderr, " (wd: %s)", polite_directory_format (jobs[job]->wd));
2152 fprintf (stderr, "\n");
2155 if (already_running == 0)
2156 set_job_running (job);
2158 /* Save the tty settings before we start the job in the foreground. */
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);
2168 jobs[job]->flags &= ~J_FOREGROUND;
2170 /* If the job is already running, then don't bother jump-starting it. */
2171 if (already_running == 0)
2173 jobs[job]->flags |= J_NOTIFIED;
2174 killpg (jobs[job]->pgrp, SIGCONT);
2177 UNBLOCK_CHILD (oset);
2184 pid = last_pid (job);
2186 shell_tty_info = save_stty;
2192 BLOCK_CHILD (set, oset);
2194 UNBLOCK_CHILD (oset);
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. */
2204 kill_pid (pid, sig, group)
2208 register PROCESS *p;
2212 BLOCK_CHILD (set, oset);
2213 p = find_pipeline (pid);
2214 job = find_job (pid);
2216 result = EXECUTION_SUCCESS;
2221 jobs[job]->flags &= ~J_NOTIFIED;
2223 /* Kill process in backquotes or one started without job control? */
2224 if (jobs[job]->pgrp == shell_pgrp)
2226 p = jobs[job]->pipe;
2231 if (p->running == 0 && (sig == SIGTERM || sig == SIGHUP))
2232 kill (p->pid, SIGCONT);
2235 while (p != jobs[job]->pipe);
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))
2246 set_job_running (job);
2247 jobs[job]->flags &= ~J_FOREGROUND;
2248 jobs[job]->flags |= J_NOTIFIED;
2253 result = killpg (pid, sig);
2256 result = kill (pid, sig);
2258 UNBLOCK_CHILD (oset);
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. */
2265 sigchld_handler (sig)
2271 REINSTALL_SIGCHLD_HANDLER;
2274 if (waiting_for_job == 0)
2275 n = waitchld (-1, 0);
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
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
2288 waitchld (wpid, block)
2295 int call_set_current, last_stopped_job, job, children_exited, waitpid_flags;
2297 call_set_current = children_exited = 0;
2298 last_stopped_job = NO_JOB;
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)
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))
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)
2319 if (children_exited == 0)
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. */
2328 continue; /* jumps right to the test */
2332 /* Locate our PROCESS for this pid. */
2333 child = find_pipeline (pid);
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. */
2342 while (child->pid != pid)
2343 child = child->next;
2345 /* Remember status, and fact that process is not running. */
2346 child->status = status;
2349 job = find_job (pid);
2354 call_set_current += set_job_status_and_cleanup (job);
2357 last_stopped_job = job;
2358 else if (DEADJOB (job) && last_stopped_job == job)
2359 last_stopped_job = NO_JOB;
2361 while ((sigchld || block == 0) && pid > (pid_t)0);
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)
2367 if (last_stopped_job != NO_JOB)
2368 set_current_job (last_stopped_job);
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);
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 ();
2385 return (children_exited);
2388 /* Set the status of JOB and perform any necessary cleanup if the job is
2391 Currently, the cleanup activity is restricted to handling any SIGINT
2392 received while waiting for a foreground job to finish. */
2394 set_job_status_and_cleanup (job)
2398 int tstatus, job_state, any_stopped, any_tstped, call_set_current;
2399 SigHandler *temp_handler;
2401 child = jobs[job]->pipe;
2402 jobs[job]->flags &= ~J_NOTIFIED;
2404 call_set_current = 0;
2407 * COMPUTE JOB STATUS
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;
2415 job_state |= child->running;
2416 if (child->running == 0 && (WIFSTOPPED (child->status)))
2419 any_tstped |= interactive && job_control &&
2420 (WSTOPSIG (child->status) == SIGTSTP);
2422 child = child->next;
2424 while (child != jobs[job]->pipe);
2426 /* If job_state != 0, the job is still running, so don't bother with
2427 setting the process exit status and job state. */
2435 /* The job is either stopped or dead. Set the state of the job accordingly. */
2438 jobs[job]->state = JSTOPPED;
2439 jobs[job]->flags &= ~J_FOREGROUND;
2441 /* Suspending a job with SIGTSTP breaks all active loops. */
2442 if (any_tstped && loop_level)
2443 breaking = loop_level;
2447 jobs[job]->state = JDEAD;
2449 if (IS_FOREGROUND (job))
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)
2458 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
2459 jobs[job]->j_cleanup = (VFunction *)NULL;
2466 * Currently, we just do special things if we got a SIGINT while waiting
2467 * for a foreground job to complete
2470 if (jobs[job]->state == JDEAD)
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))
2480 wait_sigint_received = 0;
2481 last_command_exit_value = process_exit_status (child->status);
2483 jobs_list_frozen = 1;
2484 tstatus = maybe_call_trap_handler (SIGINT);
2485 jobs_list_frozen = 0;
2488 /* If the foreground job is killed by SIGINT when job control is not
2489 active, we need to perform some special handling.
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)
2500 wait_sigint_received = 0;
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);
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)
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. */
2523 temp_handler = old_sigint_handler;
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);
2541 return call_set_current;
2544 /* Build the array of values for the $PIPESTATUS variable from the set of
2545 exit statuses of all processes in the job J. */
2550 #if defined (ARRAY_VARS)
2552 register PROCESS *p;
2554 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
2559 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
2566 pstatuses[i++] = process_exit_status (p->status);
2569 while (p != jobs[j]->pipe);
2571 pstatuses[i] = -1; /* sentinel */
2572 set_pipestatus_array (pstatuses);
2577 run_sigchld_trap (nchild)
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]);
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);
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);
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);
2606 subst_assign_varlist = (WORD_LIST *)NULL;
2607 the_pipeline = (PROCESS *)NULL;
2609 restore_default_signal (SIGCHLD);
2610 jobs_list_frozen = 1;
2611 for (i = 0; i < nchild; i++)
2613 interrupt_immediately = 1;
2614 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST);
2617 run_unwind_frame ("SIGCHLD trap");
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. */
2625 notify_of_job_status ()
2627 register int job, termsig;
2632 if (jobs == 0 || job_slots == 0)
2636 sigaddset (&set, SIGCHLD);
2637 sigaddset (&set, SIGTTOU);
2638 sigemptyset (&oset);
2639 sigprocmask (SIG_BLOCK, &set, &oset);
2641 for (job = 0, dir = (char *)NULL; job < job_slots; job++)
2643 if (jobs[job] && IS_NOTIFIED (job) == 0)
2645 s = raw_job_exit_status (job);
2646 termsig = WTERMSIG (s);
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)))
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)
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
2666 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job) != last_asynchronous_pid)))
2667 jobs[job]->flags |= J_NOTIFIED;
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))
2677 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
2678 termsig != SIGINT &&
2679 #if defined (DONT_REPORT_SIGPIPE)
2680 termsig != SIGPIPE &&
2682 signal_is_trapped (termsig) == 0)
2684 fprintf (stderr, "%s: line %d: ", get_name_for_error (), line_number);
2685 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
2687 else if (IS_FOREGROUND (job))
2689 #if !defined (DONT_REPORT_SIGPIPE)
2690 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2692 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
2695 fprintf (stderr, "%s", strsignal (termsig));
2698 fprintf (stderr, " (core dumped)");
2700 fprintf (stderr, "\n");
2706 dir = current_working_directory ();
2707 pretty_print_job (job, JLIST_STANDARD, stderr);
2708 if (dir && strcmp (dir, jobs[job]->wd) != 0)
2710 "(wd now: %s)\n", polite_directory_format (dir));
2713 jobs[job]->flags |= J_NOTIFIED;
2717 fprintf (stderr, "\n");
2719 dir = current_working_directory ();
2720 pretty_print_job (job, JLIST_STANDARD, stderr);
2721 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2723 "(wd now: %s)\n", polite_directory_format (dir));
2724 jobs[job]->flags |= J_NOTIFIED;
2732 programming_error ("notify_of_job_status");
2736 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2739 /* Initialize the job control mechanism, and set up the tty stuff. */
2741 initialize_job_control (force)
2744 shell_pgrp = getpgid (0);
2746 if (shell_pgrp == -1)
2748 sys_error ("initialize_job_control: getpgrp failed");
2752 /* We can only have job control if we are interactive. */
2753 if (interactive == 0)
2756 original_pgrp = NO_PID;
2757 shell_tty = fileno (stderr);
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 */
2766 shell_tty = move_to_high_fd (shell_tty, 1, -1);
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)
2772 shell_pgrp = getpid ();
2773 setpgid (0, shell_pgrp);
2774 tcsetpgrp (shell_tty, shell_pgrp);
2777 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2779 if (shell_pgrp != terminal_pgrp)
2781 SigHandler *old_ttin;
2783 old_ttin = set_signal_handler(SIGTTIN, SIG_DFL);
2785 set_signal_handler (SIGTTIN, old_ttin);
2791 /* Make sure that we are using the new line discipline. */
2792 if (set_new_line_discipline (shell_tty) < 0)
2794 sys_error ("initialize_job_control: line discipline");
2799 original_pgrp = shell_pgrp;
2800 shell_pgrp = getpid ();
2802 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
2804 sys_error ("initialize_job_control: setpgid");
2805 shell_pgrp = original_pgrp;
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)
2819 if (give_terminal_to (shell_pgrp, 0) < 0)
2821 setpgid (0, original_pgrp);
2822 shell_pgrp = original_pgrp;
2827 if (job_control == 0)
2828 internal_error ("no job control in this shell");
2831 if (shell_tty != fileno (stderr))
2832 SET_CLOSE_ON_EXEC (shell_tty);
2834 set_signal_handler (SIGCHLD, sigchld_handler);
2836 change_flag ('m', job_control ? '-' : '+');
2846 debug_print_pgrps ()
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));
2855 /* Set the line discipline to the best this system has to offer.
2856 Return -1 if this is not possible. */
2858 set_new_line_discipline (tty)
2861 #if defined (NEW_TTY_DRIVER)
2864 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
2867 if (ldisc != NTTYDISC)
2871 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
2875 #endif /* NEW_TTY_DRIVER */
2877 #if defined (TERMIO_TTY_DRIVER)
2878 # if defined (TERMIO_LDISC) && (NTTYDISC)
2879 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
2882 if (shell_tty_info.c_line != NTTYDISC)
2884 shell_tty_info.c_line = NTTYDISC;
2885 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
2888 # endif /* TERMIO_LDISC && NTTYDISC */
2890 #endif /* TERMIO_TTY_DRIVER */
2892 #if defined (TERMIOS_TTY_DRIVER)
2893 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
2894 if (tcgetattr (tty, &shell_tty_info) < 0)
2897 if (shell_tty_info.c_line != NTTYDISC)
2899 shell_tty_info.c_line = NTTYDISC;
2900 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2903 # endif /* TERMIOS_LDISC && NTTYDISC */
2905 #endif /* TERMIOS_TTY_DRIVER */
2907 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
2912 static SigHandler *old_tstp, *old_ttou, *old_ttin;
2913 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
2914 static sighandler sigstop_sighandler (), sigcont_sighandler ();
2916 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2917 static SigHandler *old_winch = (SigHandler *)SIG_DFL;
2920 get_new_window_size (from_sig)
2925 if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
2926 win.ws_row > 0 && win.ws_col > 0)
2929 shell_tty_info.c_winsize = win; /* structure copying */
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);
2939 sigwinch_sighandler (sig)
2942 #if defined (MUST_REINSTALL_SIGHANDLERS)
2943 set_signal_handler (SIGWINCH, sigwinch_sighandler);
2944 #endif /* MUST_REINSTALL_SIGHANDLERS */
2945 get_new_window_size (1);
2950 get_new_window_size (from_sig)
2954 #endif /* TIOCGWINSZ && SIGWINCH */
2957 set_sigwinch_handler ()
2959 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2960 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
2965 unset_sigwinch_handler ()
2967 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2968 set_signal_handler (SIGWINCH, old_winch);
2972 /* Setup this shell to handle C-C, etc. */
2974 initialize_job_signals ()
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 ();
2984 else if (job_control)
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);
2990 /* Leave these things alone for non-interactive shells without job
2994 /* Here we handle CONT signals. */
2996 sigcont_sighandler (sig)
2999 initialize_job_signals ();
3000 set_signal_handler (SIGCONT, old_cont);
3001 kill (getpid (), SIGCONT);
3006 /* Here we handle stop signals while we are running not as a login shell. */
3008 sigstop_sighandler (sig)
3011 set_signal_handler (SIGTSTP, old_tstp);
3012 set_signal_handler (SIGTTOU, old_ttou);
3013 set_signal_handler (SIGTTIN, old_ttin);
3015 old_cont = set_signal_handler (SIGCONT, sigcont_sighandler);
3017 give_terminal_to (shell_pgrp, 0);
3019 kill (getpid (), sig);
3024 /* Give the terminal to PGRP. */
3026 give_terminal_to (pgrp, force)
3034 if (job_control || force)
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);
3044 if (tcsetpgrp (shell_tty, pgrp) < 0)
3046 /* Maybe we should print an error message? */
3048 sys_error ("tcsetpgrp(%d) failed: pid %d to pgrp %d",
3049 shell_tty, getpid(), pgrp);
3054 terminal_pgrp = pgrp;
3055 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
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. */
3067 delete_all_jobs (running_only)
3073 BLOCK_CHILD (set, oset);
3077 current_job = previous_job = NO_JOB;
3079 for (i = 0; i < job_slots; i++)
3080 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3083 if (running_only == 0)
3085 free ((char *)jobs);
3090 UNBLOCK_CHILD (oset);
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. */
3096 nohup_all_jobs (running_only)
3102 BLOCK_CHILD (set, oset);
3106 for (i = 0; i < job_slots; i++)
3107 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3111 UNBLOCK_CHILD (oset);
3120 BLOCK_CHILD (set, oset);
3121 for (i = n = 0; i < job_slots; i++)
3122 if (jobs[i] && DEADJOB(i) == 0)
3124 UNBLOCK_CHILD (oset);
3129 mark_all_jobs_as_dead ()
3136 BLOCK_CHILD (set, oset);
3138 for (i = 0; i < job_slots; i++)
3140 jobs[i]->state = JDEAD;
3142 UNBLOCK_CHILD (oset);
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. */
3151 mark_dead_jobs_as_notified (force)
3154 register int i, ndead;
3159 BLOCK_CHILD (set, oset);
3161 /* Count the number of dead jobs */
3162 for (i = ndead = 0; force == 0 && i < job_slots; i++)
3164 if (jobs[i] && DEADJOB (i))
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)
3172 UNBLOCK_CHILD (oset);
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++)
3182 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i) != last_asynchronous_pid)))
3184 jobs[i]->flags |= J_NOTIFIED;
3185 if (force == 0 && --ndead <= CHILD_MAX)
3190 UNBLOCK_CHILD (oset);
3194 /* Here to allow other parts of the shell (like the trap stuff) to
3195 unfreeze the jobs list. */
3197 unfreeze_jobs_list ()
3199 jobs_list_frozen = 0;
3202 /* Allow or disallow job control to take place. Returns the old value
3205 set_job_control (arg)
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. */
3218 without_job_control ()
3220 stop_making_children ();
3222 delete_all_jobs (0);
3223 set_job_control (0);
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. */
3232 if (interactive_shell) /* XXX - should it be interactive? */
3234 terminate_stopped_jobs ();
3236 if (original_pgrp >= 0)
3237 give_terminal_to (original_pgrp, 1);
3240 if (original_pgrp >= 0)
3241 setpgid (0, original_pgrp);
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. */
3247 restart_job_control ()
3249 if (shell_tty != -1)
3251 initialize_job_control (0);
3254 /* Set the handler to run when the shell receives a SIGCHLD signal. */
3256 set_sigchld_handler ()
3258 set_signal_handler (SIGCHLD, sigchld_handler);
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. */
3278 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
3283 /* Close the read and write ends of PP, an array of file descriptors. */
3297 /* Functional interface closes our local-to-job-control pipes. */
3301 pipe_close (pgrp_pipe);
3304 #endif /* PGRP_PIPE */