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-2003 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 #include "posixtime.h"
38 #if defined (HAVE_SYS_RESOURCE_H) && defined (HAVE_WAIT3) && !defined (_POSIX_VERSION) && !defined (RLIMTYPE)
39 # include <sys/resource.h>
40 #endif /* !_POSIX_VERSION && HAVE_SYS_RESOURCE_H && HAVE_WAIT3 && !RLIMTYPE */
42 #if defined (HAVE_SYS_FILE_H)
43 # include <sys/file.h>
47 #include <sys/ioctl.h>
48 #include <sys/param.h>
50 #if defined (BUFFERED_INPUT)
54 /* Need to include this up here for *_TTY_DRIVER definitions. */
57 /* Define this if your output is getting swallowed. It's a no-op on
58 machines with the termio or termios tty drivers. */
59 /* #define DRAIN_OUTPUT */
61 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
62 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
64 #endif /* hpux && !TERMIOS_TTY_DRIVER */
66 #if !defined (STRUCT_WINSIZE_IN_SYS_IOCTL)
67 /* For struct winsize on SCO */
68 /* sys/ptem.h has winsize but needs mblk_t from sys/stream.h */
69 # if defined (HAVE_SYS_PTEM_H) && defined (TIOCGWINSZ) && defined (SIGWINCH)
70 # if defined (HAVE_SYS_STREAM_H)
71 # include <sys/stream.h>
73 # include <sys/ptem.h>
74 # endif /* HAVE_SYS_PTEM_H && TIOCGWINSZ && SIGWINCH */
75 #endif /* !STRUCT_WINSIZE_IN_SYS_IOCTL */
83 #include "builtins/builtext.h"
84 #include "builtins/common.h"
90 #define DEFAULT_CHILD_MAX 32
91 #define MAX_JOBS_IN_ARRAY 4096 /* testing */
93 /* Take care of system dependencies that must be handled when waiting for
94 children. The arguments to the WAITPID macro match those to the Posix.1
95 waitpid() function. */
97 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
98 # define WAITPID(pid, statusp, options) \
99 wait3 ((union wait *)statusp, options, (struct rusage *)0)
101 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
102 # define WAITPID(pid, statusp, options) \
103 waitpid ((pid_t)pid, statusp, options)
105 # if defined (HAVE_WAIT3)
106 # define WAITPID(pid, statusp, options) \
107 wait3 (statusp, options, (struct rusage *)0)
109 # define WAITPID(pid, statusp, options) \
110 wait3 (statusp, options, (int *)0)
111 # endif /* HAVE_WAIT3 */
112 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
113 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
115 /* getpgrp () varies between systems. Even systems that claim to be
116 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
117 #if defined (GETPGRP_VOID)
118 # define getpgid(p) getpgrp ()
120 # define getpgid(p) getpgrp (p)
121 #endif /* !GETPGRP_VOID */
123 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
124 handler for SIGCHLD. */
125 #if defined (MUST_REINSTALL_SIGHANDLERS)
126 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
128 # define REINSTALL_SIGCHLD_HANDLER
129 #endif /* !MUST_REINSTALL_SIGHANDLERS */
131 /* Some systems let waitpid(2) tell callers about stopped children. */
132 #if !defined (WCONTINUED)
133 # define WCONTINUED 0
135 #if !defined (WIFCONTINUED)
136 # define WIFCONTINUED(s) (0)
139 /* The number of additional slots to allocate when we run out. */
142 typedef int sh_job_map_func_t __P((JOB *, int, int, int));
144 #if defined (READLINE)
145 extern void rl_set_screen_size __P((int, int));
148 /* Variables used here but defined in other files. */
149 extern int subshell_environment, line_number;
150 extern int posixly_correct, shell_level;
151 extern int interrupt_immediately;
152 extern int last_command_exit_value, last_command_exit_signal;
153 extern int loop_level, breaking;
154 extern int sourcelevel;
155 extern sh_builtin_func_t *this_shell_builtin;
156 extern char *shell_name, *this_command_name;
157 extern sigset_t top_level_mask;
158 extern procenv_t wait_intr_buf;
159 extern int wait_signal_received;
160 extern WORD_LIST *subst_assign_varlist;
162 /* The array of known jobs. */
163 JOB **jobs = (JOB **)NULL;
165 /* The number of slots currently allocated to JOBS. */
168 /* The controlling tty for this shell. */
171 /* The shell's process group. */
172 pid_t shell_pgrp = NO_PID;
174 /* The terminal's process group. */
175 pid_t terminal_pgrp = NO_PID;
177 /* The process group of the shell's parent. */
178 pid_t original_pgrp = NO_PID;
180 /* The process group of the pipeline currently being made. */
181 pid_t pipeline_pgrp = (pid_t)0;
183 #if defined (PGRP_PIPE)
184 /* Pipes which each shell uses to communicate with the process group leader
185 until all of the processes in a pipeline have been started. Then the
186 process leader is allowed to continue. */
187 int pgrp_pipe[2] = { -1, -1 };
190 /* The job which is current; i.e. the one that `%+' stands for. */
191 int current_job = NO_JOB;
193 /* The previous job; i.e. the one that `%-' stands for. */
194 int previous_job = NO_JOB;
196 /* Last child made by the shell. */
197 pid_t last_made_pid = NO_PID;
199 /* Pid of the last asynchronous child. */
200 pid_t last_asynchronous_pid = NO_PID;
202 /* The pipeline currently being built. */
203 PROCESS *the_pipeline = (PROCESS *)NULL;
205 /* If this is non-zero, do job control. */
208 /* Call this when you start making children. */
209 int already_making_children = 0;
211 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
212 exits from get_tty_state(). */
213 int check_window_size;
215 /* Functions local to this file. */
217 static void get_new_window_size __P((int));
219 static void run_sigchld_trap __P((int));
221 static sighandler wait_sigint_handler __P((int));
222 static sighandler sigchld_handler __P((int));
223 static sighandler sigwinch_sighandler __P((int));
224 static sighandler sigcont_sighandler __P((int));
225 static sighandler sigstop_sighandler __P((int));
227 static int waitchld __P((pid_t, int));
229 static PROCESS *find_pipeline __P((pid_t, int, int *));
231 static char *current_working_directory __P((void));
232 static char *job_working_directory __P((void));
233 static char *j_strsignal __P((int));
234 static char *printable_job_status __P((int, PROCESS *, int));
236 static pid_t find_last_pid __P((int, int));
238 static int set_new_line_discipline __P((int));
239 static int map_over_jobs __P((sh_job_map_func_t *, int, int));
240 static int job_last_stopped __P((int));
241 static int job_last_running __P((int));
242 static int most_recent_job_in_state __P((int, JOB_STATE));
243 static int find_job __P((pid_t, int));
244 static int print_job __P((JOB *, int, int, int));
245 static int process_exit_status __P((WAIT));
246 static int process_exit_signal __P((WAIT));
247 static int job_exit_status __P((int));
248 static int job_exit_signal __P((int));
249 static int set_job_status_and_cleanup __P((int));
251 static WAIT raw_job_exit_status __P((int));
253 static void notify_of_job_status __P((void));
254 static void cleanup_dead_jobs __P((void));
255 static int compact_jobs_list __P((int));
256 static void discard_pipeline __P((PROCESS *));
257 static void add_process __P((char *, pid_t));
258 static void print_pipeline __P((PROCESS *, int, int, FILE *));
259 static void pretty_print_job __P((int, int, FILE *));
260 static void set_current_job __P((int));
261 static void reset_current __P((void));
262 static void set_job_running __P((int));
263 static void setjstatus __P((int));
264 static void mark_all_jobs_as_dead __P((void));
265 static void mark_dead_jobs_as_notified __P((int));
266 static void restore_sigint_handler __P((void));
267 #if defined (PGRP_PIPE)
268 static void pipe_read __P((int *));
269 static void pipe_close __P((int *));
272 #if defined (ARRAY_VARS)
273 static int *pstatuses; /* list of pipeline statuses */
277 /* Used to synchronize between wait_for and other functions and the SIGCHLD
280 static int queue_sigchld;
282 #define QUEUE_SIGCHLD(os) (os) = sigchld, queue_sigchld++
284 #define UNQUEUE_SIGCHLD(os) \
287 if (queue_sigchld == 0 && os != sigchld) \
291 static SigHandler *old_tstp, *old_ttou, *old_ttin;
292 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
294 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
295 static SigHandler *old_winch = (SigHandler *)SIG_DFL;
298 /* A place to temporarily save the current pipeline. */
299 static PROCESS *saved_pipeline;
300 static int saved_already_making_children;
302 /* Set this to non-zero whenever you don't want the jobs list to change at
303 all: no jobs deleted and no status change notifications. This is used,
304 for example, when executing SIGCHLD traps, which may run arbitrary
306 static int jobs_list_frozen;
308 static char retcode_name_buffer[64];
310 static long child_max = -1L;
312 #if !defined (_POSIX_VERSION)
314 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
315 library functions and system calls. */
316 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
317 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
325 /* ioctl will handle setting errno correctly. */
326 if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
331 #endif /* !_POSIX_VERSION */
333 /* Return the working directory for the current process. Unlike
334 job_working_directory, this does not call malloc (), nor do any
335 of the functions it calls. This is so that it can safely be called
336 from a signal handler. */
338 current_working_directory ()
341 static char d[PATH_MAX];
343 dir = get_string_value ("PWD");
345 if (dir == 0 && the_current_working_directory && no_symbolic_links)
346 dir = the_current_working_directory;
350 dir = getcwd (d, sizeof(d));
355 return (dir == 0) ? "<unknown>" : dir;
358 /* Return the working directory for the current process. */
360 job_working_directory ()
364 dir = get_string_value ("PWD");
366 return (savestring (dir));
368 dir = get_working_directory ("job-working-directory");
372 return (savestring ("<unknown>"));
378 if (already_making_children)
381 already_making_children = 1;
386 stop_making_children ()
388 already_making_children = 0;
392 cleanup_the_pipeline ()
396 discard_pipeline (the_pipeline);
397 the_pipeline = (PROCESS *)NULL;
402 save_pipeline (clear)
405 saved_pipeline = the_pipeline;
406 saved_already_making_children = already_making_children;
408 the_pipeline = (PROCESS *)NULL;
412 restore_pipeline (discard)
415 PROCESS *old_pipeline;
417 old_pipeline = the_pipeline;
418 the_pipeline = saved_pipeline;
419 already_making_children = saved_already_making_children;
421 discard_pipeline (old_pipeline);
424 /* Start building a pipeline. */
430 cleanup_the_pipeline ();
432 #if defined (PGRP_PIPE)
433 pipe_close (pgrp_pipe);
437 #if defined (PGRP_PIPE)
440 if (pipe (pgrp_pipe) == -1)
441 sys_error ("start_pipeline: pgrp pipe");
446 /* Stop building a pipeline. Install the process list in the job array.
447 This returns the index of the newly installed job.
448 DEFERRED is a command structure to be executed upon satisfactory
449 execution exit of this pipeline. */
451 stop_pipeline (async, deferred)
459 BLOCK_CHILD (set, oset);
461 #if defined (PGRP_PIPE)
462 /* The parent closes the process group synchronization pipe. */
463 pipe_close (pgrp_pipe);
466 cleanup_dead_jobs ();
470 job_slots = JOB_SLOTS;
471 jobs = (JOB **)xmalloc (job_slots * sizeof (JOB *));
473 /* Now blank out these new entries. */
474 for (i = 0; i < job_slots; i++)
475 jobs[i] = (JOB *)NULL;
478 /* Scan from the last slot backward, looking for the next free one. */
481 for (i = job_slots; i; i--)
487 /* If we're not interactive, we don't need to monotonically increase
488 the job number (in fact, we don't care about the job number at all),
489 so we can simply scan for the first free slot. This helps to keep
490 us from continuously reallocating the jobs array when running
491 certain kinds of shell loops, and saves time spent searching. */
492 for (i = 0; i < job_slots; i++)
497 /* Do we need more room? */
499 /* First try compaction */
500 if (subshell_environment && interactive_shell && i == job_slots && job_slots >= MAX_JOBS_IN_ARRAY)
501 i = compact_jobs_list (0);
503 /* If we can't compact, reallocate */
506 job_slots += JOB_SLOTS;
507 jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
509 for (j = i; j < job_slots; j++)
510 jobs[j] = (JOB *)NULL;
513 /* Add the current pipeline to the job list. */
517 int any_alive, any_stopped;
519 newjob = (JOB *)xmalloc (sizeof (JOB));
521 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
523 p->next = (PROCESS *)NULL;
524 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
525 for (p = newjob->pipe; p->next; p = p->next)
527 p->next = newjob->pipe;
529 the_pipeline = (PROCESS *)NULL;
530 newjob->pgrp = pipeline_pgrp;
535 /* Flag to see if in another pgrp. */
537 newjob->flags |= J_JOBCONTROL;
539 /* Set the state of this pipeline. */
541 any_alive = any_stopped = 0;
544 any_alive |= p->running;
545 any_stopped |= WIFSTOPPED (p->status);
548 while (p != newjob->pipe);
550 newjob->state = any_alive ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
551 newjob->wd = job_working_directory ();
552 newjob->deferred = deferred;
554 newjob->j_cleanup = (sh_vptrfunc_t *)NULL;
555 newjob->cleanarg = (PTR_T) NULL;
558 if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
562 newjob = (JOB *)NULL;
567 newjob->flags &= ~J_FOREGROUND;
574 newjob->flags |= J_FOREGROUND;
576 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
578 * The currently-accepted job control wisdom says to set the
579 * terminal's process group n+1 times in an n-step pipeline:
580 * once in the parent and once in each child. This is where
581 * the parent gives it away.
584 if (job_control && newjob->pgrp)
585 give_terminal_to (newjob->pgrp, 0);
589 stop_making_children ();
590 UNBLOCK_CHILD (oset);
591 return (current_job);
594 /* Delete all DEAD jobs that the user had received notification about. */
601 if (job_slots == 0 || jobs_list_frozen)
606 for (i = 0; i < job_slots; i++)
607 if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
613 /* Compact the jobs list by removing dead jobs. Assumed that we have filled
614 the jobs array to some predefined maximum. Called when the shell is not
615 the foreground process (subshell_environment != 0). Returns the first
616 available slot in the compacted list. If that value is job_slots, then
617 the list needs to be reallocated. The jobs array is in new memory if
618 this returns > 0 and < job_slots. FLAGS is reserved for future use. */
620 compact_jobs_list (flags)
628 if (job_slots == 0 || jobs_list_frozen)
632 child_max = getmaxchild ();
634 /* Take out at most a quarter of the jobs in the jobs array, but leave at
636 nremove = job_slots >> 2;
637 if ((job_slots - nremove) < child_max)
638 nremove = job_slots - child_max;
640 /* need to increase jobs list to at least CHILD_MAX entries */
644 BLOCK_CHILD (set, oset);
646 for (ndel = i = 0; i < job_slots; i++)
649 if (DEADJOB (i) && (find_last_pid (i, 0) != last_asynchronous_pid))
660 UNBLOCK_CHILD (oset);
664 newlist = (JOB **)xmalloc ((1 + job_slots) * sizeof (JOB *));
665 for (i = j = 0; i < job_slots; i++)
667 newlist[j++] = jobs[i];
670 for ( ; j < job_slots; j++)
671 newlist[j] = (JOB *)NULL;
676 UNBLOCK_CHILD (oset);
681 /* Delete the job at INDEX from the job list. Must be called
682 with SIGCHLD blocked. */
684 delete_job (job_index, warn_stopped)
685 int job_index, warn_stopped;
689 if (job_slots == 0 || jobs_list_frozen)
692 if (warn_stopped && subshell_environment == 0 && STOPPED (job_index))
693 internal_warning (_("deleting stopped job %d with process group %ld"), job_index+1, (long)jobs[job_index]->pgrp);
695 temp = jobs[job_index];
696 if (job_index == current_job || job_index == previous_job)
699 jobs[job_index] = (JOB *)NULL;
702 discard_pipeline (temp->pipe);
705 dispose_command (temp->deferred);
710 /* Must be called with SIGCHLD blocked. */
712 nohup_job (job_index)
720 if (temp = jobs[job_index])
721 temp->flags |= J_NOHUP;
724 /* Get rid of the data structure associated with a process chain. */
726 discard_pipeline (chain)
727 register PROCESS *chain;
729 register PROCESS *this, *next;
735 FREE (this->command);
739 while (this != chain);
742 /* Add this process to the chain being built in the_pipeline.
743 NAME is the command string that will be exec'ed later.
744 PID is the process id of the child. */
746 add_process (name, pid)
752 t = (PROCESS *)xmalloc (sizeof (PROCESS));
753 t->next = the_pipeline;
755 WSTATUS (t->status) = 0;
756 t->running = PS_RUNNING;
765 while (p->next != t->next)
772 /* Take the last job and make it the first job. Must be called with
775 rotate_the_pipeline ()
779 if (the_pipeline->next == the_pipeline)
781 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
786 /* Reverse the order of the processes in the_pipeline. Must be called with
789 reverse_the_pipeline ()
793 if (the_pipeline->next == the_pipeline)
796 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
798 p->next = (PROCESS *)NULL;
800 n = REVERSE_LIST (the_pipeline, PROCESS *);
803 for (p = the_pipeline; p->next; p = p->next)
805 p->next = the_pipeline;
809 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
810 then it is time to stop mapping, and that is the return value
811 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
814 map_over_jobs (func, arg1, arg2)
815 sh_job_map_func_t *func;
825 BLOCK_CHILD (set, oset);
827 for (i = result = 0; i < job_slots; i++)
831 result = (*func)(jobs[i], arg1, arg2, i);
837 UNBLOCK_CHILD (oset);
842 /* Cause all the jobs in the current pipeline to exit. */
844 terminate_current_pipeline ()
846 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
848 killpg (pipeline_pgrp, SIGTERM);
849 killpg (pipeline_pgrp, SIGCONT);
853 /* Cause all stopped jobs to exit. */
855 terminate_stopped_jobs ()
859 for (i = 0; i < job_slots; i++)
861 if (jobs[i] && STOPPED (i))
863 killpg (jobs[i]->pgrp, SIGTERM);
864 killpg (jobs[i]->pgrp, SIGCONT);
869 /* Cause all jobs, running or stopped, to receive a hangup signal. If
870 a job is marked J_NOHUP, don't send the SIGHUP. */
876 for (i = 0; i < job_slots; i++)
880 if ((jobs[i]->flags & J_NOHUP) == 0)
881 killpg (jobs[i]->pgrp, SIGHUP);
883 killpg (jobs[i]->pgrp, SIGCONT);
889 kill_current_pipeline ()
891 stop_making_children ();
895 /* Return the pipeline that PID belongs to. Note that the pipeline
896 doesn't have to belong to a job. Must be called with SIGCHLD blocked. */
898 find_pipeline (pid, running_only, jobp)
901 int *jobp; /* index into jobs list or NO_JOB */
906 /* See if this process is in the pipeline that we are building. */
914 /* Return it if we found it. */
917 if ((running_only && PRUNNING(p)) || (running_only == 0))
923 while (p != the_pipeline);
926 job = find_job (pid, running_only);
929 return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
932 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
933 belong to any job. Must be called with SIGCHLD blocked. */
935 find_job (pid, running_only)
942 for (i = 0; i < job_slots; i++)
952 if ((running_only && PRUNNING(p)) || (running_only == 0))
958 while (p != jobs[i]->pipe);
965 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
966 required by find_job. */
968 get_job_by_pid (pid, block)
976 BLOCK_CHILD (set, oset);
978 job = find_job (pid, 0);
981 UNBLOCK_CHILD (oset);
986 /* Print descriptive information about the job with leader pid PID. */
994 BLOCK_CHILD (set, oset);
996 job = find_job (pid, 0);
999 printf ("[%d] %ld\n", job + 1, (long)pid);
1001 programming_error (_("describe_pid: %ld: no such pid"), (long)pid);
1003 UNBLOCK_CHILD (oset);
1015 x = retcode_name_buffer;
1016 sprintf (x, "Signal %d", s);
1022 printable_job_status (j, p, format)
1032 if (STOPPED (j) && format == 0)
1034 if (posixly_correct == 0 || p == 0 || (WIFSTOPPED (p->status) == 0))
1038 temp = retcode_name_buffer;
1039 sprintf (temp, "Stopped(%s)", signal_name (WSTOPSIG (p->status)));
1042 else if (RUNNING (j))
1046 if (WIFSTOPPED (p->status))
1047 temp = j_strsignal (WSTOPSIG (p->status));
1048 else if (WIFSIGNALED (p->status))
1049 temp = j_strsignal (WTERMSIG (p->status));
1050 else if (WIFEXITED (p->status))
1052 temp = retcode_name_buffer;
1053 es = WEXITSTATUS (p->status);
1055 strcpy (temp, "Done");
1056 else if (posixly_correct)
1057 sprintf (temp, "Done(%d)", es);
1059 sprintf (temp, "Exit %d", es);
1062 temp = "Unknown status";
1068 /* This is the way to print out information on a job if you
1069 know the index. FORMAT is:
1071 JLIST_NORMAL) [1]+ Running emacs
1072 JLIST_LONG ) [1]+ 2378 Running emacs
1073 -1 ) [1]+ 2378 emacs
1075 JLIST_NORMAL) [1]+ Stopped ls | more
1076 JLIST_LONG ) [1]+ 2369 Stopped ls
1079 Just list the pid of the process group leader (really
1082 Use format JLIST_NORMAL, but list only jobs about which
1083 the user has not been notified. */
1085 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1086 the JOBS array corresponding to this pipeline. FORMAT is as described
1087 above. Must be called with SIGCHLD blocked.
1089 If you're printing a pipeline that's not in the jobs array, like the
1090 current pipeline as it's being created, pass -1 for JOB_INDEX */
1092 print_pipeline (p, job_index, format, stream)
1094 int job_index, format;
1097 PROCESS *first, *last, *show;
1098 int es, name_padding;
1105 while (last->next != first)
1111 fprintf (stream, format ? " " : " |");
1113 if (format != JLIST_STANDARD)
1114 fprintf (stream, "%5ld", (long)p->pid);
1116 fprintf (stream, " ");
1118 if (format > -1 && job_index >= 0)
1120 show = format ? p : last;
1121 temp = printable_job_status (job_index, show, format);
1127 if (show->running == first->running &&
1128 WSTATUS (show->status) == WSTATUS (first->status))
1132 temp = (char *)NULL;
1137 fprintf (stream, "%s", temp);
1141 es = 2; /* strlen ("| ") */
1142 name_padding = LONGEST_SIGNAL_DESC - es;
1144 fprintf (stream, "%*s", name_padding, "");
1146 if ((WIFSTOPPED (show->status) == 0) &&
1147 (WIFCONTINUED (show->status) == 0) &&
1148 WIFCORED (show->status))
1149 fprintf (stream, "(core dumped) ");
1153 if (p != first && format)
1154 fprintf (stream, "| ");
1157 fprintf (stream, "%s", p->command);
1159 if (p == last && job_index >= 0)
1161 temp = current_working_directory ();
1163 if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
1164 fprintf (stream, " &");
1166 if (strcmp (temp, jobs[job_index]->wd) != 0)
1168 " (wd: %s)", polite_directory_format (jobs[job_index]->wd));
1171 if (format || (p == last))
1173 /* We need to add a CR only if this is an interactive shell, and
1174 we're reporting the status of a completed job asynchronously.
1175 We can't really check whether this particular job is being
1176 reported asynchronously, so just add the CR if the shell is
1177 currently interactive and asynchronous notification is enabled. */
1178 if (asynchronous_notification && interactive)
1179 fprintf (stream, "\r\n");
1181 fprintf (stream, "\n");
1191 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1192 Must be called with SIGCHLD blocked or queued with queue_sigchld */
1194 pretty_print_job (job_index, format, stream)
1195 int job_index, format;
1198 register PROCESS *p;
1200 /* Format only pid information about the process group leader? */
1201 if (format == JLIST_PID_ONLY)
1203 fprintf (stream, "%ld\n", (long)jobs[job_index]->pipe->pid);
1207 if (format == JLIST_CHANGED_ONLY)
1209 if (IS_NOTIFIED (job_index))
1211 format = JLIST_STANDARD;
1214 if (format != JLIST_NONINTERACTIVE)
1215 fprintf (stream, "[%d]%c ", job_index + 1,
1216 (job_index == current_job) ? '+':
1217 (job_index == previous_job) ? '-' : ' ');
1219 if (format == JLIST_NONINTERACTIVE)
1220 format = JLIST_LONG;
1222 p = jobs[job_index]->pipe;
1224 print_pipeline (p, job_index, format, stream);
1226 /* We have printed information about this job. When the job's
1227 status changes, waitchld () sets the notification flag to 0. */
1228 jobs[job_index]->flags |= J_NOTIFIED;
1232 print_job (job, format, state, job_index)
1234 int format, state, job_index;
1236 if (state == -1 || (JOB_STATE)state == job->state)
1237 pretty_print_job (job_index, format, stdout);
1242 list_one_job (job, format, ignore, job_index)
1244 int format, ignore, job_index;
1246 pretty_print_job (job_index, format, stdout);
1250 list_stopped_jobs (format)
1253 cleanup_dead_jobs ();
1254 map_over_jobs (print_job, format, (int)JSTOPPED);
1258 list_running_jobs (format)
1261 cleanup_dead_jobs ();
1262 map_over_jobs (print_job, format, (int)JRUNNING);
1265 /* List jobs. If FORMAT is non-zero, then the long form of the information
1266 is printed, else just a short version. */
1268 list_all_jobs (format)
1271 cleanup_dead_jobs ();
1272 map_over_jobs (print_job, format, -1);
1275 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1276 COMMAND is just for remembering the name of the command; we don't do
1277 anything else with it. ASYNC_P says what to do with the tty. If
1278 non-zero, then don't give it away. */
1280 make_child (command, async_p)
1288 sigaddset (&set, SIGCHLD);
1289 sigaddset (&set, SIGINT);
1290 sigemptyset (&oset);
1291 sigprocmask (SIG_BLOCK, &set, &oset);
1295 #if defined (BUFFERED_INPUT)
1296 /* If default_buffered_input is active, we are reading a script. If
1297 the command is asynchronous, we have already duplicated /dev/null
1298 as fd 0, but have not changed the buffered stream corresponding to
1299 the old fd 0. We don't want to sync the stream in this case. */
1300 if (default_buffered_input != -1 &&
1301 (!async_p || default_buffered_input > 0))
1302 sync_buffered_stream (default_buffered_input);
1303 #endif /* BUFFERED_INPUT */
1305 /* Create the child, handle severe errors. */
1306 if ((pid = fork ()) < 0)
1310 /* Kill all of the processes in the current pipeline. */
1311 terminate_current_pipeline ();
1313 /* Discard the current pipeline, if any. */
1315 kill_current_pipeline ();
1317 throw_to_top_level (); /* Reset signals, etc. */
1322 /* In the child. Give this child the right process group, set the
1323 signals to the default state for a new process. */
1327 #if defined (BUFFERED_INPUT)
1328 /* Close default_buffered_input if it's > 0. We don't close it if it's
1329 0 because that's the file descriptor used when redirecting input,
1330 and it's wrong to close the file in that case. */
1331 unset_bash_input (0);
1332 #endif /* BUFFERED_INPUT */
1334 /* Restore top-level signal mask. */
1335 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1339 /* All processes in this pipeline belong in the same
1342 if (pipeline_pgrp == 0) /* This is the first child. */
1343 pipeline_pgrp = mypid;
1345 /* Check for running command in backquotes. */
1346 if (pipeline_pgrp == shell_pgrp)
1347 ignore_tty_job_signals ();
1349 default_tty_job_signals ();
1351 /* Set the process group before trying to mess with the terminal's
1352 process group. This is mandated by POSIX. */
1353 /* This is in accordance with the Posix 1003.1 standard,
1354 section B.7.2.4, which says that trying to set the terminal
1355 process group with tcsetpgrp() to an unused pgrp value (like
1356 this would have for the first child) is an error. Section
1357 B.4.3.3, p. 237 also covers this, in the context of job control
1359 if (setpgid (mypid, pipeline_pgrp) < 0)
1360 sys_error ("child setpgid (%ld to %ld)", (long)mypid, (long)pipeline_pgrp);
1362 /* By convention (and assumption above), if
1363 pipeline_pgrp == shell_pgrp, we are making a child for
1364 command substitution.
1365 In this case, we don't want to give the terminal to the
1366 shell's process group (we could be in the middle of a
1367 pipeline, for example). */
1368 if (async_p == 0 && pipeline_pgrp != shell_pgrp)
1369 give_terminal_to (pipeline_pgrp, 0);
1371 #if defined (PGRP_PIPE)
1372 if (pipeline_pgrp == mypid)
1373 pipe_read (pgrp_pipe);
1376 else /* Without job control... */
1378 if (pipeline_pgrp == 0)
1379 pipeline_pgrp = shell_pgrp;
1381 /* If these signals are set to SIG_DFL, we encounter the curious
1382 situation of an interactive ^Z to a running process *working*
1383 and stopping the process, but being unable to do anything with
1384 that process to change its state. On the other hand, if they
1385 are set to SIG_IGN, jobs started from scripts do not stop when
1386 the shell running the script gets a SIGTSTP and stops. */
1388 default_tty_job_signals ();
1391 #if defined (PGRP_PIPE)
1392 /* Release the process group pipe, since our call to setpgid ()
1393 is done. The last call to pipe_close is done in stop_pipeline. */
1394 pipe_close (pgrp_pipe);
1395 #endif /* PGRP_PIPE */
1398 last_asynchronous_pid = getpid ();
1402 /* In the parent. Remember the pid of the child just created
1403 as the proper pgrp if this is the first child. */
1407 if (pipeline_pgrp == 0)
1409 pipeline_pgrp = pid;
1410 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1411 not the good thing of twiddling them in the child! */
1412 /* give_terminal_to (pipeline_pgrp, 0); */
1414 /* This is done on the recommendation of the Rationale section of
1415 the POSIX 1003.1 standard, where it discusses job control and
1416 shells. It is done to avoid possible race conditions. (Ref.
1417 1003.1 Rationale, section B.4.3.3, page 236). */
1418 setpgid (pid, pipeline_pgrp);
1422 if (pipeline_pgrp == 0)
1423 pipeline_pgrp = shell_pgrp;
1426 /* Place all processes into the jobs array regardless of the
1427 state of job_control. */
1428 add_process (command, pid);
1431 last_asynchronous_pid = pid;
1433 last_made_pid = pid;
1435 /* Unblock SIGINT and SIGCHLD. */
1436 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1442 /* These two functions are called only in child processes. */
1444 ignore_tty_job_signals ()
1446 set_signal_handler (SIGTSTP, SIG_IGN);
1447 set_signal_handler (SIGTTIN, SIG_IGN);
1448 set_signal_handler (SIGTTOU, SIG_IGN);
1452 default_tty_job_signals ()
1454 set_signal_handler (SIGTSTP, SIG_DFL);
1455 set_signal_handler (SIGTTIN, SIG_DFL);
1456 set_signal_handler (SIGTTOU, SIG_DFL);
1459 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1460 state kept in here. When a job ends normally, we set the state in here
1461 to the state of the tty. */
1463 static TTYSTRUCT shell_tty_info;
1465 #if defined (NEW_TTY_DRIVER)
1466 static struct tchars shell_tchars;
1467 static struct ltchars shell_ltchars;
1468 #endif /* NEW_TTY_DRIVER */
1470 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1471 /* Since the BSD tty driver does not allow us to change the tty modes
1472 while simultaneously waiting for output to drain and preserving
1473 typeahead, we have to drain the output ourselves before calling
1474 ioctl. We cheat by finding the length of the output queue, and
1475 using select to wait for an appropriate length of time. This is
1476 a hack, and should be labeled as such (it's a hastily-adapted
1477 mutation of a `usleep' implementation). It's only reason for
1478 existing is the flaw in the BSD tty driver. */
1480 static int ttspeeds[] =
1482 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1483 1800, 2400, 4800, 9600, 19200, 38400
1490 register int delay = ttspeeds[ospeed];
1496 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1498 if (n > (delay / 100))
1502 n *= 10; /* 2 bits more for conservativeness. */
1503 tv.tv_sec = n / delay;
1504 tv.tv_usec = ((n % delay) * 1000000) / delay;
1505 select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1511 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1513 /* Return the fd from which we are actually getting input. */
1514 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1516 /* Fill the contents of shell_tty_info with the current tty info. */
1525 #if defined (NEW_TTY_DRIVER)
1526 ioctl (tty, TIOCGETP, &shell_tty_info);
1527 ioctl (tty, TIOCGETC, &shell_tchars);
1528 ioctl (tty, TIOCGLTC, &shell_ltchars);
1529 #endif /* NEW_TTY_DRIVER */
1531 #if defined (TERMIO_TTY_DRIVER)
1532 ioctl (tty, TCGETA, &shell_tty_info);
1533 #endif /* TERMIO_TTY_DRIVER */
1535 #if defined (TERMIOS_TTY_DRIVER)
1536 if (tcgetattr (tty, &shell_tty_info) < 0)
1539 /* Only print an error message if we're really interactive at
1542 sys_error ("[%ld: %d] tcgetattr", (long)getpid (), shell_level);
1546 #endif /* TERMIOS_TTY_DRIVER */
1547 if (check_window_size)
1548 get_new_window_size (0);
1553 /* Make the current tty use the state in shell_tty_info. */
1562 #if defined (NEW_TTY_DRIVER)
1563 # if defined (DRAIN_OUTPUT)
1564 draino (tty, shell_tty_info.sg_ospeed);
1565 # endif /* DRAIN_OUTPUT */
1566 ioctl (tty, TIOCSETN, &shell_tty_info);
1567 ioctl (tty, TIOCSETC, &shell_tchars);
1568 ioctl (tty, TIOCSLTC, &shell_ltchars);
1569 #endif /* NEW_TTY_DRIVER */
1571 #if defined (TERMIO_TTY_DRIVER)
1572 ioctl (tty, TCSETAW, &shell_tty_info);
1573 #endif /* TERMIO_TTY_DRIVER */
1575 #if defined (TERMIOS_TTY_DRIVER)
1576 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1578 /* Only print an error message if we're really interactive at
1581 sys_error ("[%ld: %d] tcsetattr", (long)getpid (), shell_level);
1584 #endif /* TERMIOS_TTY_DRIVER */
1589 /* Given an index into the jobs array JOB, return the pid of the last
1590 process in that job's pipeline. This is the one whose exit status
1591 counts. Must be called with SIGCHLD blocked or queued. */
1593 find_last_pid (job, block)
1597 register PROCESS *p;
1601 BLOCK_CHILD (set, oset);
1603 p = jobs[job]->pipe;
1604 while (p->next != jobs[job]->pipe)
1608 UNBLOCK_CHILD (oset);
1613 /* Wait for a particular child of the shell to finish executing.
1614 This low-level function prints an error message if PID is not
1615 a child of this shell. It returns -1 if it fails, or whatever
1616 wait_for returns otherwise. If the child is not found in the
1617 jobs table, it returns 127. */
1619 wait_for_single_pid (pid)
1622 register PROCESS *child;
1626 BLOCK_CHILD (set, oset);
1627 child = find_pipeline (pid, 0, (int *)NULL);
1628 UNBLOCK_CHILD (oset);
1632 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid);
1638 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
1640 BLOCK_CHILD (set, oset);
1641 job = find_job (pid, 0);
1642 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1643 jobs[job]->flags |= J_NOTIFIED;
1644 UNBLOCK_CHILD (oset);
1649 /* Wait for all of the backgrounds of this shell to finish. */
1651 wait_for_background_pids ()
1653 register int i, r, waited_for;
1657 for (waited_for = 0;;)
1659 BLOCK_CHILD (set, oset);
1661 /* find first running job; if none running in foreground, break */
1662 for (i = 0; i < job_slots; i++)
1663 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1668 UNBLOCK_CHILD (oset);
1672 /* now wait for the last pid in that job. */
1673 pid = find_last_pid (i, 0);
1674 UNBLOCK_CHILD (oset);
1676 errno = 0; /* XXX */
1677 r = wait_for_single_pid (pid);
1680 /* If we're mistaken about job state, compensate. */
1681 if (errno == ECHILD)
1682 mark_all_jobs_as_dead ();
1688 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
1689 `wait' is called with no arguments. */
1690 mark_dead_jobs_as_notified (1);
1691 cleanup_dead_jobs ();
1694 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
1695 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
1696 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
1699 restore_sigint_handler ()
1701 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1703 set_signal_handler (SIGINT, old_sigint_handler);
1704 old_sigint_handler = INVALID_SIGNAL_HANDLER;
1708 static int wait_sigint_received;
1710 /* Handle SIGINT while we are waiting for children in a script to exit.
1711 The `wait' builtin should be interruptible, but all others should be
1712 effectively ignored (i.e. not cause the shell to exit). */
1714 wait_sigint_handler (sig)
1717 SigHandler *sigint_handler;
1719 if (interrupt_immediately ||
1720 (this_shell_builtin && this_shell_builtin == wait_builtin))
1722 last_command_exit_value = EXECUTION_FAILURE;
1723 restore_sigint_handler ();
1724 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
1725 what POSIX.2 says (see builtins/wait.def for more info). */
1726 if (this_shell_builtin && this_shell_builtin == wait_builtin &&
1727 signal_is_trapped (SIGINT) &&
1728 ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
1730 interrupt_immediately = 0;
1731 trap_handler (SIGINT); /* set pending_traps[SIGINT] */
1732 wait_signal_received = SIGINT;
1733 longjmp (wait_intr_buf, 1);
1740 /* XXX - should this be interrupt_state? If it is, the shell will act
1741 as if it got the SIGINT interrupt. */
1742 wait_sigint_received = 1;
1744 /* Otherwise effectively ignore the SIGINT and allow the running job to
1750 process_exit_signal (status)
1753 return (WIFSIGNALED (status) ? WTERMSIG (status) : 0);
1757 process_exit_status (status)
1760 if (WIFSIGNALED (status))
1761 return (128 + WTERMSIG (status));
1762 else if (WIFSTOPPED (status) == 0)
1763 return (WEXITSTATUS (status));
1765 return (EXECUTION_SUCCESS);
1768 /* Return the exit status of the last process in the pipeline for job JOB.
1769 This is the exit status of the entire job. */
1771 raw_job_exit_status (job)
1774 register PROCESS *p;
1780 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
1781 if (p->status != EXECUTION_SUCCESS) fail = p->status;
1785 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
1790 /* Return the exit status of job JOB. This is the exit status of the last
1791 (rightmost) process in the job's pipeline, modified if the job was killed
1792 by a signal or stopped. */
1794 job_exit_status (job)
1797 return (process_exit_status (raw_job_exit_status (job)));
1801 job_exit_signal (job)
1804 return (process_exit_signal (raw_job_exit_status (job)));
1807 #define FIND_CHILD(pid, child) \
1810 child = find_pipeline (pid, 0, (int *)NULL); \
1813 give_terminal_to (shell_pgrp, 0); \
1814 UNBLOCK_CHILD (oset); \
1815 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
1816 restore_sigint_handler (); \
1817 return (termination_state = 127); \
1822 /* Wait for pid (one of our children) to terminate, then
1823 return the termination state. Returns 127 if PID is not found in
1824 the jobs table. Returns -1 if waitchld() returns -1, indicating
1825 that there are no unwaited-for child processes. */
1830 int job, termination_state, r;
1832 register PROCESS *child;
1834 register PROCESS *p;
1836 /* In the case that this code is interrupted, and we longjmp () out of it,
1837 we are relying on the code in throw_to_top_level () to restore the
1838 top-level signal mask. */
1839 BLOCK_CHILD (set, oset);
1841 /* Ignore interrupts while waiting for a job run without job control
1842 to finish. We don't want the shell to exit if an interrupt is
1843 received, only if one of the jobs run is killed via SIGINT. If
1844 job control is not set, the job will be run in the same pgrp as
1845 the shell, and the shell will see any signals the job gets. */
1847 /* This is possibly a race condition -- should it go in stop_pipeline? */
1848 wait_sigint_received = 0;
1849 if (job_control == 0)
1850 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
1852 termination_state = last_command_exit_value;
1854 if (interactive && job_control == 0)
1857 /* If we say wait_for (), then we have a record of this child somewhere.
1858 If it and none of its peers are running, don't call waitchld(). */
1863 FIND_CHILD (pid, child);
1865 /* If this child is part of a job, then we are really waiting for the
1866 job to finish. Otherwise, we are waiting for the child to finish.
1867 We check for JDEAD in case the job state has been set by waitchld
1868 after receipt of a SIGCHLD. */
1870 job = find_job (pid, 0);
1872 /* waitchld() takes care of setting the state of the job. If the job
1873 has already exited before this is called, sigchld_handler will have
1874 called waitchld and the state will be set to JDEAD. */
1876 if (child->running || (job != NO_JOB && RUNNING (job)))
1878 #if defined (WAITPID_BROKEN) /* SCOv4 */
1879 sigset_t suspend_set;
1880 sigemptyset (&suspend_set);
1881 sigsuspend (&suspend_set);
1882 #else /* !WAITPID_BROKEN */
1883 # if defined (MUST_UNBLOCK_CHLD)
1884 struct sigaction act, oact;
1885 sigset_t nullset, chldset;
1887 sigemptyset (&nullset);
1888 sigemptyset (&chldset);
1889 sigprocmask (SIG_SETMASK, &nullset, &chldset);
1890 act.sa_handler = SIG_DFL;
1891 sigemptyset (&act.sa_mask);
1892 sigemptyset (&oact.sa_mask);
1894 sigaction (SIGCHLD, &act, &oact);
1897 r = waitchld (pid, 1);
1898 # if defined (MUST_UNBLOCK_CHLD)
1899 sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
1900 sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
1903 if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
1905 termination_state = -1;
1906 goto wait_for_return;
1909 /* If child is marked as running, but waitpid() returns -1/ECHILD,
1910 there is something wrong. Somewhere, wait should have returned
1911 that child's pid. Mark the child as not running and the job,
1912 if it exists, as JDEAD. */
1913 if (r == -1 && errno == ECHILD)
1915 child->running = PS_DONE;
1916 child->status = 0; /* XXX -- can't find true status */
1918 jobs[job]->state = JDEAD;
1920 #endif /* WAITPID_BROKEN */
1923 /* If the shell is interactive, and job control is disabled, see
1924 if the foreground process has died due to SIGINT and jump out
1925 of the wait loop if it has. waitchld has already restored the
1926 old SIGINT signal handler. */
1927 if (interactive && job_control == 0)
1930 while (child->running || (job != NO_JOB && RUNNING (job)));
1932 /* The exit state of the command is either the termination state of the
1933 child, or the termination state of the job. If a job, the status
1934 of the last child in the pipeline is the significant one. If the command
1935 or job was terminated by a signal, note that value also. */
1936 termination_state = (job != NO_JOB) ? job_exit_status (job)
1937 : process_exit_status (child->status);
1938 last_command_exit_signal = (job != NO_JOB) ? job_exit_signal (job)
1939 : process_exit_signal (child->status);
1941 if (job == NO_JOB || IS_JOBCONTROL (job))
1943 /* XXX - under what circumstances is a job not present in the jobs
1944 table (job == NO_JOB)?
1945 1. command substitution
1947 In the case of command substitution, at least, it's probably not
1948 the right thing to give the terminal to the shell's process group,
1949 even though there is code in subst.c:command_substitute to work
1953 $PROMPT_COMMAND execution
1954 process substitution
1958 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp);
1961 give_terminal_to (shell_pgrp, 0);
1964 /* If the command did not exit cleanly, or the job is just
1965 being stopped, then reset the tty state back to what it
1966 was before this command. Reset the tty state and notify
1967 the user of the job termination only if the shell is
1968 interactive. Clean up any dead jobs in either case. */
1971 if (interactive_shell && subshell_environment == 0)
1973 /* This used to use `child->status'. That's wrong, however, for
1974 pipelines. `child' is the first process in the pipeline. It's
1975 likely that the process we want to check for abnormal termination
1976 or stopping is the last process in the pipeline, especially if
1977 it's long-lived and the first process is short-lived. Since we
1978 know we have a job here, we can check all the processes in this
1979 job's pipeline and see if one of them stopped or terminated due
1980 to a signal. We might want to change this later to just check
1981 the last process in the pipeline. If no process exits due to a
1982 signal, S is left as the status of the last job in the pipeline. */
1983 p = jobs[job]->pipe;
1987 if (WIFSIGNALED(s) || WIFSTOPPED(s))
1991 while (p != jobs[job]->pipe);
1993 if (WIFSIGNALED (s) || WIFSTOPPED (s))
1997 /* If the current job was stopped or killed by a signal, and
1998 the user has requested it, get a possibly new window size */
1999 if (check_window_size && (job == current_job || IS_FOREGROUND (job)))
2000 get_new_window_size (0);
2005 /* If job control is enabled, the job was started with job
2006 control, the job was the foreground job, and it was killed
2007 by SIGINT, then print a newline to compensate for the kernel
2008 printing the ^C without a trailing newline. */
2009 if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
2010 WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
2012 /* If SIGINT is not trapped and the shell is in a for, while,
2013 or until loop, act as if the shell received SIGINT as
2014 well, so the loop can be broken. This doesn't call the
2015 SIGINT signal handler; maybe it should. */
2016 if (signal_is_trapped (SIGINT) == 0 && loop_level)
2026 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
2027 signal handler path */
2028 if (DEADJOB (job) && IS_FOREGROUND (job) /*&& subshell_environment == 0*/)
2031 /* If this job is dead, notify the user of the status. If the shell
2032 is interactive, this will display a message on the terminal. If
2033 the shell is not interactive, make sure we turn on the notify bit
2034 so we don't get an unwanted message about the job's termination,
2035 and so delete_job really clears the slot in the jobs table. */
2036 notify_and_cleanup ();
2041 UNBLOCK_CHILD (oset);
2043 /* Restore the original SIGINT signal handler before we return. */
2044 restore_sigint_handler ();
2046 return (termination_state);
2049 /* Wait for the last process in the pipeline for JOB. Returns whatever
2050 wait_for returns: the last process's termination state or -1 if there
2051 are no unwaited-for child processes or an error occurs. */
2060 BLOCK_CHILD(set, oset);
2061 if (JOBSTATE (job) == JSTOPPED)
2062 internal_warning (_("wait_for_job: job %d is stopped"), job+1);
2064 pid = find_last_pid (job, 0);
2065 UNBLOCK_CHILD(oset);
2068 /* POSIX.2: we can remove the job from the jobs table if we just waited
2070 BLOCK_CHILD (set, oset);
2071 if (job != NO_JOB && jobs[job] && DEADJOB (job))
2072 jobs[job]->flags |= J_NOTIFIED;
2073 UNBLOCK_CHILD (oset);
2078 /* Print info about dead jobs, and then delete them from the list
2079 of known jobs. This does not actually delete jobs when the
2080 shell is not interactive, because the dead jobs are not marked
2083 notify_and_cleanup ()
2085 if (jobs_list_frozen)
2088 if (interactive || interactive_shell == 0 || sourcelevel)
2089 notify_of_job_status ();
2091 cleanup_dead_jobs ();
2094 /* Make dead jobs disappear from the jobs array without notification.
2095 This is used when the shell is not interactive. */
2099 mark_dead_jobs_as_notified (0);
2100 cleanup_dead_jobs ();
2103 /* Return the next closest (chronologically) job to JOB which is in
2104 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
2105 there is no next recent job. */
2107 most_recent_job_in_state (job, state)
2111 register int i, result;
2114 BLOCK_CHILD (set, oset);
2116 for (result = NO_JOB, i = job - 1; i >= 0; i--)
2118 if (jobs[i] && (JOBSTATE (i) == state))
2125 UNBLOCK_CHILD (oset);
2130 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
2133 job_last_stopped (job)
2136 return (most_recent_job_in_state (job, JSTOPPED));
2139 /* Return the newest *running* job older than JOB, or NO_JOB if not
2142 job_last_running (job)
2145 return (most_recent_job_in_state (job, JRUNNING));
2148 /* Make JOB be the current job, and make previous be useful. Must be
2149 called with SIGCHLD blocked. */
2151 set_current_job (job)
2156 if (current_job != job)
2158 previous_job = current_job;
2162 /* First choice for previous_job is the old current_job. */
2163 if (previous_job != current_job &&
2164 previous_job != NO_JOB &&
2165 jobs[previous_job] &&
2166 STOPPED (previous_job))
2169 /* Second choice: Newest stopped job that is older than
2172 if (STOPPED (current_job))
2174 candidate = job_last_stopped (current_job);
2176 if (candidate != NO_JOB)
2178 previous_job = candidate;
2183 /* If we get here, there is either only one stopped job, in which case it is
2184 the current job and the previous job should be set to the newest running
2185 job, or there are only running jobs and the previous job should be set to
2186 the newest running job older than the current job. We decide on which
2187 alternative to use based on whether or not JOBSTATE(current_job) is
2190 candidate = RUNNING (current_job) ? job_last_running (current_job)
2191 : job_last_running (job_slots);
2193 if (candidate != NO_JOB)
2195 previous_job = candidate;
2199 /* There is only a single job, and it is both `+' and `-'. */
2200 previous_job = current_job;
2203 /* Make current_job be something useful, if it isn't already. */
2205 /* Here's the deal: The newest non-running job should be `+', and the
2206 next-newest non-running job should be `-'. If there is only a single
2207 stopped job, the previous_job is the newest non-running job. If there
2208 are only running jobs, the newest running job is `+' and the
2209 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
2216 if (job_slots && current_job != NO_JOB && jobs[current_job] && STOPPED (current_job))
2217 candidate = current_job;
2222 /* First choice: the previous job. */
2223 if (previous_job != NO_JOB && jobs[previous_job] && STOPPED (previous_job))
2224 candidate = previous_job;
2226 /* Second choice: the most recently stopped job. */
2227 if (candidate == NO_JOB)
2228 candidate = job_last_stopped (job_slots);
2230 /* Third choice: the newest running job. */
2231 if (candidate == NO_JOB)
2232 candidate = job_last_running (job_slots);
2235 /* If we found a job to use, then use it. Otherwise, there
2236 are no jobs period. */
2237 if (candidate != NO_JOB)
2238 set_current_job (candidate);
2240 current_job = previous_job = NO_JOB;
2243 /* Set up the job structures so we know the job and its processes are
2246 set_job_running (job)
2249 register PROCESS *p;
2251 /* Each member of the pipeline is now running. */
2252 p = jobs[job]->pipe;
2256 if (WIFSTOPPED (p->status))
2257 p->running = PS_RUNNING; /* XXX - could be PS_STOPPED */
2260 while (p != jobs[job]->pipe);
2262 /* This means that the job is running. */
2263 JOBSTATE (job) = JRUNNING;
2266 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2267 start the job in the background. JOB is a zero-based index into
2268 JOBS. Returns -1 if it is unable to start a job, and the return
2269 status of the job otherwise. */
2271 start_job (job, foreground)
2272 int job, foreground;
2274 register PROCESS *p;
2275 int already_running;
2278 static TTYSTRUCT save_stty;
2280 BLOCK_CHILD (set, oset);
2284 internal_error (_("%s: job has terminated"), this_command_name);
2285 UNBLOCK_CHILD (oset);
2289 already_running = RUNNING (job);
2291 if (foreground == 0 && already_running)
2293 internal_error (_("%s: job %d already in background"), this_command_name, job + 1);
2294 UNBLOCK_CHILD (oset);
2298 wd = current_working_directory ();
2300 /* You don't know about the state of this job. Do you? */
2301 jobs[job]->flags &= ~J_NOTIFIED;
2305 set_current_job (job);
2306 jobs[job]->flags |= J_FOREGROUND;
2309 /* Tell the outside world what we're doing. */
2310 p = jobs[job]->pipe;
2312 if (foreground == 0)
2313 fprintf (stderr, "[%d]%c ", job + 1,
2314 (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
2318 fprintf (stderr, "%s%s",
2319 p->command ? p->command : "",
2320 p->next != jobs[job]->pipe? " | " : "");
2323 while (p != jobs[job]->pipe);
2325 if (foreground == 0)
2326 fprintf (stderr, " &");
2328 if (strcmp (wd, jobs[job]->wd) != 0)
2329 fprintf (stderr, " (wd: %s)", polite_directory_format (jobs[job]->wd));
2331 fprintf (stderr, "\n");
2334 if (already_running == 0)
2335 set_job_running (job);
2337 /* Save the tty settings before we start the job in the foreground. */
2341 save_stty = shell_tty_info;
2342 /* Give the terminal to this job. */
2343 if (IS_JOBCONTROL (job))
2344 give_terminal_to (jobs[job]->pgrp, 0);
2347 jobs[job]->flags &= ~J_FOREGROUND;
2349 /* If the job is already running, then don't bother jump-starting it. */
2350 if (already_running == 0)
2352 jobs[job]->flags |= J_NOTIFIED;
2353 killpg (jobs[job]->pgrp, SIGCONT);
2361 pid = find_last_pid (job, 0);
2362 UNBLOCK_CHILD (oset);
2364 shell_tty_info = save_stty;
2371 UNBLOCK_CHILD (oset);
2376 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2377 If PID does belong to a job, and the job is stopped, then CONTinue the
2378 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2379 then kill the process group associated with PID. */
2381 kill_pid (pid, sig, group)
2385 register PROCESS *p;
2389 result = EXECUTION_SUCCESS;
2392 BLOCK_CHILD (set, oset);
2393 p = find_pipeline (pid, 0, &job);
2397 jobs[job]->flags &= ~J_NOTIFIED;
2399 /* Kill process in backquotes or one started without job control? */
2400 if (jobs[job]->pgrp == shell_pgrp)
2402 p = jobs[job]->pipe;
2407 if (p->running == PS_DONE && (sig == SIGTERM || sig == SIGHUP))
2408 kill (p->pid, SIGCONT);
2411 while (p != jobs[job]->pipe);
2415 result = killpg (jobs[job]->pgrp, sig);
2416 if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2417 killpg (jobs[job]->pgrp, SIGCONT);
2418 /* If we're continuing a stopped job via kill rather than bg or
2419 fg, emulate the `bg' behavior. */
2420 if (p && STOPPED (job) && (sig == SIGCONT))
2422 set_job_running (job);
2423 jobs[job]->flags &= ~J_FOREGROUND;
2424 jobs[job]->flags |= J_NOTIFIED;
2429 result = killpg (pid, sig);
2431 UNBLOCK_CHILD (oset);
2434 result = kill (pid, sig);
2439 /* sigchld_handler () flushes at least one of the children that we are
2440 waiting for. It gets run when we have gotten a SIGCHLD signal. */
2442 sigchld_handler (sig)
2448 REINSTALL_SIGCHLD_HANDLER;
2451 if (queue_sigchld == 0)
2452 n = waitchld (-1, 0);
2457 /* waitchld() reaps dead or stopped children. It's called by wait_for and
2458 sigchld_handler, and runs until there aren't any children terminating any
2460 If BLOCK is 1, this is to be a blocking wait for a single child, although
2461 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
2462 the number of children reaped, or -1 if there are no unwaited-for child
2465 waitchld (wpid, block)
2472 int call_set_current, last_stopped_job, job, children_exited, waitpid_flags;
2474 call_set_current = children_exited = 0;
2475 last_stopped_job = NO_JOB;
2479 /* We don't want to be notified about jobs stopping if job control
2480 is not active. XXX - was interactive_shell instead of job_control */
2481 waitpid_flags = (job_control && subshell_environment == 0)
2482 ? (WUNTRACED|WCONTINUED)
2484 if (sigchld || block == 0)
2485 waitpid_flags |= WNOHANG;
2486 pid = WAITPID (-1, &status, waitpid_flags);
2488 /* The check for WNOHANG is to make sure we decrement sigchld only
2489 if it was non-zero before we called waitpid. */
2490 if (sigchld > 0 && (waitpid_flags & WNOHANG))
2493 /* If waitpid returns -1 with errno == ECHILD, there are no more
2494 unwaited-for child processes of this shell. */
2495 if (pid < 0 && errno == ECHILD)
2497 if (children_exited == 0)
2503 /* If waitpid returns 0, there are running children. If it returns -1,
2504 the only other error POSIX says it can return is EINTR. */
2506 continue; /* jumps right to the test */
2508 /* children_exited is used to run traps on SIGCHLD. We don't want to
2509 run the trap if a process is just being continued. */
2510 if (WIFCONTINUED(status) == 0)
2513 /* Locate our PROCESS for this pid. */
2514 child = find_pipeline (pid, 1, &job); /* want running procs only */
2516 /* It is not an error to have a child terminate that we did
2517 not have a record of. This child could have been part of
2518 a pipeline in backquote substitution. Even so, I'm not
2519 sure child is ever non-zero. */
2523 while (child->pid != pid)
2524 child = child->next;
2526 /* Remember status, and whether or not the process is running. */
2527 child->status = status;
2528 child->running = WIFCONTINUED(status) ? PS_RUNNING : PS_DONE;
2533 call_set_current += set_job_status_and_cleanup (job);
2536 last_stopped_job = job;
2537 else if (DEADJOB (job) && last_stopped_job == job)
2538 last_stopped_job = NO_JOB;
2540 while ((sigchld || block == 0) && pid > (pid_t)0);
2542 /* If a job was running and became stopped, then set the current
2543 job. Otherwise, don't change a thing. */
2544 if (call_set_current)
2546 if (last_stopped_job != NO_JOB)
2547 set_current_job (last_stopped_job);
2552 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
2553 if (job_control && signal_is_trapped (SIGCHLD) && children_exited &&
2554 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
2555 run_sigchld_trap (children_exited);
2557 /* We have successfully recorded the useful information about this process
2558 that has just changed state. If we notify asynchronously, and the job
2559 that this process belongs to is no longer running, then notify the user
2560 of that fact now. */
2561 if (asynchronous_notification && interactive)
2562 notify_of_job_status ();
2564 return (children_exited);
2567 /* Set the status of JOB and perform any necessary cleanup if the job is
2570 Currently, the cleanup activity is restricted to handling any SIGINT
2571 received while waiting for a foreground job to finish. */
2573 set_job_status_and_cleanup (job)
2577 int tstatus, job_state, any_stopped, any_tstped, call_set_current;
2578 SigHandler *temp_handler;
2580 child = jobs[job]->pipe;
2581 jobs[job]->flags &= ~J_NOTIFIED;
2583 call_set_current = 0;
2586 * COMPUTE JOB STATUS
2589 /* If all children are not running, but any of them is stopped, then
2590 the job is stopped, not dead. */
2591 job_state = any_stopped = any_tstped = 0;
2594 job_state |= child->running;
2595 if (child->running == PS_DONE && (WIFSTOPPED (child->status)))
2598 any_tstped |= interactive && job_control &&
2599 (WSTOPSIG (child->status) == SIGTSTP);
2601 child = child->next;
2603 while (child != jobs[job]->pipe);
2605 /* If job_state != 0, the job is still running, so don't bother with
2606 setting the process exit status and job state unless we're
2607 transitioning from stopped to running. */
2608 if (job_state != 0 && JOBSTATE(job) != JSTOPPED)
2615 /* The job is either stopped or dead. Set the state of the job accordingly. */
2618 jobs[job]->state = JSTOPPED;
2619 jobs[job]->flags &= ~J_FOREGROUND;
2621 /* Suspending a job with SIGTSTP breaks all active loops. */
2622 if (any_tstped && loop_level)
2623 breaking = loop_level;
2625 else if (job_state != 0) /* was stopped, now running */
2627 jobs[job]->state = JRUNNING;
2632 jobs[job]->state = JDEAD;
2635 if (IS_FOREGROUND (job))
2639 /* If this job has a cleanup function associated with it, call it
2640 with `cleanarg' as the single argument, then set the function
2641 pointer to NULL so it is not inadvertently called twice. The
2642 cleanup function is responsible for deallocating cleanarg. */
2643 if (jobs[job]->j_cleanup)
2645 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
2646 jobs[job]->j_cleanup = (sh_vptrfunc_t *)NULL;
2653 * Currently, we just do special things if we got a SIGINT while waiting
2654 * for a foreground job to complete
2657 if (jobs[job]->state == JDEAD)
2659 /* If we're running a shell script and we get a SIGINT with a
2660 SIGINT trap handler, but the foreground job handles it and
2661 does not exit due to SIGINT, run the trap handler but do not
2662 otherwise act as if we got the interrupt. */
2663 if (wait_sigint_received && interactive_shell == 0 &&
2664 WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
2665 signal_is_trapped (SIGINT))
2668 wait_sigint_received = 0;
2669 last_command_exit_value = process_exit_status (child->status);
2671 old_frozen = jobs_list_frozen;
2672 jobs_list_frozen = 1;
2673 tstatus = maybe_call_trap_handler (SIGINT);
2674 jobs_list_frozen = old_frozen;
2677 /* If the foreground job is killed by SIGINT when job control is not
2678 active, we need to perform some special handling.
2680 The check of wait_sigint_received is a way to determine if the
2681 SIGINT came from the keyboard (in which case the shell has already
2682 seen it, and wait_sigint_received is non-zero, because keyboard
2683 signals are sent to process groups) or via kill(2) to the foreground
2684 process by another process (or itself). If the shell did receive the
2685 SIGINT, it needs to perform normal SIGINT processing. */
2686 else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
2687 IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
2691 wait_sigint_received = 0;
2693 /* If SIGINT is trapped, set the exit status so that the trap
2694 handler can see it. */
2695 if (signal_is_trapped (SIGINT))
2696 last_command_exit_value = process_exit_status (child->status);
2698 /* If the signal is trapped, let the trap handler get it no matter
2699 what and simply return if the trap handler returns.
2700 maybe_call_trap_handler() may cause dead jobs to be removed from
2701 the job table because of a call to execute_command. We work
2702 around this by setting JOBS_LIST_FROZEN. */
2703 old_frozen = jobs_list_frozen;
2704 jobs_list_frozen = 1;
2705 tstatus = maybe_call_trap_handler (SIGINT);
2706 jobs_list_frozen = old_frozen;
2707 if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
2709 /* wait_sigint_handler () has already seen SIGINT and
2710 allowed the wait builtin to jump out. We need to
2711 call the original SIGINT handler, if necessary. If
2712 the original handler is SIG_DFL, we need to resend
2713 the signal to ourselves. */
2715 temp_handler = old_sigint_handler;
2717 /* Bogus. If we've reset the signal handler as the result
2718 of a trap caught on SIGINT, then old_sigint_handler
2719 will point to trap_handler, which now knows nothing about
2720 SIGINT (if we reset the sighandler to the default).
2721 In this case, we have to fix things up. What a crock. */
2722 if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
2723 temp_handler = trap_to_sighandler (SIGINT);
2724 restore_sigint_handler ();
2725 if (temp_handler == SIG_DFL)
2726 termination_unwind_protect (SIGINT);
2727 else if (temp_handler != SIG_IGN)
2728 (*temp_handler) (SIGINT);
2733 return call_set_current;
2736 /* Build the array of values for the $PIPESTATUS variable from the set of
2737 exit statuses of all processes in the job J. */
2742 #if defined (ARRAY_VARS)
2744 register PROCESS *p;
2746 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
2751 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
2758 pstatuses[i++] = process_exit_status (p->status);
2761 while (p != jobs[j]->pipe);
2763 pstatuses[i] = -1; /* sentinel */
2764 set_pipestatus_array (pstatuses, i);
2769 run_sigchld_trap (nchild)
2775 /* Turn off the trap list during the call to parse_and_execute ()
2776 to avoid potentially infinite recursive calls. Preserve the
2777 values of last_command_exit_value, last_made_pid, and the_pipeline
2778 around the execution of the trap commands. */
2779 trap_command = savestring (trap_list[SIGCHLD]);
2781 begin_unwind_frame ("SIGCHLD trap");
2782 unwind_protect_int (last_command_exit_value);
2783 unwind_protect_int (last_command_exit_signal);
2784 unwind_protect_var (last_made_pid);
2785 unwind_protect_int (interrupt_immediately);
2786 unwind_protect_int (jobs_list_frozen);
2787 unwind_protect_pointer (the_pipeline);
2788 unwind_protect_pointer (subst_assign_varlist);
2790 /* We have to add the commands this way because they will be run
2791 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
2792 to reference freed memory. */
2793 add_unwind_protect (xfree, trap_command);
2794 add_unwind_protect (maybe_set_sigchld_trap, trap_command);
2796 subst_assign_varlist = (WORD_LIST *)NULL;
2797 the_pipeline = (PROCESS *)NULL;
2799 restore_default_signal (SIGCHLD);
2800 jobs_list_frozen = 1;
2801 for (i = 0; i < nchild; i++)
2803 interrupt_immediately = 1;
2804 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST|SEVAL_RESETLINE);
2807 run_unwind_frame ("SIGCHLD trap");
2810 /* Function to call when you want to notify people of changes
2811 in job status. This prints out all jobs which are pending
2812 notification to stderr, and marks those printed as already
2813 notified, thus making them candidates for cleanup. */
2815 notify_of_job_status ()
2817 register int job, termsig;
2822 if (jobs == 0 || job_slots == 0)
2828 sigaddset (&set, SIGCHLD);
2829 sigaddset (&set, SIGTTOU);
2830 sigemptyset (&oset);
2831 sigprocmask (SIG_BLOCK, &set, &oset);
2836 for (job = 0, dir = (char *)NULL; job < job_slots; job++)
2838 if (jobs[job] && IS_NOTIFIED (job) == 0)
2840 s = raw_job_exit_status (job);
2841 termsig = WTERMSIG (s);
2843 /* POSIX.2 says we have to hang onto the statuses of at most the
2844 last CHILD_MAX background processes if the shell is running a
2845 script. If the shell is not interactive, don't print anything
2846 unless the job was killed by a signal. */
2847 if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
2848 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
2852 /* If job control is disabled, don't print the status messages.
2853 Mark dead jobs as notified so that they get cleaned up. If
2854 startup_state == 2, we were started to run `-c command', so
2855 don't print anything. */
2856 if ((job_control == 0 && interactive_shell) || startup_state == 2)
2858 /* If job control is disabled, don't print the status messages.
2859 Mark dead jobs as notified so that they get cleaned up. If
2860 startup_state == 2 and subshell_environment has the
2861 SUBSHELL_COMSUB bit turned on, we were started to run a command
2862 substitution, so don't print anything. */
2863 if ((job_control == 0 && interactive_shell) ||
2864 (startup_state == 2 && (subshell_environment & SUBSHELL_COMSUB)))
2867 /* POSIX.2 compatibility: if the shell is not interactive,
2868 hang onto the job corresponding to the last asynchronous
2869 pid until the user has been notified of its status or does
2871 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job, 0) != last_asynchronous_pid)))
2872 jobs[job]->flags |= J_NOTIFIED;
2876 /* Print info on jobs that are running in the background,
2877 and on foreground jobs that were killed by anything
2878 except SIGINT (and possibly SIGPIPE). */
2879 switch (JOBSTATE (job))
2882 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
2883 termsig != SIGINT &&
2884 #if defined (DONT_REPORT_SIGPIPE)
2885 termsig != SIGPIPE &&
2887 signal_is_trapped (termsig) == 0)
2889 /* Don't print `0' for a line number. */
2890 fprintf (stderr, "%s: line %d: ", get_name_for_error (), (line_number == 0) ? 1 : line_number);
2891 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
2893 else if (IS_FOREGROUND (job))
2895 #if !defined (DONT_REPORT_SIGPIPE)
2896 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2898 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
2901 fprintf (stderr, "%s", j_strsignal (termsig));
2904 fprintf (stderr, " (core dumped)");
2906 fprintf (stderr, "\n");
2912 dir = current_working_directory ();
2913 pretty_print_job (job, JLIST_STANDARD, stderr);
2914 if (dir && strcmp (dir, jobs[job]->wd) != 0)
2916 "(wd now: %s)\n", polite_directory_format (dir));
2919 jobs[job]->flags |= J_NOTIFIED;
2923 fprintf (stderr, "\n");
2925 dir = current_working_directory ();
2926 pretty_print_job (job, JLIST_STANDARD, stderr);
2927 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2929 "(wd now: %s)\n", polite_directory_format (dir));
2930 jobs[job]->flags |= J_NOTIFIED;
2938 programming_error ("notify_of_job_status");
2943 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2948 /* Initialize the job control mechanism, and set up the tty stuff. */
2950 initialize_job_control (force)
2953 shell_pgrp = getpgid (0);
2955 if (shell_pgrp == -1)
2957 sys_error ("initialize_job_control: getpgrp failed");
2961 /* We can only have job control if we are interactive. */
2962 if (interactive == 0)
2965 original_pgrp = NO_PID;
2966 shell_tty = fileno (stderr);
2970 /* Get our controlling terminal. If job_control is set, or
2971 interactive is set, then this is an interactive shell no
2972 matter where fd 2 is directed. */
2973 shell_tty = dup (fileno (stderr)); /* fd 2 */
2975 shell_tty = move_to_high_fd (shell_tty, 1, -1);
2977 /* Compensate for a bug in systems that compiled the BSD
2978 rlogind with DEBUG defined, like NeXT and Alliant. */
2979 if (shell_pgrp == 0)
2981 shell_pgrp = getpid ();
2982 setpgid (0, shell_pgrp);
2983 tcsetpgrp (shell_tty, shell_pgrp);
2986 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2988 if (shell_pgrp != terminal_pgrp)
2992 ottin = set_signal_handler(SIGTTIN, SIG_DFL);
2994 set_signal_handler (SIGTTIN, ottin);
3000 /* Make sure that we are using the new line discipline. */
3001 if (set_new_line_discipline (shell_tty) < 0)
3003 sys_error ("initialize_job_control: line discipline");
3008 original_pgrp = shell_pgrp;
3009 shell_pgrp = getpid ();
3011 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
3013 sys_error ("initialize_job_control: setpgid");
3014 shell_pgrp = original_pgrp;
3019 /* If (and only if) we just set our process group to our pid,
3020 thereby becoming a process group leader, and the terminal
3021 is not in the same process group as our (new) process group,
3022 then set the terminal's process group to our (new) process
3023 group. If that fails, set our process group back to what it
3024 was originally (so we can still read from the terminal) and
3025 turn off job control. */
3026 if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
3028 if (give_terminal_to (shell_pgrp, 0) < 0)
3030 setpgid (0, original_pgrp);
3031 shell_pgrp = original_pgrp;
3036 if (job_control == 0)
3037 internal_error (_("no job control in this shell"));
3040 if (shell_tty != fileno (stderr))
3041 SET_CLOSE_ON_EXEC (shell_tty);
3043 set_signal_handler (SIGCHLD, sigchld_handler);
3045 change_flag ('m', job_control ? '-' : '+');
3055 debug_print_pgrps ()
3057 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
3058 (long)original_pgrp, (long)shell_pgrp, (long)terminal_pgrp);
3059 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
3060 shell_tty, (long)tcgetpgrp (shell_tty), (long)getpgid(0));
3064 /* Set the line discipline to the best this system has to offer.
3065 Return -1 if this is not possible. */
3067 set_new_line_discipline (tty)
3070 #if defined (NEW_TTY_DRIVER)
3073 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
3076 if (ldisc != NTTYDISC)
3080 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
3084 #endif /* NEW_TTY_DRIVER */
3086 #if defined (TERMIO_TTY_DRIVER)
3087 # if defined (TERMIO_LDISC) && (NTTYDISC)
3088 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
3091 if (shell_tty_info.c_line != NTTYDISC)
3093 shell_tty_info.c_line = NTTYDISC;
3094 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
3097 # endif /* TERMIO_LDISC && NTTYDISC */
3099 #endif /* TERMIO_TTY_DRIVER */
3101 #if defined (TERMIOS_TTY_DRIVER)
3102 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
3103 if (tcgetattr (tty, &shell_tty_info) < 0)
3106 if (shell_tty_info.c_line != NTTYDISC)
3108 shell_tty_info.c_line = NTTYDISC;
3109 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
3112 # endif /* TERMIOS_LDISC && NTTYDISC */
3114 #endif /* TERMIOS_TTY_DRIVER */
3116 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
3121 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3123 get_new_window_size (from_sig)
3128 if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
3129 win.ws_row > 0 && win.ws_col > 0)
3132 shell_tty_info.c_winsize = win; /* structure copying */
3134 sh_set_lines_and_columns (win.ws_row, win.ws_col);
3135 #if defined (READLINE)
3136 rl_set_screen_size (win.ws_row, win.ws_col);
3142 sigwinch_sighandler (sig)
3145 #if defined (MUST_REINSTALL_SIGHANDLERS)
3146 set_signal_handler (SIGWINCH, sigwinch_sighandler);
3147 #endif /* MUST_REINSTALL_SIGHANDLERS */
3148 get_new_window_size (1);
3153 get_new_window_size (from_sig)
3157 #endif /* TIOCGWINSZ && SIGWINCH */
3160 set_sigwinch_handler ()
3162 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3163 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
3168 unset_sigwinch_handler ()
3170 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3171 set_signal_handler (SIGWINCH, old_winch);
3175 /* Setup this shell to handle C-C, etc. */
3177 initialize_job_signals ()
3181 set_signal_handler (SIGINT, sigint_sighandler);
3182 set_signal_handler (SIGTSTP, SIG_IGN);
3183 set_signal_handler (SIGTTOU, SIG_IGN);
3184 set_signal_handler (SIGTTIN, SIG_IGN);
3185 set_sigwinch_handler ();
3187 else if (job_control)
3189 old_tstp = set_signal_handler (SIGTSTP, sigstop_sighandler);
3190 old_ttin = set_signal_handler (SIGTTIN, sigstop_sighandler);
3191 old_ttou = set_signal_handler (SIGTTOU, sigstop_sighandler);
3193 /* Leave these things alone for non-interactive shells without job
3197 /* Here we handle CONT signals. */
3199 sigcont_sighandler (sig)
3202 initialize_job_signals ();
3203 set_signal_handler (SIGCONT, old_cont);
3204 kill (getpid (), SIGCONT);
3209 /* Here we handle stop signals while we are running not as a login shell. */
3211 sigstop_sighandler (sig)
3214 set_signal_handler (SIGTSTP, old_tstp);
3215 set_signal_handler (SIGTTOU, old_ttou);
3216 set_signal_handler (SIGTTIN, old_ttin);
3218 old_cont = set_signal_handler (SIGCONT, sigcont_sighandler);
3220 give_terminal_to (shell_pgrp, 0);
3222 kill (getpid (), sig);
3227 /* Give the terminal to PGRP. */
3229 give_terminal_to (pgrp, force)
3237 if (job_control || force)
3240 sigaddset (&set, SIGTTOU);
3241 sigaddset (&set, SIGTTIN);
3242 sigaddset (&set, SIGTSTP);
3243 sigaddset (&set, SIGCHLD);
3244 sigemptyset (&oset);
3245 sigprocmask (SIG_BLOCK, &set, &oset);
3247 if (tcsetpgrp (shell_tty, pgrp) < 0)
3249 /* Maybe we should print an error message? */
3251 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
3252 shell_tty, (long)getpid(), (long)pgrp);
3257 terminal_pgrp = pgrp;
3258 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
3264 /* Clear out any jobs in the job array. This is intended to be used by
3265 children of the shell, who should not have any job structures as baggage
3266 when they start executing (forking subshells for parenthesized execution
3267 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
3268 is nonzero, only running jobs are removed from the table. */
3270 delete_all_jobs (running_only)
3276 BLOCK_CHILD (set, oset);
3280 current_job = previous_job = NO_JOB;
3282 for (i = 0; i < job_slots; i++)
3283 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3286 if (running_only == 0)
3288 free ((char *)jobs);
3293 UNBLOCK_CHILD (oset);
3296 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
3297 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
3299 nohup_all_jobs (running_only)
3305 BLOCK_CHILD (set, oset);
3309 for (i = 0; i < job_slots; i++)
3310 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3314 UNBLOCK_CHILD (oset);
3323 BLOCK_CHILD (set, oset);
3324 for (i = n = 0; i < job_slots; i++)
3325 if (jobs[i] && DEADJOB(i) == 0)
3327 UNBLOCK_CHILD (oset);
3332 mark_all_jobs_as_dead ()
3340 BLOCK_CHILD (set, oset);
3342 for (i = 0; i < job_slots; i++)
3344 jobs[i]->state = JDEAD;
3346 UNBLOCK_CHILD (oset);
3349 /* Mark all dead jobs as notified, so delete_job () cleans them out
3350 of the job table properly. POSIX.2 says we need to save the
3351 status of the last CHILD_MAX jobs, so we count the number of dead
3352 jobs and mark only enough as notified to save CHILD_MAX statuses. */
3354 mark_dead_jobs_as_notified (force)
3357 register int i, ndead;
3363 BLOCK_CHILD (set, oset);
3365 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
3366 around; just run through the array. */
3369 for (i = 0; i < job_slots; i++)
3371 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
3372 jobs[i]->flags |= J_NOTIFIED;
3374 UNBLOCK_CHILD (oset);
3378 /* Mark enough dead jobs as notified to keep CHILD_MAX jobs left in the
3379 array not marked as notified. */
3381 /* Count the number of dead jobs */
3382 for (i = ndead = 0; i < job_slots; i++)
3384 if (jobs[i] && DEADJOB (i))
3389 child_max = getmaxchild ();
3391 child_max = DEFAULT_CHILD_MAX;
3393 /* Don't do anything if the number of dead jobs is less than CHILD_MAX and
3394 we're not forcing a cleanup. */
3395 if (ndead <= child_max)
3397 UNBLOCK_CHILD (oset);
3401 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
3402 the list. This isn't exactly right yet; changes need to be made
3403 to stop_pipeline so we don't mark the newer jobs after we've
3404 created CHILD_MAX slots in the jobs array. */
3405 for (i = 0; i < job_slots; i++)
3407 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
3409 jobs[i]->flags |= J_NOTIFIED;
3410 if (--ndead <= child_max)
3415 UNBLOCK_CHILD (oset);
3418 /* Here to allow other parts of the shell (like the trap stuff) to
3419 unfreeze the jobs list. */
3421 unfreeze_jobs_list ()
3423 jobs_list_frozen = 0;
3426 /* Allow or disallow job control to take place. Returns the old value
3429 set_job_control (arg)
3439 /* Turn off all traces of job control. This is run by children of the shell
3440 which are going to do shellsy things, like wait (), etc. */
3442 without_job_control ()
3444 stop_making_children ();
3446 delete_all_jobs (0);
3447 set_job_control (0);
3450 /* If this shell is interactive, terminate all stopped jobs and
3451 restore the original terminal process group. This is done
3452 before the `exec' builtin calls shell_execve. */
3456 if (interactive_shell) /* XXX - should it be interactive? */
3458 terminate_stopped_jobs ();
3460 if (original_pgrp >= 0)
3461 give_terminal_to (original_pgrp, 1);
3464 if (original_pgrp >= 0)
3465 setpgid (0, original_pgrp);
3468 /* Restart job control by closing shell tty and reinitializing. This is
3469 called after an exec fails in an interactive shell and we do not exit. */
3471 restart_job_control ()
3473 if (shell_tty != -1)
3475 initialize_job_control (0);
3478 /* Set the handler to run when the shell receives a SIGCHLD signal. */
3480 set_sigchld_handler ()
3482 set_signal_handler (SIGCHLD, sigchld_handler);
3485 #if defined (PGRP_PIPE)
3486 /* Read from the read end of a pipe. This is how the process group leader
3487 blocks until all of the processes in a pipeline have been made. */
3502 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
3507 /* Close the read and write ends of PP, an array of file descriptors. */
3521 /* Functional interface closes our local-to-job-control pipes. */
3525 pipe_close (pgrp_pipe);
3528 #endif /* PGRP_PIPE */