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. */
479 /* XXX - revisit this interactive assumption */
482 for (i = job_slots; i; i--)
488 /* If we're not interactive, we don't need to monotonically increase
489 the job number (in fact, we don't care about the job number at all),
490 so we can simply scan for the first free slot. This helps to keep
491 us from continuously reallocating the jobs array when running
492 certain kinds of shell loops, and saves time spent searching. */
493 for (i = 0; i < job_slots; i++)
498 /* Do we need more room? */
500 /* First try compaction */
501 if (subshell_environment && interactive_shell && i == job_slots && job_slots >= MAX_JOBS_IN_ARRAY)
502 i = compact_jobs_list (0);
504 /* If we can't compact, reallocate */
507 job_slots += JOB_SLOTS;
508 jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
510 for (j = i; j < job_slots; j++)
511 jobs[j] = (JOB *)NULL;
514 /* Add the current pipeline to the job list. */
518 int any_alive, any_stopped;
520 newjob = (JOB *)xmalloc (sizeof (JOB));
522 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
524 p->next = (PROCESS *)NULL;
525 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
526 for (p = newjob->pipe; p->next; p = p->next)
528 p->next = newjob->pipe;
530 the_pipeline = (PROCESS *)NULL;
531 newjob->pgrp = pipeline_pgrp;
536 /* Flag to see if in another pgrp. */
538 newjob->flags |= J_JOBCONTROL;
540 /* Set the state of this pipeline. */
542 any_alive = any_stopped = 0;
545 any_alive |= p->running;
546 any_stopped |= WIFSTOPPED (p->status);
549 while (p != newjob->pipe);
551 newjob->state = any_alive ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
552 newjob->wd = job_working_directory ();
553 newjob->deferred = deferred;
555 newjob->j_cleanup = (sh_vptrfunc_t *)NULL;
556 newjob->cleanarg = (PTR_T) NULL;
559 if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
563 newjob = (JOB *)NULL;
568 newjob->flags &= ~J_FOREGROUND;
575 newjob->flags |= J_FOREGROUND;
577 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
579 * The currently-accepted job control wisdom says to set the
580 * terminal's process group n+1 times in an n-step pipeline:
581 * once in the parent and once in each child. This is where
582 * the parent gives it away.
585 if (job_control && newjob->pgrp)
586 give_terminal_to (newjob->pgrp, 0);
590 stop_making_children ();
591 UNBLOCK_CHILD (oset);
592 return (current_job);
595 /* Delete all DEAD jobs that the user had received notification about. */
602 if (job_slots == 0 || jobs_list_frozen)
607 for (i = 0; i < job_slots; i++)
608 if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
614 /* Compact the jobs list by removing dead jobs. Assumed that we have filled
615 the jobs array to some predefined maximum. Called when the shell is not
616 the foreground process (subshell_environment != 0). Returns the first
617 available slot in the compacted list. If that value is job_slots, then
618 the list needs to be reallocated. The jobs array is in new memory if
619 this returns > 0 and < job_slots. FLAGS is reserved for future use. */
621 compact_jobs_list (flags)
629 if (job_slots == 0 || jobs_list_frozen)
633 child_max = getmaxchild ();
635 /* Take out at most a quarter of the jobs in the jobs array, but leave at
637 nremove = job_slots >> 2;
638 if ((job_slots - nremove) < child_max)
639 nremove = job_slots - child_max;
641 /* need to increase jobs list to at least CHILD_MAX entries */
645 BLOCK_CHILD (set, oset);
647 for (ndel = i = 0; i < job_slots; i++)
650 if (DEADJOB (i) && (find_last_pid (i, 0) != last_asynchronous_pid))
661 UNBLOCK_CHILD (oset);
665 newlist = (JOB **)xmalloc ((1 + job_slots) * sizeof (JOB *));
666 for (i = j = 0; i < job_slots; i++)
668 newlist[j++] = jobs[i];
671 for ( ; j < job_slots; j++)
672 newlist[j] = (JOB *)NULL;
677 UNBLOCK_CHILD (oset);
682 /* Delete the job at INDEX from the job list. Must be called
683 with SIGCHLD blocked. */
685 delete_job (job_index, warn_stopped)
686 int job_index, warn_stopped;
690 if (job_slots == 0 || jobs_list_frozen)
693 if (warn_stopped && subshell_environment == 0 && STOPPED (job_index))
694 internal_warning (_("deleting stopped job %d with process group %ld"), job_index+1, (long)jobs[job_index]->pgrp);
696 temp = jobs[job_index];
697 if (job_index == current_job || job_index == previous_job)
700 jobs[job_index] = (JOB *)NULL;
703 discard_pipeline (temp->pipe);
706 dispose_command (temp->deferred);
711 /* Must be called with SIGCHLD blocked. */
713 nohup_job (job_index)
721 if (temp = jobs[job_index])
722 temp->flags |= J_NOHUP;
725 /* Get rid of the data structure associated with a process chain. */
727 discard_pipeline (chain)
728 register PROCESS *chain;
730 register PROCESS *this, *next;
736 FREE (this->command);
740 while (this != chain);
743 /* Add this process to the chain being built in the_pipeline.
744 NAME is the command string that will be exec'ed later.
745 PID is the process id of the child. */
747 add_process (name, pid)
753 t = (PROCESS *)xmalloc (sizeof (PROCESS));
754 t->next = the_pipeline;
756 WSTATUS (t->status) = 0;
757 t->running = PS_RUNNING;
766 while (p->next != t->next)
773 /* Take the last job and make it the first job. Must be called with
776 rotate_the_pipeline ()
780 if (the_pipeline->next == the_pipeline)
782 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
787 /* Reverse the order of the processes in the_pipeline. Must be called with
790 reverse_the_pipeline ()
794 if (the_pipeline->next == the_pipeline)
797 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
799 p->next = (PROCESS *)NULL;
801 n = REVERSE_LIST (the_pipeline, PROCESS *);
804 for (p = the_pipeline; p->next; p = p->next)
806 p->next = the_pipeline;
810 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
811 then it is time to stop mapping, and that is the return value
812 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
815 map_over_jobs (func, arg1, arg2)
816 sh_job_map_func_t *func;
826 BLOCK_CHILD (set, oset);
828 for (i = result = 0; i < job_slots; i++)
832 result = (*func)(jobs[i], arg1, arg2, i);
838 UNBLOCK_CHILD (oset);
843 /* Cause all the jobs in the current pipeline to exit. */
845 terminate_current_pipeline ()
847 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
849 killpg (pipeline_pgrp, SIGTERM);
850 killpg (pipeline_pgrp, SIGCONT);
854 /* Cause all stopped jobs to exit. */
856 terminate_stopped_jobs ()
860 for (i = 0; i < job_slots; i++)
862 if (jobs[i] && STOPPED (i))
864 killpg (jobs[i]->pgrp, SIGTERM);
865 killpg (jobs[i]->pgrp, SIGCONT);
870 /* Cause all jobs, running or stopped, to receive a hangup signal. If
871 a job is marked J_NOHUP, don't send the SIGHUP. */
877 for (i = 0; i < job_slots; i++)
881 if ((jobs[i]->flags & J_NOHUP) == 0)
882 killpg (jobs[i]->pgrp, SIGHUP);
884 killpg (jobs[i]->pgrp, SIGCONT);
890 kill_current_pipeline ()
892 stop_making_children ();
896 /* Return the pipeline that PID belongs to. Note that the pipeline
897 doesn't have to belong to a job. Must be called with SIGCHLD blocked. */
899 find_pipeline (pid, running_only, jobp)
902 int *jobp; /* index into jobs list or NO_JOB */
907 /* See if this process is in the pipeline that we are building. */
915 /* Return it if we found it. */
918 if ((running_only && PRUNNING(p)) || (running_only == 0))
924 while (p != the_pipeline);
927 job = find_job (pid, running_only);
930 return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
933 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
934 belong to any job. Must be called with SIGCHLD blocked. */
936 find_job (pid, running_only)
943 for (i = 0; i < job_slots; i++)
953 if ((running_only && PRUNNING(p)) || (running_only == 0))
959 while (p != jobs[i]->pipe);
966 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
967 required by find_job. */
969 get_job_by_pid (pid, block)
977 BLOCK_CHILD (set, oset);
979 job = find_job (pid, 0);
982 UNBLOCK_CHILD (oset);
987 /* Print descriptive information about the job with leader pid PID. */
995 BLOCK_CHILD (set, oset);
997 job = find_job (pid, 0);
1000 printf ("[%d] %ld\n", job + 1, (long)pid);
1002 programming_error (_("describe_pid: %ld: no such pid"), (long)pid);
1004 UNBLOCK_CHILD (oset);
1016 x = retcode_name_buffer;
1017 sprintf (x, "Signal %d", s);
1023 printable_job_status (j, p, format)
1033 if (STOPPED (j) && format == 0)
1035 if (posixly_correct == 0 || p == 0 || (WIFSTOPPED (p->status) == 0))
1039 temp = retcode_name_buffer;
1040 sprintf (temp, "Stopped(%s)", signal_name (WSTOPSIG (p->status)));
1043 else if (RUNNING (j))
1047 if (WIFSTOPPED (p->status))
1048 temp = j_strsignal (WSTOPSIG (p->status));
1049 else if (WIFSIGNALED (p->status))
1050 temp = j_strsignal (WTERMSIG (p->status));
1051 else if (WIFEXITED (p->status))
1053 temp = retcode_name_buffer;
1054 es = WEXITSTATUS (p->status);
1056 strcpy (temp, "Done");
1057 else if (posixly_correct)
1058 sprintf (temp, "Done(%d)", es);
1060 sprintf (temp, "Exit %d", es);
1063 temp = "Unknown status";
1069 /* This is the way to print out information on a job if you
1070 know the index. FORMAT is:
1072 JLIST_NORMAL) [1]+ Running emacs
1073 JLIST_LONG ) [1]+ 2378 Running emacs
1074 -1 ) [1]+ 2378 emacs
1076 JLIST_NORMAL) [1]+ Stopped ls | more
1077 JLIST_LONG ) [1]+ 2369 Stopped ls
1080 Just list the pid of the process group leader (really
1083 Use format JLIST_NORMAL, but list only jobs about which
1084 the user has not been notified. */
1086 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1087 the JOBS array corresponding to this pipeline. FORMAT is as described
1088 above. Must be called with SIGCHLD blocked.
1090 If you're printing a pipeline that's not in the jobs array, like the
1091 current pipeline as it's being created, pass -1 for JOB_INDEX */
1093 print_pipeline (p, job_index, format, stream)
1095 int job_index, format;
1098 PROCESS *first, *last, *show;
1099 int es, name_padding;
1106 while (last->next != first)
1112 fprintf (stream, format ? " " : " |");
1114 if (format != JLIST_STANDARD)
1115 fprintf (stream, "%5ld", (long)p->pid);
1117 fprintf (stream, " ");
1119 if (format > -1 && job_index >= 0)
1121 show = format ? p : last;
1122 temp = printable_job_status (job_index, show, format);
1128 if (show->running == first->running &&
1129 WSTATUS (show->status) == WSTATUS (first->status))
1133 temp = (char *)NULL;
1138 fprintf (stream, "%s", temp);
1142 es = 2; /* strlen ("| ") */
1143 name_padding = LONGEST_SIGNAL_DESC - es;
1145 fprintf (stream, "%*s", name_padding, "");
1147 if ((WIFSTOPPED (show->status) == 0) &&
1148 (WIFCONTINUED (show->status) == 0) &&
1149 WIFCORED (show->status))
1150 fprintf (stream, "(core dumped) ");
1154 if (p != first && format)
1155 fprintf (stream, "| ");
1158 fprintf (stream, "%s", p->command);
1160 if (p == last && job_index >= 0)
1162 temp = current_working_directory ();
1164 if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
1165 fprintf (stream, " &");
1167 if (strcmp (temp, jobs[job_index]->wd) != 0)
1169 " (wd: %s)", polite_directory_format (jobs[job_index]->wd));
1172 if (format || (p == last))
1174 /* We need to add a CR only if this is an interactive shell, and
1175 we're reporting the status of a completed job asynchronously.
1176 We can't really check whether this particular job is being
1177 reported asynchronously, so just add the CR if the shell is
1178 currently interactive and asynchronous notification is enabled. */
1179 if (asynchronous_notification && interactive)
1180 fprintf (stream, "\r\n");
1182 fprintf (stream, "\n");
1192 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1193 Must be called with SIGCHLD blocked or queued with queue_sigchld */
1195 pretty_print_job (job_index, format, stream)
1196 int job_index, format;
1199 register PROCESS *p;
1201 /* Format only pid information about the process group leader? */
1202 if (format == JLIST_PID_ONLY)
1204 fprintf (stream, "%ld\n", (long)jobs[job_index]->pipe->pid);
1208 if (format == JLIST_CHANGED_ONLY)
1210 if (IS_NOTIFIED (job_index))
1212 format = JLIST_STANDARD;
1215 if (format != JLIST_NONINTERACTIVE)
1216 fprintf (stream, "[%d]%c ", job_index + 1,
1217 (job_index == current_job) ? '+':
1218 (job_index == previous_job) ? '-' : ' ');
1220 if (format == JLIST_NONINTERACTIVE)
1221 format = JLIST_LONG;
1223 p = jobs[job_index]->pipe;
1225 print_pipeline (p, job_index, format, stream);
1227 /* We have printed information about this job. When the job's
1228 status changes, waitchld () sets the notification flag to 0. */
1229 jobs[job_index]->flags |= J_NOTIFIED;
1233 print_job (job, format, state, job_index)
1235 int format, state, job_index;
1237 if (state == -1 || (JOB_STATE)state == job->state)
1238 pretty_print_job (job_index, format, stdout);
1243 list_one_job (job, format, ignore, job_index)
1245 int format, ignore, job_index;
1247 pretty_print_job (job_index, format, stdout);
1251 list_stopped_jobs (format)
1254 cleanup_dead_jobs ();
1255 map_over_jobs (print_job, format, (int)JSTOPPED);
1259 list_running_jobs (format)
1262 cleanup_dead_jobs ();
1263 map_over_jobs (print_job, format, (int)JRUNNING);
1266 /* List jobs. If FORMAT is non-zero, then the long form of the information
1267 is printed, else just a short version. */
1269 list_all_jobs (format)
1272 cleanup_dead_jobs ();
1273 map_over_jobs (print_job, format, -1);
1276 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1277 COMMAND is just for remembering the name of the command; we don't do
1278 anything else with it. ASYNC_P says what to do with the tty. If
1279 non-zero, then don't give it away. */
1281 make_child (command, async_p)
1289 sigaddset (&set, SIGCHLD);
1290 sigaddset (&set, SIGINT);
1291 sigemptyset (&oset);
1292 sigprocmask (SIG_BLOCK, &set, &oset);
1296 #if defined (BUFFERED_INPUT)
1297 /* If default_buffered_input is active, we are reading a script. If
1298 the command is asynchronous, we have already duplicated /dev/null
1299 as fd 0, but have not changed the buffered stream corresponding to
1300 the old fd 0. We don't want to sync the stream in this case. */
1301 if (default_buffered_input != -1 &&
1302 (!async_p || default_buffered_input > 0))
1303 sync_buffered_stream (default_buffered_input);
1304 #endif /* BUFFERED_INPUT */
1306 /* Create the child, handle severe errors. */
1307 if ((pid = fork ()) < 0)
1311 /* Kill all of the processes in the current pipeline. */
1312 terminate_current_pipeline ();
1314 /* Discard the current pipeline, if any. */
1316 kill_current_pipeline ();
1318 throw_to_top_level (); /* Reset signals, etc. */
1323 /* In the child. Give this child the right process group, set the
1324 signals to the default state for a new process. */
1328 #if defined (BUFFERED_INPUT)
1329 /* Close default_buffered_input if it's > 0. We don't close it if it's
1330 0 because that's the file descriptor used when redirecting input,
1331 and it's wrong to close the file in that case. */
1332 unset_bash_input (0);
1333 #endif /* BUFFERED_INPUT */
1335 /* Restore top-level signal mask. */
1336 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1340 /* All processes in this pipeline belong in the same
1343 if (pipeline_pgrp == 0) /* This is the first child. */
1344 pipeline_pgrp = mypid;
1346 /* Check for running command in backquotes. */
1347 if (pipeline_pgrp == shell_pgrp)
1348 ignore_tty_job_signals ();
1350 default_tty_job_signals ();
1352 /* Set the process group before trying to mess with the terminal's
1353 process group. This is mandated by POSIX. */
1354 /* This is in accordance with the Posix 1003.1 standard,
1355 section B.7.2.4, which says that trying to set the terminal
1356 process group with tcsetpgrp() to an unused pgrp value (like
1357 this would have for the first child) is an error. Section
1358 B.4.3.3, p. 237 also covers this, in the context of job control
1360 if (setpgid (mypid, pipeline_pgrp) < 0)
1361 sys_error ("child setpgid (%ld to %ld)", (long)mypid, (long)pipeline_pgrp);
1363 /* By convention (and assumption above), if
1364 pipeline_pgrp == shell_pgrp, we are making a child for
1365 command substitution.
1366 In this case, we don't want to give the terminal to the
1367 shell's process group (we could be in the middle of a
1368 pipeline, for example). */
1369 if (async_p == 0 && pipeline_pgrp != shell_pgrp)
1370 give_terminal_to (pipeline_pgrp, 0);
1372 #if defined (PGRP_PIPE)
1373 if (pipeline_pgrp == mypid)
1374 pipe_read (pgrp_pipe);
1377 else /* Without job control... */
1379 if (pipeline_pgrp == 0)
1380 pipeline_pgrp = shell_pgrp;
1382 /* If these signals are set to SIG_DFL, we encounter the curious
1383 situation of an interactive ^Z to a running process *working*
1384 and stopping the process, but being unable to do anything with
1385 that process to change its state. On the other hand, if they
1386 are set to SIG_IGN, jobs started from scripts do not stop when
1387 the shell running the script gets a SIGTSTP and stops. */
1389 default_tty_job_signals ();
1392 #if defined (PGRP_PIPE)
1393 /* Release the process group pipe, since our call to setpgid ()
1394 is done. The last call to pipe_close is done in stop_pipeline. */
1395 pipe_close (pgrp_pipe);
1396 #endif /* PGRP_PIPE */
1399 last_asynchronous_pid = getpid ();
1403 /* In the parent. Remember the pid of the child just created
1404 as the proper pgrp if this is the first child. */
1408 if (pipeline_pgrp == 0)
1410 pipeline_pgrp = pid;
1411 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1412 not the good thing of twiddling them in the child! */
1413 /* give_terminal_to (pipeline_pgrp, 0); */
1415 /* This is done on the recommendation of the Rationale section of
1416 the POSIX 1003.1 standard, where it discusses job control and
1417 shells. It is done to avoid possible race conditions. (Ref.
1418 1003.1 Rationale, section B.4.3.3, page 236). */
1419 setpgid (pid, pipeline_pgrp);
1423 if (pipeline_pgrp == 0)
1424 pipeline_pgrp = shell_pgrp;
1427 /* Place all processes into the jobs array regardless of the
1428 state of job_control. */
1429 add_process (command, pid);
1432 last_asynchronous_pid = pid;
1434 last_made_pid = pid;
1436 /* Unblock SIGINT and SIGCHLD. */
1437 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1443 /* These two functions are called only in child processes. */
1445 ignore_tty_job_signals ()
1447 set_signal_handler (SIGTSTP, SIG_IGN);
1448 set_signal_handler (SIGTTIN, SIG_IGN);
1449 set_signal_handler (SIGTTOU, SIG_IGN);
1453 default_tty_job_signals ()
1455 set_signal_handler (SIGTSTP, SIG_DFL);
1456 set_signal_handler (SIGTTIN, SIG_DFL);
1457 set_signal_handler (SIGTTOU, SIG_DFL);
1460 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1461 state kept in here. When a job ends normally, we set the state in here
1462 to the state of the tty. */
1464 static TTYSTRUCT shell_tty_info;
1466 #if defined (NEW_TTY_DRIVER)
1467 static struct tchars shell_tchars;
1468 static struct ltchars shell_ltchars;
1469 #endif /* NEW_TTY_DRIVER */
1471 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1472 /* Since the BSD tty driver does not allow us to change the tty modes
1473 while simultaneously waiting for output to drain and preserving
1474 typeahead, we have to drain the output ourselves before calling
1475 ioctl. We cheat by finding the length of the output queue, and
1476 using select to wait for an appropriate length of time. This is
1477 a hack, and should be labeled as such (it's a hastily-adapted
1478 mutation of a `usleep' implementation). It's only reason for
1479 existing is the flaw in the BSD tty driver. */
1481 static int ttspeeds[] =
1483 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1484 1800, 2400, 4800, 9600, 19200, 38400
1491 register int delay = ttspeeds[ospeed];
1497 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1499 if (n > (delay / 100))
1503 n *= 10; /* 2 bits more for conservativeness. */
1504 tv.tv_sec = n / delay;
1505 tv.tv_usec = ((n % delay) * 1000000) / delay;
1506 select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1512 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1514 /* Return the fd from which we are actually getting input. */
1515 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1517 /* Fill the contents of shell_tty_info with the current tty info. */
1526 #if defined (NEW_TTY_DRIVER)
1527 ioctl (tty, TIOCGETP, &shell_tty_info);
1528 ioctl (tty, TIOCGETC, &shell_tchars);
1529 ioctl (tty, TIOCGLTC, &shell_ltchars);
1530 #endif /* NEW_TTY_DRIVER */
1532 #if defined (TERMIO_TTY_DRIVER)
1533 ioctl (tty, TCGETA, &shell_tty_info);
1534 #endif /* TERMIO_TTY_DRIVER */
1536 #if defined (TERMIOS_TTY_DRIVER)
1537 if (tcgetattr (tty, &shell_tty_info) < 0)
1540 /* Only print an error message if we're really interactive at
1543 sys_error ("[%ld: %d] tcgetattr", (long)getpid (), shell_level);
1547 #endif /* TERMIOS_TTY_DRIVER */
1548 if (check_window_size)
1549 get_new_window_size (0);
1554 /* Make the current tty use the state in shell_tty_info. */
1563 #if defined (NEW_TTY_DRIVER)
1564 # if defined (DRAIN_OUTPUT)
1565 draino (tty, shell_tty_info.sg_ospeed);
1566 # endif /* DRAIN_OUTPUT */
1567 ioctl (tty, TIOCSETN, &shell_tty_info);
1568 ioctl (tty, TIOCSETC, &shell_tchars);
1569 ioctl (tty, TIOCSLTC, &shell_ltchars);
1570 #endif /* NEW_TTY_DRIVER */
1572 #if defined (TERMIO_TTY_DRIVER)
1573 ioctl (tty, TCSETAW, &shell_tty_info);
1574 #endif /* TERMIO_TTY_DRIVER */
1576 #if defined (TERMIOS_TTY_DRIVER)
1577 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1579 /* Only print an error message if we're really interactive at
1582 sys_error ("[%ld: %d] tcsetattr", (long)getpid (), shell_level);
1585 #endif /* TERMIOS_TTY_DRIVER */
1590 /* Given an index into the jobs array JOB, return the pid of the last
1591 process in that job's pipeline. This is the one whose exit status
1592 counts. Must be called with SIGCHLD blocked or queued. */
1594 find_last_pid (job, block)
1598 register PROCESS *p;
1602 BLOCK_CHILD (set, oset);
1604 p = jobs[job]->pipe;
1605 while (p->next != jobs[job]->pipe)
1609 UNBLOCK_CHILD (oset);
1614 /* Wait for a particular child of the shell to finish executing.
1615 This low-level function prints an error message if PID is not
1616 a child of this shell. It returns -1 if it fails, or whatever
1617 wait_for returns otherwise. If the child is not found in the
1618 jobs table, it returns 127. */
1620 wait_for_single_pid (pid)
1623 register PROCESS *child;
1627 BLOCK_CHILD (set, oset);
1628 child = find_pipeline (pid, 0, (int *)NULL);
1629 UNBLOCK_CHILD (oset);
1633 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid);
1639 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
1641 BLOCK_CHILD (set, oset);
1642 job = find_job (pid, 0);
1643 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1644 jobs[job]->flags |= J_NOTIFIED;
1645 UNBLOCK_CHILD (oset);
1650 /* Wait for all of the backgrounds of this shell to finish. */
1652 wait_for_background_pids ()
1654 register int i, r, waited_for;
1658 for (waited_for = 0;;)
1660 BLOCK_CHILD (set, oset);
1662 /* find first running job; if none running in foreground, break */
1663 for (i = 0; i < job_slots; i++)
1664 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1669 UNBLOCK_CHILD (oset);
1673 /* now wait for the last pid in that job. */
1674 pid = find_last_pid (i, 0);
1675 UNBLOCK_CHILD (oset);
1677 errno = 0; /* XXX */
1678 r = wait_for_single_pid (pid);
1681 /* If we're mistaken about job state, compensate. */
1682 if (errno == ECHILD)
1683 mark_all_jobs_as_dead ();
1689 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
1690 `wait' is called with no arguments. */
1691 mark_dead_jobs_as_notified (1);
1692 cleanup_dead_jobs ();
1695 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
1696 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
1697 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
1700 restore_sigint_handler ()
1702 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1704 set_signal_handler (SIGINT, old_sigint_handler);
1705 old_sigint_handler = INVALID_SIGNAL_HANDLER;
1709 static int wait_sigint_received;
1711 /* Handle SIGINT while we are waiting for children in a script to exit.
1712 The `wait' builtin should be interruptible, but all others should be
1713 effectively ignored (i.e. not cause the shell to exit). */
1715 wait_sigint_handler (sig)
1718 SigHandler *sigint_handler;
1720 if (interrupt_immediately ||
1721 (this_shell_builtin && this_shell_builtin == wait_builtin))
1723 last_command_exit_value = EXECUTION_FAILURE;
1724 restore_sigint_handler ();
1725 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
1726 what POSIX.2 says (see builtins/wait.def for more info). */
1727 if (this_shell_builtin && this_shell_builtin == wait_builtin &&
1728 signal_is_trapped (SIGINT) &&
1729 ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
1731 interrupt_immediately = 0;
1732 trap_handler (SIGINT); /* set pending_traps[SIGINT] */
1733 wait_signal_received = SIGINT;
1734 longjmp (wait_intr_buf, 1);
1741 /* XXX - should this be interrupt_state? If it is, the shell will act
1742 as if it got the SIGINT interrupt. */
1743 wait_sigint_received = 1;
1745 /* Otherwise effectively ignore the SIGINT and allow the running job to
1751 process_exit_signal (status)
1754 return (WIFSIGNALED (status) ? WTERMSIG (status) : 0);
1758 process_exit_status (status)
1761 if (WIFSIGNALED (status))
1762 return (128 + WTERMSIG (status));
1763 else if (WIFSTOPPED (status) == 0)
1764 return (WEXITSTATUS (status));
1766 return (EXECUTION_SUCCESS);
1769 /* Return the exit status of the last process in the pipeline for job JOB.
1770 This is the exit status of the entire job. */
1772 raw_job_exit_status (job)
1775 register PROCESS *p;
1781 p = jobs[job]->pipe;
1784 if (p->status != EXECUTION_SUCCESS) fail = p->status;
1787 while (p != jobs[job]->pipe);
1791 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
1796 /* Return the exit status of job JOB. This is the exit status of the last
1797 (rightmost) process in the job's pipeline, modified if the job was killed
1798 by a signal or stopped. */
1800 job_exit_status (job)
1803 return (process_exit_status (raw_job_exit_status (job)));
1807 job_exit_signal (job)
1810 return (process_exit_signal (raw_job_exit_status (job)));
1813 #define FIND_CHILD(pid, child) \
1816 child = find_pipeline (pid, 0, (int *)NULL); \
1819 give_terminal_to (shell_pgrp, 0); \
1820 UNBLOCK_CHILD (oset); \
1821 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
1822 restore_sigint_handler (); \
1823 return (termination_state = 127); \
1828 /* Wait for pid (one of our children) to terminate, then
1829 return the termination state. Returns 127 if PID is not found in
1830 the jobs table. Returns -1 if waitchld() returns -1, indicating
1831 that there are no unwaited-for child processes. */
1836 int job, termination_state, r;
1838 register PROCESS *child;
1840 register PROCESS *p;
1842 /* In the case that this code is interrupted, and we longjmp () out of it,
1843 we are relying on the code in throw_to_top_level () to restore the
1844 top-level signal mask. */
1845 BLOCK_CHILD (set, oset);
1847 /* Ignore interrupts while waiting for a job run without job control
1848 to finish. We don't want the shell to exit if an interrupt is
1849 received, only if one of the jobs run is killed via SIGINT. If
1850 job control is not set, the job will be run in the same pgrp as
1851 the shell, and the shell will see any signals the job gets. */
1853 /* This is possibly a race condition -- should it go in stop_pipeline? */
1854 wait_sigint_received = 0;
1855 if (job_control == 0)
1856 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
1858 termination_state = last_command_exit_value;
1860 if (interactive && job_control == 0)
1863 /* If we say wait_for (), then we have a record of this child somewhere.
1864 If it and none of its peers are running, don't call waitchld(). */
1869 FIND_CHILD (pid, child);
1871 /* If this child is part of a job, then we are really waiting for the
1872 job to finish. Otherwise, we are waiting for the child to finish.
1873 We check for JDEAD in case the job state has been set by waitchld
1874 after receipt of a SIGCHLD. */
1876 job = find_job (pid, 0);
1878 /* waitchld() takes care of setting the state of the job. If the job
1879 has already exited before this is called, sigchld_handler will have
1880 called waitchld and the state will be set to JDEAD. */
1882 if (child->running || (job != NO_JOB && RUNNING (job)))
1884 #if defined (WAITPID_BROKEN) /* SCOv4 */
1885 sigset_t suspend_set;
1886 sigemptyset (&suspend_set);
1887 sigsuspend (&suspend_set);
1888 #else /* !WAITPID_BROKEN */
1889 # if defined (MUST_UNBLOCK_CHLD)
1890 struct sigaction act, oact;
1891 sigset_t nullset, chldset;
1893 sigemptyset (&nullset);
1894 sigemptyset (&chldset);
1895 sigprocmask (SIG_SETMASK, &nullset, &chldset);
1896 act.sa_handler = SIG_DFL;
1897 sigemptyset (&act.sa_mask);
1898 sigemptyset (&oact.sa_mask);
1900 sigaction (SIGCHLD, &act, &oact);
1903 r = waitchld (pid, 1);
1904 # if defined (MUST_UNBLOCK_CHLD)
1905 sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
1906 sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
1909 if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
1911 termination_state = -1;
1912 goto wait_for_return;
1915 /* If child is marked as running, but waitpid() returns -1/ECHILD,
1916 there is something wrong. Somewhere, wait should have returned
1917 that child's pid. Mark the child as not running and the job,
1918 if it exists, as JDEAD. */
1919 if (r == -1 && errno == ECHILD)
1921 child->running = PS_DONE;
1922 child->status = 0; /* XXX -- can't find true status */
1924 jobs[job]->state = JDEAD;
1926 #endif /* WAITPID_BROKEN */
1929 /* If the shell is interactive, and job control is disabled, see
1930 if the foreground process has died due to SIGINT and jump out
1931 of the wait loop if it has. waitchld has already restored the
1932 old SIGINT signal handler. */
1933 if (interactive && job_control == 0)
1936 while (child->running || (job != NO_JOB && RUNNING (job)));
1938 /* The exit state of the command is either the termination state of the
1939 child, or the termination state of the job. If a job, the status
1940 of the last child in the pipeline is the significant one. If the command
1941 or job was terminated by a signal, note that value also. */
1942 termination_state = (job != NO_JOB) ? job_exit_status (job)
1943 : process_exit_status (child->status);
1944 last_command_exit_signal = (job != NO_JOB) ? job_exit_signal (job)
1945 : process_exit_signal (child->status);
1947 if (job == NO_JOB || IS_JOBCONTROL (job))
1949 /* XXX - under what circumstances is a job not present in the jobs
1950 table (job == NO_JOB)?
1951 1. command substitution
1953 In the case of command substitution, at least, it's probably not
1954 the right thing to give the terminal to the shell's process group,
1955 even though there is code in subst.c:command_substitute to work
1959 $PROMPT_COMMAND execution
1960 process substitution
1964 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp);
1967 give_terminal_to (shell_pgrp, 0);
1970 /* If the command did not exit cleanly, or the job is just
1971 being stopped, then reset the tty state back to what it
1972 was before this command. Reset the tty state and notify
1973 the user of the job termination only if the shell is
1974 interactive. Clean up any dead jobs in either case. */
1977 if (interactive_shell && subshell_environment == 0)
1979 /* This used to use `child->status'. That's wrong, however, for
1980 pipelines. `child' is the first process in the pipeline. It's
1981 likely that the process we want to check for abnormal termination
1982 or stopping is the last process in the pipeline, especially if
1983 it's long-lived and the first process is short-lived. Since we
1984 know we have a job here, we can check all the processes in this
1985 job's pipeline and see if one of them stopped or terminated due
1986 to a signal. We might want to change this later to just check
1987 the last process in the pipeline. If no process exits due to a
1988 signal, S is left as the status of the last job in the pipeline. */
1989 p = jobs[job]->pipe;
1993 if (WIFSIGNALED(s) || WIFSTOPPED(s))
1997 while (p != jobs[job]->pipe);
1999 if (WIFSIGNALED (s) || WIFSTOPPED (s))
2003 /* If the current job was stopped or killed by a signal, and
2004 the user has requested it, get a possibly new window size */
2005 if (check_window_size && (job == current_job || IS_FOREGROUND (job)))
2006 get_new_window_size (0);
2011 /* If job control is enabled, the job was started with job
2012 control, the job was the foreground job, and it was killed
2013 by SIGINT, then print a newline to compensate for the kernel
2014 printing the ^C without a trailing newline. */
2015 if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
2016 WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
2018 /* If SIGINT is not trapped and the shell is in a for, while,
2019 or until loop, act as if the shell received SIGINT as
2020 well, so the loop can be broken. This doesn't call the
2021 SIGINT signal handler; maybe it should. */
2022 if (signal_is_trapped (SIGINT) == 0 && loop_level)
2032 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
2033 signal handler path */
2034 if (DEADJOB (job) && IS_FOREGROUND (job) /*&& subshell_environment == 0*/)
2037 /* If this job is dead, notify the user of the status. If the shell
2038 is interactive, this will display a message on the terminal. If
2039 the shell is not interactive, make sure we turn on the notify bit
2040 so we don't get an unwanted message about the job's termination,
2041 and so delete_job really clears the slot in the jobs table. */
2042 notify_and_cleanup ();
2047 UNBLOCK_CHILD (oset);
2049 /* Restore the original SIGINT signal handler before we return. */
2050 restore_sigint_handler ();
2052 return (termination_state);
2055 /* Wait for the last process in the pipeline for JOB. Returns whatever
2056 wait_for returns: the last process's termination state or -1 if there
2057 are no unwaited-for child processes or an error occurs. */
2066 BLOCK_CHILD(set, oset);
2067 if (JOBSTATE (job) == JSTOPPED)
2068 internal_warning (_("wait_for_job: job %d is stopped"), job+1);
2070 pid = find_last_pid (job, 0);
2071 UNBLOCK_CHILD(oset);
2074 /* POSIX.2: we can remove the job from the jobs table if we just waited
2076 BLOCK_CHILD (set, oset);
2077 if (job != NO_JOB && jobs[job] && DEADJOB (job))
2078 jobs[job]->flags |= J_NOTIFIED;
2079 UNBLOCK_CHILD (oset);
2084 /* Print info about dead jobs, and then delete them from the list
2085 of known jobs. This does not actually delete jobs when the
2086 shell is not interactive, because the dead jobs are not marked
2089 notify_and_cleanup ()
2091 if (jobs_list_frozen)
2094 if (interactive || interactive_shell == 0 || sourcelevel)
2095 notify_of_job_status ();
2097 cleanup_dead_jobs ();
2100 /* Make dead jobs disappear from the jobs array without notification.
2101 This is used when the shell is not interactive. */
2105 mark_dead_jobs_as_notified (0);
2106 cleanup_dead_jobs ();
2109 /* Return the next closest (chronologically) job to JOB which is in
2110 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
2111 there is no next recent job. */
2113 most_recent_job_in_state (job, state)
2117 register int i, result;
2120 BLOCK_CHILD (set, oset);
2122 for (result = NO_JOB, i = job - 1; i >= 0; i--)
2124 if (jobs[i] && (JOBSTATE (i) == state))
2131 UNBLOCK_CHILD (oset);
2136 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
2139 job_last_stopped (job)
2142 return (most_recent_job_in_state (job, JSTOPPED));
2145 /* Return the newest *running* job older than JOB, or NO_JOB if not
2148 job_last_running (job)
2151 return (most_recent_job_in_state (job, JRUNNING));
2154 /* Make JOB be the current job, and make previous be useful. Must be
2155 called with SIGCHLD blocked. */
2157 set_current_job (job)
2162 if (current_job != job)
2164 previous_job = current_job;
2168 /* First choice for previous_job is the old current_job. */
2169 if (previous_job != current_job &&
2170 previous_job != NO_JOB &&
2171 jobs[previous_job] &&
2172 STOPPED (previous_job))
2175 /* Second choice: Newest stopped job that is older than
2178 if (STOPPED (current_job))
2180 candidate = job_last_stopped (current_job);
2182 if (candidate != NO_JOB)
2184 previous_job = candidate;
2189 /* If we get here, there is either only one stopped job, in which case it is
2190 the current job and the previous job should be set to the newest running
2191 job, or there are only running jobs and the previous job should be set to
2192 the newest running job older than the current job. We decide on which
2193 alternative to use based on whether or not JOBSTATE(current_job) is
2196 candidate = RUNNING (current_job) ? job_last_running (current_job)
2197 : job_last_running (job_slots);
2199 if (candidate != NO_JOB)
2201 previous_job = candidate;
2205 /* There is only a single job, and it is both `+' and `-'. */
2206 previous_job = current_job;
2209 /* Make current_job be something useful, if it isn't already. */
2211 /* Here's the deal: The newest non-running job should be `+', and the
2212 next-newest non-running job should be `-'. If there is only a single
2213 stopped job, the previous_job is the newest non-running job. If there
2214 are only running jobs, the newest running job is `+' and the
2215 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
2222 if (job_slots && current_job != NO_JOB && jobs[current_job] && STOPPED (current_job))
2223 candidate = current_job;
2228 /* First choice: the previous job. */
2229 if (previous_job != NO_JOB && jobs[previous_job] && STOPPED (previous_job))
2230 candidate = previous_job;
2232 /* Second choice: the most recently stopped job. */
2233 if (candidate == NO_JOB)
2234 candidate = job_last_stopped (job_slots);
2236 /* Third choice: the newest running job. */
2237 if (candidate == NO_JOB)
2238 candidate = job_last_running (job_slots);
2241 /* If we found a job to use, then use it. Otherwise, there
2242 are no jobs period. */
2243 if (candidate != NO_JOB)
2244 set_current_job (candidate);
2246 current_job = previous_job = NO_JOB;
2249 /* Set up the job structures so we know the job and its processes are
2252 set_job_running (job)
2255 register PROCESS *p;
2257 /* Each member of the pipeline is now running. */
2258 p = jobs[job]->pipe;
2262 if (WIFSTOPPED (p->status))
2263 p->running = PS_RUNNING; /* XXX - could be PS_STOPPED */
2266 while (p != jobs[job]->pipe);
2268 /* This means that the job is running. */
2269 JOBSTATE (job) = JRUNNING;
2272 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2273 start the job in the background. JOB is a zero-based index into
2274 JOBS. Returns -1 if it is unable to start a job, and the return
2275 status of the job otherwise. */
2277 start_job (job, foreground)
2278 int job, foreground;
2280 register PROCESS *p;
2281 int already_running;
2284 static TTYSTRUCT save_stty;
2286 BLOCK_CHILD (set, oset);
2290 internal_error (_("%s: job has terminated"), this_command_name);
2291 UNBLOCK_CHILD (oset);
2295 already_running = RUNNING (job);
2297 if (foreground == 0 && already_running)
2299 internal_error (_("%s: job %d already in background"), this_command_name, job + 1);
2300 UNBLOCK_CHILD (oset);
2304 wd = current_working_directory ();
2306 /* You don't know about the state of this job. Do you? */
2307 jobs[job]->flags &= ~J_NOTIFIED;
2311 set_current_job (job);
2312 jobs[job]->flags |= J_FOREGROUND;
2315 /* Tell the outside world what we're doing. */
2316 p = jobs[job]->pipe;
2318 if (foreground == 0)
2319 fprintf (stderr, "[%d]%c ", job + 1,
2320 (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
2324 fprintf (stderr, "%s%s",
2325 p->command ? p->command : "",
2326 p->next != jobs[job]->pipe? " | " : "");
2329 while (p != jobs[job]->pipe);
2331 if (foreground == 0)
2332 fprintf (stderr, " &");
2334 if (strcmp (wd, jobs[job]->wd) != 0)
2335 fprintf (stderr, " (wd: %s)", polite_directory_format (jobs[job]->wd));
2337 fprintf (stderr, "\n");
2340 if (already_running == 0)
2341 set_job_running (job);
2343 /* Save the tty settings before we start the job in the foreground. */
2347 save_stty = shell_tty_info;
2348 /* Give the terminal to this job. */
2349 if (IS_JOBCONTROL (job))
2350 give_terminal_to (jobs[job]->pgrp, 0);
2353 jobs[job]->flags &= ~J_FOREGROUND;
2355 /* If the job is already running, then don't bother jump-starting it. */
2356 if (already_running == 0)
2358 jobs[job]->flags |= J_NOTIFIED;
2359 killpg (jobs[job]->pgrp, SIGCONT);
2367 pid = find_last_pid (job, 0);
2368 UNBLOCK_CHILD (oset);
2370 shell_tty_info = save_stty;
2377 UNBLOCK_CHILD (oset);
2382 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2383 If PID does belong to a job, and the job is stopped, then CONTinue the
2384 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2385 then kill the process group associated with PID. */
2387 kill_pid (pid, sig, group)
2391 register PROCESS *p;
2395 result = EXECUTION_SUCCESS;
2398 BLOCK_CHILD (set, oset);
2399 p = find_pipeline (pid, 0, &job);
2403 jobs[job]->flags &= ~J_NOTIFIED;
2405 /* Kill process in backquotes or one started without job control? */
2406 if (jobs[job]->pgrp == shell_pgrp)
2408 p = jobs[job]->pipe;
2413 if (p->running == PS_DONE && (sig == SIGTERM || sig == SIGHUP))
2414 kill (p->pid, SIGCONT);
2417 while (p != jobs[job]->pipe);
2421 result = killpg (jobs[job]->pgrp, sig);
2422 if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2423 killpg (jobs[job]->pgrp, SIGCONT);
2424 /* If we're continuing a stopped job via kill rather than bg or
2425 fg, emulate the `bg' behavior. */
2426 if (p && STOPPED (job) && (sig == SIGCONT))
2428 set_job_running (job);
2429 jobs[job]->flags &= ~J_FOREGROUND;
2430 jobs[job]->flags |= J_NOTIFIED;
2435 result = killpg (pid, sig);
2437 UNBLOCK_CHILD (oset);
2440 result = kill (pid, sig);
2445 /* sigchld_handler () flushes at least one of the children that we are
2446 waiting for. It gets run when we have gotten a SIGCHLD signal. */
2448 sigchld_handler (sig)
2454 REINSTALL_SIGCHLD_HANDLER;
2457 if (queue_sigchld == 0)
2458 n = waitchld (-1, 0);
2463 /* waitchld() reaps dead or stopped children. It's called by wait_for and
2464 sigchld_handler, and runs until there aren't any children terminating any
2466 If BLOCK is 1, this is to be a blocking wait for a single child, although
2467 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
2468 the number of children reaped, or -1 if there are no unwaited-for child
2471 waitchld (wpid, block)
2478 int call_set_current, last_stopped_job, job, children_exited, waitpid_flags;
2480 call_set_current = children_exited = 0;
2481 last_stopped_job = NO_JOB;
2485 /* We don't want to be notified about jobs stopping if job control
2486 is not active. XXX - was interactive_shell instead of job_control */
2487 waitpid_flags = (job_control && subshell_environment == 0)
2488 ? (WUNTRACED|WCONTINUED)
2490 if (sigchld || block == 0)
2491 waitpid_flags |= WNOHANG;
2492 pid = WAITPID (-1, &status, waitpid_flags);
2494 /* The check for WNOHANG is to make sure we decrement sigchld only
2495 if it was non-zero before we called waitpid. */
2496 if (sigchld > 0 && (waitpid_flags & WNOHANG))
2499 /* If waitpid returns -1 with errno == ECHILD, there are no more
2500 unwaited-for child processes of this shell. */
2501 if (pid < 0 && errno == ECHILD)
2503 if (children_exited == 0)
2509 /* If waitpid returns 0, there are running children. If it returns -1,
2510 the only other error POSIX says it can return is EINTR. */
2512 continue; /* jumps right to the test */
2514 /* children_exited is used to run traps on SIGCHLD. We don't want to
2515 run the trap if a process is just being continued. */
2516 if (WIFCONTINUED(status) == 0)
2519 /* Locate our PROCESS for this pid. */
2520 child = find_pipeline (pid, 1, &job); /* want running procs only */
2522 /* It is not an error to have a child terminate that we did
2523 not have a record of. This child could have been part of
2524 a pipeline in backquote substitution. Even so, I'm not
2525 sure child is ever non-zero. */
2529 while (child->pid != pid)
2530 child = child->next;
2532 /* Remember status, and whether or not the process is running. */
2533 child->status = status;
2534 child->running = WIFCONTINUED(status) ? PS_RUNNING : PS_DONE;
2539 call_set_current += set_job_status_and_cleanup (job);
2542 last_stopped_job = job;
2543 else if (DEADJOB (job) && last_stopped_job == job)
2544 last_stopped_job = NO_JOB;
2546 while ((sigchld || block == 0) && pid > (pid_t)0);
2548 /* If a job was running and became stopped, then set the current
2549 job. Otherwise, don't change a thing. */
2550 if (call_set_current)
2552 if (last_stopped_job != NO_JOB)
2553 set_current_job (last_stopped_job);
2558 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
2559 if (job_control && signal_is_trapped (SIGCHLD) && children_exited &&
2560 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
2561 run_sigchld_trap (children_exited);
2563 /* We have successfully recorded the useful information about this process
2564 that has just changed state. If we notify asynchronously, and the job
2565 that this process belongs to is no longer running, then notify the user
2566 of that fact now. */
2567 if (asynchronous_notification && interactive)
2568 notify_of_job_status ();
2570 return (children_exited);
2573 /* Set the status of JOB and perform any necessary cleanup if the job is
2576 Currently, the cleanup activity is restricted to handling any SIGINT
2577 received while waiting for a foreground job to finish. */
2579 set_job_status_and_cleanup (job)
2583 int tstatus, job_state, any_stopped, any_tstped, call_set_current;
2584 SigHandler *temp_handler;
2586 child = jobs[job]->pipe;
2587 jobs[job]->flags &= ~J_NOTIFIED;
2589 call_set_current = 0;
2592 * COMPUTE JOB STATUS
2595 /* If all children are not running, but any of them is stopped, then
2596 the job is stopped, not dead. */
2597 job_state = any_stopped = any_tstped = 0;
2600 job_state |= child->running;
2601 if (child->running == PS_DONE && (WIFSTOPPED (child->status)))
2604 any_tstped |= interactive && job_control &&
2605 (WSTOPSIG (child->status) == SIGTSTP);
2607 child = child->next;
2609 while (child != jobs[job]->pipe);
2611 /* If job_state != 0, the job is still running, so don't bother with
2612 setting the process exit status and job state unless we're
2613 transitioning from stopped to running. */
2614 if (job_state != 0 && JOBSTATE(job) != JSTOPPED)
2621 /* The job is either stopped or dead. Set the state of the job accordingly. */
2624 jobs[job]->state = JSTOPPED;
2625 jobs[job]->flags &= ~J_FOREGROUND;
2627 /* Suspending a job with SIGTSTP breaks all active loops. */
2628 if (any_tstped && loop_level)
2629 breaking = loop_level;
2631 else if (job_state != 0) /* was stopped, now running */
2633 jobs[job]->state = JRUNNING;
2638 jobs[job]->state = JDEAD;
2641 if (IS_FOREGROUND (job))
2645 /* If this job has a cleanup function associated with it, call it
2646 with `cleanarg' as the single argument, then set the function
2647 pointer to NULL so it is not inadvertently called twice. The
2648 cleanup function is responsible for deallocating cleanarg. */
2649 if (jobs[job]->j_cleanup)
2651 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
2652 jobs[job]->j_cleanup = (sh_vptrfunc_t *)NULL;
2659 * Currently, we just do special things if we got a SIGINT while waiting
2660 * for a foreground job to complete
2663 if (jobs[job]->state == JDEAD)
2665 /* If we're running a shell script and we get a SIGINT with a
2666 SIGINT trap handler, but the foreground job handles it and
2667 does not exit due to SIGINT, run the trap handler but do not
2668 otherwise act as if we got the interrupt. */
2669 if (wait_sigint_received && interactive_shell == 0 &&
2670 WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
2671 signal_is_trapped (SIGINT))
2674 wait_sigint_received = 0;
2675 last_command_exit_value = process_exit_status (child->status);
2677 old_frozen = jobs_list_frozen;
2678 jobs_list_frozen = 1;
2679 tstatus = maybe_call_trap_handler (SIGINT);
2680 jobs_list_frozen = old_frozen;
2683 /* If the foreground job is killed by SIGINT when job control is not
2684 active, we need to perform some special handling.
2686 The check of wait_sigint_received is a way to determine if the
2687 SIGINT came from the keyboard (in which case the shell has already
2688 seen it, and wait_sigint_received is non-zero, because keyboard
2689 signals are sent to process groups) or via kill(2) to the foreground
2690 process by another process (or itself). If the shell did receive the
2691 SIGINT, it needs to perform normal SIGINT processing. */
2692 else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
2693 IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
2697 wait_sigint_received = 0;
2699 /* If SIGINT is trapped, set the exit status so that the trap
2700 handler can see it. */
2701 if (signal_is_trapped (SIGINT))
2702 last_command_exit_value = process_exit_status (child->status);
2704 /* If the signal is trapped, let the trap handler get it no matter
2705 what and simply return if the trap handler returns.
2706 maybe_call_trap_handler() may cause dead jobs to be removed from
2707 the job table because of a call to execute_command. We work
2708 around this by setting JOBS_LIST_FROZEN. */
2709 old_frozen = jobs_list_frozen;
2710 jobs_list_frozen = 1;
2711 tstatus = maybe_call_trap_handler (SIGINT);
2712 jobs_list_frozen = old_frozen;
2713 if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
2715 /* wait_sigint_handler () has already seen SIGINT and
2716 allowed the wait builtin to jump out. We need to
2717 call the original SIGINT handler, if necessary. If
2718 the original handler is SIG_DFL, we need to resend
2719 the signal to ourselves. */
2721 temp_handler = old_sigint_handler;
2723 /* Bogus. If we've reset the signal handler as the result
2724 of a trap caught on SIGINT, then old_sigint_handler
2725 will point to trap_handler, which now knows nothing about
2726 SIGINT (if we reset the sighandler to the default).
2727 In this case, we have to fix things up. What a crock. */
2728 if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
2729 temp_handler = trap_to_sighandler (SIGINT);
2730 restore_sigint_handler ();
2731 if (temp_handler == SIG_DFL)
2732 termination_unwind_protect (SIGINT);
2733 else if (temp_handler != SIG_IGN)
2734 (*temp_handler) (SIGINT);
2739 return call_set_current;
2742 /* Build the array of values for the $PIPESTATUS variable from the set of
2743 exit statuses of all processes in the job J. */
2748 #if defined (ARRAY_VARS)
2750 register PROCESS *p;
2752 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
2757 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
2764 pstatuses[i++] = process_exit_status (p->status);
2767 while (p != jobs[j]->pipe);
2769 pstatuses[i] = -1; /* sentinel */
2770 set_pipestatus_array (pstatuses, i);
2775 run_sigchld_trap (nchild)
2781 /* Turn off the trap list during the call to parse_and_execute ()
2782 to avoid potentially infinite recursive calls. Preserve the
2783 values of last_command_exit_value, last_made_pid, and the_pipeline
2784 around the execution of the trap commands. */
2785 trap_command = savestring (trap_list[SIGCHLD]);
2787 begin_unwind_frame ("SIGCHLD trap");
2788 unwind_protect_int (last_command_exit_value);
2789 unwind_protect_int (last_command_exit_signal);
2790 unwind_protect_var (last_made_pid);
2791 unwind_protect_int (interrupt_immediately);
2792 unwind_protect_int (jobs_list_frozen);
2793 unwind_protect_pointer (the_pipeline);
2794 unwind_protect_pointer (subst_assign_varlist);
2796 /* We have to add the commands this way because they will be run
2797 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
2798 to reference freed memory. */
2799 add_unwind_protect (xfree, trap_command);
2800 add_unwind_protect (maybe_set_sigchld_trap, trap_command);
2802 subst_assign_varlist = (WORD_LIST *)NULL;
2803 the_pipeline = (PROCESS *)NULL;
2805 restore_default_signal (SIGCHLD);
2806 jobs_list_frozen = 1;
2807 for (i = 0; i < nchild; i++)
2809 interrupt_immediately = 1;
2810 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST|SEVAL_RESETLINE);
2813 run_unwind_frame ("SIGCHLD trap");
2816 /* Function to call when you want to notify people of changes
2817 in job status. This prints out all jobs which are pending
2818 notification to stderr, and marks those printed as already
2819 notified, thus making them candidates for cleanup. */
2821 notify_of_job_status ()
2823 register int job, termsig;
2828 if (jobs == 0 || job_slots == 0)
2834 sigaddset (&set, SIGCHLD);
2835 sigaddset (&set, SIGTTOU);
2836 sigemptyset (&oset);
2837 sigprocmask (SIG_BLOCK, &set, &oset);
2842 for (job = 0, dir = (char *)NULL; job < job_slots; job++)
2844 if (jobs[job] && IS_NOTIFIED (job) == 0)
2846 s = raw_job_exit_status (job);
2847 termsig = WTERMSIG (s);
2849 /* POSIX.2 says we have to hang onto the statuses of at most the
2850 last CHILD_MAX background processes if the shell is running a
2851 script. If the shell is not interactive, don't print anything
2852 unless the job was killed by a signal. */
2853 if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
2854 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
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, we were started to run `-c command', so
2861 don't print anything. */
2862 if ((job_control == 0 && interactive_shell) || startup_state == 2)
2864 /* If job control is disabled, don't print the status messages.
2865 Mark dead jobs as notified so that they get cleaned up. If
2866 startup_state == 2 and subshell_environment has the
2867 SUBSHELL_COMSUB bit turned on, we were started to run a command
2868 substitution, so don't print anything. */
2869 if ((job_control == 0 && interactive_shell) ||
2870 (startup_state == 2 && (subshell_environment & SUBSHELL_COMSUB)))
2873 /* POSIX.2 compatibility: if the shell is not interactive,
2874 hang onto the job corresponding to the last asynchronous
2875 pid until the user has been notified of its status or does
2877 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job, 0) != last_asynchronous_pid)))
2878 jobs[job]->flags |= J_NOTIFIED;
2882 /* Print info on jobs that are running in the background,
2883 and on foreground jobs that were killed by anything
2884 except SIGINT (and possibly SIGPIPE). */
2885 switch (JOBSTATE (job))
2888 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
2889 termsig != SIGINT &&
2890 #if defined (DONT_REPORT_SIGPIPE)
2891 termsig != SIGPIPE &&
2893 signal_is_trapped (termsig) == 0)
2895 /* Don't print `0' for a line number. */
2896 fprintf (stderr, "%s: line %d: ", get_name_for_error (), (line_number == 0) ? 1 : line_number);
2897 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
2899 else if (IS_FOREGROUND (job))
2901 #if !defined (DONT_REPORT_SIGPIPE)
2902 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2904 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
2907 fprintf (stderr, "%s", j_strsignal (termsig));
2910 fprintf (stderr, " (core dumped)");
2912 fprintf (stderr, "\n");
2918 dir = current_working_directory ();
2919 pretty_print_job (job, JLIST_STANDARD, stderr);
2920 if (dir && strcmp (dir, jobs[job]->wd) != 0)
2922 "(wd now: %s)\n", polite_directory_format (dir));
2925 jobs[job]->flags |= J_NOTIFIED;
2929 fprintf (stderr, "\n");
2931 dir = current_working_directory ();
2932 pretty_print_job (job, JLIST_STANDARD, stderr);
2933 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2935 "(wd now: %s)\n", polite_directory_format (dir));
2936 jobs[job]->flags |= J_NOTIFIED;
2944 programming_error ("notify_of_job_status");
2949 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2954 /* Initialize the job control mechanism, and set up the tty stuff. */
2956 initialize_job_control (force)
2959 shell_pgrp = getpgid (0);
2961 if (shell_pgrp == -1)
2963 sys_error ("initialize_job_control: getpgrp failed");
2967 /* We can only have job control if we are interactive. */
2968 if (interactive == 0)
2971 original_pgrp = NO_PID;
2972 shell_tty = fileno (stderr);
2976 /* Get our controlling terminal. If job_control is set, or
2977 interactive is set, then this is an interactive shell no
2978 matter where fd 2 is directed. */
2979 shell_tty = dup (fileno (stderr)); /* fd 2 */
2981 shell_tty = move_to_high_fd (shell_tty, 1, -1);
2983 /* Compensate for a bug in systems that compiled the BSD
2984 rlogind with DEBUG defined, like NeXT and Alliant. */
2985 if (shell_pgrp == 0)
2987 shell_pgrp = getpid ();
2988 setpgid (0, shell_pgrp);
2989 tcsetpgrp (shell_tty, shell_pgrp);
2992 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2994 if (shell_pgrp != terminal_pgrp)
2998 ottin = set_signal_handler(SIGTTIN, SIG_DFL);
3000 set_signal_handler (SIGTTIN, ottin);
3006 /* Make sure that we are using the new line discipline. */
3007 if (set_new_line_discipline (shell_tty) < 0)
3009 sys_error ("initialize_job_control: line discipline");
3014 original_pgrp = shell_pgrp;
3015 shell_pgrp = getpid ();
3017 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
3019 sys_error ("initialize_job_control: setpgid");
3020 shell_pgrp = original_pgrp;
3025 /* If (and only if) we just set our process group to our pid,
3026 thereby becoming a process group leader, and the terminal
3027 is not in the same process group as our (new) process group,
3028 then set the terminal's process group to our (new) process
3029 group. If that fails, set our process group back to what it
3030 was originally (so we can still read from the terminal) and
3031 turn off job control. */
3032 if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
3034 if (give_terminal_to (shell_pgrp, 0) < 0)
3036 setpgid (0, original_pgrp);
3037 shell_pgrp = original_pgrp;
3042 if (job_control == 0)
3043 internal_error (_("no job control in this shell"));
3046 if (shell_tty != fileno (stderr))
3047 SET_CLOSE_ON_EXEC (shell_tty);
3049 set_signal_handler (SIGCHLD, sigchld_handler);
3051 change_flag ('m', job_control ? '-' : '+');
3061 debug_print_pgrps ()
3063 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
3064 (long)original_pgrp, (long)shell_pgrp, (long)terminal_pgrp);
3065 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
3066 shell_tty, (long)tcgetpgrp (shell_tty), (long)getpgid(0));
3070 /* Set the line discipline to the best this system has to offer.
3071 Return -1 if this is not possible. */
3073 set_new_line_discipline (tty)
3076 #if defined (NEW_TTY_DRIVER)
3079 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
3082 if (ldisc != NTTYDISC)
3086 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
3090 #endif /* NEW_TTY_DRIVER */
3092 #if defined (TERMIO_TTY_DRIVER)
3093 # if defined (TERMIO_LDISC) && (NTTYDISC)
3094 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
3097 if (shell_tty_info.c_line != NTTYDISC)
3099 shell_tty_info.c_line = NTTYDISC;
3100 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
3103 # endif /* TERMIO_LDISC && NTTYDISC */
3105 #endif /* TERMIO_TTY_DRIVER */
3107 #if defined (TERMIOS_TTY_DRIVER)
3108 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
3109 if (tcgetattr (tty, &shell_tty_info) < 0)
3112 if (shell_tty_info.c_line != NTTYDISC)
3114 shell_tty_info.c_line = NTTYDISC;
3115 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
3118 # endif /* TERMIOS_LDISC && NTTYDISC */
3120 #endif /* TERMIOS_TTY_DRIVER */
3122 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
3127 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3129 get_new_window_size (from_sig)
3134 if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
3135 win.ws_row > 0 && win.ws_col > 0)
3138 shell_tty_info.c_winsize = win; /* structure copying */
3140 sh_set_lines_and_columns (win.ws_row, win.ws_col);
3141 #if defined (READLINE)
3142 rl_set_screen_size (win.ws_row, win.ws_col);
3148 sigwinch_sighandler (sig)
3151 #if defined (MUST_REINSTALL_SIGHANDLERS)
3152 set_signal_handler (SIGWINCH, sigwinch_sighandler);
3153 #endif /* MUST_REINSTALL_SIGHANDLERS */
3154 get_new_window_size (1);
3159 get_new_window_size (from_sig)
3163 #endif /* TIOCGWINSZ && SIGWINCH */
3166 set_sigwinch_handler ()
3168 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3169 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
3174 unset_sigwinch_handler ()
3176 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3177 set_signal_handler (SIGWINCH, old_winch);
3181 /* Setup this shell to handle C-C, etc. */
3183 initialize_job_signals ()
3187 set_signal_handler (SIGINT, sigint_sighandler);
3188 set_signal_handler (SIGTSTP, SIG_IGN);
3189 set_signal_handler (SIGTTOU, SIG_IGN);
3190 set_signal_handler (SIGTTIN, SIG_IGN);
3191 set_sigwinch_handler ();
3193 else if (job_control)
3195 old_tstp = set_signal_handler (SIGTSTP, sigstop_sighandler);
3196 old_ttin = set_signal_handler (SIGTTIN, sigstop_sighandler);
3197 old_ttou = set_signal_handler (SIGTTOU, sigstop_sighandler);
3199 /* Leave these things alone for non-interactive shells without job
3203 /* Here we handle CONT signals. */
3205 sigcont_sighandler (sig)
3208 initialize_job_signals ();
3209 set_signal_handler (SIGCONT, old_cont);
3210 kill (getpid (), SIGCONT);
3215 /* Here we handle stop signals while we are running not as a login shell. */
3217 sigstop_sighandler (sig)
3220 set_signal_handler (SIGTSTP, old_tstp);
3221 set_signal_handler (SIGTTOU, old_ttou);
3222 set_signal_handler (SIGTTIN, old_ttin);
3224 old_cont = set_signal_handler (SIGCONT, sigcont_sighandler);
3226 give_terminal_to (shell_pgrp, 0);
3228 kill (getpid (), sig);
3233 /* Give the terminal to PGRP. */
3235 give_terminal_to (pgrp, force)
3243 if (job_control || force)
3246 sigaddset (&set, SIGTTOU);
3247 sigaddset (&set, SIGTTIN);
3248 sigaddset (&set, SIGTSTP);
3249 sigaddset (&set, SIGCHLD);
3250 sigemptyset (&oset);
3251 sigprocmask (SIG_BLOCK, &set, &oset);
3253 if (tcsetpgrp (shell_tty, pgrp) < 0)
3255 /* Maybe we should print an error message? */
3257 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
3258 shell_tty, (long)getpid(), (long)pgrp);
3263 terminal_pgrp = pgrp;
3264 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
3270 /* Clear out any jobs in the job array. This is intended to be used by
3271 children of the shell, who should not have any job structures as baggage
3272 when they start executing (forking subshells for parenthesized execution
3273 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
3274 is nonzero, only running jobs are removed from the table. */
3276 delete_all_jobs (running_only)
3282 BLOCK_CHILD (set, oset);
3286 current_job = previous_job = NO_JOB;
3288 for (i = 0; i < job_slots; i++)
3289 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3292 if (running_only == 0)
3294 free ((char *)jobs);
3299 UNBLOCK_CHILD (oset);
3302 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
3303 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
3305 nohup_all_jobs (running_only)
3311 BLOCK_CHILD (set, oset);
3315 for (i = 0; i < job_slots; i++)
3316 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3320 UNBLOCK_CHILD (oset);
3329 BLOCK_CHILD (set, oset);
3330 for (i = n = 0; i < job_slots; i++)
3331 if (jobs[i] && DEADJOB(i) == 0)
3333 UNBLOCK_CHILD (oset);
3338 mark_all_jobs_as_dead ()
3346 BLOCK_CHILD (set, oset);
3348 for (i = 0; i < job_slots; i++)
3350 jobs[i]->state = JDEAD;
3352 UNBLOCK_CHILD (oset);
3355 /* Mark all dead jobs as notified, so delete_job () cleans them out
3356 of the job table properly. POSIX.2 says we need to save the
3357 status of the last CHILD_MAX jobs, so we count the number of dead
3358 jobs and mark only enough as notified to save CHILD_MAX statuses. */
3360 mark_dead_jobs_as_notified (force)
3363 register int i, ndead;
3369 BLOCK_CHILD (set, oset);
3371 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
3372 around; just run through the array. */
3375 for (i = 0; i < job_slots; i++)
3377 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
3378 jobs[i]->flags |= J_NOTIFIED;
3380 UNBLOCK_CHILD (oset);
3384 /* Mark enough dead jobs as notified to keep CHILD_MAX jobs left in the
3385 array not marked as notified. */
3387 /* Count the number of dead jobs */
3388 for (i = ndead = 0; i < job_slots; i++)
3390 if (jobs[i] && DEADJOB (i))
3395 child_max = getmaxchild ();
3397 child_max = DEFAULT_CHILD_MAX;
3399 /* Don't do anything if the number of dead jobs is less than CHILD_MAX and
3400 we're not forcing a cleanup. */
3401 if (ndead <= child_max)
3403 UNBLOCK_CHILD (oset);
3407 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
3408 the list. This isn't exactly right yet; changes need to be made
3409 to stop_pipeline so we don't mark the newer jobs after we've
3410 created CHILD_MAX slots in the jobs array. */
3411 for (i = 0; i < job_slots; i++)
3413 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
3415 jobs[i]->flags |= J_NOTIFIED;
3416 if (--ndead <= child_max)
3421 UNBLOCK_CHILD (oset);
3424 /* Here to allow other parts of the shell (like the trap stuff) to
3425 unfreeze the jobs list. */
3427 unfreeze_jobs_list ()
3429 jobs_list_frozen = 0;
3432 /* Allow or disallow job control to take place. Returns the old value
3435 set_job_control (arg)
3443 /* If we're turning on job control, reset pipeline_pgrp so make_child will
3444 put new child processes into the right pgrp */
3445 if (job_control != old && job_control)
3451 /* Turn off all traces of job control. This is run by children of the shell
3452 which are going to do shellsy things, like wait (), etc. */
3454 without_job_control ()
3456 stop_making_children ();
3458 delete_all_jobs (0);
3459 set_job_control (0);
3462 /* If this shell is interactive, terminate all stopped jobs and
3463 restore the original terminal process group. This is done
3464 before the `exec' builtin calls shell_execve. */
3468 if (interactive_shell) /* XXX - should it be interactive? */
3470 terminate_stopped_jobs ();
3472 if (original_pgrp >= 0)
3473 give_terminal_to (original_pgrp, 1);
3476 if (original_pgrp >= 0)
3477 setpgid (0, original_pgrp);
3480 /* Restart job control by closing shell tty and reinitializing. This is
3481 called after an exec fails in an interactive shell and we do not exit. */
3483 restart_job_control ()
3485 if (shell_tty != -1)
3487 initialize_job_control (0);
3490 /* Set the handler to run when the shell receives a SIGCHLD signal. */
3492 set_sigchld_handler ()
3494 set_signal_handler (SIGCHLD, sigchld_handler);
3497 #if defined (PGRP_PIPE)
3498 /* Read from the read end of a pipe. This is how the process group leader
3499 blocks until all of the processes in a pipeline have been made. */
3514 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
3519 /* Close the read and write ends of PP, an array of file descriptors. */
3533 /* Functional interface closes our local-to-job-control pipes. */
3537 pipe_close (pgrp_pipe);
3540 #endif /* PGRP_PIPE */