1 /* The thing that makes children, remembers them, and contains wait loops. */
3 /* This file works with both POSIX and BSD systems. */
5 /* Copyright (C) 1989, 1992 Free Software Foundation, Inc.
7 This file is part of GNU Bash, the Bourne Again SHell.
9 Bash is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 1, or (at your option) any later
14 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 You should have received a copy of the GNU General Public License along
20 with Bash; see the file COPYING. If not, write to the Free Software
21 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
23 /* Something that can be ignored. */
24 #define IGNORE_ARG (char *)0
28 #if !defined (JOB_CONTROL)
30 #else /* JOB_CONTROL */
32 #include "bashtypes.h"
38 #if !defined (USG) || defined (HAVE_RESOURCE)
42 #if !defined (_POSIX_VERSION)
43 # if defined (HAVE_RESOURCE)
44 # include <sys/resource.h>
46 #endif /* _POSIX_VERSION */
50 #include <sys/ioctl.h>
51 #include <sys/param.h>
53 #if defined (BUFFERED_INPUT)
57 /* Terminal handling stuff, to save and restore tty state. */
58 #define NEW_TTY_DRIVER
60 /* Define this if your output is getting swallowed. It's a no-op on
61 machines with the termio or termios tty drivers. */
62 /* #define DRAIN_OUTPUT */
64 #if defined (_POSIX_VERSION) && !defined (TERMIOS_MISSING)
65 # undef NEW_TTY_DRIVER
66 # define TERMIOS_TTY_DRIVER
67 # if defined (sun) && !defined (_POSIX_SOURCE) /* XXX - SunOS4, SunOS5? */
68 # define _POSIX_SOURCE
70 #else /* !_POSIX_VERSION */
71 # if defined (USG) || defined (hpux) || defined (Xenix) || defined (sgi)
72 # undef NEW_TTY_DRIVER
73 # define TERMIO_TTY_DRIVER
74 # endif /* USG | hpux | Xenix | sgi */
75 #endif /* !_POSIX_VERSION */
77 /* Include the right header file for the specific type of terminal
78 handler installed on this system. */
79 #if defined (NEW_TTY_DRIVER)
83 #if defined (TERMIO_TTY_DRIVER)
87 #if defined (TERMIOS_TTY_DRIVER)
88 /* For Sun workstations we undefine a couple of defines so that
89 the inclusion of termios.h won't cause complaints. */
96 #endif /* TERMIOS_TTY_DRIVER */
98 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
100 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
102 #endif /* hpux && !TERMIOS_TTY_DRIVER */
104 #include "bashansi.h"
108 #include "builtins/builtext.h"
109 #include "builtins/common.h"
111 /* Not all systems declare errno in errno.h... and some systems #define it! */
116 /* Variables used here but defined in other files. */
117 extern int interactive, interactive_shell, asynchronous_notification;
118 extern int subshell_environment;
119 extern int posixly_correct, no_symbolic_links, shell_level;
120 extern int interrupt_immediately, last_command_exit_value;
121 extern int loop_level, breaking;
122 extern Function *this_shell_builtin;
123 extern char *shell_name, *this_command_name;
124 extern sigset_t top_level_mask;
126 /* The array of known jobs. */
127 JOB **jobs = (JOB **)NULL;
129 /* The number of slots currently allocated to JOBS. */
132 /* The number of additional slots to allocate when we run out. */
135 /* The controlling tty for this shell. */
138 /* The shell's process group. */
139 pid_t shell_pgrp = NO_PID;
141 /* The terminal's process group. */
142 pid_t terminal_pgrp = NO_PID;
144 /* The process group of the shell's parent. */
145 pid_t original_pgrp = NO_PID;
147 /* The process group of the pipeline currently being made. */
148 pid_t pipeline_pgrp = (pid_t)0;
150 #if defined (PGRP_PIPE)
151 /* Pipes which each shell uses to communicate with the process group leader
152 until all of the processes in a pipeline have been started. Then the
153 process leader is allowed to continue. */
154 int pgrp_pipe[2] = { -1, -1 };
157 /* The job which is current; i.e. the one that `%+' stands for. */
158 int current_job = NO_JOB;
160 /* The previous job; i.e. the one that `%-' stands for. */
161 int previous_job = NO_JOB;
163 /* Last child made by the shell. */
164 pid_t last_made_pid = NO_PID;
166 /* Pid of the last asynchronous child. */
167 pid_t last_asynchronous_pid = NO_PID;
169 /* The pipeline currently being built. */
170 PROCESS *the_pipeline = (PROCESS *)NULL;
172 /* If this is non-zero, do job control. */
175 /* Call this when you start making children. */
176 int already_making_children = 0;
178 /* Functions local to this file. */
179 static sighandler flush_child ();
180 static int waitchld();
181 static PROCESS *find_pipeline ();
182 static char *current_working_directory ();
183 static char *job_working_directory ();
184 static pid_t last_pid ();
185 static int set_new_line_discipline (), map_over_jobs (), last_running_job ();
186 static int most_recent_job_in_state (), last_stopped_job (), find_job ();
187 static void notify_of_job_status (), cleanup_dead_jobs (), discard_pipeline ();
188 static void add_process (), set_current_job (), reset_current ();
189 static void pretty_print_job ();
190 static void mark_dead_jobs_as_notified ();
191 #if defined (PGRP_PIPE)
192 static void pipe_read (), pipe_close ();
195 static int waiting_for_job, sigchld;
197 /* Set this to non-zero whenever you don't want the jobs list to change at
198 all: no jobs deleted and no status change notifications. This is used,
199 for example, when executing SIGCHLD traps, which may run arbitrary
201 static int freeze_jobs_list;
203 #if !defined (_POSIX_VERSION)
205 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
206 library functions and system calls. */
207 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
208 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
216 /* ioctl will handle setting errno correctly. */
217 if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
222 /* Perform OPERATION on NEWSET, perhaps leaving information in OLDSET. */
223 sigprocmask (operation, newset, oldset)
224 int operation, *newset, *oldset;
236 old = sigblock (new);
244 internal_error ("Bad code in jobs.c: sigprocmask");
250 #endif /* !_POSIX_VERSION */
252 /* Return the working directory for the current process. Unlike
253 job_working_directory, this does not call malloc (), nor do any
254 of the functions it calls. This is so that it can safely be called
255 from a signal handler. */
257 current_working_directory ()
260 static char d[MAXPATHLEN];
262 dir = get_string_value ("PWD");
264 if (!dir && the_current_working_directory && no_symbolic_links)
265 dir = the_current_working_directory;
275 return ("<unknown>");
280 /* Return the working directory for the current process. */
282 job_working_directory ()
286 dir = get_string_value ("PWD");
288 return (savestring (dir));
290 dir = get_working_directory ("job-working-directory");
294 return (savestring ("<unknown>"));
300 if (already_making_children)
303 already_making_children = 1;
308 stop_making_children ()
310 already_making_children = 0;
314 cleanup_the_pipeline ()
318 discard_pipeline (the_pipeline);
319 the_pipeline = (PROCESS *)NULL;
323 /* Start building a pipeline. */
329 discard_pipeline (the_pipeline);
330 the_pipeline = (PROCESS *)NULL;
332 #if defined (PGRP_PIPE)
333 pipe_close (pgrp_pipe);
337 #if defined (PGRP_PIPE)
340 if (pipe (pgrp_pipe) == -1)
341 internal_error ("start_pipeline: pgrp pipe");
346 /* Stop building a pipeline. Install the process list in the job array.
347 This returns the index of the newly installed job.
348 DEFERRED is a command structure to be executed upon satisfactory
349 execution exit of this pipeline. */
351 stop_pipeline (async, deferred)
356 JOB *newjob = (JOB *)NULL;
359 BLOCK_CHILD (set, oset);
361 #if defined (PGRP_PIPE)
362 /* The parent closes the process group synchronization pipe. */
363 pipe_close (pgrp_pipe);
366 cleanup_dead_jobs ();
371 (JOB **)xmalloc ((job_slots = JOB_SLOTS) * sizeof (JOB *));
373 /* Now blank out these new entries. */
374 for (i = 0; i < job_slots; i++)
375 jobs[i] = (JOB *)NULL;
378 /* Scan from the last slot backward, looking for the next free one. */
381 for (i = job_slots; i; i--)
387 /* If we're not interactive, we don't need to monotonically increase
388 the job number (in fact, we don't care about the job number at all),
389 so we can simply scan for the first free slot. This helps to keep
390 us from continuously reallocating the jobs array when running
391 certain kinds of shell loops, and saves time spent searching. */
392 for (i = 0; i < job_slots; i++)
397 /* Do we need more room? */
400 job_slots += JOB_SLOTS;
401 jobs = (JOB **)xrealloc (jobs, ((1 + job_slots) * sizeof (JOB *)));
403 for (j = i; j < job_slots; j++)
404 jobs[j] = (JOB *)NULL;
407 /* Add the current pipeline to the job list. */
412 newjob = (JOB *)xmalloc (sizeof (JOB));
414 for (p = the_pipeline; p->next != the_pipeline; p = p->next);
415 p->next = (PROCESS *)NULL;
416 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
417 for (p = newjob->pipe; p->next; p = p->next);
418 p->next = newjob->pipe;
420 the_pipeline = (PROCESS *)NULL;
421 newjob->pgrp = pipeline_pgrp;
426 /* Flag to see if in another pgrp. */
428 newjob->flags |= J_JOBCONTROL;
430 /* Set the state of this pipeline. */
432 register PROCESS *p = newjob->pipe;
433 register int any_alive = 0;
434 register int any_stopped = 0;
438 any_alive |= p->running;
439 any_stopped |= WIFSTOPPED (p->status);
442 while (p != newjob->pipe);
446 newjob->state = JRUNNING;
451 newjob->state = JSTOPPED;
453 newjob->state = JDEAD;
457 newjob->wd = job_working_directory ();
458 newjob->deferred = deferred;
466 newjob->flags &= ~J_FOREGROUND;
473 newjob->flags |= J_FOREGROUND;
475 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
477 * The currently-accepted job control wisdom says to set the
478 * terminal's process group n+1 times in an n-step pipeline:
479 * once in the parent and once in each child. This is where
480 * the parent gives it away.
483 if (job_control && newjob->pgrp)
484 give_terminal_to (newjob->pgrp);
488 stop_making_children ();
489 UNBLOCK_CHILD (oset);
490 return (current_job);
493 /* Delete all DEAD jobs that the user had received notification about. */
500 if (!job_slots || freeze_jobs_list)
503 BLOCK_CHILD (set, oset);
505 for (i = 0; i < job_slots; i++)
506 if (jobs[i] && JOBSTATE (i) == JDEAD && (jobs[i]->flags & J_NOTIFIED))
509 UNBLOCK_CHILD (oset);
512 /* Delete the job at INDEX from the job list. Must be called
513 with SIGCHLD blocked. */
515 delete_job (job_index)
520 if (freeze_jobs_list)
523 temp = jobs[job_index];
524 if (job_index == current_job || job_index == previous_job)
527 jobs[job_index] = (JOB *)NULL;
530 discard_pipeline (temp->pipe);
533 dispose_command (temp->deferred);
538 /* Get rid of the data structure associated with a process chain. */
540 discard_pipeline (chain)
541 register PROCESS *chain;
543 register PROCESS *this, *next;
550 free (this->command);
554 while (this != chain);
557 /* Add this process to the chain being built in the_pipeline.
558 NAME is the command string that will be exec'ed later.
559 PID is the process id of the child. */
561 add_process (name, pid)
565 PROCESS *t = (PROCESS *)xmalloc (sizeof (PROCESS));
567 t->next = the_pipeline;
569 WSTATUS (t->status) = 0;
578 register PROCESS *p = t->next;
580 while (p->next != t->next)
587 /* Take the last job and make it the first job. Must be called with
589 rotate_the_pipeline ()
593 if (the_pipeline->next == the_pipeline)
595 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
600 /* Reverse the order of the processes in the_pipeline. Must be called with
602 reverse_the_pipeline ()
606 if (the_pipeline->next == the_pipeline)
609 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
611 p->next = (PROCESS *)NULL;
613 n = REVERSE_LIST (the_pipeline, PROCESS *);
616 for (p = the_pipeline; p->next; p = p->next)
618 p->next = the_pipeline;
622 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
623 then it is time to stop mapping, and that is the return value
624 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
627 map_over_jobs (func, arg1, arg2)
635 BLOCK_CHILD (set, oset);
638 for (i = 0; i < job_slots; i++)
642 result = (*func)(jobs[i], arg1, arg2, i);
648 UNBLOCK_CHILD (oset);
652 /* Cause all the jobs in the current pipeline to exit. */
654 terminate_current_pipeline ()
656 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
658 killpg (pipeline_pgrp, SIGTERM);
659 killpg (pipeline_pgrp, SIGCONT);
663 /* Cause all stopped jobs to exit. */
665 terminate_stopped_jobs ()
669 for (i = 0; i < job_slots; i++)
671 if (jobs[i] && (JOBSTATE (i) == JSTOPPED))
673 killpg (jobs[i]->pgrp, SIGTERM);
674 killpg (jobs[i]->pgrp, SIGCONT);
679 /* Cause all jobs, running or stopped, to receive a hangup signal. */
685 for (i = 0; i < job_slots; i++)
689 killpg (jobs[i]->pgrp, SIGHUP);
690 if (JOBSTATE (i) == JSTOPPED)
691 killpg (jobs[i]->pgrp, SIGCONT);
697 kill_current_pipeline ()
699 stop_making_children ();
703 /* Return the pipeline that PID belongs to. Note that the pipeline
704 doesn't have to belong to a job. Must be called with SIGCHLD blocked. */
711 /* See if this process is in the pipeline that we are building. */
714 register PROCESS *p = the_pipeline;
718 /* Return it if we found it. */
724 while (p != the_pipeline);
727 job = find_job (pid);
730 return ((PROCESS *)NULL);
732 return (jobs[job]->pipe);
735 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
736 belong to any job. Must be called with SIGCHLD blocked. */
744 for (i = 0; i < job_slots; i++)
757 while (p != jobs[i]->pipe);
764 /* Print descriptive information about the job with leader pid PID. */
772 BLOCK_CHILD (set, oset);
774 job = find_job (pid);
777 printf ("[%d] %d\n", job + 1, pid);
779 programming_error ("describe_pid: No such pid (%d)!\n", pid);
781 UNBLOCK_CHILD (oset);
784 /* This is the way to print out information on a job if you
785 know the index. FORMAT is:
787 JLIST_NORMAL) [1]+ Running emacs
788 JLIST_LONG ) [1]+ 2378 Running emacs
791 JLIST_NORMAL) [1]+ Stopped ls | more
792 JLIST_LONG ) [1]+ 2369 Stopped ls
795 Just list the pid of the process group leader (really
798 Use format JLIST_NORMAL, but list only jobs about which
799 the user has not been notified. */
801 pretty_print_job (job_index, format, stream)
802 int job_index, format;
805 register PROCESS *p, *first, *last;
807 char retcode_name_buffer[20];
810 BLOCK_CHILD (set, oset);
812 /* Format only pid information about the process group leader? */
813 if (format == JLIST_PID_ONLY)
815 fprintf (stream, "%d\n", jobs[job_index]->pipe->pid);
816 UNBLOCK_CHILD (oset);
820 if (format == JLIST_CHANGED_ONLY)
822 if (jobs[job_index]->flags & J_NOTIFIED)
824 UNBLOCK_CHILD (oset);
827 format = JLIST_STANDARD;
830 fprintf (stream, "[%d]%c ", job_index + 1,
831 (job_index == current_job) ? '+':
832 (job_index == previous_job) ? '-' : ' ');
834 first = last = p = jobs[job_index]->pipe;
835 while (last->next != first)
838 /* We have printed information about this job. When the job's
839 status changes, waitchld () sets the notification flag to 0. */
840 jobs[job_index]->flags |= J_NOTIFIED;
845 fprintf (stream, format ? " " : " |");
848 fprintf (stream, "%5d", p->pid);
850 fprintf (stream, " ");
854 PROCESS *show = format ? p : last;
857 if (JOBSTATE (job_index) == JSTOPPED && !format)
860 if (JOBSTATE (job_index) == JRUNNING)
864 if (WIFSTOPPED (show->status))
865 temp = strsignal (WSTOPSIG (show->status));
866 else if (WIFSIGNALED (show->status))
867 temp = strsignal (WTERMSIG (show->status));
868 else if (WIFEXITED (show->status))
872 temp = retcode_name_buffer;
873 exit_status = WEXITSTATUS (show->status);
876 strcpy (temp, "Done");
877 else if (posixly_correct)
878 sprintf (temp, "Done(%d)", exit_status);
880 sprintf (temp, "Exit %d", exit_status);
883 temp = "Unknown status";
890 if (show->running == first->running &&
891 WSTATUS (show->status) == WSTATUS (first->status))
900 int templ = strlen (temp);
901 fprintf (stream, "%s", temp);
904 name_padding = LONGEST_SIGNAL_DESC - templ;
906 name_padding = LONGEST_SIGNAL_DESC - 2; /* strlen ("| ") */
908 fprintf (stream, "%*s", name_padding, "");
910 if ((WIFSTOPPED (show->status) == 0) && (WIFCORED (show->status)))
911 fprintf (stream, "(core dumped) ");
915 if (p != first && format)
916 fprintf (stream, "| ");
919 fprintf (stream, "%s", p->command);
923 char *wd = current_working_directory ();
925 if (JOBSTATE (job_index) == JRUNNING &&
926 !(jobs[job_index]->flags & J_FOREGROUND))
927 fprintf (stream, " &");
929 if (strcmp (wd, jobs[job_index]->wd) != 0)
931 " (wd: %s)", polite_directory_format (jobs[job_index]->wd));
934 if (format || (p == last))
935 fprintf (stream, "\r\n");
943 UNBLOCK_CHILD (oset);
947 list_one_job (job, format, ignore, job_index)
949 int format, ignore, job_index;
951 pretty_print_job (job_index, format, stdout);
955 /* List jobs. If FORMAT is non-zero, then the long form of the information
956 is printed, else just a short version. */
961 cleanup_dead_jobs ();
962 map_over_jobs (list_one_job, format, (int)IGNORE_ARG);
965 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
966 COMMAND is just for remembering the name of the command; we don't do
967 anything else with it. ASYNC_P says what to do with the tty. If
968 non-zero, then don't give it away. */
970 make_child (command, async_p)
978 sigaddset (&set, SIGCHLD);
979 sigaddset (&set, SIGINT);
981 sigprocmask (SIG_BLOCK, &set, &oset);
985 #if defined (BUFFERED_INPUT)
986 /* If default_buffered_input is active, we are reading a script. If
987 the command is asynchronous, we have already duplicated /dev/null
988 as fd 0, but have not changed the buffered stream corresponding to
989 the old fd 0. We don't want to sync the stream in this case. */
990 if (default_buffered_input != -1 &&
991 (!async_p || default_buffered_input > 0))
992 sync_buffered_stream (default_buffered_input);
993 #endif /* BUFFERED_INPUT */
995 /* Create the child, handle severe errors. */
996 if ((pid = fork ()) < 0)
998 internal_error ("fork: %s", strerror (errno));
1000 /* Kill all of the processes in the current pipeline. */
1001 terminate_current_pipeline ();
1003 /* Discard the current pipeline, if any. */
1005 kill_current_pipeline ();
1007 throw_to_top_level (); /* Reset signals, etc. */
1012 /* In the child. Give this child the right process group, set the
1013 signals to the default state for a new process. */
1014 pid_t mine = getpid ();
1016 #if defined (BUFFERED_INPUT)
1017 /* Close default_buffered_input if it's > 0. We don't close it if it's
1018 0 because that's the file descriptor used when redirecting input,
1019 and it's wrong to close the file in that case. */
1020 if (default_buffered_input > 0)
1022 close_buffered_fd (default_buffered_input);
1023 default_buffered_input = bash_input.location.buffered_fd = -1;
1025 #endif /* BUFFERED_INPUT */
1027 /* Restore top-level signal mask. */
1028 sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
1032 /* All processes in this pipeline belong in the same
1035 if (!pipeline_pgrp) /* Then this is the first child. */
1036 pipeline_pgrp = mine;
1038 /* Check for running command in backquotes. */
1039 if (pipeline_pgrp == shell_pgrp)
1041 set_signal_handler (SIGTSTP, SIG_IGN);
1042 set_signal_handler (SIGTTOU, SIG_IGN);
1043 set_signal_handler (SIGTTIN, SIG_IGN);
1047 set_signal_handler (SIGTSTP, SIG_DFL);
1048 set_signal_handler (SIGTTOU, SIG_DFL);
1049 set_signal_handler (SIGTTIN, SIG_DFL);
1052 /* Set the process group before trying to mess with the terminal's
1053 process group. This is mandated by POSIX. */
1054 /* This is in accordance with the Posix 1003.1 standard,
1055 section B.7.2.4, which says that trying to set the terminal
1056 process group with tcsetpgrp() to an unused pgrp value (like
1057 this would have for the first child) is an error. Section
1058 B.4.3.3, p. 237 also covers this, in the context of job control
1060 if (setpgid (mine, pipeline_pgrp) < 0)
1061 internal_error ("child setpgid (%d to %d) error %d: %s\n",
1062 mine, pipeline_pgrp, errno, strerror (errno));
1063 #if defined (PGRP_PIPE)
1064 if (pipeline_pgrp == mine)
1068 give_terminal_to (pipeline_pgrp);
1070 #if defined (PGRP_PIPE)
1071 pipe_read (pgrp_pipe);
1075 else /* Without job control... */
1078 pipeline_pgrp = shell_pgrp;
1080 /* If these signals are set to SIG_DFL, we encounter the curious
1081 situation of an interactive ^Z to a running process *working*
1082 and stopping the process, but being unable to do anything with
1083 that process to change its state. On the other hand, if they
1084 are set to SIG_IGN, jobs started from scripts do not stop when
1085 the shell running the script gets a SIGTSTP and stops. */
1087 set_signal_handler (SIGTSTP, SIG_DFL);
1088 set_signal_handler (SIGTTOU, SIG_DFL);
1089 set_signal_handler (SIGTTIN, SIG_DFL);
1092 #if defined (PGRP_PIPE)
1093 /* Release the process group pipe, since our call to setpgid ()
1094 is done. The last call to pipe_close is done in stop_pipeline. */
1095 pipe_close (pgrp_pipe);
1096 #endif /* PGRP_PIPE */
1099 last_asynchronous_pid = getpid ();
1103 /* In the parent. Remember the pid of the child just created
1104 as the proper pgrp if this is the first child. */
1110 pipeline_pgrp = pid;
1111 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1112 not the good thing of twiddling them in the child! */
1113 /* give_terminal_to (pipeline_pgrp); */
1115 /* This is done on the recommendation of the Rationale section of
1116 the POSIX 1003.1 standard, where it discusses job control and
1117 shells. It is done to avoid possible race conditions. (Ref.
1118 1003.1 Rationale, section B.4.3.3, page 236). */
1119 setpgid (pid, pipeline_pgrp);
1124 pipeline_pgrp = shell_pgrp;
1127 /* Place all processes into the jobs array regardless of the
1128 state of job_control. */
1129 add_process (command, pid);
1132 last_asynchronous_pid = pid;
1134 last_made_pid = pid;
1136 /* Unblock SIGINT and SIGCHLD. */
1137 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
1143 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1144 state kept in here. When a job ends normally, we set the state in here
1145 to the state of the tty. */
1147 #if defined (NEW_TTY_DRIVER)
1148 static struct sgttyb shell_tty_info;
1149 static struct tchars shell_tchars;
1150 static struct ltchars shell_ltchars;
1151 #endif /* NEW_TTY_DRIVER */
1153 #if defined (TERMIO_TTY_DRIVER)
1154 static struct termio shell_tty_info;
1155 #endif /* TERMIO_TTY_DRIVER */
1157 #if defined (TERMIOS_TTY_DRIVER)
1158 static struct termios shell_tty_info;
1159 #endif /* TERMIOS_TTY_DRIVER */
1161 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1162 /* Since the BSD tty driver does not allow us to change the tty modes
1163 while simultaneously waiting for output to drain and preserving
1164 typeahead, we have to drain the output ourselves before calling
1165 ioctl. We cheat by finding the length of the output queue, and
1166 using select to wait for an appropriate length of time. This is
1167 a hack, and should be labeled as such (it's a hastily-adapted
1168 mutation of a `usleep' implementation). It's only reason for
1169 existing is the flaw in the BSD tty driver. */
1171 static int ttspeeds[] =
1173 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1174 1800, 2400, 4800, 9600, 19200, 38400
1181 register int delay = ttspeeds[ospeed];
1187 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
1189 if (n > (delay / 100))
1193 n *= 10; /* 2 bits more for conservativeness. */
1194 tv.tv_sec = n / delay;
1195 tv.tv_usec = ((n % delay) * 1000000) / delay;
1196 select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
1202 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1204 /* Return the fd from which we are actually getting input. */
1205 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1207 /* Fill the contents of shell_tty_info with the current tty info. */
1210 int tty = input_tty ();
1214 #if defined (NEW_TTY_DRIVER)
1215 ioctl (tty, TIOCGETP, &shell_tty_info);
1216 ioctl (tty, TIOCGETC, &shell_tchars);
1217 ioctl (tty, TIOCGLTC, &shell_ltchars);
1218 #endif /* NEW_TTY_DRIVER */
1220 #if defined (TERMIO_TTY_DRIVER)
1221 ioctl (tty, TCGETA, &shell_tty_info);
1222 #endif /* TERMIO_TTY_DRIVER */
1224 #if defined (TERMIOS_TTY_DRIVER)
1225 if (tcgetattr (tty, &shell_tty_info) < 0)
1228 /* Only print an error message if we're really interactive at
1231 internal_error ("[%d: %d] tcgetattr: %s",
1232 getpid (), shell_level, strerror (errno));
1236 #endif /* TERMIOS_TTY_DRIVER */
1241 /* Make the current tty use the state in shell_tty_info. */
1244 int tty = input_tty ();
1248 #if defined (NEW_TTY_DRIVER)
1249 # if defined (DRAIN_OUTPUT)
1250 draino (tty, shell_tty_info.sg_ospeed);
1251 # endif /* DRAIN_OUTPUT */
1252 ioctl (tty, TIOCSETN, &shell_tty_info);
1253 ioctl (tty, TIOCSETC, &shell_tchars);
1254 ioctl (tty, TIOCSLTC, &shell_ltchars);
1255 #endif /* NEW_TTY_DRIVER */
1257 #if defined (TERMIO_TTY_DRIVER)
1258 ioctl (tty, TCSETAW, &shell_tty_info);
1259 #endif /* TERMIO_TTY_DRIVER */
1261 #if defined (TERMIOS_TTY_DRIVER)
1262 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
1264 /* Only print an error message if we're really interactive at
1267 internal_error ("[%d: %d] tcsetattr: %s",
1268 getpid (), shell_level, strerror (errno));
1271 #endif /* TERMIOS_TTY_DRIVER */
1276 /* Given an index into the jobs array JOB, return the pid of the last
1277 process in that job's pipeline. This is the one whose exit status
1283 register PROCESS *p;
1286 BLOCK_CHILD (set, oset);
1288 p = jobs[job]->pipe;
1289 while (p->next != jobs[job]->pipe)
1292 UNBLOCK_CHILD (oset);
1296 /* Wait for a particular child of the shell to finish executing.
1297 This low-level function prints an error message if PID is not
1298 a child of this shell. It returns -1 if it fails, or 0 if not. */
1300 wait_for_single_pid (pid)
1303 register PROCESS *child;
1308 BLOCK_CHILD (set, oset);
1309 child = find_pipeline (pid);
1310 UNBLOCK_CHILD (oset);
1315 report_error ("wait: pid %d is not a child of this shell", pid);
1319 return (wait_for (pid));
1322 /* Wait for all of the backgrounds of this shell to finish. */
1324 wait_for_background_pids ()
1328 register int i, count = 0;
1331 BLOCK_CHILD (set, oset);
1333 for (i = 0; i < job_slots; i++)
1334 if (jobs[i] && (JOBSTATE (i) == JRUNNING) &&
1335 (jobs[i]->flags & J_FOREGROUND) == 0)
1343 UNBLOCK_CHILD (oset);
1347 for (i = 0; i < job_slots; i++)
1348 if (jobs[i] && (JOBSTATE (i) == JRUNNING) &&
1349 (jobs[i]->flags & J_FOREGROUND) == 0)
1351 pid_t pid = last_pid (i);
1352 UNBLOCK_CHILD (oset);
1354 wait_for_single_pid (pid);
1360 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
1361 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
1362 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
1365 restore_sigint_handler ()
1367 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
1369 set_signal_handler (SIGINT, old_sigint_handler);
1370 old_sigint_handler = INVALID_SIGNAL_HANDLER;
1374 static int wait_sigint_received = 0;
1376 /* Handle SIGINT while we are waiting for children in a script to exit.
1377 The `wait' builtin should be interruptible, but all others should be
1378 effectively ignored (i.e. not cause the shell to exit). */
1380 wait_sigint_handler (sig)
1383 if (interrupt_immediately ||
1384 (this_shell_builtin && this_shell_builtin == wait_builtin))
1386 last_command_exit_value = EXECUTION_FAILURE;
1387 restore_sigint_handler ();
1392 wait_sigint_received = 1; /* XXX - should this be interrupt_state? */
1393 /* Otherwise effectively ignore the SIGINT and allow the running job to
1395 #if !defined (VOID_SIGHANDLER)
1397 #endif /* !VOID_SIGHANDLER */
1401 process_exit_status (status)
1404 if (WIFSIGNALED (status))
1405 return (128 + WTERMSIG (status));
1406 else if (!WIFSTOPPED (status))
1407 return (WEXITSTATUS (status));
1409 return (EXECUTION_SUCCESS);
1412 /* Wait for pid (one of our children) to terminate, then
1413 return the termination state. */
1418 int job, termination_state;
1419 register PROCESS *child;
1422 /* In the case that this code is interrupted, and we longjmp () out of it,
1423 we are relying on the code in throw_to_top_level () to restore the
1424 top-level signal mask. */
1425 BLOCK_CHILD (set, oset);
1427 /* Ignore interrupts while waiting for a job run without job control
1428 to finish. We don't want the shell to exit if an interrupt is
1429 received, only if one of the jobs run is killed via SIGINT. If
1430 job control is not set, the job will be run in the same pgrp as
1431 the shell, and the shell will see any signals the job gets. */
1433 /* This is possibly a race condition -- should it go in stop_pipeline? */
1434 wait_sigint_received = 0;
1436 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
1438 termination_state = last_command_exit_value;
1440 /* If we say wait_for (), then we have a record of this child somewhere.
1441 If this child and all of its peers are not running, then don't
1442 sigpause (), since there is no need to. */
1445 /* If the shell is interactive, and job control is disabled, see if the
1446 foreground process has died due to SIGINT and jump out of the wait
1447 loop if it has. waitchld has already restored the old SIGINT
1449 if (interactive && !job_control)
1452 child = find_pipeline (pid);
1456 give_terminal_to (shell_pgrp);
1457 UNBLOCK_CHILD (oset);
1458 programming_error ("wait_for: No record of pid %d", pid);
1461 /* If this child is part of a job, then we are really waiting for the
1462 job to finish. Otherwise, we are waiting for the child to finish. */
1464 job = find_job (pid);
1468 register int job_state = 0, any_stopped = 0;
1469 register PROCESS *p = jobs[job]->pipe;
1473 job_state |= p->running;
1475 any_stopped |= WIFSTOPPED (p->status);
1478 while (p != jobs[job]->pipe);
1483 jobs[job]->state = JSTOPPED;
1485 jobs[job]->state = JDEAD;
1489 if (child->running || ((job != NO_JOB) && (JOBSTATE (job) == JRUNNING)))
1491 #if defined (WAITPID_BROKEN) /* SCOv4 */
1492 sigset_t suspend_set;
1493 sigemptyset (&suspend_set);
1494 sigsuspend (&suspend_set);
1495 #else /* !WAITPID_BROKEN */
1496 # if defined (MUST_UNBLOCK_CHILD) /* SCO */
1497 struct sigaction act, oact;
1498 sigset_t nullset, chldset;
1500 sigemptyset (&nullset);
1501 sigemptyset (&chldset);
1502 sigprocmask (SIG_SETMASK, &nullset, &chldset);
1503 act.sa_handler = SIG_DFL;
1504 sigemptyset (&act.sa_mask);
1505 sigemptyset (&oact.sa_mask);
1507 sigaction (SIGCHLD, &act, &oact);
1509 waiting_for_job = 1;
1511 waiting_for_job = 0;
1512 # if defined (MUST_UNBLOCK_CHILD)
1513 sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
1514 sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
1516 #endif /* !WAITPID_BROKEN */
1520 /* The exit state of the command is either the termination state of the
1521 child, or the termination state of the job. If a job, the status
1522 of the last child in the pipeline is the significant one. */
1526 register PROCESS *p = jobs[job]->pipe;
1528 while (p->next != jobs[job]->pipe)
1530 termination_state = process_exit_status (p->status);
1533 termination_state = process_exit_status (child->status);
1535 if (job == NO_JOB || (jobs[job]->flags & J_JOBCONTROL))
1536 give_terminal_to (shell_pgrp);
1538 /* If the command did not exit cleanly, or the job is just
1539 being stopped, then reset the tty state back to what it
1540 was before this command. Reset the tty state and notify
1541 the user of the job termination only if the shell is
1542 interactive. Clean up any dead jobs in either case. */
1545 if (interactive_shell && !subshell_environment)
1547 if (WIFSIGNALED (child->status) || WIFSTOPPED (child->status))
1552 /* If job control is enabled, the job was started with job
1553 control, the job was the foreground job, and it was killed
1554 by SIGINT, then print a newline to compensate for the kernel
1555 printing the ^C without a trailing newline. */
1556 if (job_control && (jobs[job]->flags & J_JOBCONTROL) &&
1557 (jobs[job]->flags & J_FOREGROUND) &&
1558 WIFSIGNALED (child->status) &&
1559 WTERMSIG (child->status) == SIGINT)
1561 /* If SIGINT is not trapped, set the interrupt state if in a
1562 loop so the loop will be broken. If not in a loop, print
1563 the newline that the kernel does not. */
1564 if (signal_is_trapped (SIGINT) == 0)
1576 notify_and_cleanup ();
1580 /* If this job is dead, and the shell is not interactive, make
1581 sure we turn on the notify bit so we don't get an unwanted
1582 message about the job's termination, and so delete_job really
1583 clears the slot in the jobs table. */
1584 if (JOBSTATE(job) == JDEAD)
1585 jobs[job]->flags |= J_NOTIFIED;
1586 cleanup_dead_jobs ();
1590 UNBLOCK_CHILD (oset);
1592 /* Restore the original SIGINT signal handler before we return. */
1593 restore_sigint_handler ();
1595 return (termination_state);
1598 /* Wait for the last process in the pipeline for JOB. */
1603 pid_t pid = last_pid (job);
1604 return (wait_for (pid));
1607 /* Print info about dead jobs, and then delete them from the list
1608 of known jobs. This does not actually delete jobs when the
1609 shell is not interactive, because the dead jobs are not marked
1612 notify_and_cleanup ()
1614 if (freeze_jobs_list)
1618 notify_of_job_status ();
1620 cleanup_dead_jobs ();
1623 /* Make dead jobs disappear from the jobs array without notification.
1624 This is used when the shell is not interactive. */
1628 mark_dead_jobs_as_notified ();
1629 cleanup_dead_jobs ();
1632 /* Return the next closest (chronologically) job to JOB which is in
1633 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
1634 there is no next recent job. */
1636 most_recent_job_in_state (job, state)
1640 register int i, result;
1643 BLOCK_CHILD (set, oset);
1646 for (i = job - 1; i >= 0; i--)
1650 if (JOBSTATE (i) == state)
1657 UNBLOCK_CHILD (oset);
1661 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
1664 last_stopped_job (job)
1667 return (most_recent_job_in_state (job, JSTOPPED));
1670 /* Return the newest *running* job older than JOB, or NO_JOB if not
1673 last_running_job (job)
1676 return (most_recent_job_in_state (job, JRUNNING));
1679 /* Make JOB be the current job, and make previous be useful. Must be
1680 called with SIGCHLD blocked. */
1682 set_current_job (job)
1685 int candidate = NO_JOB;
1687 if (current_job != job)
1689 previous_job = current_job;
1693 /* First choice for previous_job is the old current_job. */
1694 if (previous_job != current_job &&
1695 previous_job != NO_JOB &&
1696 jobs[previous_job] &&
1697 JOBSTATE (previous_job) == JSTOPPED)
1700 /* Second choice: Newest stopped job that is older than
1702 if (JOBSTATE (current_job) == JSTOPPED)
1704 candidate = last_stopped_job (current_job);
1706 if (candidate != NO_JOB)
1708 previous_job = candidate;
1713 /* If we get here, there is either only one stopped job, in which case it is
1714 the current job and the previous job should be set to the newest running
1715 job, or there are only running jobs and the previous job should be set to
1716 the newest running job older than the current job. We decide on which
1717 alternative to use based on whether or not JOBSTATE(current_job) is
1720 if (JOBSTATE (current_job) == JRUNNING)
1721 candidate = last_running_job (current_job);
1723 candidate = last_running_job (job_slots);
1725 if (candidate != NO_JOB)
1727 previous_job = candidate;
1731 /* There is only a single job, and it is both `+' and `-'. */
1732 previous_job = current_job;
1735 /* Make current_job be something useful, if it isn't already. */
1737 /* Here's the deal: The newest non-running job should be `+', and the
1738 next-newest non-running job should be `-'. If there is only a single
1739 stopped job, the previous_job is the newest non-running job. If there
1740 are only running jobs, the newest running job is `+' and the
1741 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
1745 int candidate = NO_JOB;
1747 if (current_job != NO_JOB &&
1748 job_slots && jobs[current_job] &&
1749 JOBSTATE (current_job) == JSTOPPED)
1751 candidate = current_job;
1755 /* First choice: the previous job! */
1756 if (previous_job != NO_JOB && jobs[previous_job] &&
1757 JOBSTATE (previous_job) == JSTOPPED)
1758 candidate = previous_job;
1760 /* Second choice: the most recently stopped job. */
1761 if (candidate == NO_JOB)
1762 candidate = last_stopped_job (job_slots);
1764 if (candidate == NO_JOB)
1766 /* Third choice: the newest running job. */
1767 candidate = last_running_job (job_slots);
1771 /* If we found a job to use, then use it. Otherwise, there
1772 are no jobs period. */
1773 if (candidate != NO_JOB)
1774 set_current_job (candidate);
1776 current_job = previous_job = NO_JOB;
1779 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
1780 start the job in the background. JOB is a zero-based index into
1781 JOBS. Returns -1 if it is unable to start a job, and the return
1782 status of the job otherwise. */
1784 start_job (job, foreground)
1785 int job, foreground;
1787 register PROCESS *p;
1788 int already_running;
1791 #if defined (NEW_TTY_DRIVER)
1792 static struct sgttyb save_stty;
1795 #if defined (TERMIO_TTY_DRIVER)
1796 static struct termio save_stty;
1799 #if defined (TERMIOS_TTY_DRIVER)
1800 static struct termios save_stty;
1803 BLOCK_CHILD (set, oset);
1804 already_running = (JOBSTATE (job) == JRUNNING);
1806 if (JOBSTATE (job) == JDEAD)
1808 report_error ("%s: job has terminated", this_command_name);
1809 UNBLOCK_CHILD (oset);
1813 if (!foreground && already_running)
1815 report_error ("%s: bg background job?", this_command_name);
1816 UNBLOCK_CHILD (oset);
1820 wd = current_working_directory ();
1822 /* You don't know about the state of this job. Do you? */
1823 jobs[job]->flags &= ~J_NOTIFIED;
1827 set_current_job (job);
1828 jobs[job]->flags |= J_FOREGROUND;
1831 /* Tell the outside world what we're doing. */
1832 p = jobs[job]->pipe;
1835 fprintf (stderr, "[%d]%c ", job + 1,
1836 (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
1840 fprintf (stderr, "%s%s",
1841 p->command ? p->command : "",
1842 p->next != jobs[job]->pipe? " | " : "");
1845 while (p != jobs[job]->pipe);
1848 fprintf (stderr, " &");
1850 if (strcmp (wd, jobs[job]->wd) != 0)
1851 fprintf (stderr, " (wd: %s)", polite_directory_format (jobs[job]->wd));
1853 fprintf (stderr, "\n");
1856 if (!already_running)
1858 /* Each member of the pipeline is now running. */
1859 p = jobs[job]->pipe;
1863 if (WIFSTOPPED (p->status))
1867 while (p != jobs[job]->pipe);
1869 /* This means that the job is running. */
1870 JOBSTATE (job) = JRUNNING;
1873 /* Save the tty settings before we start the job in the foreground. */
1877 save_stty = shell_tty_info;
1880 /* Give the terminal to this job. */
1883 if (jobs[job]->flags & J_JOBCONTROL)
1884 give_terminal_to (jobs[job]->pgrp);
1887 jobs[job]->flags &= ~J_FOREGROUND;
1889 /* If the job is already running, then don't bother jump-starting it. */
1890 if (!already_running)
1892 jobs[job]->flags |= J_NOTIFIED;
1893 killpg (jobs[job]->pgrp, SIGCONT);
1896 UNBLOCK_CHILD (oset);
1900 pid_t pid = last_pid (job);
1901 int s = wait_for (pid);
1903 shell_tty_info = save_stty;
1909 BLOCK_CHILD (set, oset);
1911 UNBLOCK_CHILD (oset);
1916 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
1917 If PID does belong to a job, and the job is stopped, then CONTinue the
1918 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
1919 then kill the process group associated with PID. */
1921 kill_pid (pid, sig, group)
1925 register PROCESS *p;
1926 int job, result = EXECUTION_SUCCESS;
1929 BLOCK_CHILD (set, oset);
1930 p = find_pipeline (pid);
1931 job = find_job (pid);
1937 jobs[job]->flags &= ~J_NOTIFIED;
1939 /* Kill process in backquotes or one started without job control? */
1940 if (jobs[job]->pgrp == shell_pgrp)
1942 p = jobs[job]->pipe;
1947 if (p->running == 0 && (sig == SIGTERM || sig == SIGHUP))
1948 kill (p->pid, SIGCONT);
1951 while (p != jobs[job]->pipe);
1955 result = killpg (jobs[job]->pgrp, sig);
1956 if (p && (JOBSTATE (job) == JSTOPPED) &&
1957 (sig == SIGTERM || sig == SIGHUP))
1958 killpg (jobs[job]->pgrp, SIGCONT);
1962 result = killpg (pid, sig);
1965 result = kill (pid, sig);
1967 UNBLOCK_CHILD (oset);
1971 /* Take care of system dependencies that must be handled when waiting for
1972 children. The arguments to the WAITPID macro match those to the Posix.1
1973 waitpid() function. */
1975 #if defined (Ultrix) && defined (mips) && defined (_POSIX_VERSION)
1976 # define WAITPID(pid, statusp, options) \
1977 wait3 ((union wait *)statusp, options, (struct rusage *)0)
1979 # if defined (_POSIX_VERSION)
1980 # define WAITPID(pid, statusp, options) \
1981 waitpid ((pid_t)pid, statusp, options)
1984 # define WAITPID(pid, statusp, options) \
1985 wait3 (statusp, options, (int *)0)
1987 # define WAITPID(pid, statusp, options) \
1988 wait3 (statusp, options, (struct rusage *)0)
1990 # endif /* !_POSIX_VERSION */
1991 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
1993 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
1994 handler for SIGCHLD. */
1996 #if defined (hpux) && !defined (_POSIX_VERSION)
1997 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, flush_child)
1999 # define REINSTALL_SIGCHLD_HANDLER
2000 #endif /* !hpux || _POSIX_VERSION */
2002 /* Flush_child () flushes at least one of the children that we are waiting for.
2003 It gets run when we have gotten a SIGCHLD signal, and stops when there
2004 aren't any children terminating any more. If SIG is 0, this is to be a
2005 blocking wait for a single child. */
2010 REINSTALL_SIGCHLD_HANDLER;
2012 if (waiting_for_job == 0)
2015 #if !defined (VOID_SIGHANDLER)
2017 #endif /* VOID_SIGHANDLER */
2027 int call_set_current = 0, last_stopped_job = NO_JOB;
2028 int children_exited = 0, flag;
2035 pid = WAITPID (-1, &status, flag);
2036 if (sigchld && (flag & WNOHANG))
2041 /* Locate our PROCESS for this pid. */
2042 child = find_pipeline (pid);
2044 /* It is not an error to have a child terminate that we did
2045 not have a record of. This child could have been part of
2046 a pipeline in backquote substitution. */
2049 int job = find_job (pid);
2051 while (child->pid != pid)
2052 child = child->next;
2054 /* Remember status, and fact that process is not running. */
2055 child->status = status;
2061 int any_stopped = 0;
2064 child = jobs[job]->pipe;
2065 jobs[job]->flags &= ~J_NOTIFIED;
2067 /* If all children are not running, but any of them is
2068 stopped, then the job is stopped, not dead. */
2071 job_state |= child->running;
2072 if (!child->running)
2074 any_stopped |= WIFSTOPPED (child->status);
2075 any_tstped |= interactive && job_control &&
2076 WIFSTOPPED (child->status) &&
2077 WSTOPSIG (child->status) == SIGTSTP;
2079 child = child->next;
2081 while (child != jobs[job]->pipe);
2087 jobs[job]->state = JSTOPPED;
2088 jobs[job]->flags &= ~J_FOREGROUND;
2090 last_stopped_job = job;
2091 /* Suspending a job in a loop from the keyboard
2092 breaks out of all active loops. */
2093 if (any_tstped && loop_level)
2094 breaking = loop_level;
2098 jobs[job]->state = JDEAD;
2100 if (job == last_stopped_job)
2101 last_stopped_job = NO_JOB;
2103 /* If the foreground job is killed by SIGINT when
2104 job control is not active, we need to perform
2105 some special handling. */
2106 /* The check of wait_sigint_received is a way to
2107 determine if the SIGINT came from the keyboard
2108 (in which case the shell has already seen it,
2109 and wait_sigint_received is non-zero, because
2110 keyboard signals are sent to process groups)
2111 or via kill(2) to the foreground process by
2112 another process (or itself). If the shell did
2113 receive the SIGINT, it needs to perform normal
2114 SIGINT processing. */
2115 if ((WTERMSIG (jobs[job]->pipe->status) == SIGINT) &&
2116 (jobs[job]->flags & J_FOREGROUND) &&
2117 (jobs[job]->flags & J_JOBCONTROL) == 0 &&
2118 wait_sigint_received)
2120 wait_sigint_received = 0;
2122 /* If SIGINT is trapped, set the exit status so
2123 that the trap handler can see it. */
2124 if (signal_is_trapped (SIGINT))
2125 last_command_exit_value = process_exit_status
2126 (jobs[job]->pipe->status);
2128 /* If the signal is trapped, let the trap handler
2129 get it no matter what and simply return if
2130 the trap handler returns.
2131 maybe_call_trap_handler may cause dead jobs
2132 to be removed from the job table because of
2133 a call to execute_command. Watch out for
2135 if (maybe_call_trap_handler (SIGINT) == 0 &&
2136 old_sigint_handler != INVALID_SIGNAL_HANDLER)
2138 /* wait_sigint_handler () has already
2139 seen SIGINT and allowed the wait
2140 builtin to jump out. We need to
2141 call the original SIGINT handler. */
2142 SigHandler *temp_handler;
2143 temp_handler = old_sigint_handler;
2144 restore_sigint_handler ();
2145 if (temp_handler != SIG_IGN)
2146 (*temp_handler) (SIGINT);
2153 /* If we have caught a child, and a trap was set for SIGCHLD, then
2154 bump up the count of the number of children that have exited,
2155 so we know how many times to call it. */
2159 while ((s || sigchld) && pid > (pid_t)0);
2161 /* If a job was running and became stopped, then set the current
2162 job. Otherwise, don't change a thing. */
2163 if (call_set_current)
2164 if (last_stopped_job != NO_JOB)
2165 set_current_job (last_stopped_job);
2169 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
2170 if (job_control && signal_is_trapped (SIGCHLD) &&
2171 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
2175 /* Turn off the trap list during the call to parse_and_execute ()
2176 to avoid potentially infinite recursive calls. Preserve the
2177 values of last_command_exit_value, last_made_pid, and the_pipeline
2178 around the execution of the trap commands. */
2179 trap_command = savestring (trap_list[SIGCHLD]);
2181 begin_unwind_frame ("SIGCHLD trap");
2182 unwind_protect_int (last_command_exit_value);
2183 unwind_protect_int (last_made_pid);
2184 unwind_protect_int (interrupt_immediately);
2185 unwind_protect_int (freeze_jobs_list);
2186 unwind_protect_pointer (the_pipeline);
2188 /* We have to add the commands this way because they will be run
2189 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
2190 to reference freed memory. */
2191 add_unwind_protect ((Function *)xfree, trap_command);
2192 add_unwind_protect ((Function *)maybe_set_sigchld_trap, trap_command);
2194 the_pipeline = (PROCESS *)NULL;
2195 restore_default_signal (SIGCHLD);
2196 freeze_jobs_list = 1;
2197 while (children_exited--)
2199 interrupt_immediately = 1;
2200 parse_and_execute (savestring (trap_command), "trap", -1);
2203 run_unwind_frame ("SIGCHLD trap");
2206 /* We have successfully recorded the useful information about this process
2207 that has just changed state. If we notify asynchronously, and the job
2208 that this process belongs to is no longer running, then notify the user
2209 of that fact now. */
2210 if (asynchronous_notification && interactive)
2211 notify_of_job_status ();
2215 /* Function to call when you want to notify people of changes
2216 in job status. This prints out all jobs which are pending
2217 notification to stderr, and marks those printed as already
2218 notified, thus making them candidates for cleanup. */
2220 notify_of_job_status ()
2222 register int job, termsig;
2227 sigaddset (&set, SIGCHLD);
2228 sigaddset (&set, SIGTTOU);
2229 sigemptyset (&oset);
2230 sigprocmask (SIG_BLOCK, &set, &oset);
2234 for (job = 0; job < job_slots; job++)
2236 if (jobs[job] && (jobs[job]->flags & J_NOTIFIED) == 0)
2240 s = jobs[job]->pipe->status;
2241 termsig = WTERMSIG (s);
2243 /* If job control is disabled, don't print the status messages.
2244 Mark dead jobs as notified so that they get cleaned up. */
2247 if (JOBSTATE (job) == JDEAD)
2248 jobs[job]->flags |= J_NOTIFIED;
2252 switch (JOBSTATE (job))
2254 /* Print info on jobs that are running in the background,
2255 and on foreground jobs that were killed by anything
2260 if (jobs[job]->flags & J_FOREGROUND)
2262 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
2264 fprintf (stderr, "%s", strsignal (termsig));
2267 fprintf (stderr, " (core dumped)");
2269 fprintf (stderr, "\n");
2275 dir = current_working_directory ();
2276 pretty_print_job (job, 0, stderr);
2277 if (dir && strcmp (dir, jobs[job]->wd) != 0)
2279 "(wd now: %s)\n", polite_directory_format (dir));
2282 jobs[job]->flags |= J_NOTIFIED;
2286 fprintf (stderr, "\n");
2288 dir = current_working_directory ();
2289 pretty_print_job (job, 0, stderr);
2290 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
2292 "(wd now: %s)\n", polite_directory_format (dir));
2293 jobs[job]->flags |= J_NOTIFIED;
2301 programming_error ("notify_of_job_status");
2305 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2308 /* getpgrp () varies between systems. Even systems that claim to be
2309 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
2310 #if defined (_POSIX_VERSION) && !defined (BSD_GETPGRP)
2311 # define getpgid(p) getpgrp ()
2313 # define getpgid(p) getpgrp (p)
2314 #endif /* !_POSIX_VERSION || BSD_GETPGRP */
2316 /* Initialize the job control mechanism, and set up the tty stuff. */
2319 shell_pgrp = getpgid (0);
2321 if (shell_pgrp == -1)
2323 internal_error ("initialize_jobs: getpgrp failed: %s", strerror (errno));
2327 /* We can only have job control if we are interactive?
2328 I guess that makes sense. */
2333 original_pgrp = NO_PID;
2337 /* Make sure that we are using the new line discipline. */
2339 /* Get our controlling terminal. If job_control is set, or
2340 interactive is set, then this is an interactive shell no
2342 shell_tty = dup (fileno (stderr));
2344 /* Find the highest unused file descriptor we can. */
2346 int ignore, nds = getdtablesize ();
2355 if (fcntl (nds, F_GETFD, &ignore) == -1)
2359 if (nds && shell_tty != nds && (dup2 (shell_tty, nds) != -1))
2361 if (shell_tty != fileno (stderr))
2367 #if defined (RLOGIN_PGRP_BUG)
2368 /* Compensate for a bug in systems that compiled the BSD
2369 /usr/etc/rlogind with DEBUG defined, like NeXT and Alliant. */
2370 if (shell_pgrp == 0)
2372 shell_pgrp = getpid ();
2373 setpgid (0, shell_pgrp);
2374 tcsetpgrp (shell_tty, shell_pgrp);
2376 #endif /* RLOGIN_PGRP_BUG */
2378 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
2380 if (shell_pgrp != terminal_pgrp)
2382 SigHandler *old_ttin = (SigHandler *)set_signal_handler (SIGTTIN, SIG_DFL);
2384 set_signal_handler (SIGTTIN, old_ttin);
2390 if (set_new_line_discipline (shell_tty) < 0)
2392 internal_error ("initialize_jobs: line discipline: %s",
2398 original_pgrp = shell_pgrp;
2399 shell_pgrp = getpid ();
2401 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
2403 internal_error ("initialize_jobs: setpgid: %s", strerror (errno));
2404 shell_pgrp = original_pgrp;
2408 if (give_terminal_to (shell_pgrp) < 0) /* XXX */
2409 /* job_control = 0 */; /* XXX */
2411 if (job_control == 0)
2412 internal_error ("no job control in this shell"); /* XXX */
2415 if (shell_tty != fileno (stderr))
2416 SET_CLOSE_ON_EXEC (shell_tty);
2418 set_signal_handler (SIGCHLD, flush_child);
2420 change_flag ('m', job_control ? '-' : '+');
2427 /* Set the line discipline to the best this system has to offer.
2428 Return -1 if this is not possible. */
2430 set_new_line_discipline (tty)
2433 #if defined (NEW_TTY_DRIVER)
2436 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
2439 if (ldisc != NTTYDISC)
2443 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
2447 #endif /* NEW_TTY_DRIVER */
2449 #if defined (TERMIO_TTY_DRIVER)
2450 # if defined (NTTYDISC)
2451 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
2454 if (shell_tty_info.c_line != NTTYDISC)
2456 shell_tty_info.c_line = NTTYDISC;
2457 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
2460 # endif /* NTTYDISC */
2462 #endif /* TERMIO_TTY_DRIVER */
2464 #if defined (TERMIOS_TTY_DRIVER)
2465 # if defined (TERMIOS_LDISC)
2466 if (tcgetattr (tty, &shell_tty_info) < 0)
2469 if (shell_tty_info.c_line != NTTYDISC)
2471 shell_tty_info.c_line = NTTYDISC;
2472 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2475 # endif /* TERMIOS_LDISC */
2477 #endif /* TERMIOS_TTY_DRIVER */
2479 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
2484 static SigHandler *old_tstp, *old_ttou, *old_ttin;
2485 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
2486 static sighandler stop_signal_handler (), cont_signal_handler ();
2488 #if !defined (READLINE) && defined (TIOCGWINSZ) && defined (SIGWINCH)
2489 static SigHandler *old_winch;
2492 sigwinch_sighandler (sig)
2497 #if defined (USG) && !defined (_POSIX_VERSION)
2498 set_signal_handler (SIGWINCH, sigwinch_sighandler);
2499 #endif /* USG && !_POSIX_VERSION */
2500 if ((ioctl (shell_tty, TIOCGWINSZ, &win) == 0) &&
2501 win.ws_row > 0 && win.ws_col > 0)
2504 shell_tty_info.c_winsize = win; /* structure copying */
2506 set_lines_and_columns (win.ws_row, win.ws_col);
2509 #endif /* !READLINE && TIOCGWINSZ && SIGWINCH */
2511 /* Setup this shell to handle C-C, etc. */
2513 initialize_job_signals ()
2517 set_signal_handler (SIGINT, sigint_sighandler);
2518 set_signal_handler (SIGTSTP, SIG_IGN);
2519 set_signal_handler (SIGTTOU, SIG_IGN);
2520 set_signal_handler (SIGTTIN, SIG_IGN);
2521 #if !defined (READLINE) && defined (TIOCGWINSZ) && defined (SIGWINCH)
2522 old_winch = set_signal_handler (SIGWINCH, sigwinch_sighandler);
2523 #endif /* !READLINE && TIOCGWINSZ && SIGWINCH */
2525 else if (job_control)
2527 old_tstp = set_signal_handler (SIGTSTP, stop_signal_handler);
2528 old_ttou = set_signal_handler (SIGTTOU, stop_signal_handler);
2529 old_ttin = set_signal_handler (SIGTTIN, stop_signal_handler);
2531 /* Leave these things alone for non-interactive shells without job
2535 /* Here we handle CONT signals. */
2537 cont_signal_handler (sig)
2540 initialize_job_signals ();
2541 set_signal_handler (SIGCONT, old_cont);
2542 kill (getpid (), SIGCONT);
2544 #if !defined (VOID_SIGHANDLER)
2546 #endif /* VOID_SIGHANDLER */
2549 /* Here we handle stop signals while we are running not as a login shell. */
2551 stop_signal_handler (sig)
2554 set_signal_handler (SIGTSTP, old_tstp);
2555 set_signal_handler (SIGTTOU, old_ttou);
2556 set_signal_handler (SIGTTIN, old_ttin);
2558 old_cont = set_signal_handler (SIGCONT, cont_signal_handler);
2560 give_terminal_to (shell_pgrp);
2562 kill (getpid (), sig);
2564 #if !defined (VOID_SIGHANDLER)
2566 #endif /* VOID_SIGHANDLER */
2569 /* Give the terminal to PGRP. */
2570 give_terminal_to (pgrp)
2579 sigaddset (&set, SIGTTOU);
2580 sigaddset (&set, SIGTTIN);
2581 sigaddset (&set, SIGTSTP);
2582 sigaddset (&set, SIGCHLD);
2583 sigemptyset (&oset);
2584 sigprocmask (SIG_BLOCK, &set, &oset);
2586 if (tcsetpgrp (shell_tty, pgrp) < 0)
2588 /* Maybe we should print an error message? */
2589 /* internal_error ("tcsetpgrp(%d) failed: pid %d to pgrp %d: %s",
2590 shell_tty, getpid(), pgrp, strerror (errno)); */
2594 terminal_pgrp = pgrp;
2596 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2602 /* Clear out any jobs in the job array. This is intended to be used by
2603 children of the shell, who should not have any job structures as baggage
2604 when they start executing (forking subshells for parenthesized execution
2605 and functions with pipes are the two that spring to mind). */
2614 BLOCK_CHILD (set, oset);
2618 current_job = previous_job = NO_JOB;
2620 for (i = 0; i < job_slots; i++)
2621 if (jobs[i] != (JOB *) NULL)
2624 free ((char *)jobs);
2628 UNBLOCK_CHILD (oset);
2632 /* Mark all dead jobs as notified, so delete_job () cleans them out
2633 of the job table properly. */
2635 mark_dead_jobs_as_notified ()
2642 BLOCK_CHILD (set, oset);
2644 for (i = 0; i < job_slots; i++)
2645 if (jobs[i] && JOBSTATE (i) == JDEAD)
2646 jobs[i]->flags |= J_NOTIFIED;
2648 UNBLOCK_CHILD (oset);
2652 /* Allow or disallow job control to take place. Returns the old value
2655 set_job_control (arg)
2665 /* Turn off all traces of job control. This is run by children of the shell
2666 which are going to do shellsy things, like wait (), etc. */
2668 without_job_control ()
2670 stop_making_children ();
2673 set_job_control (0);
2676 /* If this shell is interactive, terminate all stopped jobs and
2677 restore the original terminal process group. This is done
2678 before the `exec' builtin calls shell_execve. */
2682 if (interactive_shell) /* XXX - should it be interactive? */
2684 terminate_stopped_jobs ();
2686 if (original_pgrp >= 0)
2687 give_terminal_to (original_pgrp);
2690 if (original_pgrp >= 0)
2691 setpgid (0, original_pgrp);
2694 /* Restart job control by closing shell tty and reinitializing. This is
2695 called after an exec fails in an interactive shell and we do not exit. */
2697 restart_job_control ()
2699 if (shell_tty != -1)
2704 /* Set the handler to run when the shell receives a SIGCHLD signal. */
2706 set_sigchld_handler ()
2708 set_signal_handler (SIGCHLD, flush_child);
2711 #if defined (PGRP_PIPE)
2712 /* Read from the read end of a pipe. This is how the process group leader
2713 blocks until all of the processes in a pipeline have been made. */
2728 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
2733 /* Close the read and write ends of PP, an array of file descriptors. */
2747 /* Functional interface closes our local-to-job-control pipes. */
2750 pipe_close (pgrp_pipe);
2753 #endif /* PGRP_PIPE */
2755 #endif /* JOB_CONTROL */