1 /* The thing that makes children, remembers them, and contains wait loops. */
3 /* This file works with both POSIX and BSD systems. It implements job
6 /* Copyright (C) 1989, 1992 Free Software Foundation, Inc.
8 This file is part of GNU Bash, the Bourne Again SHell.
10 Bash is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 2, or (at your option) any later
15 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 You should have received a copy of the GNU General Public License along
21 with Bash; see the file COPYING. If not, write to the Free Software
22 Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
26 #include "bashtypes.h"
32 #if defined (HAVE_UNISTD_H)
36 #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 */
44 #include <sys/ioctl.h>
45 #include <sys/param.h>
47 #if defined (BUFFERED_INPUT)
51 /* Need to include this up here for *_TTY_DRIVER definitions. */
54 /* Define this if your output is getting swallowed. It's a no-op on
55 machines with the termio or termios tty drivers. */
56 /* #define DRAIN_OUTPUT */
58 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
59 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
61 #endif /* hpux && !TERMIOS_TTY_DRIVER */
63 #if !defined (STRUCT_WINSIZE_IN_SYS_IOCTL)
64 /* For struct winsize on SCO */
65 /* sys/ptem.h has winsize but needs mblk_t from sys/stream.h */
66 # if defined (HAVE_SYS_PTEM_H) && defined (TIOCGWINSZ) && defined (SIGWINCH)
67 # if defined (HAVE_SYS_STREAM_H)
68 # include <sys/stream.h>
70 # include <sys/ptem.h>
71 # endif /* HAVE_SYS_PTEM_H && TIOCGWINSZ && SIGWINCH */
72 #endif /* !STRUCT_WINSIZE_IN_SYS_IOCTL */
79 #include "builtins/builtext.h"
80 #include "builtins/common.h"
86 #if !defined (CHILD_MAX)
90 /* Take care of system dependencies that must be handled when waiting for
91 children. The arguments to the WAITPID macro match those to the Posix.1
92 waitpid() function. */
94 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
95 # define WAITPID(pid, statusp, options) \
96 wait3 ((union wait *)statusp, options, (struct rusage *)0)
98 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
99 # define WAITPID(pid, statusp, options) \
100 waitpid ((pid_t)pid, statusp, options)
102 # if defined (HAVE_WAIT3)
103 # define WAITPID(pid, statusp, options) \
104 wait3 (statusp, options, (struct rusage *)0)
106 # define WAITPID(pid, statusp, options) \
107 wait3 (statusp, options, (int *)0)
108 # endif /* HAVE_WAIT3 */
109 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
110 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
112 /* getpgrp () varies between systems. Even systems that claim to be
113 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
114 #if defined (GETPGRP_VOID)
115 # define getpgid(p) getpgrp ()
117 # define getpgid(p) getpgrp (p)
118 #endif /* !GETPGRP_VOID */
120 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
121 handler for SIGCHLD. */
122 #if defined (MUST_REINSTALL_SIGHANDLERS)
123 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
125 # define REINSTALL_SIGCHLD_HANDLER
126 #endif /* !MUST_REINSTALL_SIGHANDLERS */
128 /* Some systems let waitpid(2) tell callers about stopped children. */
129 #if !defined (WCONTINUED)
130 # define WCONTINUED 0
131 # define WIFCONTINUED(s) (0)
134 /* The number of additional slots to allocate when we run out. */
137 typedef int sh_job_map_func_t __P((JOB *, int, int, int));
139 #if defined (READLINE)
140 extern void rl_set_screen_size __P((int, int));
143 /* Variables used here but defined in other files. */
144 extern int startup_state, subshell_environment, line_number;
145 extern int posixly_correct, shell_level;
146 extern int interrupt_immediately, last_command_exit_value;
147 extern int loop_level, breaking;
148 extern int sourcelevel;
149 extern sh_builtin_func_t *this_shell_builtin;
150 extern char *shell_name, *this_command_name;
151 extern sigset_t top_level_mask;
152 extern procenv_t wait_intr_buf;
153 extern WORD_LIST *subst_assign_varlist;
155 #if defined (ARRAY_VARS)
156 static int *pstatuses; /* list of pipeline statuses */
160 /* The array of known jobs. */
161 JOB **jobs = (JOB **)NULL;
163 /* The number of slots currently allocated to JOBS. */
166 /* The controlling tty for this shell. */
169 /* The shell's process group. */
170 pid_t shell_pgrp = NO_PID;
172 /* The terminal's process group. */
173 pid_t terminal_pgrp = NO_PID;
175 /* The process group of the shell's parent. */
176 pid_t original_pgrp = NO_PID;
178 /* The process group of the pipeline currently being made. */
179 pid_t pipeline_pgrp = (pid_t)0;
181 #if defined (PGRP_PIPE)
182 /* Pipes which each shell uses to communicate with the process group leader
183 until all of the processes in a pipeline have been started. Then the
184 process leader is allowed to continue. */
185 int pgrp_pipe[2] = { -1, -1 };
188 /* The job which is current; i.e. the one that `%+' stands for. */
189 int current_job = NO_JOB;
191 /* The previous job; i.e. the one that `%-' stands for. */
192 int previous_job = NO_JOB;
194 /* Last child made by the shell. */
195 pid_t last_made_pid = NO_PID;
197 /* Pid of the last asynchronous child. */
198 pid_t last_asynchronous_pid = NO_PID;
200 /* The pipeline currently being built. */
201 PROCESS *the_pipeline = (PROCESS *)NULL;
203 /* If this is non-zero, do job control. */
206 /* Call this when you start making children. */
207 int already_making_children = 0;
209 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
210 exits from get_tty_state(). */
211 int check_window_size;
213 /* Functions local to this file. */
215 static void get_new_window_size __P((int));
217 static void run_sigchld_trap __P((int));
219 static sighandler wait_sigint_handler __P((int));
220 static sighandler sigchld_handler __P((int));
221 static sighandler sigwinch_sighandler __P((int));
222 static sighandler sigcont_sighandler __P((int));
223 static sighandler sigstop_sighandler __P((int));
225 static int waitchld __P((pid_t, int));
227 static PROCESS *find_pipeline __P((pid_t));
229 static char *current_working_directory __P((void));
230 static char *job_working_directory __P((void));
231 static char *printable_job_status __P((int, PROCESS *, int));
233 static pid_t find_last_pid __P((int));
234 static pid_t last_pid __P((int));
236 static int set_new_line_discipline __P((int));
237 static int map_over_jobs __P((sh_job_map_func_t *, int, int));
238 static int job_last_stopped __P((int));
239 static int job_last_running __P((int));
240 static int most_recent_job_in_state __P((int, JOB_STATE));
241 static int find_job __P((pid_t));
242 static int print_job __P((JOB *, int, int, int));
243 static int process_exit_status __P((WAIT));
244 static int job_exit_status __P((int));
245 static int set_job_status_and_cleanup __P((int));
247 static WAIT raw_job_exit_status __P((int));
249 static void notify_of_job_status __P((void));
250 static void cleanup_dead_jobs __P((void));
251 static void discard_pipeline __P((PROCESS *));
252 static void add_process __P((char *, pid_t));
253 static void print_pipeline __P((PROCESS *, int, int, FILE *));
254 static void pretty_print_job __P((int, int, FILE *));
255 static void set_current_job __P((int));
256 static void reset_current __P((void));
257 static void set_job_running __P((int));
258 static void setjstatus __P((int));
259 static void mark_all_jobs_as_dead __P((void));
260 static void mark_dead_jobs_as_notified __P((int));
261 static void restore_sigint_handler __P((void));
262 #if defined (PGRP_PIPE)
263 static void pipe_read __P((int *));
264 static void pipe_close __P((int *));
267 /* Used to synchronize between wait_for and the SIGCHLD signal handler. */
269 static int waiting_for_job;
271 /* A place to temporarily save the current pipeline. */
272 static PROCESS *saved_pipeline;
273 static int saved_already_making_children;
275 /* Set this to non-zero whenever you don't want the jobs list to change at
276 all: no jobs deleted and no status change notifications. This is used,
277 for example, when executing SIGCHLD traps, which may run arbitrary
279 static int jobs_list_frozen;
281 static char retcode_name_buffer[64];
283 #if !defined (_POSIX_VERSION)
285 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
286 library functions and system calls. */
287 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
288 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
296 /* ioctl will handle setting errno correctly. */
297 if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
302 #endif /* !_POSIX_VERSION */
304 /* Return the working directory for the current process. Unlike
305 job_working_directory, this does not call malloc (), nor do any
306 of the functions it calls. This is so that it can safely be called
307 from a signal handler. */
309 current_working_directory ()
312 static char d[PATH_MAX];
314 dir = get_string_value ("PWD");
316 if (dir == 0 && the_current_working_directory && no_symbolic_links)
317 dir = the_current_working_directory;
321 dir = getcwd (d, sizeof(d));
326 return (dir == 0) ? "<unknown>" : dir;
329 /* Return the working directory for the current process. */
331 job_working_directory ()
335 dir = get_string_value ("PWD");
337 return (savestring (dir));
339 dir = get_working_directory ("job-working-directory");
343 return (savestring ("<unknown>"));
349 if (already_making_children)
352 already_making_children = 1;
357 stop_making_children ()
359 already_making_children = 0;
363 cleanup_the_pipeline ()
367 discard_pipeline (the_pipeline);
368 the_pipeline = (PROCESS *)NULL;
373 save_pipeline (clear)
376 saved_pipeline = the_pipeline;
377 saved_already_making_children = already_making_children;
379 the_pipeline = (PROCESS *)NULL;
383 restore_pipeline (discard)
386 PROCESS *old_pipeline;
388 old_pipeline = the_pipeline;
389 the_pipeline = saved_pipeline;
390 already_making_children = saved_already_making_children;
392 discard_pipeline (old_pipeline);
395 /* Start building a pipeline. */
401 cleanup_the_pipeline ();
403 #if defined (PGRP_PIPE)
404 pipe_close (pgrp_pipe);
408 #if defined (PGRP_PIPE)
411 if (pipe (pgrp_pipe) == -1)
412 sys_error ("start_pipeline: pgrp pipe");
417 /* Stop building a pipeline. Install the process list in the job array.
418 This returns the index of the newly installed job.
419 DEFERRED is a command structure to be executed upon satisfactory
420 execution exit of this pipeline. */
422 stop_pipeline (async, deferred)
430 BLOCK_CHILD (set, oset);
432 #if defined (PGRP_PIPE)
433 /* The parent closes the process group synchronization pipe. */
434 pipe_close (pgrp_pipe);
437 cleanup_dead_jobs ();
441 job_slots = JOB_SLOTS;
442 jobs = (JOB **)xmalloc (job_slots * sizeof (JOB *));
444 /* Now blank out these new entries. */
445 for (i = 0; i < job_slots; i++)
446 jobs[i] = (JOB *)NULL;
449 /* Scan from the last slot backward, looking for the next free one. */
452 for (i = job_slots; i; i--)
458 /* If we're not interactive, we don't need to monotonically increase
459 the job number (in fact, we don't care about the job number at all),
460 so we can simply scan for the first free slot. This helps to keep
461 us from continuously reallocating the jobs array when running
462 certain kinds of shell loops, and saves time spent searching. */
463 for (i = 0; i < job_slots; i++)
468 /* Do we need more room? */
471 job_slots += JOB_SLOTS;
472 jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
474 for (j = i; j < job_slots; j++)
475 jobs[j] = (JOB *)NULL;
478 /* Add the current pipeline to the job list. */
482 int any_alive, any_stopped;
484 newjob = (JOB *)xmalloc (sizeof (JOB));
486 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
488 p->next = (PROCESS *)NULL;
489 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
490 for (p = newjob->pipe; p->next; p = p->next)
492 p->next = newjob->pipe;
494 the_pipeline = (PROCESS *)NULL;
495 newjob->pgrp = pipeline_pgrp;
500 /* Flag to see if in another pgrp. */
502 newjob->flags |= J_JOBCONTROL;
504 /* Set the state of this pipeline. */
506 any_alive = any_stopped = 0;
509 any_alive |= p->running;
510 any_stopped |= WIFSTOPPED (p->status);
513 while (p != newjob->pipe);
515 newjob->state = any_alive ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
516 newjob->wd = job_working_directory ();
517 newjob->deferred = deferred;
519 newjob->j_cleanup = (sh_vptrfunc_t *)NULL;
520 newjob->cleanarg = (PTR_T) NULL;
523 if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
527 newjob = (JOB *)NULL;
532 newjob->flags &= ~J_FOREGROUND;
539 newjob->flags |= J_FOREGROUND;
541 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
543 * The currently-accepted job control wisdom says to set the
544 * terminal's process group n+1 times in an n-step pipeline:
545 * once in the parent and once in each child. This is where
546 * the parent gives it away.
549 if (job_control && newjob->pgrp)
550 give_terminal_to (newjob->pgrp, 0);
554 stop_making_children ();
555 UNBLOCK_CHILD (oset);
556 return (current_job);
559 /* Delete all DEAD jobs that the user had received notification about. */
566 if (job_slots == 0 || jobs_list_frozen)
569 BLOCK_CHILD (set, oset);
571 for (i = 0; i < job_slots; i++)
572 if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
575 UNBLOCK_CHILD (oset);
578 /* Delete the job at INDEX from the job list. Must be called
579 with SIGCHLD blocked. */
581 delete_job (job_index, warn_stopped)
582 int job_index, warn_stopped;
586 if (job_slots == 0 || jobs_list_frozen)
589 if (warn_stopped && subshell_environment == 0 && STOPPED (job_index))
590 internal_warning ("deleting stopped job %d with process group %ld", job_index+1, (long)jobs[job_index]->pgrp);
592 temp = jobs[job_index];
593 if (job_index == current_job || job_index == previous_job)
596 jobs[job_index] = (JOB *)NULL;
599 discard_pipeline (temp->pipe);
602 dispose_command (temp->deferred);
607 /* Must be called with SIGCHLD blocked. */
609 nohup_job (job_index)
617 if (temp = jobs[job_index])
618 temp->flags |= J_NOHUP;
621 /* Get rid of the data structure associated with a process chain. */
623 discard_pipeline (chain)
624 register PROCESS *chain;
626 register PROCESS *this, *next;
632 FREE (this->command);
636 while (this != chain);
639 /* Add this process to the chain being built in the_pipeline.
640 NAME is the command string that will be exec'ed later.
641 PID is the process id of the child. */
643 add_process (name, pid)
649 t = (PROCESS *)xmalloc (sizeof (PROCESS));
650 t->next = the_pipeline;
652 WSTATUS (t->status) = 0;
662 while (p->next != t->next)
669 /* Take the last job and make it the first job. Must be called with
672 rotate_the_pipeline ()
676 if (the_pipeline->next == the_pipeline)
678 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
683 /* Reverse the order of the processes in the_pipeline. Must be called with
686 reverse_the_pipeline ()
690 if (the_pipeline->next == the_pipeline)
693 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
695 p->next = (PROCESS *)NULL;
697 n = REVERSE_LIST (the_pipeline, PROCESS *);
700 for (p = the_pipeline; p->next; p = p->next)
702 p->next = the_pipeline;
706 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
707 then it is time to stop mapping, and that is the return value
708 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
711 map_over_jobs (func, arg1, arg2)
712 sh_job_map_func_t *func;
722 BLOCK_CHILD (set, oset);
724 for (i = result = 0; i < job_slots; i++)
728 result = (*func)(jobs[i], arg1, arg2, i);
734 UNBLOCK_CHILD (oset);
739 /* Cause all the jobs in the current pipeline to exit. */
741 terminate_current_pipeline ()
743 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
745 killpg (pipeline_pgrp, SIGTERM);
746 killpg (pipeline_pgrp, SIGCONT);
750 /* Cause all stopped jobs to exit. */
752 terminate_stopped_jobs ()
756 for (i = 0; i < job_slots; i++)
758 if (jobs[i] && STOPPED (i))
760 killpg (jobs[i]->pgrp, SIGTERM);
761 killpg (jobs[i]->pgrp, SIGCONT);
766 /* Cause all jobs, running or stopped, to receive a hangup signal. If
767 a job is marked J_NOHUP, don't send the SIGHUP. */
773 for (i = 0; i < job_slots; i++)
777 if ((jobs[i]->flags & J_NOHUP) == 0)
778 killpg (jobs[i]->pgrp, SIGHUP);
780 killpg (jobs[i]->pgrp, SIGCONT);
786 kill_current_pipeline ()
788 stop_making_children ();
792 /* Return the pipeline that PID belongs to. Note that the pipeline
793 doesn't have to belong to a job. Must be called with SIGCHLD blocked. */
801 /* See if this process is in the pipeline that we are building. */
807 /* Return it if we found it. */
813 while (p != the_pipeline);
816 job = find_job (pid);
818 return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
821 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
822 belong to any job. Must be called with SIGCHLD blocked. */
830 for (i = 0; i < job_slots; i++)
843 while (p != jobs[i]->pipe);
850 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
851 required by find_job. */
853 get_job_by_pid (pid, block)
861 BLOCK_CHILD (set, oset);
862 job = find_job (pid);
864 UNBLOCK_CHILD (oset);
869 /* Print descriptive information about the job with leader pid PID. */
877 BLOCK_CHILD (set, oset);
879 job = find_job (pid);
882 printf ("[%d] %ld\n", job + 1, (long)pid);
884 programming_error ("describe_pid: %ld: no such pid", (long)pid);
886 UNBLOCK_CHILD (oset);
890 printable_job_status (j, p, format)
900 if (STOPPED (j) && format == 0)
902 if (posixly_correct == 0 || p == 0 || (WIFSTOPPED (p->status) == 0))
906 temp = retcode_name_buffer;
907 sprintf (temp, "Stopped(%s)", signal_name (WSTOPSIG (p->status)));
910 else if (RUNNING (j))
914 if (WIFSTOPPED (p->status))
915 temp = strsignal (WSTOPSIG (p->status));
916 else if (WIFSIGNALED (p->status))
917 temp = strsignal (WTERMSIG (p->status));
918 else if (WIFEXITED (p->status))
920 temp = retcode_name_buffer;
921 es = WEXITSTATUS (p->status);
923 strcpy (temp, "Done");
924 else if (posixly_correct)
925 sprintf (temp, "Done(%d)", es);
927 sprintf (temp, "Exit %d", es);
930 temp = "Unknown status";
936 /* This is the way to print out information on a job if you
937 know the index. FORMAT is:
939 JLIST_NORMAL) [1]+ Running emacs
940 JLIST_LONG ) [1]+ 2378 Running emacs
943 JLIST_NORMAL) [1]+ Stopped ls | more
944 JLIST_LONG ) [1]+ 2369 Stopped ls
947 Just list the pid of the process group leader (really
950 Use format JLIST_NORMAL, but list only jobs about which
951 the user has not been notified. */
953 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
954 the JOBS array corresponding to this pipeline. FORMAT is as described
955 above. Must be called with SIGCHLD blocked.
957 If you're printing a pipeline that's not in the jobs array, like the
958 current pipeline as it's being created, pass -1 for JOB_INDEX */
960 print_pipeline (p, job_index, format, stream)
962 int job_index, format;
965 PROCESS *first, *last, *show;
966 int es, name_padding;
973 while (last->next != first)
979 fprintf (stream, format ? " " : " |");
981 if (format != JLIST_STANDARD)
982 fprintf (stream, "%5ld", (long)p->pid);
984 fprintf (stream, " ");
986 if (format > -1 && job_index >= 0)
988 show = format ? p : last;
989 temp = printable_job_status (job_index, show, format);
995 if (show->running == first->running &&
996 WSTATUS (show->status) == WSTATUS (first->status))
1000 temp = (char *)NULL;
1005 fprintf (stream, "%s", temp);
1009 es = 2; /* strlen ("| ") */
1010 name_padding = LONGEST_SIGNAL_DESC - es;
1012 fprintf (stream, "%*s", name_padding, "");
1014 if ((WIFSTOPPED (show->status) == 0) &&
1015 (WIFCONTINUED (show->status) == 0) &&
1016 WIFCORED (show->status))
1017 fprintf (stream, "(core dumped) ");
1021 if (p != first && format)
1022 fprintf (stream, "| ");
1025 fprintf (stream, "%s", p->command);
1027 if (p == last && job_index >= 0)
1029 temp = current_working_directory ();
1031 if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
1032 fprintf (stream, " &");
1034 if (strcmp (temp, jobs[job_index]->wd) != 0)
1036 " (wd: %s)", polite_directory_format (jobs[job_index]->wd));
1039 if (format || (p == last))
1041 /* We need to add a CR only if this is an interactive shell, and
1042 we're reporting the status of a completed job asynchronously.
1043 We can't really check whether this particular job is being
1044 reported asynchronously, so just add the CR if the shell is
1045 currently interactive and asynchronous notification is enabled. */
1046 if (asynchronous_notification && interactive)
1047 fprintf (stream, "\r\n");
1049 fprintf (stream, "\n");
1060 pretty_print_job (job_index, format, stream)
1061 int job_index, format;
1064 register PROCESS *p;
1067 BLOCK_CHILD (set, oset);
1069 /* Format only pid information about the process group leader? */
1070 if (format == JLIST_PID_ONLY)
1072 fprintf (stream, "%ld\n", (long)jobs[job_index]->pipe->pid);
1073 UNBLOCK_CHILD (oset);
1077 if (format == JLIST_CHANGED_ONLY)
1079 if (IS_NOTIFIED (job_index))
1081 UNBLOCK_CHILD (oset);
1084 format = JLIST_STANDARD;
1087 if (format != JLIST_NONINTERACTIVE)
1088 fprintf (stream, "[%d]%c ", job_index + 1,
1089 (job_index == current_job) ? '+':
1090 (job_index == previous_job) ? '-' : ' ');
1092 if (format == JLIST_NONINTERACTIVE)
1093 format = JLIST_LONG;
1095 p = jobs[job_index]->pipe;
1097 print_pipeline (p, job_index, format, stream);
1099 /* We have printed information about this job. When the job's
1100 status changes, waitchld () sets the notification flag to 0. */
1101 jobs[job_index]->flags |= J_NOTIFIED;
1103 UNBLOCK_CHILD (oset);
1107 print_job (job, format, state, job_index)
1109 int format, state, job_index;
1111 if (state == -1 || (JOB_STATE)state == job->state)
1112 pretty_print_job (job_index, format, stdout);
1117 list_one_job (job, format, ignore, job_index)
1119 int format, ignore, job_index;
1121 print_job (job, format, -1, job_index);
1125 list_stopped_jobs (format)
1128 cleanup_dead_jobs ();
1129 map_over_jobs (print_job, format, (int)JSTOPPED);
1133 list_running_jobs (format)
1136 cleanup_dead_jobs ();
1137 map_over_jobs (print_job, format, (int)JRUNNING);
1140 /* List jobs. If FORMAT is non-zero, then the long form of the information
1141 is printed, else just a short version. */
1143 list_all_jobs (format)
1146 cleanup_dead_jobs ();
1147 map_over_jobs (print_job, format, -1);
1150 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1151 COMMAND is just for remembering the name of the command; we don't do
1152 anything else with it. ASYNC_P says what to do with the tty. If
1153 non-zero, then don't give it away. */
1155 make_child (command, async_p)
1163 sigaddset (&set, SIGCHLD);
1164 sigaddset (&set, SIGINT);
1165 sigemptyset (&oset);
1166 sigprocmask (SIG_BLOCK, &set, &oset);
1170 #if defined (BUFFERED_INPUT)
1171 /* If default_buffered_input is active, we are reading a script. If
1172 the command is asynchronous, we have already duplicated /dev/null
1173 as fd 0, but have not changed the buffered stream corresponding to
1174 the old fd 0. We don't want to sync the stream in this case. */
1175 if (default_buffered_input != -1 &&
1176 (!async_p || default_buffered_input > 0))
1177 sync_buffered_stream (default_buffered_input);
1178 #endif /* BUFFERED_INPUT */
1180 /* Create the child, handle severe errors. */
1181 if ((pid = fork ()) < 0)
1185 /* Kill all of the processes in the current pipeline. */
1186 terminate_current_pipeline ();
1188 /* Discard the current pipeline, if any. */
1190 kill_current_pipeline ();
1192 throw_to_top_level (); /* Reset signals, etc. */
1197 /* In the child. Give this child the right process group, set the
1198 signals to the default state for a new process. */
1202 #if defined (BUFFERED_INPUT)
1203 /* Close default_buffered_input if it's > 0. We don't close it if it's
1204 0 because that's the file descriptor used when redirecting input,
1205 and it's wrong to close the file in that case. */
1206 unset_bash_input (0);
1207 #endif /* BUFFERED_INPUT */
1209 /* Restore top-level signal mask. */
1210 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1214 /* All processes in this pipeline belong in the same
1217 if (pipeline_pgrp == 0) /* This is the first child. */
1218 pipeline_pgrp = mypid;
1220 /* Check for running command in backquotes. */
1221 if (pipeline_pgrp == shell_pgrp)
1222 ignore_tty_job_signals ();
1224 default_tty_job_signals ();
1226 /* Set the process group before trying to mess with the terminal's
1227 process group. This is mandated by POSIX. */
1228 /* This is in accordance with the Posix 1003.1 standard,
1229 section B.7.2.4, which says that trying to set the terminal
1230 process group with tcsetpgrp() to an unused pgrp value (like
1231 this would have for the first child) is an error. Section
1232 B.4.3.3, p. 237 also covers this, in the context of job control
1234 if (setpgid (mypid, pipeline_pgrp) < 0)
1235 sys_error ("child setpgid (%ld to %ld)", (long)mypid, (long)pipeline_pgrp);
1236 #if defined (PGRP_PIPE)
1237 if (pipeline_pgrp == mypid)
1240 /* By convention (and assumption above), if
1241 pipeline_pgrp == shell_pgrp, we are making a child for
1242 command substitution.
1243 In this case, we don't want to give the terminal to the
1244 shell's process group (we could be in the middle of a
1245 pipeline, for example). */
1246 if (async_p == 0 && pipeline_pgrp != shell_pgrp)
1247 give_terminal_to (pipeline_pgrp, 0);
1249 #if defined (PGRP_PIPE)
1250 pipe_read (pgrp_pipe);
1254 else /* Without job control... */
1256 if (pipeline_pgrp == 0)
1257 pipeline_pgrp = shell_pgrp;
1259 /* If these signals are set to SIG_DFL, we encounter the curious
1260 situation of an interactive ^Z to a running process *working*
1261 and stopping the process, but being unable to do anything with
1262 that process to change its state. On the other hand, if they
1263 are set to SIG_IGN, jobs started from scripts do not stop when
1264 the shell running the script gets a SIGTSTP and stops. */
1266 default_tty_job_signals ();
1269 #if defined (PGRP_PIPE)
1270 /* Release the process group pipe, since our call to setpgid ()
1271 is done. The last call to pipe_close is done in stop_pipeline. */
1272 pipe_close (pgrp_pipe);
1273 #endif /* PGRP_PIPE */
1276 last_asynchronous_pid = getpid ();
1280 /* In the parent. Remember the pid of the child just created
1281 as the proper pgrp if this is the first child. */
1285 if (pipeline_pgrp == 0)
1287 pipeline_pgrp = pid;
1288 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1289 not the good thing of twiddling them in the child! */
1290 /* give_terminal_to (pipeline_pgrp, 0); */
1292 /* This is done on the recommendation of the Rationale section of
1293 the POSIX 1003.1 standard, where it discusses job control and
1294 shells. It is done to avoid possible race conditions. (Ref.
1295 1003.1 Rationale, section B.4.3.3, page 236). */
1296 setpgid (pid, pipeline_pgrp);
1300 if (pipeline_pgrp == 0)
1301 pipeline_pgrp = shell_pgrp;
1304 /* Place all processes into the jobs array regardless of the
1305 state of job_control. */
1306 add_process (command, pid);
1309 last_asynchronous_pid = pid;
1311 last_made_pid = pid;
1313 /* Unblock SIGINT and SIGCHLD. */
1314 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1321 ignore_tty_job_signals ()
1323 set_signal_handler (SIGTSTP, SIG_IGN);
1324 set_signal_handler (SIGTTIN, SIG_IGN);
1325 set_signal_handler (SIGTTOU, SIG_IGN);
1329 default_tty_job_signals ()
1331 set_signal_handler (SIGTSTP, SIG_DFL);
1332 set_signal_handler (SIGTTIN, SIG_DFL);
1333 set_signal_handler (SIGTTOU, SIG_DFL);
1336 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1337 state kept in here. When a job ends normally, we set the state in here
1338 to the state of the tty. */
1340 static TTYSTRUCT shell_tty_info;
1342 #if defined (NEW_TTY_DRIVER)
1343 static struct tchars shell_tchars;
1344 static struct ltchars shell_ltchars;
1345 #endif /* NEW_TTY_DRIVER */
1347 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1348 /* Since the BSD tty driver does not allow us to change the tty modes
1349 while simultaneously waiting for output to drain and preserving
1350 typeahead, we have to drain the output ourselves before calling
1351 ioctl. We cheat by finding the length of the output queue, and
1352 using select to wait for an appropriate length of time. This is
1353 a hack, and should be labeled as such (it's a hastily-adapted
1354 mutation of a `usleep' implementation). It's only reason for
1355 existing is the flaw in the BSD tty driver. */
1357 static int ttspeeds[] =
1359 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1360 1800, 2400, 4800, 9600, 19200, 38400
1367 register int delay = ttspeeds[ospeed];
1373 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1375 if (n > (delay / 100))
1379 n *= 10; /* 2 bits more for conservativeness. */
1380 tv.tv_sec = n / delay;
1381 tv.tv_usec = ((n % delay) * 1000000) / delay;
1382 select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1388 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1390 /* Return the fd from which we are actually getting input. */
1391 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1393 /* Fill the contents of shell_tty_info with the current tty info. */
1402 #if defined (NEW_TTY_DRIVER)
1403 ioctl (tty, TIOCGETP, &shell_tty_info);
1404 ioctl (tty, TIOCGETC, &shell_tchars);
1405 ioctl (tty, TIOCGLTC, &shell_ltchars);
1406 #endif /* NEW_TTY_DRIVER */
1408 #if defined (TERMIO_TTY_DRIVER)
1409 ioctl (tty, TCGETA, &shell_tty_info);
1410 #endif /* TERMIO_TTY_DRIVER */
1412 #if defined (TERMIOS_TTY_DRIVER)
1413 if (tcgetattr (tty, &shell_tty_info) < 0)
1416 /* Only print an error message if we're really interactive at
1419 sys_error ("[%ld: %d] tcgetattr", (long)getpid (), shell_level);
1423 #endif /* TERMIOS_TTY_DRIVER */
1424 if (check_window_size)
1425 get_new_window_size (0);
1430 /* Make the current tty use the state in shell_tty_info. */
1439 #if defined (NEW_TTY_DRIVER)
1440 # if defined (DRAIN_OUTPUT)
1441 draino (tty, shell_tty_info.sg_ospeed);
1442 # endif /* DRAIN_OUTPUT */
1443 ioctl (tty, TIOCSETN, &shell_tty_info);
1444 ioctl (tty, TIOCSETC, &shell_tchars);
1445 ioctl (tty, TIOCSLTC, &shell_ltchars);
1446 #endif /* NEW_TTY_DRIVER */
1448 #if defined (TERMIO_TTY_DRIVER)
1449 ioctl (tty, TCSETAW, &shell_tty_info);
1450 #endif /* TERMIO_TTY_DRIVER */
1452 #if defined (TERMIOS_TTY_DRIVER)
1453 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1455 /* Only print an error message if we're really interactive at
1458 sys_error ("[%ld: %d] tcsetattr", (long)getpid (), shell_level);
1461 #endif /* TERMIOS_TTY_DRIVER */
1466 /* Given an index into the jobs array JOB, return the pid of the last
1467 process in that job's pipeline. This is the one whose exit status
1473 register PROCESS *p;
1475 p = jobs[job]->pipe;
1476 while (p->next != jobs[job]->pipe)
1489 BLOCK_CHILD (set, oset);
1490 pid = find_last_pid (job);
1491 UNBLOCK_CHILD (oset);
1496 /* Wait for a particular child of the shell to finish executing.
1497 This low-level function prints an error message if PID is not
1498 a child of this shell. It returns -1 if it fails, or 0 if not
1499 (whatever wait_for returns). If the child is not found in the
1500 jobs table, it returns 127. */
1502 wait_for_single_pid (pid)
1505 register PROCESS *child;
1509 BLOCK_CHILD (set, oset);
1510 child = find_pipeline (pid);
1511 UNBLOCK_CHILD (oset);
1515 internal_error ("wait: pid %ld is not a child of this shell", (long)pid);
1521 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
1523 BLOCK_CHILD (set, oset);
1524 job = find_job (pid);
1525 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1526 jobs[job]->flags |= J_NOTIFIED;
1527 UNBLOCK_CHILD (oset);
1532 /* Wait for all of the backgrounds of this shell to finish. */
1534 wait_for_background_pids ()
1536 register int i, count, r, waited_for;
1540 for (waited_for = 0;;)
1542 BLOCK_CHILD (set, oset);
1545 for (i = 0; i < job_slots; i++)
1546 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1554 UNBLOCK_CHILD (oset);
1558 for (i = 0; i < job_slots; i++)
1559 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1562 UNBLOCK_CHILD (oset);
1564 errno = 0; /* XXX */
1565 r = wait_for_single_pid (pid);
1568 if (errno == ECHILD)
1569 mark_all_jobs_as_dead ();
1577 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
1578 `wait' is called with no arguments. */
1579 mark_dead_jobs_as_notified (1);
1580 cleanup_dead_jobs ();
1583 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
1584 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
1585 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
1588 restore_sigint_handler ()
1590 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1592 set_signal_handler (SIGINT, old_sigint_handler);
1593 old_sigint_handler = INVALID_SIGNAL_HANDLER;
1597 static int wait_sigint_received;
1599 /* Handle SIGINT while we are waiting for children in a script to exit.
1600 The `wait' builtin should be interruptible, but all others should be
1601 effectively ignored (i.e. not cause the shell to exit). */
1603 wait_sigint_handler (sig)
1606 SigHandler *sigint_handler;
1608 if (interrupt_immediately ||
1609 (this_shell_builtin && this_shell_builtin == wait_builtin))
1611 last_command_exit_value = EXECUTION_FAILURE;
1612 restore_sigint_handler ();
1613 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
1614 what POSIX.2 says (see builtins/wait.def for more info). */
1615 if (this_shell_builtin && this_shell_builtin == wait_builtin &&
1616 signal_is_trapped (SIGINT) &&
1617 ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
1619 interrupt_immediately = 0;
1620 trap_handler (SIGINT); /* set pending_traps[SIGINT] */
1621 longjmp (wait_intr_buf, 1);
1628 /* XXX - should this be interrupt_state? If it is, the shell will act
1629 as if it got the SIGINT interrupt. */
1630 wait_sigint_received = 1;
1632 /* Otherwise effectively ignore the SIGINT and allow the running job to
1638 process_exit_status (status)
1641 if (WIFSIGNALED (status))
1642 return (128 + WTERMSIG (status));
1643 else if (WIFSTOPPED (status) == 0)
1644 return (WEXITSTATUS (status));
1646 return (EXECUTION_SUCCESS);
1649 /* Return the exit status of the last process in the pipeline for job JOB.
1650 This is the exit status of the entire job. */
1652 raw_job_exit_status (job)
1655 register PROCESS *p;
1656 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
1661 /* Return the exit status of job JOB. This is the exit status of the last
1662 (rightmost) process in the job's pipeline, modified if the job was killed
1663 by a signal or stopped. */
1665 job_exit_status (job)
1668 return (process_exit_status (raw_job_exit_status (job)));
1671 #define FIND_CHILD(pid, child) \
1674 child = find_pipeline (pid); \
1677 give_terminal_to (shell_pgrp, 0); \
1678 UNBLOCK_CHILD (oset); \
1679 internal_error ("wait_for: No record of process %ld", (long)pid); \
1680 restore_sigint_handler (); \
1681 return (termination_state = 127); \
1686 /* Wait for pid (one of our children) to terminate, then
1687 return the termination state. Returns 127 if PID is not found in
1688 the jobs table. Returns -1 if waitchld() returns -1, indicating
1689 that there are no unwaited-for child processes. */
1694 int job, termination_state, r;
1696 register PROCESS *child;
1698 register PROCESS *p;
1700 /* In the case that this code is interrupted, and we longjmp () out of it,
1701 we are relying on the code in throw_to_top_level () to restore the
1702 top-level signal mask. */
1703 BLOCK_CHILD (set, oset);
1705 /* Ignore interrupts while waiting for a job run without job control
1706 to finish. We don't want the shell to exit if an interrupt is
1707 received, only if one of the jobs run is killed via SIGINT. If
1708 job control is not set, the job will be run in the same pgrp as
1709 the shell, and the shell will see any signals the job gets. */
1711 /* This is possibly a race condition -- should it go in stop_pipeline? */
1712 wait_sigint_received = 0;
1713 if (job_control == 0)
1714 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
1716 termination_state = last_command_exit_value;
1718 if (interactive && job_control == 0)
1721 /* If we say wait_for (), then we have a record of this child somewhere.
1722 If it and none of its peers are running, don't call waitchld(). */
1727 FIND_CHILD (pid, child);
1729 /* If this child is part of a job, then we are really waiting for the
1730 job to finish. Otherwise, we are waiting for the child to finish.
1731 We check for JDEAD in case the job state has been set by waitchld
1732 after receipt of a SIGCHLD. */
1734 job = find_job (pid);
1736 /* waitchld() takes care of setting the state of the job. If the job
1737 has already exited before this is called, sigchld_handler will have
1738 called waitchld and the state will be set to JDEAD. */
1740 if (child->running || (job != NO_JOB && RUNNING (job)))
1742 #if defined (WAITPID_BROKEN) /* SCOv4 */
1743 sigset_t suspend_set;
1744 sigemptyset (&suspend_set);
1745 sigsuspend (&suspend_set);
1746 #else /* !WAITPID_BROKEN */
1747 # if defined (MUST_UNBLOCK_CHLD)
1748 struct sigaction act, oact;
1749 sigset_t nullset, chldset;
1751 sigemptyset (&nullset);
1752 sigemptyset (&chldset);
1753 sigprocmask (SIG_SETMASK, &nullset, &chldset);
1754 act.sa_handler = SIG_DFL;
1755 sigemptyset (&act.sa_mask);
1756 sigemptyset (&oact.sa_mask);
1758 sigaction (SIGCHLD, &act, &oact);
1760 waiting_for_job = 1;
1761 r = waitchld (pid, 1);
1762 # if defined (MUST_UNBLOCK_CHLD)
1763 sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
1764 sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
1766 waiting_for_job = 0;
1767 if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
1769 termination_state = -1;
1770 goto wait_for_return;
1773 /* If child is marked as running, but waitpid() returns -1/ECHILD,
1774 there is something wrong. Somewhere, wait should have returned
1775 that child's pid. Mark the child as not running and the job,
1776 if it exists, as JDEAD. */
1777 if (r == -1 && errno == ECHILD)
1780 child->status = 0; /* XXX */
1782 jobs[job]->state = JDEAD;
1784 #endif /* WAITPID_BROKEN */
1787 /* If the shell is interactive, and job control is disabled, see
1788 if the foreground process has died due to SIGINT and jump out
1789 of the wait loop if it has. waitchld has already restored the
1790 old SIGINT signal handler. */
1791 if (interactive && job_control == 0)
1794 while (child->running || (job != NO_JOB && RUNNING (job)));
1796 /* The exit state of the command is either the termination state of the
1797 child, or the termination state of the job. If a job, the status
1798 of the last child in the pipeline is the significant one. */
1800 termination_state = job_exit_status (job);
1802 termination_state = process_exit_status (child->status);
1804 if (job == NO_JOB || IS_JOBCONTROL (job))
1806 /* XXX - under what circumstances is a job not present in the jobs
1807 table (job == NO_JOB)?
1808 1. command substitution
1810 In the case of command substitution, at least, it's probably not
1811 the right thing to give the terminal to the shell's process group,
1812 even though there is code in subst.c:command_substitute to work
1816 $PROMPT_COMMAND execution
1817 process substitution
1821 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp);
1824 give_terminal_to (shell_pgrp, 0);
1827 /* If the command did not exit cleanly, or the job is just
1828 being stopped, then reset the tty state back to what it
1829 was before this command. Reset the tty state and notify
1830 the user of the job termination only if the shell is
1831 interactive. Clean up any dead jobs in either case. */
1834 if (interactive_shell && subshell_environment == 0)
1836 /* This used to use `child->status'. That's wrong, however, for
1837 pipelines. `child' is the first process in the pipeline. It's
1838 likely that the process we want to check for abnormal termination
1839 or stopping is the last process in the pipeline, especially if
1840 it's long-lived and the first process is short-lived. Since we
1841 know we have a job here, we can check all the processes in this
1842 job's pipeline and see if one of them stopped or terminated due
1843 to a signal. We might want to change this later to just check
1844 the last process in the pipeline. If no process exits due to a
1845 signal, S is left as the status of the last job in the pipeline. */
1846 p = jobs[job]->pipe;
1850 if (WIFSIGNALED(s) || WIFSTOPPED(s))
1854 while (p != jobs[job]->pipe);
1856 if (WIFSIGNALED (s) || WIFSTOPPED (s))
1860 /* If the current job was stopped or killed by a signal, and
1861 the user has requested it, get a possibly new window size */
1862 if (check_window_size && job == current_job)
1863 get_new_window_size (0);
1868 /* If job control is enabled, the job was started with job
1869 control, the job was the foreground job, and it was killed
1870 by SIGINT, then print a newline to compensate for the kernel
1871 printing the ^C without a trailing newline. */
1872 if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
1873 WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
1875 /* If SIGINT is not trapped and the shell is in a for, while,
1876 or until loop, act as if the shell received SIGINT as
1877 well, so the loop can be broken. This doesn't call the
1878 SIGINT signal handler; maybe it should. */
1879 if (signal_is_trapped (SIGINT) == 0 && loop_level)
1889 /* If this job is dead, notify the user of the status. If the shell
1890 is interactive, this will display a message on the terminal. If
1891 the shell is not interactive, make sure we turn on the notify bit
1892 so we don't get an unwanted message about the job's termination,
1893 and so delete_job really clears the slot in the jobs table. */
1894 notify_and_cleanup ();
1899 UNBLOCK_CHILD (oset);
1901 /* Restore the original SIGINT signal handler before we return. */
1902 restore_sigint_handler ();
1904 return (termination_state);
1907 /* Wait for the last process in the pipeline for JOB. Returns whatever
1908 wait_for returns: the last process's termination state or -1 if there
1909 are no unwaited-for child processes or an error occurs. */
1918 BLOCK_CHILD(set, oset);
1919 if (JOBSTATE (job) == JSTOPPED)
1920 internal_warning ("wait_for_job: job %d is stopped", job+1);
1921 UNBLOCK_CHILD(oset);
1923 pid = last_pid (job);
1926 /* POSIX.2: we can remove the job from the jobs table if we just waited
1928 BLOCK_CHILD (set, oset);
1929 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1930 jobs[job]->flags |= J_NOTIFIED;
1931 UNBLOCK_CHILD (oset);
1936 /* Print info about dead jobs, and then delete them from the list
1937 of known jobs. This does not actually delete jobs when the
1938 shell is not interactive, because the dead jobs are not marked
1941 notify_and_cleanup ()
1943 if (jobs_list_frozen)
1946 if (interactive || interactive_shell == 0 || sourcelevel)
1947 notify_of_job_status ();
1949 cleanup_dead_jobs ();
1952 /* Make dead jobs disappear from the jobs array without notification.
1953 This is used when the shell is not interactive. */
1957 mark_dead_jobs_as_notified (0);
1958 cleanup_dead_jobs ();
1961 /* Return the next closest (chronologically) job to JOB which is in
1962 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
1963 there is no next recent job. */
1965 most_recent_job_in_state (job, state)
1969 register int i, result;
1972 BLOCK_CHILD (set, oset);
1973 for (result = NO_JOB, i = job - 1; i >= 0; i--)
1975 if (jobs[i] && (JOBSTATE (i) == state))
1981 UNBLOCK_CHILD (oset);
1986 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
1989 job_last_stopped (job)
1992 return (most_recent_job_in_state (job, JSTOPPED));
1995 /* Return the newest *running* job older than JOB, or NO_JOB if not
1998 job_last_running (job)
2001 return (most_recent_job_in_state (job, JRUNNING));
2004 /* Make JOB be the current job, and make previous be useful. Must be
2005 called with SIGCHLD blocked. */
2007 set_current_job (job)
2012 if (current_job != job)
2014 previous_job = current_job;
2018 /* First choice for previous_job is the old current_job. */
2019 if (previous_job != current_job &&
2020 previous_job != NO_JOB &&
2021 jobs[previous_job] &&
2022 STOPPED (previous_job))
2025 /* Second choice: Newest stopped job that is older than
2028 if (STOPPED (current_job))
2030 candidate = job_last_stopped (current_job);
2032 if (candidate != NO_JOB)
2034 previous_job = candidate;
2039 /* If we get here, there is either only one stopped job, in which case it is
2040 the current job and the previous job should be set to the newest running
2041 job, or there are only running jobs and the previous job should be set to
2042 the newest running job older than the current job. We decide on which
2043 alternative to use based on whether or not JOBSTATE(current_job) is
2046 candidate = RUNNING (current_job) ? job_last_running (current_job)
2047 : job_last_running (job_slots);
2049 if (candidate != NO_JOB)
2051 previous_job = candidate;
2055 /* There is only a single job, and it is both `+' and `-'. */
2056 previous_job = current_job;
2059 /* Make current_job be something useful, if it isn't already. */
2061 /* Here's the deal: The newest non-running job should be `+', and the
2062 next-newest non-running job should be `-'. If there is only a single
2063 stopped job, the previous_job is the newest non-running job. If there
2064 are only running jobs, the newest running job is `+' and the
2065 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
2072 if (job_slots && current_job != NO_JOB && jobs[current_job] && STOPPED (current_job))
2073 candidate = current_job;
2078 /* First choice: the previous job. */
2079 if (previous_job != NO_JOB && jobs[previous_job] && STOPPED (previous_job))
2080 candidate = previous_job;
2082 /* Second choice: the most recently stopped job. */
2083 if (candidate == NO_JOB)
2084 candidate = job_last_stopped (job_slots);
2086 /* Third choice: the newest running job. */
2087 if (candidate == NO_JOB)
2088 candidate = job_last_running (job_slots);
2091 /* If we found a job to use, then use it. Otherwise, there
2092 are no jobs period. */
2093 if (candidate != NO_JOB)
2094 set_current_job (candidate);
2096 current_job = previous_job = NO_JOB;
2099 /* Set up the job structures so we know the job and its processes are
2102 set_job_running (job)
2105 register PROCESS *p;
2107 /* Each member of the pipeline is now running. */
2108 p = jobs[job]->pipe;
2112 if (WIFSTOPPED (p->status))
2116 while (p != jobs[job]->pipe);
2118 /* This means that the job is running. */
2119 JOBSTATE (job) = JRUNNING;
2122 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2123 start the job in the background. JOB is a zero-based index into
2124 JOBS. Returns -1 if it is unable to start a job, and the return
2125 status of the job otherwise. */
2127 start_job (job, foreground)
2128 int job, foreground;
2130 register PROCESS *p;
2131 int already_running;
2134 static TTYSTRUCT save_stty;
2136 BLOCK_CHILD (set, oset);
2140 internal_error ("%s: job has terminated", this_command_name);
2141 UNBLOCK_CHILD (oset);
2145 already_running = RUNNING (job);
2147 if (foreground == 0 && already_running)
2149 internal_error ("%s: bg background job?", this_command_name);
2150 UNBLOCK_CHILD (oset);
2154 wd = current_working_directory ();
2156 /* You don't know about the state of this job. Do you? */
2157 jobs[job]->flags &= ~J_NOTIFIED;
2161 set_current_job (job);
2162 jobs[job]->flags |= J_FOREGROUND;
2165 /* Tell the outside world what we're doing. */
2166 p = jobs[job]->pipe;
2168 if (foreground == 0)
2169 fprintf (stderr, "[%d]%c ", job + 1,
2170 (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
2174 fprintf (stderr, "%s%s",
2175 p->command ? p->command : "",
2176 p->next != jobs[job]->pipe? " | " : "");
2179 while (p != jobs[job]->pipe);
2181 if (foreground == 0)
2182 fprintf (stderr, " &");
2184 if (strcmp (wd, jobs[job]->wd) != 0)
2185 fprintf (stderr, " (wd: %s)", polite_directory_format (jobs[job]->wd));
2187 fprintf (stderr, "\n");
2190 if (already_running == 0)
2191 set_job_running (job);
2193 /* Save the tty settings before we start the job in the foreground. */
2197 save_stty = shell_tty_info;
2198 /* Give the terminal to this job. */
2199 if (IS_JOBCONTROL (job))
2200 give_terminal_to (jobs[job]->pgrp, 0);
2203 jobs[job]->flags &= ~J_FOREGROUND;
2205 /* If the job is already running, then don't bother jump-starting it. */
2206 if (already_running == 0)
2208 jobs[job]->flags |= J_NOTIFIED;
2209 killpg (jobs[job]->pgrp, SIGCONT);
2212 UNBLOCK_CHILD (oset);
2219 pid = last_pid (job);
2221 shell_tty_info = save_stty;
2227 BLOCK_CHILD (set, oset);
2229 UNBLOCK_CHILD (oset);
2234 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2235 If PID does belong to a job, and the job is stopped, then CONTinue the
2236 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2237 then kill the process group associated with PID. */
2239 kill_pid (pid, sig, group)
2243 register PROCESS *p;
2247 result = EXECUTION_SUCCESS;
2250 BLOCK_CHILD (set, oset);
2251 p = find_pipeline (pid);
2252 job = find_job (pid);
2256 jobs[job]->flags &= ~J_NOTIFIED;
2258 /* Kill process in backquotes or one started without job control? */
2259 if (jobs[job]->pgrp == shell_pgrp)
2261 p = jobs[job]->pipe;
2266 if (p->running == 0 && (sig == SIGTERM || sig == SIGHUP))
2267 kill (p->pid, SIGCONT);
2270 while (p != jobs[job]->pipe);
2274 result = killpg (jobs[job]->pgrp, sig);
2275 if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2276 killpg (jobs[job]->pgrp, SIGCONT);
2277 /* If we're continuing a stopped job via kill rather than bg or
2278 fg, emulate the `bg' behavior. */
2279 if (p && STOPPED (job) && (sig == SIGCONT))
2281 set_job_running (job);
2282 jobs[job]->flags &= ~J_FOREGROUND;
2283 jobs[job]->flags |= J_NOTIFIED;
2288 result = killpg (pid, sig);
2290 UNBLOCK_CHILD (oset);
2293 result = kill (pid, sig);
2298 /* sigchld_handler () flushes at least one of the children that we are
2299 waiting for. It gets run when we have gotten a SIGCHLD signal. */
2301 sigchld_handler (sig)
2307 REINSTALL_SIGCHLD_HANDLER;
2310 if (waiting_for_job == 0)
2311 n = waitchld (-1, 0);
2316 /* waitchld() reaps dead or stopped children. It's called by wait_for and
2317 sigchld_handler, and runs until there aren't any children terminating any
2319 If BLOCK is 1, this is to be a blocking wait for a single child, although
2320 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
2321 the number of children reaped, or -1 if there are no unwaited-for child
2324 waitchld (wpid, block)
2331 int call_set_current, last_stopped_job, job, children_exited, waitpid_flags;
2333 call_set_current = children_exited = 0;
2334 last_stopped_job = NO_JOB;
2338 /* We don't want to be notified about jobs stopping if job control
2339 is not active. XXX - was interactive_shell instead of job_control */
2340 waitpid_flags = (job_control && subshell_environment == 0)
2341 ? (WUNTRACED|WCONTINUED)
2343 if (sigchld || block == 0)
2344 waitpid_flags |= WNOHANG;
2345 pid = WAITPID (-1, &status, waitpid_flags);
2347 /* The check for WNOHANG is to make sure we decrement sigchld only
2348 if it was non-zero before we called waitpid. */
2349 if (sigchld > 0 && (waitpid_flags & WNOHANG))
2352 /* If waitpid returns -1 with errno == ECHILD, there are no more
2353 unwaited-for child processes of this shell. */
2354 if (pid < 0 && errno == ECHILD)
2356 if (children_exited == 0)
2362 /* If waitpid returns 0, there are running children. If it returns -1,
2363 the only other error POSIX says it can return is EINTR. */
2365 continue; /* jumps right to the test */
2367 /* children_exited is used to run traps on SIGCHLD. We don't want to
2368 run the trap if a process is just being continued. */
2369 if (WIFCONTINUED(status) == 0)
2372 /* Locate our PROCESS for this pid. */
2373 child = find_pipeline (pid);
2375 /* It is not an error to have a child terminate that we did
2376 not have a record of. This child could have been part of
2377 a pipeline in backquote substitution. Even so, I'm not
2378 sure child is ever non-zero. */
2382 while (child->pid != pid)
2383 child = child->next;
2385 /* Remember status, and whether or not the process is running. */
2386 child->status = status;
2387 child->running = WIFCONTINUED(status) ? 1 : 0;
2389 job = find_job (pid);
2394 call_set_current += set_job_status_and_cleanup (job);
2397 last_stopped_job = job;
2398 else if (DEADJOB (job) && last_stopped_job == job)
2399 last_stopped_job = NO_JOB;
2401 while ((sigchld || block == 0) && pid > (pid_t)0);
2403 /* If a job was running and became stopped, then set the current
2404 job. Otherwise, don't change a thing. */
2405 if (call_set_current)
2407 if (last_stopped_job != NO_JOB)
2408 set_current_job (last_stopped_job);
2413 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
2414 if (job_control && signal_is_trapped (SIGCHLD) && children_exited &&
2415 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
2416 run_sigchld_trap (children_exited);
2418 /* We have successfully recorded the useful information about this process
2419 that has just changed state. If we notify asynchronously, and the job
2420 that this process belongs to is no longer running, then notify the user
2421 of that fact now. */
2422 if (asynchronous_notification && interactive)
2423 notify_of_job_status ();
2425 return (children_exited);
2428 /* Set the status of JOB and perform any necessary cleanup if the job is
2431 Currently, the cleanup activity is restricted to handling any SIGINT
2432 received while waiting for a foreground job to finish. */
2434 set_job_status_and_cleanup (job)
2438 int tstatus, job_state, any_stopped, any_tstped, call_set_current;
2439 SigHandler *temp_handler;
2441 child = jobs[job]->pipe;
2442 jobs[job]->flags &= ~J_NOTIFIED;
2444 call_set_current = 0;
2447 * COMPUTE JOB STATUS
2450 /* If all children are not running, but any of them is stopped, then
2451 the job is stopped, not dead. */
2452 job_state = any_stopped = any_tstped = 0;
2455 job_state |= child->running;
2456 if (child->running == 0 && (WIFSTOPPED (child->status)))
2459 any_tstped |= interactive && job_control &&
2460 (WSTOPSIG (child->status) == SIGTSTP);
2462 child = child->next;
2464 while (child != jobs[job]->pipe);
2466 /* If job_state != 0, the job is still running, so don't bother with
2467 setting the process exit status and job state unless we're
2468 transitioning from stopped to running. */
2469 if (job_state != 0 && JOBSTATE(job) != JSTOPPED)
2476 /* The job is either stopped or dead. Set the state of the job accordingly. */
2479 jobs[job]->state = JSTOPPED;
2480 jobs[job]->flags &= ~J_FOREGROUND;
2482 /* Suspending a job with SIGTSTP breaks all active loops. */
2483 if (any_tstped && loop_level)
2484 breaking = loop_level;
2486 else if (job_state != 0) /* was stopped, now running */
2488 jobs[job]->state = JRUNNING;
2493 jobs[job]->state = JDEAD;
2495 if (IS_FOREGROUND (job))
2498 /* If this job has a cleanup function associated with it, call it
2499 with `cleanarg' as the single argument, then set the function
2500 pointer to NULL so it is not inadvertently called twice. The
2501 cleanup function is responsible for deallocating cleanarg. */
2502 if (jobs[job]->j_cleanup)
2504 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
2505 jobs[job]->j_cleanup = (sh_vptrfunc_t *)NULL;
2512 * Currently, we just do special things if we got a SIGINT while waiting
2513 * for a foreground job to complete
2516 if (jobs[job]->state == JDEAD)
2518 /* If we're running a shell script and we get a SIGINT with a
2519 SIGINT trap handler, but the foreground job handles it and
2520 does not exit due to SIGINT, run the trap handler but do not
2521 otherwise act as if we got the interrupt. */
2522 if (wait_sigint_received && interactive_shell == 0 &&
2523 WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
2524 signal_is_trapped (SIGINT))
2526 wait_sigint_received = 0;
2527 last_command_exit_value = process_exit_status (child->status);
2529 jobs_list_frozen = 1;
2530 tstatus = maybe_call_trap_handler (SIGINT);
2531 jobs_list_frozen = 0;
2534 /* If the foreground job is killed by SIGINT when job control is not
2535 active, we need to perform some special handling.
2537 The check of wait_sigint_received is a way to determine if the
2538 SIGINT came from the keyboard (in which case the shell has already
2539 seen it, and wait_sigint_received is non-zero, because keyboard
2540 signals are sent to process groups) or via kill(2) to the foreground
2541 process by another process (or itself). If the shell did receive the
2542 SIGINT, it needs to perform normal SIGINT processing. */
2543 else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
2544 IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
2546 wait_sigint_received = 0;
2548 /* If SIGINT is trapped, set the exit status so that the trap
2549 handler can see it. */
2550 if (signal_is_trapped (SIGINT))
2551 last_command_exit_value = process_exit_status (child->status);
2553 /* If the signal is trapped, let the trap handler get it no matter
2554 what and simply return if the trap handler returns.
2555 maybe_call_trap_handler() may cause dead jobs to be removed from
2556 the job table because of a call to execute_command. We work
2557 around this by setting JOBS_LIST_FROZEN. */
2558 jobs_list_frozen = 1;
2559 tstatus = maybe_call_trap_handler (SIGINT);
2560 jobs_list_frozen = 0;
2561 if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
2563 /* wait_sigint_handler () has already seen SIGINT and
2564 allowed the wait builtin to jump out. We need to
2565 call the original SIGINT handler, if necessary. If
2566 the original handler is SIG_DFL, we need to resend
2567 the signal to ourselves. */
2569 temp_handler = old_sigint_handler;
2571 /* Bogus. If we've reset the signal handler as the result
2572 of a trap caught on SIGINT, then old_sigint_handler
2573 will point to trap_handler, which now knows nothing about
2574 SIGINT (if we reset the sighandler to the default).
2575 In this case, we have to fix things up. What a crock. */
2576 if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
2577 temp_handler = trap_to_sighandler (SIGINT);
2578 restore_sigint_handler ();
2579 if (temp_handler == SIG_DFL)
2580 termination_unwind_protect (SIGINT);
2581 else if (temp_handler != SIG_IGN)
2582 (*temp_handler) (SIGINT);
2587 return call_set_current;
2590 /* Build the array of values for the $PIPESTATUS variable from the set of
2591 exit statuses of all processes in the job J. */
2596 #if defined (ARRAY_VARS)
2598 register PROCESS *p;
2600 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
2605 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
2612 pstatuses[i++] = process_exit_status (p->status);
2615 while (p != jobs[j]->pipe);
2617 pstatuses[i] = -1; /* sentinel */
2618 set_pipestatus_array (pstatuses);
2623 run_sigchld_trap (nchild)
2629 /* Turn off the trap list during the call to parse_and_execute ()
2630 to avoid potentially infinite recursive calls. Preserve the
2631 values of last_command_exit_value, last_made_pid, and the_pipeline
2632 around the execution of the trap commands. */
2633 trap_command = savestring (trap_list[SIGCHLD]);
2635 begin_unwind_frame ("SIGCHLD trap");
2636 unwind_protect_int (last_command_exit_value);
2637 unwind_protect_var (last_made_pid);
2638 unwind_protect_int (interrupt_immediately);
2639 unwind_protect_int (jobs_list_frozen);
2640 unwind_protect_pointer (the_pipeline);
2641 unwind_protect_pointer (subst_assign_varlist);
2643 /* We have to add the commands this way because they will be run
2644 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
2645 to reference freed memory. */
2646 add_unwind_protect ((Function *)xfree, trap_command);
2647 add_unwind_protect ((Function *)maybe_set_sigchld_trap, trap_command);
2649 subst_assign_varlist = (WORD_LIST *)NULL;
2650 the_pipeline = (PROCESS *)NULL;
2652 restore_default_signal (SIGCHLD);
2653 jobs_list_frozen = 1;
2654 for (i = 0; i < nchild; i++)
2656 interrupt_immediately = 1;
2657 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST);
2660 run_unwind_frame ("SIGCHLD trap");
2663 /* Function to call when you want to notify people of changes
2664 in job status. This prints out all jobs which are pending
2665 notification to stderr, and marks those printed as already
2666 notified, thus making them candidates for cleanup. */
2668 notify_of_job_status ()
2670 register int job, termsig;
2675 if (jobs == 0 || job_slots == 0)
2679 sigaddset (&set, SIGCHLD);
2680 sigaddset (&set, SIGTTOU);
2681 sigemptyset (&oset);
2682 sigprocmask (SIG_BLOCK, &set, &oset);
2684 for (job = 0, dir = (char *)NULL; job < job_slots; job++)
2686 if (jobs[job] && IS_NOTIFIED (job) == 0)
2688 s = raw_job_exit_status (job);
2689 termsig = WTERMSIG (s);
2691 /* POSIX.2 says we have to hang onto the statuses of at most the
2692 last CHILD_MAX background processes if the shell is running a
2693 script. If the shell is not interactive, don't print anything
2694 unless the job was killed by a signal. */
2695 if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
2696 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
2699 /* If job control is disabled, don't print the status messages.
2700 Mark dead jobs as notified so that they get cleaned up. If
2701 startup_state == 2, we were started to run `-c command', so
2702 don't print anything. */
2703 if ((job_control == 0 && interactive_shell) || startup_state == 2)
2705 /* POSIX.2 compatibility: if the shell is not interactive,
2706 hang onto the job corresponding to the last asynchronous
2707 pid until the user has been notified of its status or does
2709 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job) != last_asynchronous_pid)))
2710 jobs[job]->flags |= J_NOTIFIED;
2714 /* Print info on jobs that are running in the background,
2715 and on foreground jobs that were killed by anything
2716 except SIGINT (and possibly SIGPIPE). */
2717 switch (JOBSTATE (job))
2720 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
2721 termsig != SIGINT &&
2722 #if defined (DONT_REPORT_SIGPIPE)
2723 termsig != SIGPIPE &&
2725 signal_is_trapped (termsig) == 0)
2727 fprintf (stderr, "%s: line %d: ", get_name_for_error (), line_number);
2728 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
2730 else if (IS_FOREGROUND (job))
2732 #if !defined (DONT_REPORT_SIGPIPE)
2733 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2735 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
2738 fprintf (stderr, "%s", strsignal (termsig));
2741 fprintf (stderr, " (core dumped)");
2743 fprintf (stderr, "\n");
2749 dir = current_working_directory ();
2750 pretty_print_job (job, JLIST_STANDARD, stderr);
2751 if (dir && strcmp (dir, jobs[job]->wd) != 0)
2753 "(wd now: %s)\n", polite_directory_format (dir));
2756 jobs[job]->flags |= J_NOTIFIED;
2760 fprintf (stderr, "\n");
2762 dir = current_working_directory ();
2763 pretty_print_job (job, JLIST_STANDARD, stderr);
2764 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2766 "(wd now: %s)\n", polite_directory_format (dir));
2767 jobs[job]->flags |= J_NOTIFIED;
2775 programming_error ("notify_of_job_status");
2779 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2782 /* Initialize the job control mechanism, and set up the tty stuff. */
2784 initialize_job_control (force)
2787 shell_pgrp = getpgid (0);
2789 if (shell_pgrp == -1)
2791 sys_error ("initialize_job_control: getpgrp failed");
2795 /* We can only have job control if we are interactive. */
2796 if (interactive == 0)
2799 original_pgrp = NO_PID;
2800 shell_tty = fileno (stderr);
2804 /* Get our controlling terminal. If job_control is set, or
2805 interactive is set, then this is an interactive shell no
2806 matter where fd 2 is directed. */
2807 shell_tty = dup (fileno (stderr)); /* fd 2 */
2809 shell_tty = move_to_high_fd (shell_tty, 1, -1);
2811 /* Compensate for a bug in systems that compiled the BSD
2812 rlogind with DEBUG defined, like NeXT and Alliant. */
2813 if (shell_pgrp == 0)
2815 shell_pgrp = getpid ();
2816 setpgid (0, shell_pgrp);
2817 tcsetpgrp (shell_tty, shell_pgrp);
2820 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2822 if (shell_pgrp != terminal_pgrp)
2824 SigHandler *old_ttin;
2826 old_ttin = set_signal_handler(SIGTTIN, SIG_DFL);
2828 set_signal_handler (SIGTTIN, old_ttin);
2834 /* Make sure that we are using the new line discipline. */
2835 if (set_new_line_discipline (shell_tty) < 0)
2837 sys_error ("initialize_job_control: line discipline");
2842 original_pgrp = shell_pgrp;
2843 shell_pgrp = getpid ();
2845 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
2847 sys_error ("initialize_job_control: setpgid");
2848 shell_pgrp = original_pgrp;
2853 /* If (and only if) we just set our process group to our pid,
2854 thereby becoming a process group leader, and the terminal
2855 is not in the same process group as our (new) process group,
2856 then set the terminal's process group to our (new) process
2857 group. If that fails, set our process group back to what it
2858 was originally (so we can still read from the terminal) and
2859 turn off job control. */
2860 if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
2862 if (give_terminal_to (shell_pgrp, 0) < 0)
2864 setpgid (0, original_pgrp);
2865 shell_pgrp = original_pgrp;
2870 if (job_control == 0)
2871 internal_error ("no job control in this shell");
2874 if (shell_tty != fileno (stderr))
2875 SET_CLOSE_ON_EXEC (shell_tty);
2877 set_signal_handler (SIGCHLD, sigchld_handler);
2879 change_flag ('m', job_control ? '-' : '+');
2889 debug_print_pgrps ()
2891 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
2892 (long)original_pgrp, (long)shell_pgrp, (long)terminal_pgrp);
2893 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
2894 shell_tty, (long)tcgetpgrp (shell_tty), (long)getpgid(0));
2898 /* Set the line discipline to the best this system has to offer.
2899 Return -1 if this is not possible. */
2901 set_new_line_discipline (tty)
2904 #if defined (NEW_TTY_DRIVER)
2907 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
2910 if (ldisc != NTTYDISC)
2914 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
2918 #endif /* NEW_TTY_DRIVER */
2920 #if defined (TERMIO_TTY_DRIVER)
2921 # if defined (TERMIO_LDISC) && (NTTYDISC)
2922 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
2925 if (shell_tty_info.c_line != NTTYDISC)
2927 shell_tty_info.c_line = NTTYDISC;
2928 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
2931 # endif /* TERMIO_LDISC && NTTYDISC */
2933 #endif /* TERMIO_TTY_DRIVER */
2935 #if defined (TERMIOS_TTY_DRIVER)
2936 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
2937 if (tcgetattr (tty, &shell_tty_info) < 0)
2940 if (shell_tty_info.c_line != NTTYDISC)
2942 shell_tty_info.c_line = NTTYDISC;
2943 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2946 # endif /* TERMIOS_LDISC && NTTYDISC */
2948 #endif /* TERMIOS_TTY_DRIVER */
2950 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
2955 static SigHandler *old_tstp, *old_ttou, *old_ttin;
2956 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
2958 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2959 static SigHandler *old_winch = (SigHandler *)SIG_DFL;
2962 get_new_window_size (from_sig)
2967 if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
2968 win.ws_row > 0 && win.ws_col > 0)
2971 shell_tty_info.c_winsize = win; /* structure copying */
2973 sh_set_lines_and_columns (win.ws_row, win.ws_col);
2974 #if defined (READLINE)
2975 rl_set_screen_size (win.ws_row, win.ws_col);
2981 sigwinch_sighandler (sig)
2984 #if defined (MUST_REINSTALL_SIGHANDLERS)
2985 set_signal_handler (SIGWINCH, sigwinch_sighandler);
2986 #endif /* MUST_REINSTALL_SIGHANDLERS */
2987 get_new_window_size (1);
2992 get_new_window_size (from_sig)
2996 #endif /* TIOCGWINSZ && SIGWINCH */
2999 set_sigwinch_handler ()
3001 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3002 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
3007 unset_sigwinch_handler ()
3009 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
3010 set_signal_handler (SIGWINCH, old_winch);
3014 /* Setup this shell to handle C-C, etc. */
3016 initialize_job_signals ()
3020 set_signal_handler (SIGINT, sigint_sighandler);
3021 set_signal_handler (SIGTSTP, SIG_IGN);
3022 set_signal_handler (SIGTTOU, SIG_IGN);
3023 set_signal_handler (SIGTTIN, SIG_IGN);
3024 set_sigwinch_handler ();
3026 else if (job_control)
3028 old_tstp = set_signal_handler (SIGTSTP, sigstop_sighandler);
3029 old_ttou = set_signal_handler (SIGTTOU, sigstop_sighandler);
3030 old_ttin = set_signal_handler (SIGTTIN, sigstop_sighandler);
3032 /* Leave these things alone for non-interactive shells without job
3036 /* Here we handle CONT signals. */
3038 sigcont_sighandler (sig)
3041 initialize_job_signals ();
3042 set_signal_handler (SIGCONT, old_cont);
3043 kill (getpid (), SIGCONT);
3048 /* Here we handle stop signals while we are running not as a login shell. */
3050 sigstop_sighandler (sig)
3053 set_signal_handler (SIGTSTP, old_tstp);
3054 set_signal_handler (SIGTTOU, old_ttou);
3055 set_signal_handler (SIGTTIN, old_ttin);
3057 old_cont = set_signal_handler (SIGCONT, sigcont_sighandler);
3059 give_terminal_to (shell_pgrp, 0);
3061 kill (getpid (), sig);
3066 /* Give the terminal to PGRP. */
3068 give_terminal_to (pgrp, force)
3076 if (job_control || force)
3079 sigaddset (&set, SIGTTOU);
3080 sigaddset (&set, SIGTTIN);
3081 sigaddset (&set, SIGTSTP);
3082 sigaddset (&set, SIGCHLD);
3083 sigemptyset (&oset);
3084 sigprocmask (SIG_BLOCK, &set, &oset);
3086 if (tcsetpgrp (shell_tty, pgrp) < 0)
3088 /* Maybe we should print an error message? */
3090 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
3091 shell_tty, (long)getpid(), (long)pgrp);
3096 terminal_pgrp = pgrp;
3097 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
3103 /* Clear out any jobs in the job array. This is intended to be used by
3104 children of the shell, who should not have any job structures as baggage
3105 when they start executing (forking subshells for parenthesized execution
3106 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
3107 is nonzero, only running jobs are removed from the table. */
3109 delete_all_jobs (running_only)
3115 BLOCK_CHILD (set, oset);
3119 current_job = previous_job = NO_JOB;
3121 for (i = 0; i < job_slots; i++)
3122 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3125 if (running_only == 0)
3127 free ((char *)jobs);
3132 UNBLOCK_CHILD (oset);
3135 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
3136 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
3138 nohup_all_jobs (running_only)
3144 BLOCK_CHILD (set, oset);
3148 for (i = 0; i < job_slots; i++)
3149 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3153 UNBLOCK_CHILD (oset);
3162 BLOCK_CHILD (set, oset);
3163 for (i = n = 0; i < job_slots; i++)
3164 if (jobs[i] && DEADJOB(i) == 0)
3166 UNBLOCK_CHILD (oset);
3171 mark_all_jobs_as_dead ()
3178 BLOCK_CHILD (set, oset);
3180 for (i = 0; i < job_slots; i++)
3182 jobs[i]->state = JDEAD;
3184 UNBLOCK_CHILD (oset);
3188 /* Mark all dead jobs as notified, so delete_job () cleans them out
3189 of the job table properly. POSIX.2 says we need to save the
3190 status of the last CHILD_MAX jobs, so we count the number of dead
3191 jobs and mark only enough as notified to save CHILD_MAX statuses. */
3193 mark_dead_jobs_as_notified (force)
3196 register int i, ndead;
3201 BLOCK_CHILD (set, oset);
3203 /* Count the number of dead jobs */
3204 for (i = ndead = 0; force == 0 && i < job_slots; i++)
3206 if (jobs[i] && DEADJOB (i))
3210 /* Don't do anything if the number of jobs is less than CHILD_MAX and
3211 we're not forcing a cleanup. */
3212 if (force == 0 && ndead <= CHILD_MAX)
3214 UNBLOCK_CHILD (oset);
3218 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
3219 the list. This isn't exactly right yet; changes need to be made
3220 to stop_pipeline so we don't mark the newer jobs after we've
3221 created CHILD_MAX slots in the jobs array. */
3222 for (i = 0; i < job_slots; i++)
3224 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i) != last_asynchronous_pid)))
3226 jobs[i]->flags |= J_NOTIFIED;
3227 if (force == 0 && --ndead <= CHILD_MAX)
3232 UNBLOCK_CHILD (oset);
3236 /* Here to allow other parts of the shell (like the trap stuff) to
3237 unfreeze the jobs list. */
3239 unfreeze_jobs_list ()
3241 jobs_list_frozen = 0;
3244 /* Allow or disallow job control to take place. Returns the old value
3247 set_job_control (arg)
3257 /* Turn off all traces of job control. This is run by children of the shell
3258 which are going to do shellsy things, like wait (), etc. */
3260 without_job_control ()
3262 stop_making_children ();
3264 delete_all_jobs (0);
3265 set_job_control (0);
3268 /* If this shell is interactive, terminate all stopped jobs and
3269 restore the original terminal process group. This is done
3270 before the `exec' builtin calls shell_execve. */
3274 if (interactive_shell) /* XXX - should it be interactive? */
3276 terminate_stopped_jobs ();
3278 if (original_pgrp >= 0)
3279 give_terminal_to (original_pgrp, 1);
3282 if (original_pgrp >= 0)
3283 setpgid (0, original_pgrp);
3286 /* Restart job control by closing shell tty and reinitializing. This is
3287 called after an exec fails in an interactive shell and we do not exit. */
3289 restart_job_control ()
3291 if (shell_tty != -1)
3293 initialize_job_control (0);
3296 /* Set the handler to run when the shell receives a SIGCHLD signal. */
3298 set_sigchld_handler ()
3300 set_signal_handler (SIGCHLD, sigchld_handler);
3303 #if defined (PGRP_PIPE)
3304 /* Read from the read end of a pipe. This is how the process group leader
3305 blocks until all of the processes in a pipeline have been made. */
3320 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
3325 /* Close the read and write ends of PP, an array of file descriptors. */
3339 /* Functional interface closes our local-to-job-control pipes. */
3343 pipe_close (pgrp_pipe);
3346 #endif /* PGRP_PIPE */