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 1, 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, 675 Mass Ave, Cambridge, MA 02139, USA. */
26 #include "bashtypes.h"
32 #if defined (HAVE_UNISTD_H)
36 #if defined (HAVE_SYS_TIME_H)
37 # include <sys/time.h>
40 #if defined (HAVE_SYS_RESOURCE_H) && defined (HAVE_WAIT3) && !defined (_POSIX_VERSION) && !defined (RLIMTYPE)
41 # include <sys/resource.h>
42 #endif /* !_POSIX_VERSION && HAVE_SYS_RESOURCE_H && HAVE_WAIT3 && !RLIMTYPE */
46 #include <sys/ioctl.h>
47 #include <sys/param.h>
49 #if defined (BUFFERED_INPUT)
53 /* Need to include this up here for *_TTY_DRIVER definitions. */
56 /* Define this if your output is getting swallowed. It's a no-op on
57 machines with the termio or termios tty drivers. */
58 /* #define DRAIN_OUTPUT */
60 /* The _POSIX_SOURCE define is to avoid multiple symbol definitions
61 between sys/ioctl.h and termios.h. Ditto for the test against SunOS4
62 and the undefining of several symbols. */
63 #if defined (TERMIOS_TTY_DRIVER)
64 # if (defined (SunOS4) || defined (SunOS5)) && !defined (_POSIX_SOURCE)
65 # define _POSIX_SOURCE
73 #else /* !TERMIOS_TTY_DRIVER */
74 # if defined (TERMIO_TTY_DRIVER)
79 #endif /* !TERMIOS_TTY_DRIVER */
81 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
82 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
84 #endif /* hpux && !TERMIOS_TTY_DRIVER */
86 #if !defined (STRUCT_WINSIZE_IN_SYS_IOCTL)
87 /* For struct winsize on SCO */
88 /* sys/ptem.h has winsize but needs mblk_t from sys/stream.h */
89 # if defined (HAVE_SYS_PTEM_H) && defined (TIOCGWINSZ) && defined (SIGWINCH)
90 # if defined (HAVE_SYS_STREAM_H)
91 # include <sys/stream.h>
93 # include <sys/ptem.h>
94 # endif /* HAVE_SYS_PTEM_H && TIOCGWINSZ && SIGWINCH */
95 #endif /* !STRUCT_WINSIZE_IN_SYS_IOCTL */
103 #include "builtins/builtext.h"
104 #include "builtins/common.h"
110 #if !defined (CHILD_MAX)
111 # define CHILD_MAX 32
114 /* Take care of system dependencies that must be handled when waiting for
115 children. The arguments to the WAITPID macro match those to the Posix.1
116 waitpid() function. */
118 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
119 # define WAITPID(pid, statusp, options) \
120 wait3 ((union wait *)statusp, options, (struct rusage *)0)
122 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
123 # define WAITPID(pid, statusp, options) \
124 waitpid ((pid_t)pid, statusp, options)
126 # if defined (HAVE_WAIT3)
127 # define WAITPID(pid, statusp, options) \
128 wait3 (statusp, options, (struct rusage *)0)
130 # define WAITPID(pid, statusp, options) \
131 wait3 (statusp, options, (int *)0)
132 # endif /* HAVE_WAIT3 */
133 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
134 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
136 /* getpgrp () varies between systems. Even systems that claim to be
137 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
138 #if defined (GETPGRP_VOID)
139 # define getpgid(p) getpgrp ()
141 # define getpgid(p) getpgrp (p)
142 #endif /* !GETPGRP_VOID */
144 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
145 handler for SIGCHLD. */
146 #if defined (MUST_REINSTALL_SIGHANDLERS)
147 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
149 # define REINSTALL_SIGCHLD_HANDLER
150 #endif /* !MUST_REINSTALL_SIGHANDLERS */
152 /* The number of additional slots to allocate when we run out. */
155 #if defined (READLINE)
156 extern void _rl_set_screen_size ();
159 /* Variables used here but defined in other files. */
160 extern int interactive, interactive_shell, asynchronous_notification;
161 extern int startup_state, subshell_environment, line_number;
162 extern int posixly_correct, no_symbolic_links, shell_level;
163 extern int interrupt_immediately, last_command_exit_value;
164 extern int loop_level, breaking;
165 extern Function *this_shell_builtin;
166 extern char *shell_name, *this_command_name;
167 extern sigset_t top_level_mask;
169 #if defined (ARRAY_VARS)
170 static int *pstatuses; /* list of pipeline statuses */
173 static void setjstatus ();
174 static void get_new_window_size ();
176 /* The array of known jobs. */
177 JOB **jobs = (JOB **)NULL;
179 /* The number of slots currently allocated to JOBS. */
182 /* The controlling tty for this shell. */
185 /* The shell's process group. */
186 pid_t shell_pgrp = NO_PID;
188 /* The terminal's process group. */
189 pid_t terminal_pgrp = NO_PID;
191 /* The process group of the shell's parent. */
192 pid_t original_pgrp = NO_PID;
194 /* The process group of the pipeline currently being made. */
195 pid_t pipeline_pgrp = (pid_t)0;
197 #if defined (PGRP_PIPE)
198 /* Pipes which each shell uses to communicate with the process group leader
199 until all of the processes in a pipeline have been started. Then the
200 process leader is allowed to continue. */
201 int pgrp_pipe[2] = { -1, -1 };
204 /* The job which is current; i.e. the one that `%+' stands for. */
205 int current_job = NO_JOB;
207 /* The previous job; i.e. the one that `%-' stands for. */
208 int previous_job = NO_JOB;
210 /* Last child made by the shell. */
211 pid_t last_made_pid = NO_PID;
213 /* Pid of the last asynchronous child. */
214 pid_t last_asynchronous_pid = NO_PID;
216 /* The pipeline currently being built. */
217 PROCESS *the_pipeline = (PROCESS *)NULL;
219 /* If this is non-zero, do job control. */
222 /* Call this when you start making children. */
223 int already_making_children = 0;
225 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
226 exits from get_tty_state(). */
227 int check_window_size;
229 /* Functions local to this file. */
230 static sighandler sigchld_handler ();
231 static int waitchld ();
232 static PROCESS *find_pipeline ();
233 static char *current_working_directory ();
234 static char *job_working_directory ();
235 static pid_t find_last_pid (), last_pid ();
236 static int set_new_line_discipline (), map_over_jobs (), last_running_job ();
237 static int most_recent_job_in_state (), last_stopped_job (), find_job ();
238 static void notify_of_job_status (), cleanup_dead_jobs (), discard_pipeline ();
239 static void add_process (), set_current_job (), reset_current ();
240 static void print_pipeline ();
241 static void pretty_print_job ();
242 static void mark_dead_jobs_as_notified ();
243 #if defined (PGRP_PIPE)
244 static void pipe_read (), pipe_close ();
247 /* Used to synchronize between wait_for and the SIGCHLD signal handler. */
249 static int waiting_for_job;
251 /* A place to temporarily save the current pipeline. */
252 static PROCESS *saved_pipeline;
253 static int saved_already_making_children;
255 /* Set this to non-zero whenever you don't want the jobs list to change at
256 all: no jobs deleted and no status change notifications. This is used,
257 for example, when executing SIGCHLD traps, which may run arbitrary
259 static int jobs_list_frozen;
261 #if !defined (_POSIX_VERSION)
263 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
264 library functions and system calls. */
265 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
266 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
274 /* ioctl will handle setting errno correctly. */
275 if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
280 #endif /* !_POSIX_VERSION */
282 /* Return the working directory for the current process. Unlike
283 job_working_directory, this does not call malloc (), nor do any
284 of the functions it calls. This is so that it can safely be called
285 from a signal handler. */
287 current_working_directory ()
290 static char d[PATH_MAX];
292 dir = get_string_value ("PWD");
294 if (dir == 0 && the_current_working_directory && no_symbolic_links)
295 dir = the_current_working_directory;
299 dir = getcwd (d, sizeof(d));
304 return (dir == 0) ? "<unknown>" : dir;
307 /* Return the working directory for the current process. */
309 job_working_directory ()
313 dir = get_string_value ("PWD");
315 return (savestring (dir));
317 dir = get_working_directory ("job-working-directory");
321 return (savestring ("<unknown>"));
327 if (already_making_children)
330 already_making_children = 1;
335 stop_making_children ()
337 already_making_children = 0;
341 cleanup_the_pipeline ()
345 discard_pipeline (the_pipeline);
346 the_pipeline = (PROCESS *)NULL;
351 save_pipeline (clear)
354 saved_pipeline = the_pipeline;
355 saved_already_making_children = already_making_children;
357 the_pipeline = (PROCESS *)NULL;
361 restore_pipeline (discard)
364 PROCESS *old_pipeline;
366 old_pipeline = the_pipeline;
367 the_pipeline = saved_pipeline;
368 already_making_children = saved_already_making_children;
370 discard_pipeline (old_pipeline);
373 /* Start building a pipeline. */
379 cleanup_the_pipeline ();
381 #if defined (PGRP_PIPE)
382 pipe_close (pgrp_pipe);
386 #if defined (PGRP_PIPE)
389 if (pipe (pgrp_pipe) == -1)
390 sys_error ("start_pipeline: pgrp pipe");
395 /* Stop building a pipeline. Install the process list in the job array.
396 This returns the index of the newly installed job.
397 DEFERRED is a command structure to be executed upon satisfactory
398 execution exit of this pipeline. */
400 stop_pipeline (async, deferred)
408 BLOCK_CHILD (set, oset);
410 #if defined (PGRP_PIPE)
411 /* The parent closes the process group synchronization pipe. */
412 pipe_close (pgrp_pipe);
415 cleanup_dead_jobs ();
419 job_slots = JOB_SLOTS;
420 jobs = (JOB **)xmalloc (job_slots * sizeof (JOB *));
422 /* Now blank out these new entries. */
423 for (i = 0; i < job_slots; i++)
424 jobs[i] = (JOB *)NULL;
427 /* Scan from the last slot backward, looking for the next free one. */
430 for (i = job_slots; i; i--)
436 /* If we're not interactive, we don't need to monotonically increase
437 the job number (in fact, we don't care about the job number at all),
438 so we can simply scan for the first free slot. This helps to keep
439 us from continuously reallocating the jobs array when running
440 certain kinds of shell loops, and saves time spent searching. */
441 for (i = 0; i < job_slots; i++)
446 /* Do we need more room? */
449 job_slots += JOB_SLOTS;
450 jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
452 for (j = i; j < job_slots; j++)
453 jobs[j] = (JOB *)NULL;
456 /* Add the current pipeline to the job list. */
460 int any_alive, any_stopped;
462 newjob = (JOB *)xmalloc (sizeof (JOB));
464 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
466 p->next = (PROCESS *)NULL;
467 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
468 for (p = newjob->pipe; p->next; p = p->next)
470 p->next = newjob->pipe;
472 the_pipeline = (PROCESS *)NULL;
473 newjob->pgrp = pipeline_pgrp;
478 /* Flag to see if in another pgrp. */
480 newjob->flags |= J_JOBCONTROL;
482 /* Set the state of this pipeline. */
484 any_alive = any_stopped = 0;
487 any_alive |= p->running;
488 any_stopped |= WIFSTOPPED (p->status);
491 while (p != newjob->pipe);
493 newjob->state = any_alive ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
494 newjob->wd = job_working_directory ();
495 newjob->deferred = deferred;
497 newjob->j_cleanup = (VFunction *)NULL;
498 newjob->cleanarg = (PTR_T) NULL;
501 if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
505 newjob = (JOB *)NULL;
510 newjob->flags &= ~J_FOREGROUND;
517 newjob->flags |= J_FOREGROUND;
519 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
521 * The currently-accepted job control wisdom says to set the
522 * terminal's process group n+1 times in an n-step pipeline:
523 * once in the parent and once in each child. This is where
524 * the parent gives it away.
527 if (job_control && newjob->pgrp)
528 give_terminal_to (newjob->pgrp);
532 stop_making_children ();
533 UNBLOCK_CHILD (oset);
534 return (current_job);
537 /* Delete all DEAD jobs that the user had received notification about. */
544 if (job_slots == 0 || jobs_list_frozen)
547 BLOCK_CHILD (set, oset);
549 for (i = 0; i < job_slots; i++)
550 if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i))
553 UNBLOCK_CHILD (oset);
556 /* Delete the job at INDEX from the job list. Must be called
557 with SIGCHLD blocked. */
559 delete_job (job_index, warn_stopped)
560 int job_index, warn_stopped;
564 if (job_slots == 0 || jobs_list_frozen)
567 if (warn_stopped && subshell_environment == 0 && STOPPED (job_index))
568 internal_warning ("deleting stopped job %d with process group %d", job_index+1, jobs[job_index]->pgrp);
570 temp = jobs[job_index];
571 if (job_index == current_job || job_index == previous_job)
574 jobs[job_index] = (JOB *)NULL;
577 discard_pipeline (temp->pipe);
580 dispose_command (temp->deferred);
585 /* Must be called with SIGCHLD blocked. */
587 nohup_job (job_index)
595 if (temp = jobs[job_index])
596 temp->flags |= J_NOHUP;
599 /* Get rid of the data structure associated with a process chain. */
601 discard_pipeline (chain)
602 register PROCESS *chain;
604 register PROCESS *this, *next;
610 FREE (this->command);
614 while (this != chain);
617 /* Add this process to the chain being built in the_pipeline.
618 NAME is the command string that will be exec'ed later.
619 PID is the process id of the child. */
621 add_process (name, pid)
627 t = (PROCESS *)xmalloc (sizeof (PROCESS));
628 t->next = the_pipeline;
630 WSTATUS (t->status) = 0;
640 while (p->next != t->next)
647 /* Take the last job and make it the first job. Must be called with
650 rotate_the_pipeline ()
654 if (the_pipeline->next == the_pipeline)
656 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
661 /* Reverse the order of the processes in the_pipeline. Must be called with
664 reverse_the_pipeline ()
668 if (the_pipeline->next == the_pipeline)
671 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
673 p->next = (PROCESS *)NULL;
675 n = REVERSE_LIST (the_pipeline, PROCESS *);
678 for (p = the_pipeline; p->next; p = p->next)
680 p->next = the_pipeline;
684 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
685 then it is time to stop mapping, and that is the return value
686 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
689 map_over_jobs (func, arg1, arg2)
697 BLOCK_CHILD (set, oset);
699 for (i = result = 0; i < job_slots; i++)
703 result = (*func)(jobs[i], arg1, arg2, i);
709 UNBLOCK_CHILD (oset);
714 /* Cause all the jobs in the current pipeline to exit. */
716 terminate_current_pipeline ()
718 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
720 killpg (pipeline_pgrp, SIGTERM);
721 killpg (pipeline_pgrp, SIGCONT);
725 /* Cause all stopped jobs to exit. */
727 terminate_stopped_jobs ()
731 for (i = 0; i < job_slots; i++)
733 if (jobs[i] && STOPPED (i))
735 killpg (jobs[i]->pgrp, SIGTERM);
736 killpg (jobs[i]->pgrp, SIGCONT);
741 /* Cause all jobs, running or stopped, to receive a hangup signal. If
742 a job is marked J_NOHUP, don't send the SIGHUP. */
748 for (i = 0; i < job_slots; i++)
752 if ((jobs[i]->flags & J_NOHUP) == 0)
753 killpg (jobs[i]->pgrp, SIGHUP);
755 killpg (jobs[i]->pgrp, SIGCONT);
761 kill_current_pipeline ()
763 stop_making_children ();
767 /* Return the pipeline that PID belongs to. Note that the pipeline
768 doesn't have to belong to a job. Must be called with SIGCHLD blocked. */
776 /* See if this process is in the pipeline that we are building. */
782 /* Return it if we found it. */
788 while (p != the_pipeline);
791 job = find_job (pid);
793 return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
796 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
797 belong to any job. Must be called with SIGCHLD blocked. */
805 for (i = 0; i < job_slots; i++)
818 while (p != jobs[i]->pipe);
825 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
826 required by find_job. */
828 get_job_by_pid (pid, block)
836 BLOCK_CHILD (set, oset);
837 job = find_job (pid);
839 UNBLOCK_CHILD (oset);
844 /* Print descriptive information about the job with leader pid PID. */
852 BLOCK_CHILD (set, oset);
854 job = find_job (pid);
857 printf ("[%d] %d\n", job + 1, (int)pid);
859 programming_error ("describe_pid: %d: no such pid", (int)pid);
861 UNBLOCK_CHILD (oset);
864 /* This is the way to print out information on a job if you
865 know the index. FORMAT is:
867 JLIST_NORMAL) [1]+ Running emacs
868 JLIST_LONG ) [1]+ 2378 Running emacs
871 JLIST_NORMAL) [1]+ Stopped ls | more
872 JLIST_LONG ) [1]+ 2369 Stopped ls
875 Just list the pid of the process group leader (really
878 Use format JLIST_NORMAL, but list only jobs about which
879 the user has not been notified. */
881 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
882 the JOBS array corresponding to this pipeline. FORMAT is as described
883 above. Must be called with SIGCHLD blocked.
885 If you're printing a pipeline that's not in the jobs array, like the
886 current pipeline as it's being created, pass -1 for JOB_INDEX */
888 print_pipeline (p, job_index, format, stream)
890 int job_index, format;
893 PROCESS *first, *last, *show;
894 int es, name_padding;
895 char retcode_name_buffer[20], *temp;
901 while (last->next != first)
907 fprintf (stream, format ? " " : " |");
909 if (format != JLIST_STANDARD)
910 fprintf (stream, "%5d", (int)p->pid);
912 fprintf (stream, " ");
914 if (format > -1 && job_index >= 0)
916 show = format ? p : last;
919 if (STOPPED (job_index) && format == 0)
922 else if (RUNNING (job_index))
926 if (WIFSTOPPED (show->status))
927 temp = (char *)strsignal (WSTOPSIG (show->status));
928 else if (WIFSIGNALED (show->status))
929 temp = (char *)strsignal (WTERMSIG (show->status));
930 else if (WIFEXITED (show->status))
932 temp = retcode_name_buffer;
933 es = WEXITSTATUS (show->status);
936 strcpy (temp, "Done");
937 else if (posixly_correct)
938 sprintf (temp, "Done(%d)", es);
940 sprintf (temp, "Exit %d", es);
943 temp = "Unknown status";
950 if (show->running == first->running &&
951 WSTATUS (show->status) == WSTATUS (first->status))
960 fprintf (stream, "%s", temp);
964 es = 2; /* strlen ("| ") */
965 name_padding = LONGEST_SIGNAL_DESC - es;
967 fprintf (stream, "%*s", name_padding, "");
969 if ((WIFSTOPPED (show->status) == 0) && WIFCORED (show->status))
970 fprintf (stream, "(core dumped) ");
974 if (p != first && format)
975 fprintf (stream, "| ");
978 fprintf (stream, "%s", p->command);
980 if (p == last && job_index >= 0)
982 temp = current_working_directory ();
984 if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
985 fprintf (stream, " &");
987 if (strcmp (temp, jobs[job_index]->wd) != 0)
989 " (wd: %s)", polite_directory_format (jobs[job_index]->wd));
992 if (format || (p == last))
994 /* We need to add a CR only if this is an interactive shell, and
995 we're reporting the status of a completed job asynchronously.
996 We can't really check whether this particular job is being
997 reported asynchronously, so just add the CR if the shell is
998 currently interactive and asynchronous notification is enabled. */
999 if (asynchronous_notification && interactive)
1000 fprintf (stream, "\r\n");
1002 fprintf (stream, "\n");
1013 pretty_print_job (job_index, format, stream)
1014 int job_index, format;
1017 register PROCESS *p;
1020 BLOCK_CHILD (set, oset);
1022 /* Format only pid information about the process group leader? */
1023 if (format == JLIST_PID_ONLY)
1025 fprintf (stream, "%d\n", (int)jobs[job_index]->pipe->pid);
1026 UNBLOCK_CHILD (oset);
1030 if (format == JLIST_CHANGED_ONLY)
1032 if (IS_NOTIFIED (job_index))
1034 UNBLOCK_CHILD (oset);
1037 format = JLIST_STANDARD;
1040 if (format != JLIST_NONINTERACTIVE)
1041 fprintf (stream, "[%d]%c ", job_index + 1,
1042 (job_index == current_job) ? '+':
1043 (job_index == previous_job) ? '-' : ' ');
1045 if (format == JLIST_NONINTERACTIVE)
1046 format = JLIST_LONG;
1048 p = jobs[job_index]->pipe;
1050 print_pipeline (p, job_index, format, stream);
1052 /* We have printed information about this job. When the job's
1053 status changes, waitchld () sets the notification flag to 0. */
1054 jobs[job_index]->flags |= J_NOTIFIED;
1056 UNBLOCK_CHILD (oset);
1060 print_job (job, format, state, job_index)
1062 int format, state, job_index;
1064 if (state == -1 || (JOB_STATE)state == job->state)
1065 pretty_print_job (job_index, format, stdout);
1070 list_one_job (job, format, ignore, job_index)
1072 int format, ignore, job_index;
1074 print_job (job, format, -1, job_index);
1078 list_stopped_jobs (format)
1081 cleanup_dead_jobs ();
1082 map_over_jobs (print_job, format, (int)JSTOPPED);
1086 list_running_jobs (format)
1089 cleanup_dead_jobs ();
1090 map_over_jobs (print_job, format, (int)JRUNNING);
1093 /* List jobs. If FORMAT is non-zero, then the long form of the information
1094 is printed, else just a short version. */
1096 list_all_jobs (format)
1099 cleanup_dead_jobs ();
1100 map_over_jobs (print_job, format, -1);
1103 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1104 COMMAND is just for remembering the name of the command; we don't do
1105 anything else with it. ASYNC_P says what to do with the tty. If
1106 non-zero, then don't give it away. */
1108 make_child (command, async_p)
1116 sigaddset (&set, SIGCHLD);
1117 sigaddset (&set, SIGINT);
1118 sigemptyset (&oset);
1119 sigprocmask (SIG_BLOCK, &set, &oset);
1123 #if defined (BUFFERED_INPUT)
1124 /* If default_buffered_input is active, we are reading a script. If
1125 the command is asynchronous, we have already duplicated /dev/null
1126 as fd 0, but have not changed the buffered stream corresponding to
1127 the old fd 0. We don't want to sync the stream in this case. */
1128 if (default_buffered_input != -1 &&
1129 (!async_p || default_buffered_input > 0))
1130 sync_buffered_stream (default_buffered_input);
1131 #endif /* BUFFERED_INPUT */
1133 /* Create the child, handle severe errors. */
1134 if ((pid = fork ()) < 0)
1138 /* Kill all of the processes in the current pipeline. */
1139 terminate_current_pipeline ();
1141 /* Discard the current pipeline, if any. */
1143 kill_current_pipeline ();
1145 throw_to_top_level (); /* Reset signals, etc. */
1150 /* In the child. Give this child the right process group, set the
1151 signals to the default state for a new process. */
1155 #if defined (BUFFERED_INPUT)
1156 /* Close default_buffered_input if it's > 0. We don't close it if it's
1157 0 because that's the file descriptor used when redirecting input,
1158 and it's wrong to close the file in that case. */
1159 unset_bash_input (0);
1160 #endif /* BUFFERED_INPUT */
1162 /* Restore top-level signal mask. */
1163 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1167 /* All processes in this pipeline belong in the same
1170 if (pipeline_pgrp == 0) /* This is the first child. */
1171 pipeline_pgrp = mypid;
1173 /* Check for running command in backquotes. */
1174 if (pipeline_pgrp == shell_pgrp)
1175 ignore_tty_job_signals ();
1177 default_tty_job_signals ();
1179 /* Set the process group before trying to mess with the terminal's
1180 process group. This is mandated by POSIX. */
1181 /* This is in accordance with the Posix 1003.1 standard,
1182 section B.7.2.4, which says that trying to set the terminal
1183 process group with tcsetpgrp() to an unused pgrp value (like
1184 this would have for the first child) is an error. Section
1185 B.4.3.3, p. 237 also covers this, in the context of job control
1187 if (setpgid (mypid, pipeline_pgrp) < 0)
1188 sys_error ("child setpgid (%d to %d)", mypid, pipeline_pgrp);
1189 #if defined (PGRP_PIPE)
1190 if (pipeline_pgrp == mypid)
1193 /* XXX - By convention (and assumption above), if
1194 pipeline_pgrp == shell_pgrp, we are making a child for
1195 command substitution.
1196 In this case, we don't want to give the terminal to the
1197 shell's process group (we could be in the middle of a
1198 pipeline, for example). */
1199 if (async_p == 0 && pipeline_pgrp != shell_pgrp)
1200 give_terminal_to (pipeline_pgrp);
1202 #if defined (PGRP_PIPE)
1203 pipe_read (pgrp_pipe);
1207 else /* Without job control... */
1209 if (pipeline_pgrp == 0)
1210 pipeline_pgrp = shell_pgrp;
1212 /* If these signals are set to SIG_DFL, we encounter the curious
1213 situation of an interactive ^Z to a running process *working*
1214 and stopping the process, but being unable to do anything with
1215 that process to change its state. On the other hand, if they
1216 are set to SIG_IGN, jobs started from scripts do not stop when
1217 the shell running the script gets a SIGTSTP and stops. */
1219 default_tty_job_signals ();
1222 #if defined (PGRP_PIPE)
1223 /* Release the process group pipe, since our call to setpgid ()
1224 is done. The last call to pipe_close is done in stop_pipeline. */
1225 pipe_close (pgrp_pipe);
1226 #endif /* PGRP_PIPE */
1229 last_asynchronous_pid = getpid ();
1233 /* In the parent. Remember the pid of the child just created
1234 as the proper pgrp if this is the first child. */
1238 if (pipeline_pgrp == 0)
1240 pipeline_pgrp = pid;
1241 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1242 not the good thing of twiddling them in the child! */
1243 /* give_terminal_to (pipeline_pgrp); */
1245 /* This is done on the recommendation of the Rationale section of
1246 the POSIX 1003.1 standard, where it discusses job control and
1247 shells. It is done to avoid possible race conditions. (Ref.
1248 1003.1 Rationale, section B.4.3.3, page 236). */
1249 setpgid (pid, pipeline_pgrp);
1253 if (pipeline_pgrp == 0)
1254 pipeline_pgrp = shell_pgrp;
1257 /* Place all processes into the jobs array regardless of the
1258 state of job_control. */
1259 add_process (command, pid);
1262 last_asynchronous_pid = pid;
1264 last_made_pid = pid;
1266 /* Unblock SIGINT and SIGCHLD. */
1267 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1274 ignore_tty_job_signals ()
1276 set_signal_handler (SIGTSTP, SIG_IGN);
1277 set_signal_handler (SIGTTIN, SIG_IGN);
1278 set_signal_handler (SIGTTOU, SIG_IGN);
1282 default_tty_job_signals ()
1284 set_signal_handler (SIGTSTP, SIG_DFL);
1285 set_signal_handler (SIGTTIN, SIG_DFL);
1286 set_signal_handler (SIGTTOU, SIG_DFL);
1289 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1290 state kept in here. When a job ends normally, we set the state in here
1291 to the state of the tty. */
1293 #if defined (NEW_TTY_DRIVER)
1294 static struct sgttyb shell_tty_info;
1295 static struct tchars shell_tchars;
1296 static struct ltchars shell_ltchars;
1297 #endif /* NEW_TTY_DRIVER */
1299 #if defined (TERMIO_TTY_DRIVER)
1300 static struct termio shell_tty_info;
1301 #endif /* TERMIO_TTY_DRIVER */
1303 #if defined (TERMIOS_TTY_DRIVER)
1304 static struct termios shell_tty_info;
1305 #endif /* TERMIOS_TTY_DRIVER */
1307 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1308 /* Since the BSD tty driver does not allow us to change the tty modes
1309 while simultaneously waiting for output to drain and preserving
1310 typeahead, we have to drain the output ourselves before calling
1311 ioctl. We cheat by finding the length of the output queue, and
1312 using select to wait for an appropriate length of time. This is
1313 a hack, and should be labeled as such (it's a hastily-adapted
1314 mutation of a `usleep' implementation). It's only reason for
1315 existing is the flaw in the BSD tty driver. */
1317 static int ttspeeds[] =
1319 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1320 1800, 2400, 4800, 9600, 19200, 38400
1327 register int delay = ttspeeds[ospeed];
1333 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1335 if (n > (delay / 100))
1339 n *= 10; /* 2 bits more for conservativeness. */
1340 tv.tv_sec = n / delay;
1341 tv.tv_usec = ((n % delay) * 1000000) / delay;
1342 select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1348 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1350 /* Return the fd from which we are actually getting input. */
1351 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1353 /* Fill the contents of shell_tty_info with the current tty info. */
1362 #if defined (NEW_TTY_DRIVER)
1363 ioctl (tty, TIOCGETP, &shell_tty_info);
1364 ioctl (tty, TIOCGETC, &shell_tchars);
1365 ioctl (tty, TIOCGLTC, &shell_ltchars);
1366 #endif /* NEW_TTY_DRIVER */
1368 #if defined (TERMIO_TTY_DRIVER)
1369 ioctl (tty, TCGETA, &shell_tty_info);
1370 #endif /* TERMIO_TTY_DRIVER */
1372 #if defined (TERMIOS_TTY_DRIVER)
1373 if (tcgetattr (tty, &shell_tty_info) < 0)
1376 /* Only print an error message if we're really interactive at
1379 sys_error ("[%d: %d] tcgetattr", getpid (), shell_level);
1383 #endif /* TERMIOS_TTY_DRIVER */
1384 if (check_window_size)
1385 get_new_window_size (0);
1390 /* Make the current tty use the state in shell_tty_info. */
1399 #if defined (NEW_TTY_DRIVER)
1400 # if defined (DRAIN_OUTPUT)
1401 draino (tty, shell_tty_info.sg_ospeed);
1402 # endif /* DRAIN_OUTPUT */
1403 ioctl (tty, TIOCSETN, &shell_tty_info);
1404 ioctl (tty, TIOCSETC, &shell_tchars);
1405 ioctl (tty, TIOCSLTC, &shell_ltchars);
1406 #endif /* NEW_TTY_DRIVER */
1408 #if defined (TERMIO_TTY_DRIVER)
1409 ioctl (tty, TCSETAW, &shell_tty_info);
1410 #endif /* TERMIO_TTY_DRIVER */
1412 #if defined (TERMIOS_TTY_DRIVER)
1413 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1415 /* Only print an error message if we're really interactive at
1418 sys_error ("[%d: %d] tcsetattr", getpid (), shell_level);
1421 #endif /* TERMIOS_TTY_DRIVER */
1426 /* Given an index into the jobs array JOB, return the pid of the last
1427 process in that job's pipeline. This is the one whose exit status
1433 register PROCESS *p;
1435 p = jobs[job]->pipe;
1436 while (p->next != jobs[job]->pipe)
1449 BLOCK_CHILD (set, oset);
1450 pid = find_last_pid (job);
1451 UNBLOCK_CHILD (oset);
1456 /* Wait for a particular child of the shell to finish executing.
1457 This low-level function prints an error message if PID is not
1458 a child of this shell. It returns -1 if it fails, or 0 if not. */
1460 wait_for_single_pid (pid)
1463 register PROCESS *child;
1467 BLOCK_CHILD (set, oset);
1468 child = find_pipeline (pid);
1469 UNBLOCK_CHILD (oset);
1473 internal_error ("wait: pid %d is not a child of this shell", pid);
1479 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
1481 BLOCK_CHILD (set, oset);
1482 job = find_job (pid);
1483 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1484 jobs[job]->flags |= J_NOTIFIED;
1485 UNBLOCK_CHILD (oset);
1490 /* Wait for all of the backgrounds of this shell to finish. */
1492 wait_for_background_pids ()
1494 register int i, count;
1500 BLOCK_CHILD (set, oset);
1503 for (i = 0; i < job_slots; i++)
1504 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1512 UNBLOCK_CHILD (oset);
1516 for (i = 0; i < job_slots; i++)
1517 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
1520 UNBLOCK_CHILD (oset);
1522 wait_for_single_pid (pid);
1527 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
1528 `wait' is called with no arguments. */
1529 mark_dead_jobs_as_notified (1);
1530 cleanup_dead_jobs ();
1533 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
1534 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
1535 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
1538 restore_sigint_handler ()
1540 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1542 set_signal_handler (SIGINT, old_sigint_handler);
1543 old_sigint_handler = INVALID_SIGNAL_HANDLER;
1547 static int wait_sigint_received;
1549 /* Handle SIGINT while we are waiting for children in a script to exit.
1550 The `wait' builtin should be interruptible, but all others should be
1551 effectively ignored (i.e. not cause the shell to exit). */
1553 wait_sigint_handler (sig)
1556 if (interrupt_immediately ||
1557 (this_shell_builtin && this_shell_builtin == wait_builtin))
1559 last_command_exit_value = EXECUTION_FAILURE;
1560 restore_sigint_handler ();
1565 /* XXX - should this be interrupt_state? If it is, the shell will act
1566 as if it got the SIGINT interrupt. */
1567 wait_sigint_received = 1;
1569 /* Otherwise effectively ignore the SIGINT and allow the running job to
1575 process_exit_status (status)
1578 if (WIFSIGNALED (status))
1579 return (128 + WTERMSIG (status));
1580 else if (WIFSTOPPED (status) == 0)
1581 return (WEXITSTATUS (status));
1583 return (EXECUTION_SUCCESS);
1587 job_exit_status (job)
1590 register PROCESS *p;
1591 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
1593 return (process_exit_status (p->status));
1596 /* Wait for pid (one of our children) to terminate, then
1597 return the termination state. */
1598 #define FIND_CHILD(pid, child) \
1601 child = find_pipeline (pid); \
1604 give_terminal_to (shell_pgrp); \
1605 UNBLOCK_CHILD (oset); \
1606 internal_error ("wait_for: No record of process %d", pid); \
1607 restore_sigint_handler (); \
1608 return (termination_state = 127); \
1617 int job, termination_state;
1618 register PROCESS *child;
1621 register PROCESS *p;
1622 int job_state, any_stopped;
1625 /* In the case that this code is interrupted, and we longjmp () out of it,
1626 we are relying on the code in throw_to_top_level () to restore the
1627 top-level signal mask. */
1628 BLOCK_CHILD (set, oset);
1630 /* Ignore interrupts while waiting for a job run without job control
1631 to finish. We don't want the shell to exit if an interrupt is
1632 received, only if one of the jobs run is killed via SIGINT. If
1633 job control is not set, the job will be run in the same pgrp as
1634 the shell, and the shell will see any signals the job gets. */
1636 /* This is possibly a race condition -- should it go in stop_pipeline? */
1637 wait_sigint_received = 0;
1638 if (job_control == 0)
1639 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
1641 termination_state = last_command_exit_value;
1643 if (interactive && job_control == 0)
1646 /* If we say wait_for (), then we have a record of this child somewhere.
1647 If it and none of its peers are running, don't call waitchld(). */
1652 FIND_CHILD (pid, child);
1654 /* If this child is part of a job, then we are really waiting for the
1655 job to finish. Otherwise, we are waiting for the child to finish.
1656 We check for JDEAD in case the job state has been set by waitchld
1657 after receipt of a SIGCHLD. */
1659 job = find_job (pid);
1662 /* XXX - let waitchld take care of setting this. If the job has
1663 already exited before this is called, sigchld_handler will have
1664 called waitchld and this will be set to JDEAD. */
1665 if (job != NO_JOB && JOBSTATE (job) != JDEAD)
1667 job_state = any_stopped = 0;
1668 p = jobs[job]->pipe;
1671 job_state |= p->running;
1672 if (p->running == 0)
1673 any_stopped |= WIFSTOPPED (p->status);
1676 while (p != jobs[job]->pipe);
1679 jobs[job]->state = any_stopped ? JSTOPPED : JDEAD;
1683 if (child->running || (job != NO_JOB && RUNNING (job)))
1685 #if defined (WAITPID_BROKEN) /* SCOv4 */
1686 sigset_t suspend_set;
1687 sigemptyset (&suspend_set);
1688 sigsuspend (&suspend_set);
1689 #else /* !WAITPID_BROKEN */
1690 # if defined (MUST_UNBLOCK_CHLD)
1691 struct sigaction act, oact;
1692 sigset_t nullset, chldset;
1694 sigemptyset (&nullset);
1695 sigemptyset (&chldset);
1696 sigprocmask (SIG_SETMASK, &nullset, &chldset);
1697 act.sa_handler = SIG_DFL;
1698 sigemptyset (&act.sa_mask);
1699 sigemptyset (&oact.sa_mask);
1701 sigaction (SIGCHLD, &act, &oact);
1703 waiting_for_job = 1;
1705 # if defined (MUST_UNBLOCK_CHLD)
1706 sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
1707 sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
1709 waiting_for_job = 0;
1710 #endif /* WAITPID_BROKEN */
1713 /* If the shell is interactive, and job control is disabled, see
1714 if the foreground process has died due to SIGINT and jump out
1715 of the wait loop if it has. waitchld has already restored the
1716 old SIGINT signal handler. */
1717 if (interactive && job_control == 0)
1720 while (child->running || (job != NO_JOB && RUNNING (job)));
1722 /* The exit state of the command is either the termination state of the
1723 child, or the termination state of the job. If a job, the status
1724 of the last child in the pipeline is the significant one. */
1727 termination_state = job_exit_status (job);
1729 termination_state = process_exit_status (child->status);
1731 if (job == NO_JOB || IS_JOBCONTROL (job))
1733 /* XXX - under what circumstances is a job not present in the jobs
1734 table (job == NO_JOB)?
1735 1. command substitution
1737 In the case of command substitution, at least, it's probably not
1738 the right thing to give the terminal to the shell's process group,
1739 even though there is code in subst.c:command_substitute to work
1743 $PROMPT_COMMAND execution
1744 process substitution
1748 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%d)", shell_pgrp);
1751 give_terminal_to (shell_pgrp);
1754 /* If the command did not exit cleanly, or the job is just
1755 being stopped, then reset the tty state back to what it
1756 was before this command. Reset the tty state and notify
1757 the user of the job termination only if the shell is
1758 interactive. Clean up any dead jobs in either case. */
1761 if (interactive_shell && subshell_environment == 0)
1763 if (WIFSIGNALED (child->status) || WIFSTOPPED (child->status))
1766 /* If the foreground job was suspended with ^Z (SIGTSTP), and
1767 the user has requested it, get a new window size. */
1768 if (check_window_size && WIFSTOPPED (child->status) &&
1769 (WSTOPSIG (child->status) == SIGTSTP) &&
1771 get_new_window_size (0);
1776 /* If job control is enabled, the job was started with job
1777 control, the job was the foreground job, and it was killed
1778 by SIGINT, then print a newline to compensate for the kernel
1779 printing the ^C without a trailing newline. */
1780 if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
1781 WIFSIGNALED (child->status) &&
1782 WTERMSIG (child->status) == SIGINT)
1784 /* If SIGINT is not trapped and the shell is in a for, while,
1785 or until loop, act as if the shell received SIGINT as
1786 well, so the loop can be broken. This doesn't call the
1787 SIGINT signal handler; maybe it should. */
1788 if (signal_is_trapped (SIGINT) == 0 && loop_level)
1797 notify_and_cleanup ();
1801 /* If this job is dead, and the shell is not interactive, make
1802 sure we turn on the notify bit so we don't get an unwanted
1803 message about the job's termination, and so delete_job really
1804 clears the slot in the jobs table. */
1805 notify_and_cleanup ();
1809 UNBLOCK_CHILD (oset);
1811 /* Restore the original SIGINT signal handler before we return. */
1812 restore_sigint_handler ();
1814 return (termination_state);
1817 /* Wait for the last process in the pipeline for JOB. */
1826 BLOCK_CHILD(set, oset);
1827 if (JOBSTATE (job) == JSTOPPED)
1828 internal_warning ("wait_for_job: job %d is stopped", job+1);
1829 UNBLOCK_CHILD(oset);
1831 pid = last_pid (job);
1834 /* POSIX.2: we can remove the job from the jobs table if we just waited
1836 BLOCK_CHILD (set, oset);
1837 if (job != NO_JOB && jobs[job] && DEADJOB (job))
1838 jobs[job]->flags |= J_NOTIFIED;
1839 UNBLOCK_CHILD (oset);
1844 /* Print info about dead jobs, and then delete them from the list
1845 of known jobs. This does not actually delete jobs when the
1846 shell is not interactive, because the dead jobs are not marked
1849 notify_and_cleanup ()
1851 if (jobs_list_frozen)
1854 if (interactive || interactive_shell == 0)
1855 notify_of_job_status ();
1857 cleanup_dead_jobs ();
1860 /* Make dead jobs disappear from the jobs array without notification.
1861 This is used when the shell is not interactive. */
1865 mark_dead_jobs_as_notified (0);
1866 cleanup_dead_jobs ();
1869 /* Return the next closest (chronologically) job to JOB which is in
1870 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
1871 there is no next recent job. */
1873 most_recent_job_in_state (job, state)
1877 register int i, result;
1880 BLOCK_CHILD (set, oset);
1881 for (result = NO_JOB, i = job - 1; i >= 0; i--)
1883 if (jobs[i] && (JOBSTATE (i) == state))
1889 UNBLOCK_CHILD (oset);
1894 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
1897 last_stopped_job (job)
1900 return (most_recent_job_in_state (job, JSTOPPED));
1903 /* Return the newest *running* job older than JOB, or NO_JOB if not
1906 last_running_job (job)
1909 return (most_recent_job_in_state (job, JRUNNING));
1912 /* Make JOB be the current job, and make previous be useful. Must be
1913 called with SIGCHLD blocked. */
1915 set_current_job (job)
1920 if (current_job != job)
1922 previous_job = current_job;
1926 /* First choice for previous_job is the old current_job. */
1927 if (previous_job != current_job &&
1928 previous_job != NO_JOB &&
1929 jobs[previous_job] &&
1930 STOPPED (previous_job))
1933 /* Second choice: Newest stopped job that is older than
1936 if (STOPPED (current_job))
1938 candidate = last_stopped_job (current_job);
1940 if (candidate != NO_JOB)
1942 previous_job = candidate;
1947 /* If we get here, there is either only one stopped job, in which case it is
1948 the current job and the previous job should be set to the newest running
1949 job, or there are only running jobs and the previous job should be set to
1950 the newest running job older than the current job. We decide on which
1951 alternative to use based on whether or not JOBSTATE(current_job) is
1954 candidate = RUNNING (current_job) ? last_running_job (current_job)
1955 : last_running_job (job_slots);
1957 if (candidate != NO_JOB)
1959 previous_job = candidate;
1963 /* There is only a single job, and it is both `+' and `-'. */
1964 previous_job = current_job;
1967 /* Make current_job be something useful, if it isn't already. */
1969 /* Here's the deal: The newest non-running job should be `+', and the
1970 next-newest non-running job should be `-'. If there is only a single
1971 stopped job, the previous_job is the newest non-running job. If there
1972 are only running jobs, the newest running job is `+' and the
1973 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
1980 if (job_slots && current_job != NO_JOB && jobs[current_job] && STOPPED (current_job))
1981 candidate = current_job;
1986 /* First choice: the previous job. */
1987 if (previous_job != NO_JOB && jobs[previous_job] && STOPPED (previous_job))
1988 candidate = previous_job;
1990 /* Second choice: the most recently stopped job. */
1991 if (candidate == NO_JOB)
1992 candidate = last_stopped_job (job_slots);
1994 /* Third choice: the newest running job. */
1995 if (candidate == NO_JOB)
1996 candidate = last_running_job (job_slots);
1999 /* If we found a job to use, then use it. Otherwise, there
2000 are no jobs period. */
2001 if (candidate != NO_JOB)
2002 set_current_job (candidate);
2004 current_job = previous_job = NO_JOB;
2007 /* Set up the job structures so we know the job and its processes are
2010 set_job_running (job)
2013 register PROCESS *p;
2015 /* Each member of the pipeline is now running. */
2016 p = jobs[job]->pipe;
2020 if (WIFSTOPPED (p->status))
2024 while (p != jobs[job]->pipe);
2026 /* This means that the job is running. */
2027 JOBSTATE (job) = JRUNNING;
2030 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2031 start the job in the background. JOB is a zero-based index into
2032 JOBS. Returns -1 if it is unable to start a job, and the return
2033 status of the job otherwise. */
2035 start_job (job, foreground)
2036 int job, foreground;
2038 register PROCESS *p;
2039 int already_running;
2042 #if defined (NEW_TTY_DRIVER)
2043 static struct sgttyb save_stty;
2045 #if defined (TERMIO_TTY_DRIVER)
2046 static struct termio save_stty;
2048 #if defined (TERMIOS_TTY_DRIVER)
2049 static struct termios save_stty;
2052 BLOCK_CHILD (set, oset);
2056 internal_error ("%s: job has terminated", this_command_name);
2057 UNBLOCK_CHILD (oset);
2061 already_running = RUNNING (job);
2063 if (foreground == 0 && already_running)
2065 internal_error ("%s: bg background job?", this_command_name);
2066 UNBLOCK_CHILD (oset);
2070 wd = current_working_directory ();
2072 /* You don't know about the state of this job. Do you? */
2073 jobs[job]->flags &= ~J_NOTIFIED;
2077 set_current_job (job);
2078 jobs[job]->flags |= J_FOREGROUND;
2081 /* Tell the outside world what we're doing. */
2082 p = jobs[job]->pipe;
2084 if (foreground == 0)
2085 fprintf (stderr, "[%d]%c ", job + 1,
2086 (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
2090 fprintf (stderr, "%s%s",
2091 p->command ? p->command : "",
2092 p->next != jobs[job]->pipe? " | " : "");
2095 while (p != jobs[job]->pipe);
2097 if (foreground == 0)
2098 fprintf (stderr, " &");
2100 if (strcmp (wd, jobs[job]->wd) != 0)
2101 fprintf (stderr, " (wd: %s)", polite_directory_format (jobs[job]->wd));
2103 fprintf (stderr, "\n");
2106 if (already_running == 0)
2107 set_job_running (job);
2109 /* Save the tty settings before we start the job in the foreground. */
2113 save_stty = shell_tty_info;
2114 /* Give the terminal to this job. */
2115 if (IS_JOBCONTROL (job))
2116 give_terminal_to (jobs[job]->pgrp);
2119 jobs[job]->flags &= ~J_FOREGROUND;
2121 /* If the job is already running, then don't bother jump-starting it. */
2122 if (already_running == 0)
2124 jobs[job]->flags |= J_NOTIFIED;
2125 killpg (jobs[job]->pgrp, SIGCONT);
2128 UNBLOCK_CHILD (oset);
2135 pid = last_pid (job);
2137 shell_tty_info = save_stty;
2143 BLOCK_CHILD (set, oset);
2145 UNBLOCK_CHILD (oset);
2150 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2151 If PID does belong to a job, and the job is stopped, then CONTinue the
2152 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2153 then kill the process group associated with PID. */
2155 kill_pid (pid, sig, group)
2159 register PROCESS *p;
2163 BLOCK_CHILD (set, oset);
2164 p = find_pipeline (pid);
2165 job = find_job (pid);
2167 result = EXECUTION_SUCCESS;
2172 jobs[job]->flags &= ~J_NOTIFIED;
2174 /* Kill process in backquotes or one started without job control? */
2175 if (jobs[job]->pgrp == shell_pgrp)
2177 p = jobs[job]->pipe;
2182 if (p->running == 0 && (sig == SIGTERM || sig == SIGHUP))
2183 kill (p->pid, SIGCONT);
2186 while (p != jobs[job]->pipe);
2190 result = killpg (jobs[job]->pgrp, sig);
2191 if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2192 killpg (jobs[job]->pgrp, SIGCONT);
2193 /* If we're continuing a stopped job via kill rather than bg or
2194 fg, emulate the `bg' behavior. */
2195 if (p && STOPPED (job) && (sig == SIGCONT))
2197 set_job_running (job);
2198 jobs[job]->flags &= ~J_FOREGROUND;
2199 jobs[job]->flags |= J_NOTIFIED;
2204 result = killpg (pid, sig);
2207 result = kill (pid, sig);
2209 UNBLOCK_CHILD (oset);
2213 /* sigchld_handler () flushes at least one of the children that we are
2214 waiting for. It gets run when we have gotten a SIGCHLD signal. */
2216 sigchld_handler (sig)
2221 REINSTALL_SIGCHLD_HANDLER;
2224 if (waiting_for_job == 0)
2225 n = waitchld (-1, 0);
2229 /* waitchld() reaps dead or stopped children. It's called by wait_for and
2230 flush_child, and runs until there aren't any children terminating any more.
2231 If BLOCK is 1, this is to be a blocking wait for a single child, although
2232 an arriving SIGCHLD could cause the wait to be non-blocking. */
2234 waitchld (wpid, block)
2241 int call_set_current, last_stopped_job, job, children_exited;
2242 int job_state, any_stopped, any_tstped, waitpid_flags, tstatus;
2244 call_set_current = children_exited = 0;
2245 last_stopped_job = NO_JOB;
2249 /* We don't want to be notified about jobs stopping if job control
2250 is not active. XXX - was interactive_shell instead of job_control */
2251 waitpid_flags = (job_control && subshell_environment == 0)
2254 if (sigchld || block == 0)
2255 waitpid_flags |= WNOHANG;
2256 pid = WAITPID (-1, &status, waitpid_flags);
2257 /* The check for WNOHANG is to make sure we decrement sigchld only
2258 if it was non-zero before we called waitpid. */
2259 if (sigchld > 0 && (waitpid_flags & WNOHANG))
2262 /* If waitpid returns 0, there are running children. */
2264 continue; /* jumps right to the test */
2268 /* Locate our PROCESS for this pid. */
2269 child = find_pipeline (pid);
2271 /* It is not an error to have a child terminate that we did
2272 not have a record of. This child could have been part of
2273 a pipeline in backquote substitution. Even so, I'm not
2274 sure child is ever non-zero. */
2278 while (child->pid != pid)
2279 child = child->next;
2281 /* Remember status, and fact that process is not running. */
2282 child->status = status;
2285 job = find_job (pid);
2290 /* Note that we're resetting `child' here because we now want to
2291 deal with the job. */
2292 child = jobs[job]->pipe;
2293 jobs[job]->flags &= ~J_NOTIFIED;
2295 /* If all children are not running, but any of them is
2296 stopped, then the job is stopped, not dead. */
2297 job_state = any_stopped = any_tstped = 0;
2300 job_state |= child->running;
2301 if (child->running == 0 && (WIFSTOPPED (child->status)))
2304 any_tstped |= interactive && job_control &&
2305 (WSTOPSIG (child->status) == SIGTSTP);
2307 child = child->next;
2309 while (child != jobs[job]->pipe);
2311 /* If job_state != 0, the job is still running, so don't bother with
2312 setting the process exit status and job state. */
2316 /* The job is either stopped or dead. Set the state of the job
2320 jobs[job]->state = JSTOPPED;
2321 jobs[job]->flags &= ~J_FOREGROUND;
2323 last_stopped_job = job;
2324 /* Suspending a job with SIGTSTP breaks all active loops. */
2325 if (any_tstped && loop_level)
2326 breaking = loop_level;
2330 /* ASSERT(child == jobs[job]->pipe); */
2331 jobs[job]->state = JDEAD;
2332 if (job == last_stopped_job)
2333 last_stopped_job = NO_JOB;
2335 if (IS_FOREGROUND (job))
2336 setjstatus (job); /* XXX */
2338 /* If this job has a cleanup function associated with it, call it
2339 with `cleanarg' as the single argument, then set the function
2340 pointer to NULL so it is not inadvertently called twice. The
2341 cleanup function is responsible for deallocating cleanarg. */
2342 if (jobs[job]->j_cleanup)
2344 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
2345 jobs[job]->j_cleanup = (VFunction *)NULL;
2349 If we're running a shell script and we get a SIGINT with a
2350 SIGINT trap handler, but the foreground job handles it and
2351 does not exit due to SIGINT, run the trap handler but do not
2352 otherwise act as if we got the interrupt. */
2353 if (wait_sigint_received && interactive_shell == 0 &&
2354 WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
2355 signal_is_trapped (SIGINT))
2357 wait_sigint_received = 0;
2358 last_command_exit_value = process_exit_status (child->status);
2360 jobs_list_frozen = 1;
2361 tstatus = maybe_call_trap_handler (SIGINT);
2362 jobs_list_frozen = 0;
2365 /* If the foreground job is killed by SIGINT when
2366 job control is not active, we need to perform
2367 some special handling.
2369 The check of wait_sigint_received is a way to
2370 determine if the SIGINT came from the keyboard
2371 (in which case the shell has already seen it,
2372 and wait_sigint_received is non-zero, because
2373 keyboard signals are sent to process groups)
2374 or via kill(2) to the foreground process by
2375 another process (or itself). If the shell did
2376 receive the SIGINT, it needs to perform normal
2377 SIGINT processing. */
2378 else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
2379 IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
2381 wait_sigint_received = 0;
2383 /* If SIGINT is trapped, set the exit status so
2384 that the trap handler can see it. */
2385 if (signal_is_trapped (SIGINT))
2386 last_command_exit_value = process_exit_status (child->status);
2388 /* If the signal is trapped, let the trap handler
2389 get it no matter what and simply return if
2390 the trap handler returns.
2391 maybe_call_trap_handler() may cause dead jobs
2392 to be removed from the job table because of
2393 a call to execute_command. Watch out for this. */
2394 jobs_list_frozen = 1;
2395 tstatus = maybe_call_trap_handler (SIGINT);
2396 jobs_list_frozen = 0;
2397 if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
2399 /* wait_sigint_handler () has already seen SIGINT and
2400 allowed the wait builtin to jump out. We need to
2401 call the original SIGINT handler, if necessary. If
2402 the original handler is SIG_DFL, we need to resend
2403 the signal to ourselves. */
2404 SigHandler *temp_handler;
2406 temp_handler = old_sigint_handler;
2407 /* Bogus. If we've reset the signal handler as the result
2408 of a trap caught on SIGINT, then old_sigint_handler
2409 will point to trap_handler, which now knows nothing about
2410 SIGINT (if we reset the sighandler to the default).
2411 In this case, we have to fix things up. What a crock. */
2412 if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
2413 temp_handler = trap_to_sighandler (SIGINT);
2414 restore_sigint_handler ();
2415 if (temp_handler == SIG_DFL)
2416 termination_unwind_protect (SIGINT);
2417 else if (temp_handler != SIG_IGN)
2418 (*temp_handler) (SIGINT);
2423 while ((sigchld || block == 0) && pid > (pid_t)0);
2425 /* If a job was running and became stopped, then set the current
2426 job. Otherwise, don't change a thing. */
2427 if (call_set_current)
2428 if (last_stopped_job != NO_JOB)
2429 set_current_job (last_stopped_job);
2433 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
2434 if (job_control && signal_is_trapped (SIGCHLD) &&
2435 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
2440 /* Turn off the trap list during the call to parse_and_execute ()
2441 to avoid potentially infinite recursive calls. Preserve the
2442 values of last_command_exit_value, last_made_pid, and the_pipeline
2443 around the execution of the trap commands. */
2444 trap_command = savestring (trap_list[SIGCHLD]);
2446 begin_unwind_frame ("SIGCHLD trap");
2447 unwind_protect_int (last_command_exit_value);
2448 if (sizeof (pid_t) == sizeof (short))
2449 unwind_protect_short (last_made_pid);
2451 unwind_protect_int (last_made_pid);
2452 unwind_protect_int (interrupt_immediately);
2453 unwind_protect_int (jobs_list_frozen);
2454 unwind_protect_pointer (the_pipeline);
2456 /* We have to add the commands this way because they will be run
2457 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
2458 to reference freed memory. */
2459 add_unwind_protect ((Function *)xfree, trap_command);
2460 add_unwind_protect ((Function *)maybe_set_sigchld_trap, trap_command);
2462 the_pipeline = (PROCESS *)NULL;
2463 restore_default_signal (SIGCHLD);
2464 jobs_list_frozen = 1;
2465 for (i = 0; i < children_exited; i++)
2467 interrupt_immediately = 1;
2468 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST);
2471 run_unwind_frame ("SIGCHLD trap");
2474 /* We have successfully recorded the useful information about this process
2475 that has just changed state. If we notify asynchronously, and the job
2476 that this process belongs to is no longer running, then notify the user
2477 of that fact now. */
2478 if (asynchronous_notification && interactive)
2479 notify_of_job_status ();
2481 return (children_exited);
2484 /* Function to call when you want to notify people of changes
2485 in job status. This prints out all jobs which are pending
2486 notification to stderr, and marks those printed as already
2487 notified, thus making them candidates for cleanup. */
2489 notify_of_job_status ()
2491 register int job, termsig;
2497 sigaddset (&set, SIGCHLD);
2498 sigaddset (&set, SIGTTOU);
2499 sigemptyset (&oset);
2500 sigprocmask (SIG_BLOCK, &set, &oset);
2502 for (job = 0, dir = (char *)NULL; job < job_slots; job++)
2504 if (jobs[job] && IS_NOTIFIED (job) == 0)
2506 s = jobs[job]->pipe->status;
2507 termsig = WTERMSIG (s);
2509 /* POSIX.2 says we have to hang onto the statuses of at most the
2510 last CHILD_MAX background processes if the shell is running a
2511 script. If the shell is not interactive, don't print anything
2512 unless the job was killed by a signal. */
2513 if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
2514 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
2517 /* If job control is disabled, don't print the status messages.
2518 Mark dead jobs as notified so that they get cleaned up. If
2519 startup_state == 2, we were started to run `-c command', so
2520 don't print anything. */
2521 if ((job_control == 0 && interactive_shell) || startup_state == 2)
2523 /* POSIX.2 compatibility: if the shell is not interactive,
2524 hang onto the job corresponding to the last asynchronous
2525 pid until the user has been notified of its status or does
2527 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job) != last_asynchronous_pid)))
2528 jobs[job]->flags |= J_NOTIFIED;
2532 /* Print info on jobs that are running in the background,
2533 and on foreground jobs that were killed by anything
2534 except SIGINT (and possibly SIGPIPE). */
2535 switch (JOBSTATE (job))
2538 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
2539 termsig != SIGINT &&
2540 #if defined (DONT_REPORT_SIGPIPE)
2541 termsig != SIGPIPE &&
2543 signal_is_trapped (termsig) == 0)
2545 fprintf (stderr, "%s: line %d: ", get_name_for_error (), line_number);
2546 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
2548 else if (IS_FOREGROUND (job))
2550 #if !defined (DONT_REPORT_SIGPIPE)
2551 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2553 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
2556 fprintf (stderr, "%s", strsignal (termsig));
2559 fprintf (stderr, " (core dumped)");
2561 fprintf (stderr, "\n");
2567 dir = current_working_directory ();
2568 pretty_print_job (job, JLIST_STANDARD, stderr);
2569 if (dir && strcmp (dir, jobs[job]->wd) != 0)
2571 "(wd now: %s)\n", polite_directory_format (dir));
2574 jobs[job]->flags |= J_NOTIFIED;
2578 fprintf (stderr, "\n");
2580 dir = current_working_directory ();
2581 pretty_print_job (job, JLIST_STANDARD, stderr);
2582 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2584 "(wd now: %s)\n", polite_directory_format (dir));
2585 jobs[job]->flags |= J_NOTIFIED;
2593 programming_error ("notify_of_job_status");
2597 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2600 /* Initialize the job control mechanism, and set up the tty stuff. */
2602 initialize_job_control (force)
2605 shell_pgrp = getpgid (0);
2607 if (shell_pgrp == -1)
2609 sys_error ("initialize_job_control: getpgrp failed");
2613 /* We can only have job control if we are interactive. */
2614 if (interactive == 0)
2617 original_pgrp = NO_PID;
2618 shell_tty = fileno (stderr);
2622 /* Get our controlling terminal. If job_control is set, or
2623 interactive is set, then this is an interactive shell no
2624 matter where fd 2 is directed. */
2625 shell_tty = dup (fileno (stderr)); /* fd 2 */
2627 shell_tty = move_to_high_fd (shell_tty, 1, -1);
2629 /* Compensate for a bug in systems that compiled the BSD
2630 rlogind with DEBUG defined, like NeXT and Alliant. */
2631 if (shell_pgrp == 0)
2633 shell_pgrp = getpid ();
2634 setpgid (0, shell_pgrp);
2635 tcsetpgrp (shell_tty, shell_pgrp);
2638 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2640 if (shell_pgrp != terminal_pgrp)
2642 SigHandler *old_ttin;
2644 old_ttin = set_signal_handler(SIGTTIN, SIG_DFL);
2646 set_signal_handler (SIGTTIN, old_ttin);
2652 /* Make sure that we are using the new line discipline. */
2653 if (set_new_line_discipline (shell_tty) < 0)
2655 sys_error ("initialize_job_control: line discipline");
2660 original_pgrp = shell_pgrp;
2661 shell_pgrp = getpid ();
2663 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
2665 sys_error ("initialize_job_control: setpgid");
2666 shell_pgrp = original_pgrp;
2671 /* If (and only if) we just set our process group to our pid,
2672 thereby becoming a process group leader, and the terminal
2673 is not in the same process group as our (new) process group,
2674 then set the terminal's process group to our (new) process
2675 group. If that fails, set our process group back to what it
2676 was originally (so we can still read from the terminal) and
2677 turn off job control. */
2678 if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
2680 if (give_terminal_to (shell_pgrp) < 0) /* XXX */
2682 setpgid (0, original_pgrp); /* XXX */
2683 shell_pgrp = original_pgrp; /* XXX */
2684 job_control = 0; /* XXX */
2688 if (job_control == 0)
2689 internal_error ("no job control in this shell"); /* XXX */
2692 if (shell_tty != fileno (stderr))
2693 SET_CLOSE_ON_EXEC (shell_tty);
2695 set_signal_handler (SIGCHLD, sigchld_handler);
2697 change_flag ('m', job_control ? '-' : '+');
2705 /* Set the line discipline to the best this system has to offer.
2706 Return -1 if this is not possible. */
2708 set_new_line_discipline (tty)
2711 #if defined (NEW_TTY_DRIVER)
2714 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
2717 if (ldisc != NTTYDISC)
2721 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
2725 #endif /* NEW_TTY_DRIVER */
2727 #if defined (TERMIO_TTY_DRIVER)
2728 # if defined (TERMIO_LDISC) && (NTTYDISC)
2729 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
2732 if (shell_tty_info.c_line != NTTYDISC)
2734 shell_tty_info.c_line = NTTYDISC;
2735 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
2738 # endif /* TERMIO_LDISC && NTTYDISC */
2740 #endif /* TERMIO_TTY_DRIVER */
2742 #if defined (TERMIOS_TTY_DRIVER)
2743 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
2744 if (tcgetattr (tty, &shell_tty_info) < 0)
2747 if (shell_tty_info.c_line != NTTYDISC)
2749 shell_tty_info.c_line = NTTYDISC;
2750 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2753 # endif /* TERMIOS_LDISC && NTTYDISC */
2755 #endif /* TERMIOS_TTY_DRIVER */
2757 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
2762 static SigHandler *old_tstp, *old_ttou, *old_ttin;
2763 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
2764 static sighandler stop_signal_handler (), cont_signal_handler ();
2766 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2767 static SigHandler *old_winch = (SigHandler *)SIG_DFL;
2770 get_new_window_size (from_sig)
2775 if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
2776 win.ws_row > 0 && win.ws_col > 0)
2779 shell_tty_info.c_winsize = win; /* structure copying */
2781 set_lines_and_columns (win.ws_row, win.ws_col);
2782 #if defined (READLINE)
2783 _rl_set_screen_size (win.ws_row, win.ws_col);
2789 sigwinch_sighandler (sig)
2792 #if defined (MUST_REINSTALL_SIGHANDLERS)
2793 set_signal_handler (SIGWINCH, sigwinch_sighandler);
2794 #endif /* MUST_REINSTALL_SIGHANDLERS */
2795 get_new_window_size (1);
2800 get_new_window_size (from_sig)
2804 #endif /* TIOCGWINSZ && SIGWINCH */
2807 set_sigwinch_handler ()
2809 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2810 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
2815 unset_sigwinch_handler ()
2817 #if defined (TIOCGWINSZ) && defined (SIGWINCH)
2818 set_signal_handler (SIGWINCH, old_winch);
2822 /* Setup this shell to handle C-C, etc. */
2824 initialize_job_signals ()
2828 set_signal_handler (SIGINT, sigint_sighandler);
2829 set_signal_handler (SIGTSTP, SIG_IGN);
2830 set_signal_handler (SIGTTOU, SIG_IGN);
2831 set_signal_handler (SIGTTIN, SIG_IGN);
2832 set_sigwinch_handler ();
2834 else if (job_control)
2836 old_tstp = set_signal_handler (SIGTSTP, stop_signal_handler);
2837 old_ttou = set_signal_handler (SIGTTOU, stop_signal_handler);
2838 old_ttin = set_signal_handler (SIGTTIN, stop_signal_handler);
2840 /* Leave these things alone for non-interactive shells without job
2844 /* Here we handle CONT signals. */
2846 cont_signal_handler (sig)
2849 initialize_job_signals ();
2850 set_signal_handler (SIGCONT, old_cont);
2851 kill (getpid (), SIGCONT);
2856 /* Here we handle stop signals while we are running not as a login shell. */
2858 stop_signal_handler (sig)
2861 set_signal_handler (SIGTSTP, old_tstp);
2862 set_signal_handler (SIGTTOU, old_ttou);
2863 set_signal_handler (SIGTTIN, old_ttin);
2865 old_cont = set_signal_handler (SIGCONT, cont_signal_handler);
2867 give_terminal_to (shell_pgrp);
2869 kill (getpid (), sig);
2874 /* Give the terminal to PGRP. */
2876 give_terminal_to (pgrp)
2886 sigaddset (&set, SIGTTOU);
2887 sigaddset (&set, SIGTTIN);
2888 sigaddset (&set, SIGTSTP);
2889 sigaddset (&set, SIGCHLD);
2890 sigemptyset (&oset);
2891 sigprocmask (SIG_BLOCK, &set, &oset);
2893 if (tcsetpgrp (shell_tty, pgrp) < 0)
2895 /* Maybe we should print an error message? */
2897 sys_error ("tcsetpgrp(%d) failed: pid %d to pgrp %d",
2898 shell_tty, getpid(), pgrp);
2903 terminal_pgrp = pgrp;
2904 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2910 /* Clear out any jobs in the job array. This is intended to be used by
2911 children of the shell, who should not have any job structures as baggage
2912 when they start executing (forking subshells for parenthesized execution
2913 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
2914 is nonzero, only running jobs are removed from the table. */
2916 delete_all_jobs (running_only)
2922 BLOCK_CHILD (set, oset);
2926 current_job = previous_job = NO_JOB;
2928 for (i = 0; i < job_slots; i++)
2929 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
2932 if (running_only == 0)
2934 free ((char *)jobs);
2939 UNBLOCK_CHILD (oset);
2942 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
2943 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
2945 nohup_all_jobs (running_only)
2951 BLOCK_CHILD (set, oset);
2955 for (i = 0; i < job_slots; i++)
2956 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
2960 UNBLOCK_CHILD (oset);
2963 /* Mark all dead jobs as notified, so delete_job () cleans them out
2964 of the job table properly. POSIX.2 says we need to save the
2965 status of the last CHILD_MAX jobs, so we count the number of dead
2966 jobs and mark only enough as notified to save CHILD_MAX statuses. */
2968 mark_dead_jobs_as_notified (force)
2971 register int i, ndead;
2976 BLOCK_CHILD (set, oset);
2978 /* Count the number of dead jobs */
2979 for (i = ndead = 0; force == 0 && i < job_slots; i++)
2981 if (jobs[i] && DEADJOB (i))
2985 /* Don't do anything if the number of jobs is less than CHILD_MAX and
2986 we're not forcing a cleanup. */
2987 if (force == 0 && ndead <= CHILD_MAX)
2989 UNBLOCK_CHILD (oset);
2993 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
2994 the list. This isn't exactly right yet; changes need to be made
2995 to stop_pipeline so we don't mark the newer jobs after we've
2996 created CHILD_MAX slots in the jobs array. */
2997 for (i = 0; i < job_slots; i++)
2999 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i) != last_asynchronous_pid)))
3001 jobs[i]->flags |= J_NOTIFIED;
3002 if (force == 0 && --ndead <= CHILD_MAX)
3007 UNBLOCK_CHILD (oset);
3011 /* Here to allow other parts of the shell (like the trap stuff) to
3012 unfreeze the jobs list. */
3014 unfreeze_jobs_list ()
3016 jobs_list_frozen = 0;
3019 /* Allow or disallow job control to take place. Returns the old value
3022 set_job_control (arg)
3032 /* Turn off all traces of job control. This is run by children of the shell
3033 which are going to do shellsy things, like wait (), etc. */
3035 without_job_control ()
3037 stop_making_children ();
3039 delete_all_jobs (0);
3040 set_job_control (0);
3043 /* If this shell is interactive, terminate all stopped jobs and
3044 restore the original terminal process group. This is done
3045 before the `exec' builtin calls shell_execve. */
3049 if (interactive_shell) /* XXX - should it be interactive? */
3051 terminate_stopped_jobs ();
3053 if (original_pgrp >= 0)
3054 give_terminal_to (original_pgrp);
3057 if (original_pgrp >= 0)
3058 setpgid (0, original_pgrp);
3061 /* Restart job control by closing shell tty and reinitializing. This is
3062 called after an exec fails in an interactive shell and we do not exit. */
3064 restart_job_control ()
3066 if (shell_tty != -1)
3068 initialize_job_control (0);
3071 /* Set the handler to run when the shell receives a SIGCHLD signal. */
3073 set_sigchld_handler ()
3075 set_signal_handler (SIGCHLD, sigchld_handler);
3078 #if defined (PGRP_PIPE)
3079 /* Read from the read end of a pipe. This is how the process group leader
3080 blocks until all of the processes in a pipeline have been made. */
3095 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
3100 /* Close the read and write ends of PP, an array of file descriptors. */
3114 /* Functional interface closes our local-to-job-control pipes. */
3118 pipe_close (pgrp_pipe);
3121 #endif /* PGRP_PIPE */
3127 #if defined (ARRAY_VARS)
3129 register PROCESS *p;
3131 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
3136 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
3143 pstatuses[i++] = process_exit_status (p->status);
3146 while (p != jobs[j]->pipe);
3148 pstatuses[i] = -1; /* sentinel */
3149 set_pipestatus_array (pstatuses);