1 /* jobs.c - functions that make children, remember them, and handle their termination. */
3 /* This file works with both POSIX and BSD systems. It implements job
6 /* Copyright (C) 1989-2015 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
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
15 Bash is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with Bash. If not, see <http://www.gnu.org/licenses/>.
26 #include "bashtypes.h"
32 #if defined (HAVE_UNISTD_H)
36 #include "posixtime.h"
38 #if defined (HAVE_SYS_RESOURCE_H) && defined (HAVE_WAIT3) && !defined (_POSIX_VERSION) && !defined (RLIMTYPE)
39 # include <sys/resource.h>
40 #endif /* !_POSIX_VERSION && HAVE_SYS_RESOURCE_H && HAVE_WAIT3 && !RLIMTYPE */
42 #if defined (HAVE_SYS_FILE_H)
43 # include <sys/file.h>
47 #include <sys/ioctl.h>
48 #if defined (HAVE_SYS_PARAM_H)
49 #include <sys/param.h>
52 #if defined (BUFFERED_INPUT)
56 /* Need to include this up here for *_TTY_DRIVER definitions. */
59 /* Define this if your output is getting swallowed. It's a no-op on
60 machines with the termio or termios tty drivers. */
61 /* #define DRAIN_OUTPUT */
63 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
64 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
66 #endif /* hpux && !TERMIOS_TTY_DRIVER */
72 #include "execute_cmd.h"
75 #include "builtins/builtext.h"
76 #include "builtins/common.h"
78 #if defined (READLINE)
79 # include <readline/readline.h>
86 #if !defined (HAVE_KILLPG)
87 extern int killpg
__P((pid_t
, int));
90 #if !DEFAULT_CHILD_MAX
91 # define DEFAULT_CHILD_MAX 32
95 # define MAX_CHILD_MAX 8192
99 #define MAX_JOBS_IN_ARRAY 4096 /* production */
101 #define MAX_JOBS_IN_ARRAY 128 /* testing */
105 #define PIDSTAT_TABLE_SZ 4096
106 #define BGPIDS_TABLE_SZ 512
108 /* Flag values for second argument to delete_job */
109 #define DEL_WARNSTOPPED 1 /* warn about deleting stopped jobs */
110 #define DEL_NOBGPID 2 /* don't add pgrp leader to bgpids */
112 /* Take care of system dependencies that must be handled when waiting for
113 children. The arguments to the WAITPID macro match those to the Posix.1
114 waitpid() function. */
116 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
117 # define WAITPID(pid, statusp, options) \
118 wait3 ((union wait *)statusp, options, (struct rusage *)0)
120 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
121 # define WAITPID(pid, statusp, options) \
122 waitpid ((pid_t)pid, statusp, options)
124 # if defined (HAVE_WAIT3)
125 # define WAITPID(pid, statusp, options) \
126 wait3 (statusp, options, (struct rusage *)0)
128 # define WAITPID(pid, statusp, options) \
129 wait3 (statusp, options, (int *)0)
130 # endif /* HAVE_WAIT3 */
131 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
132 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
134 /* getpgrp () varies between systems. Even systems that claim to be
135 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
136 #if defined (GETPGRP_VOID)
137 # define getpgid(p) getpgrp ()
139 # define getpgid(p) getpgrp (p)
140 #endif /* !GETPGRP_VOID */
142 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
143 handler for SIGCHLD. */
144 #if defined (MUST_REINSTALL_SIGHANDLERS)
145 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
147 # define REINSTALL_SIGCHLD_HANDLER
148 #endif /* !MUST_REINSTALL_SIGHANDLERS */
150 /* Some systems let waitpid(2) tell callers about stopped children. */
151 #if !defined (WCONTINUED) || defined (WCONTINUED_BROKEN)
153 # define WCONTINUED 0
155 #if !defined (WIFCONTINUED)
156 # define WIFCONTINUED(s) (0)
159 /* The number of additional slots to allocate when we run out. */
162 typedef int sh_job_map_func_t
__P((JOB
*, int, int, int));
164 /* Variables used here but defined in other files. */
165 extern int subshell_environment
, line_number
;
166 extern int posixly_correct
, shell_level
;
167 extern int last_command_exit_value
, last_command_exit_signal
;
168 extern int loop_level
, breaking
;
169 extern int executing_list
;
170 extern int sourcelevel
;
171 extern int running_trap
;
172 extern sh_builtin_func_t
*this_shell_builtin
;
173 extern char *shell_name
, *this_command_name
;
174 extern sigset_t top_level_mask
;
175 extern procenv_t wait_intr_buf
;
176 extern int wait_intr_flag
;
177 extern int wait_signal_received
;
178 extern WORD_LIST
*subst_assign_varlist
;
180 extern SigHandler
**original_signals
;
182 extern void set_original_signal
__P((int, SigHandler
*));
184 static struct jobstats zerojs
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
185 struct jobstats js
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
187 ps_index_t pidstat_table
[PIDSTAT_TABLE_SZ
];
188 struct bgpids bgpids
= { 0, 0, 0 };
190 /* The array of known jobs. */
191 JOB
**jobs
= (JOB
**)NULL
;
194 /* The number of slots currently allocated to JOBS. */
198 /* The controlling tty for this shell. */
201 /* The shell's process group. */
202 pid_t shell_pgrp
= NO_PID
;
204 /* The terminal's process group. */
205 pid_t terminal_pgrp
= NO_PID
;
207 /* The process group of the shell's parent. */
208 pid_t original_pgrp
= NO_PID
;
210 /* The process group of the pipeline currently being made. */
211 pid_t pipeline_pgrp
= (pid_t
)0;
213 #if defined (PGRP_PIPE)
214 /* Pipes which each shell uses to communicate with the process group leader
215 until all of the processes in a pipeline have been started. Then the
216 process leader is allowed to continue. */
217 int pgrp_pipe
[2] = { -1, -1 };
221 /* The job which is current; i.e. the one that `%+' stands for. */
222 int current_job
= NO_JOB
;
224 /* The previous job; i.e. the one that `%-' stands for. */
225 int previous_job
= NO_JOB
;
228 /* Last child made by the shell. */
229 volatile pid_t last_made_pid
= NO_PID
;
231 /* Pid of the last asynchronous child. */
232 volatile pid_t last_asynchronous_pid
= NO_PID
;
234 /* The pipeline currently being built. */
235 PROCESS
*the_pipeline
= (PROCESS
*)NULL
;
237 /* If this is non-zero, do job control. */
240 /* Are we running in background? (terminal_pgrp != shell_pgrp) */
241 int running_in_background
= 0;
243 /* Call this when you start making children. */
244 int already_making_children
= 0;
246 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
247 exits from get_tty_state(). */
248 int check_window_size
= CHECKWINSIZE_DEFAULT
;
250 PROCESS
*last_procsub_child
= (PROCESS
*)NULL
;
252 /* Functions local to this file. */
254 static sighandler wait_sigint_handler
__P((int));
255 static sighandler sigchld_handler
__P((int));
256 static sighandler sigcont_sighandler
__P((int));
257 static sighandler sigstop_sighandler
__P((int));
259 static int waitchld
__P((pid_t
, int));
261 static PROCESS
*find_pipeline
__P((pid_t
, int, int *));
262 static PROCESS
*find_process
__P((pid_t
, int, int *));
264 static char *current_working_directory
__P((void));
265 static char *job_working_directory
__P((void));
266 static char *j_strsignal
__P((int));
267 static char *printable_job_status
__P((int, PROCESS
*, int));
269 static PROCESS
*find_last_proc
__P((int, int));
270 static pid_t find_last_pid
__P((int, int));
272 static int set_new_line_discipline
__P((int));
273 static int map_over_jobs
__P((sh_job_map_func_t
*, int, int));
274 static int job_last_stopped
__P((int));
275 static int job_last_running
__P((int));
276 static int most_recent_job_in_state
__P((int, JOB_STATE
));
277 static int find_job
__P((pid_t
, int, PROCESS
**));
278 static int print_job
__P((JOB
*, int, int, int));
279 static int process_exit_status
__P((WAIT
));
280 static int process_exit_signal
__P((WAIT
));
281 static int set_job_status_and_cleanup
__P((int));
283 static WAIT job_signal_status
__P((int));
284 static WAIT raw_job_exit_status
__P((int));
286 static void notify_of_job_status
__P((void));
287 static void reset_job_indices
__P((void));
288 static void cleanup_dead_jobs
__P((void));
289 static int processes_in_job
__P((int));
290 static void realloc_jobs_list
__P((void));
291 static int compact_jobs_list
__P((int));
292 static void add_process
__P((char *, pid_t
));
293 static void print_pipeline
__P((PROCESS
*, int, int, FILE *));
294 static void pretty_print_job
__P((int, int, FILE *));
295 static void set_current_job
__P((int));
296 static void reset_current
__P((void));
297 static void set_job_running
__P((int));
298 static void setjstatus
__P((int));
299 static int maybe_give_terminal_to
__P((pid_t
, pid_t
, int));
300 static void mark_all_jobs_as_dead
__P((void));
301 static void mark_dead_jobs_as_notified
__P((int));
302 static void restore_sigint_handler
__P((void));
303 #if defined (PGRP_PIPE)
304 static void pipe_read
__P((int *));
307 /* Hash table manipulation */
309 static ps_index_t
*pshash_getbucket
__P((pid_t
));
310 static void pshash_delindex
__P((ps_index_t
));
312 /* Saved background process status management */
313 static struct pidstat
*bgp_add
__P((pid_t
, int));
314 static int bgp_delete
__P((pid_t
));
315 static void bgp_clear
__P((void));
316 static int bgp_search
__P((pid_t
));
318 static ps_index_t bgp_getindex
__P((void));
319 static void bgp_resize
__P((void)); /* XXX */
321 #if defined (ARRAY_VARS)
322 static int *pstatuses
; /* list of pipeline statuses */
326 /* Used to synchronize between wait_for and other functions and the SIGCHLD
329 static int queue_sigchld
;
331 #define QUEUE_SIGCHLD(os) (os) = sigchld, queue_sigchld++
333 #define UNQUEUE_SIGCHLD(os) \
336 if (queue_sigchld == 0 && os != sigchld) \
340 static SigHandler
*old_tstp
, *old_ttou
, *old_ttin
;
341 static SigHandler
*old_cont
= (SigHandler
*)SIG_DFL
;
343 /* A place to temporarily save the current pipeline. */
344 static struct pipeline_saver
*saved_pipeline
;
345 static int saved_already_making_children
;
347 /* Set this to non-zero whenever you don't want the jobs list to change at
348 all: no jobs deleted and no status change notifications. This is used,
349 for example, when executing SIGCHLD traps, which may run arbitrary
351 static int jobs_list_frozen
;
353 static char retcode_name_buffer
[64];
355 #if !defined (_POSIX_VERSION)
357 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
358 library functions and system calls. */
359 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
360 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
368 /* ioctl will handle setting errno correctly. */
369 if (ioctl (fd
, TIOCGPGRP
, &pgrp
) < 0)
374 #endif /* !_POSIX_VERSION */
376 /* Initialize the global job stats structure and other bookkeeping variables */
383 /* Return the working directory for the current process. Unlike
384 job_working_directory, this does not call malloc (), nor do any
385 of the functions it calls. This is so that it can safely be called
386 from a signal handler. */
388 current_working_directory ()
391 static char d
[PATH_MAX
];
393 dir
= get_string_value ("PWD");
395 if (dir
== 0 && the_current_working_directory
&& no_symbolic_links
)
396 dir
= the_current_working_directory
;
400 dir
= getcwd (d
, sizeof(d
));
405 return (dir
== 0) ? "<unknown>" : dir
;
408 /* Return the working directory for the current process. */
410 job_working_directory ()
414 dir
= get_string_value ("PWD");
416 return (savestring (dir
));
418 dir
= get_working_directory ("job-working-directory");
422 return (savestring ("<unknown>"));
428 if (already_making_children
)
431 already_making_children
= 1;
436 stop_making_children ()
438 already_making_children
= 0;
442 cleanup_the_pipeline ()
447 BLOCK_CHILD (set
, oset
);
448 disposer
= the_pipeline
;
449 the_pipeline
= (PROCESS
*)NULL
;
450 UNBLOCK_CHILD (oset
);
453 discard_pipeline (disposer
);
457 discard_last_procsub_child ()
462 BLOCK_CHILD (set
, oset
);
463 disposer
= last_procsub_child
;
464 last_procsub_child
= (PROCESS
*)NULL
;
465 UNBLOCK_CHILD (oset
);
468 discard_pipeline (disposer
);
471 struct pipeline_saver
*
472 alloc_pipeline_saver ()
474 struct pipeline_saver
*ret
;
476 ret
= (struct pipeline_saver
*)xmalloc (sizeof (struct pipeline_saver
));
483 save_pipeline (clear
)
487 struct pipeline_saver
*saver
;
489 BLOCK_CHILD (set
, oset
);
490 saver
= alloc_pipeline_saver ();
491 saver
->pipeline
= the_pipeline
;
492 saver
->next
= saved_pipeline
;
493 saved_pipeline
= saver
;
495 the_pipeline
= (PROCESS
*)NULL
;
496 saved_already_making_children
= already_making_children
;
497 UNBLOCK_CHILD (oset
);
501 restore_pipeline (discard
)
504 PROCESS
*old_pipeline
;
506 struct pipeline_saver
*saver
;
508 BLOCK_CHILD (set
, oset
);
509 old_pipeline
= the_pipeline
;
510 the_pipeline
= saved_pipeline
->pipeline
;
511 saver
= saved_pipeline
;
512 saved_pipeline
= saved_pipeline
->next
;
514 already_making_children
= saved_already_making_children
;
515 UNBLOCK_CHILD (oset
);
517 if (discard
&& old_pipeline
)
519 discard_pipeline (old_pipeline
);
520 return ((PROCESS
*)NULL
);
525 /* Start building a pipeline. */
531 cleanup_the_pipeline ();
533 #if defined (PGRP_PIPE)
534 sh_closepipe (pgrp_pipe
);
538 #if defined (PGRP_PIPE)
541 if (pipe (pgrp_pipe
) == -1)
542 sys_error (_("start_pipeline: pgrp pipe"));
547 /* Stop building a pipeline. Install the process list in the job array.
548 This returns the index of the newly installed job.
549 DEFERRED is a command structure to be executed upon satisfactory
550 execution exit of this pipeline. */
552 stop_pipeline (async
, deferred
)
560 BLOCK_CHILD (set
, oset
);
562 #if defined (PGRP_PIPE)
563 /* The parent closes the process group synchronization pipe. */
564 sh_closepipe (pgrp_pipe
);
567 cleanup_dead_jobs ();
569 if (js
.j_jobslots
== 0)
571 js
.j_jobslots
= JOB_SLOTS
;
572 jobs
= (JOB
**)xmalloc (js
.j_jobslots
* sizeof (JOB
*));
574 /* Now blank out these new entries. */
575 for (i
= 0; i
< js
.j_jobslots
; i
++)
576 jobs
[i
] = (JOB
*)NULL
;
578 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
581 /* Scan from the last slot backward, looking for the next free one. */
582 /* XXX - revisit this interactive assumption */
583 /* XXX - this way for now */
586 for (i
= js
.j_jobslots
; i
; i
--)
593 /* This wraps around, but makes it inconvenient to extend the array */
594 for (i
= js
.j_lastj
+1; i
!= js
.j_lastj
; i
++)
596 if (i
>= js
.j_jobslots
)
604 /* This doesn't wrap around yet. */
605 for (i
= js
.j_lastj
? js
.j_lastj
+ 1 : js
.j_lastj
; i
< js
.j_jobslots
; i
++)
611 /* Do we need more room? */
613 /* First try compaction */
614 if ((interactive_shell
== 0 || subshell_environment
) && i
== js
.j_jobslots
&& js
.j_jobslots
>= MAX_JOBS_IN_ARRAY
)
615 i
= compact_jobs_list (0);
617 /* If we can't compact, reallocate */
618 if (i
== js
.j_jobslots
)
620 js
.j_jobslots
+= JOB_SLOTS
;
621 jobs
= (JOB
**)xrealloc (jobs
, (js
.j_jobslots
* sizeof (JOB
*)));
623 for (j
= i
; j
< js
.j_jobslots
; j
++)
624 jobs
[j
] = (JOB
*)NULL
;
627 /* Add the current pipeline to the job list. */
631 int any_running
, any_stopped
, n
;
633 newjob
= (JOB
*)xmalloc (sizeof (JOB
));
635 for (n
= 1, p
= the_pipeline
; p
->next
!= the_pipeline
; n
++, p
= p
->next
)
637 p
->next
= (PROCESS
*)NULL
;
638 newjob
->pipe
= REVERSE_LIST (the_pipeline
, PROCESS
*);
639 for (p
= newjob
->pipe
; p
->next
; p
= p
->next
)
641 p
->next
= newjob
->pipe
;
643 the_pipeline
= (PROCESS
*)NULL
;
644 newjob
->pgrp
= pipeline_pgrp
;
649 /* Flag to see if in another pgrp. */
651 newjob
->flags
|= J_JOBCONTROL
;
653 /* Set the state of this pipeline. */
655 any_running
= any_stopped
= 0;
658 any_running
|= PRUNNING (p
);
659 any_stopped
|= PSTOPPED (p
);
662 while (p
!= newjob
->pipe
);
664 newjob
->state
= any_running
? JRUNNING
: (any_stopped
? JSTOPPED
: JDEAD
);
665 newjob
->wd
= job_working_directory ();
666 newjob
->deferred
= deferred
;
668 newjob
->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
669 newjob
->cleanarg
= (PTR_T
) NULL
;
672 if (newjob
->state
== JDEAD
&& (newjob
->flags
& J_FOREGROUND
))
674 if (newjob
->state
== JDEAD
)
676 js
.c_reaped
+= n
; /* wouldn't have been done since this was not part of a job */
685 newjob
= (JOB
*)NULL
;
688 js
.j_lastmade
= newjob
;
694 newjob
->flags
&= ~J_FOREGROUND
;
695 newjob
->flags
|= J_ASYNC
;
696 js
.j_lastasync
= newjob
;
704 newjob
->flags
|= J_FOREGROUND
;
706 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
708 * The currently-accepted job control wisdom says to set the
709 * terminal's process group n+1 times in an n-step pipeline:
710 * once in the parent and once in each child. This is where
711 * the parent gives it away.
713 * Don't give the terminal away if this shell is an asynchronous
714 * subshell or if we're a (presumably non-interactive) shell running
718 if (job_control
&& newjob
->pgrp
&& (subshell_environment
&SUBSHELL_ASYNC
) == 0 && running_in_background
== 0)
719 maybe_give_terminal_to (shell_pgrp
, newjob
->pgrp
, 0);
723 stop_making_children ();
724 UNBLOCK_CHILD (oset
);
725 return (newjob
? i
: js
.j_current
);
728 /* Functions to manage the list of exited background pids whose status has
733 The current implementation is a hash table using a single (separate) arena
734 for storage that can be allocated and freed as a unit. The size of the hash
735 table is a multiple of PIDSTAT_TABLE_SZ (4096) and multiple PIDs that hash
736 to the same value are chained through the bucket_next and bucket_prev
737 pointers (basically coalesced hashing for collision resolution).
741 All pid/status storage is done using the circular buffer bgpids.storage.
742 This must contain at least js.c_childmax entries. The circular buffer is
743 used to supply the ordered list Posix requires ("the last CHILD_MAX
744 processes"). To avoid searching the entire storage table for a given PID,
745 the hash table (pidstat_table) holds pointers into the storage arena and
746 uses a doubly-linked list of cells (bucket_next/bucket_prev, also pointers
747 into the arena) to implement collision resolution. */
749 /* The number of elements in bgpids.storage always has to be > js.c_childmax for
750 the circular buffer to work right. */
757 if (bgpids
.nalloc
== 0)
759 /* invalidate hash table when bgpids table is reallocated */
760 for (psi
= 0; psi
< PIDSTAT_TABLE_SZ
; psi
++)
761 pidstat_table
[psi
] = NO_PIDSTAT
;
762 nsize
= BGPIDS_TABLE_SZ
; /* should be power of 2 */
766 nsize
= bgpids
.nalloc
;
768 while (nsize
< js
.c_childmax
)
771 if (bgpids
.nalloc
< js
.c_childmax
)
773 bgpids
.storage
= (struct pidstat
*)xrealloc (bgpids
.storage
, nsize
* sizeof (struct pidstat
));
775 for (psi
= bgpids
.nalloc
; psi
< nsize
; psi
++)
776 bgpids
.storage
[psi
].pid
= NO_PID
;
778 bgpids
.nalloc
= nsize
;
781 else if (bgpids
.head
>= bgpids
.nalloc
) /* wrap around */
790 if (bgpids
.nalloc
< js
.c_childmax
|| bgpids
.head
>= bgpids
.nalloc
)
793 pshash_delindex (bgpids
.head
); /* XXX - clear before reusing */
794 return bgpids
.head
++;
798 pshash_getbucket (pid
)
801 unsigned long hash
; /* XXX - u_bits32_t */
803 hash
= pid
* 0x9e370001UL
;
804 return (&pidstat_table
[hash
% PIDSTAT_TABLE_SZ
]);
807 static struct pidstat
*
808 bgp_add (pid
, status
)
812 ps_index_t
*bucket
, psi
;
815 /* bucket == existing chain of pids hashing to same value
816 psi = where were going to put this pid/status */
818 bucket
= pshash_getbucket (pid
); /* index into pidstat_table */
819 psi
= bgp_getindex (); /* bgpids.head, index into storage */
821 /* XXX - what if psi == *bucket? */
825 internal_warning ("hashed pid %d (pid %d) collides with bgpids.head, skipping", psi
, pid
);
827 bgpids
.storage
[psi
].pid
= NO_PID
; /* make sure */
828 psi
= bgp_getindex (); /* skip to next one */
831 ps
= &bgpids
.storage
[psi
];
835 ps
->bucket_next
= *bucket
;
836 ps
->bucket_prev
= NO_PIDSTAT
;
841 if (bgpids
.npid
> js
.c_childmax
)
845 if (ps
->bucket_next
!= NO_PIDSTAT
)
846 bgpids
.storage
[ps
->bucket_next
].bucket_prev
= psi
;
848 *bucket
= psi
; /* set chain head in hash table */
854 pshash_delindex (psi
)
860 ps
= &bgpids
.storage
[psi
];
861 if (ps
->pid
== NO_PID
)
864 if (ps
->bucket_next
!= NO_PIDSTAT
)
865 bgpids
.storage
[ps
->bucket_next
].bucket_prev
= ps
->bucket_prev
;
866 if (ps
->bucket_prev
!= NO_PIDSTAT
)
867 bgpids
.storage
[ps
->bucket_prev
].bucket_next
= ps
->bucket_next
;
870 bucket
= pshash_getbucket (ps
->pid
);
871 *bucket
= ps
->bucket_next
; /* deleting chain head in hash table */
874 /* clear out this cell, just in case */
876 ps
->bucket_next
= ps
->bucket_prev
= NO_PIDSTAT
;
883 ps_index_t psi
, orig_psi
;
885 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0 || bgpids
.npid
== 0)
888 /* Search chain using hash to find bucket in pidstat_table */
889 for (orig_psi
= psi
= *(pshash_getbucket (pid
)); psi
!= NO_PIDSTAT
; psi
= bgpids
.storage
[psi
].bucket_next
)
891 if (bgpids
.storage
[psi
].pid
== pid
)
893 if (orig_psi
== bgpids
.storage
[psi
].bucket_next
) /* catch reported bug */
895 internal_warning ("bgp_delete: LOOP: psi (%d) == storage[psi].bucket_next", psi
);
900 if (psi
== NO_PIDSTAT
)
901 return 0; /* not found */
904 itrace("bgp_delete: deleting %d", pid
);
907 pshash_delindex (psi
); /* hash table management */
913 /* Clear out the list of saved statuses */
917 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0)
920 free (bgpids
.storage
);
929 /* Search for PID in the list of saved background pids; return its status if
930 found. If not found, return -1. We hash to the right spot in pidstat_table
931 and follow the bucket chain to the end. */
936 ps_index_t psi
, orig_psi
;
938 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0 || bgpids
.npid
== 0)
941 /* Search chain using hash to find bucket in pidstat_table */
942 for (orig_psi
= psi
= *(pshash_getbucket (pid
)); psi
!= NO_PIDSTAT
; psi
= bgpids
.storage
[psi
].bucket_next
)
944 if (bgpids
.storage
[psi
].pid
== pid
)
945 return (bgpids
.storage
[psi
].status
);
946 if (orig_psi
== bgpids
.storage
[psi
].bucket_next
) /* catch reported bug */
948 internal_warning ("bgp_search: LOOP: psi (%d) == storage[psi].bucket_next", psi
);
964 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
965 been deleted. The caller should check whether js.j_njobs is 0 before
966 calling this. This wraps around, but the rest of the code does not. At
967 this point, it should not matter. */
973 if (jobs
[js
.j_firstj
] == 0)
976 if (old
>= js
.j_jobslots
)
977 old
= js
.j_jobslots
- 1;
978 while (js
.j_firstj
!= old
)
980 if (js
.j_firstj
>= js
.j_jobslots
)
982 if (jobs
[js
.j_firstj
] || js
.j_firstj
== old
) /* needed if old == 0 */
986 if (js
.j_firstj
== old
)
987 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
989 if (jobs
[js
.j_lastj
] == 0)
994 while (js
.j_lastj
!= old
)
997 js
.j_lastj
= js
.j_jobslots
- 1;
998 if (jobs
[js
.j_lastj
] || js
.j_lastj
== old
) /* needed if old == js.j_jobslots */
1002 if (js
.j_lastj
== old
)
1003 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
1007 /* Delete all DEAD jobs that the user had received notification about. */
1009 cleanup_dead_jobs ()
1014 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1019 /* XXX could use js.j_firstj and js.j_lastj here */
1020 for (i
= 0; i
< js
.j_jobslots
; i
++)
1023 if (i
< js
.j_firstj
&& jobs
[i
])
1024 itrace("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1025 if (i
> js
.j_lastj
&& jobs
[i
])
1026 itrace("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1029 if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
))
1033 #if defined (PROCESS_SUBSTITUTION)
1034 if (last_procsub_child
&& last_procsub_child
->running
== PS_DONE
)
1036 bgp_add (last_procsub_child
->pid
, process_exit_status (last_procsub_child
->status
)); /* XXX */
1037 discard_pipeline (last_procsub_child
);
1038 last_procsub_child
= (PROCESS
*)NULL
;
1042 #if defined (COPROCESS_SUPPORT)
1046 UNQUEUE_SIGCHLD(os
);
1050 processes_in_job (job
)
1054 register PROCESS
*p
;
1057 p
= jobs
[job
]->pipe
;
1063 while (p
!= jobs
[job
]->pipe
);
1069 delete_old_job (pid
)
1075 job
= find_job (pid
, 0, &p
);
1079 itrace ("delete_old_job: found pid %d in job %d with state %d", pid
, job
, jobs
[job
]->state
);
1081 if (JOBSTATE (job
) == JDEAD
)
1082 delete_job (job
, DEL_NOBGPID
);
1086 internal_warning (_("forked pid %d appears in running job %d"), pid
, job
+1);
1094 /* Reallocate and compress the jobs list. This returns with a jobs array
1095 whose size is a multiple of JOB_SLOTS and can hold the current number of
1096 jobs. Heuristics are used to minimize the number of new reallocs. */
1098 realloc_jobs_list ()
1101 int nsize
, i
, j
, ncur
, nprev
;
1104 ncur
= nprev
= NO_JOB
;
1105 nsize
= ((js
.j_njobs
+ JOB_SLOTS
- 1) / JOB_SLOTS
);
1107 i
= js
.j_njobs
% JOB_SLOTS
;
1108 if (i
== 0 || i
> (JOB_SLOTS
>> 1))
1111 BLOCK_CHILD (set
, oset
);
1112 nlist
= (js
.j_jobslots
== nsize
) ? jobs
: (JOB
**) xmalloc (nsize
* sizeof (JOB
*));
1114 js
.c_reaped
= js
.j_ndead
= 0;
1115 for (i
= j
= 0; i
< js
.j_jobslots
; i
++)
1118 if (i
== js
.j_current
)
1120 if (i
== js
.j_previous
)
1122 nlist
[j
++] = jobs
[i
];
1123 if (jobs
[i
]->state
== JDEAD
)
1126 js
.c_reaped
+= processes_in_job (i
);
1131 itrace ("realloc_jobs_list: resize jobs list from %d to %d", js
.j_jobslots
, nsize
);
1132 itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js
.j_lastj
, (j
> 0) ? j
- 1 : 0);
1133 itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js
.j_njobs
, j
);
1134 itrace ("realloc_jobs_list: js.j_ndead %d js.c_reaped %d", js
.j_ndead
, js
.c_reaped
);
1138 js
.j_lastj
= (j
> 0) ? j
- 1 : 0;
1140 js
.j_jobslots
= nsize
;
1142 /* Zero out remaining slots in new jobs list */
1143 for ( ; j
< nsize
; j
++)
1144 nlist
[j
] = (JOB
*)NULL
;
1153 js
.j_current
= ncur
;
1154 if (nprev
!= NO_JOB
)
1155 js
.j_previous
= nprev
;
1157 /* Need to reset these */
1158 if (js
.j_current
== NO_JOB
|| js
.j_previous
== NO_JOB
|| js
.j_current
> js
.j_lastj
|| js
.j_previous
> js
.j_lastj
)
1162 itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js
.j_current
, js
.j_previous
);
1165 UNBLOCK_CHILD (oset
);
1168 /* Compact the jobs list by removing dead jobs. Assume that we have filled
1169 the jobs array to some predefined maximum. Called when the shell is not
1170 the foreground process (subshell_environment != 0). Returns the first
1171 available slot in the compacted list. If that value is js.j_jobslots, then
1172 the list needs to be reallocated. The jobs array may be in new memory if
1173 this returns > 0 and < js.j_jobslots. FLAGS is reserved for future use. */
1175 compact_jobs_list (flags
)
1178 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1179 return js
.j_jobslots
;
1182 realloc_jobs_list ();
1185 itrace("compact_jobs_list: returning %d", (js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
1188 return ((js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
1191 /* Delete the job at INDEX from the job list. Must be called
1192 with SIGCHLD blocked. */
1194 delete_job (job_index
, dflags
)
1195 int job_index
, dflags
;
1201 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1204 if ((dflags
& DEL_WARNSTOPPED
) && subshell_environment
== 0 && STOPPED (job_index
))
1205 internal_warning (_("deleting stopped job %d with process group %ld"), job_index
+1, (long)jobs
[job_index
]->pgrp
);
1206 temp
= jobs
[job_index
];
1210 if ((dflags
& DEL_NOBGPID
) == 0 && (temp
->flags
& (J_ASYNC
|J_FOREGROUND
)) == J_ASYNC
)
1212 proc
= find_last_proc (job_index
, 0);
1214 bgp_add (proc
->pid
, process_exit_status (proc
->status
));
1217 jobs
[job_index
] = (JOB
*)NULL
;
1218 if (temp
== js
.j_lastmade
)
1220 else if (temp
== js
.j_lastasync
)
1224 ndel
= discard_pipeline (temp
->pipe
);
1226 js
.c_injobs
-= ndel
;
1227 if (temp
->state
== JDEAD
)
1229 js
.c_reaped
-= ndel
;
1231 if (js
.c_reaped
< 0)
1234 itrace("delete_job (%d pgrp %d): js.c_reaped (%d) < 0 ndel = %d js.j_ndead = %d", job_index
, temp
->pgrp
, js
.c_reaped
, ndel
, js
.j_ndead
);
1241 dispose_command (temp
->deferred
);
1246 if (js
.j_njobs
== 0)
1247 js
.j_firstj
= js
.j_lastj
= 0;
1248 else if (jobs
[js
.j_firstj
] == 0 || jobs
[js
.j_lastj
] == 0)
1249 reset_job_indices ();
1251 if (job_index
== js
.j_current
|| job_index
== js
.j_previous
)
1255 /* Must be called with SIGCHLD blocked. */
1257 nohup_job (job_index
)
1262 if (js
.j_jobslots
== 0)
1265 if (temp
= jobs
[job_index
])
1266 temp
->flags
|= J_NOHUP
;
1269 /* Get rid of the data structure associated with a process chain. */
1271 discard_pipeline (chain
)
1272 register PROCESS
*chain
;
1274 register PROCESS
*this, *next
;
1282 FREE (this->command
);
1287 while (this != chain
);
1292 /* Add this process to the chain being built in the_pipeline.
1293 NAME is the command string that will be exec'ed later.
1294 PID is the process id of the child. */
1296 add_process (name
, pid
)
1302 #if defined (RECYCLES_PIDS)
1304 p
= find_process (pid
, 0, &j
);
1309 internal_warning (_("add_process: process %5ld (%s) in the_pipeline"), (long)p
->pid
, p
->command
);
1312 internal_warning (_("add_process: pid %5ld (%s) marked as still alive"), (long)p
->pid
, p
->command
);
1313 p
->running
= PS_RECYCLED
; /* mark as recycled */
1317 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1318 t
->next
= the_pipeline
;
1320 WSTATUS (t
->status
) = 0;
1321 t
->running
= PS_RUNNING
;
1330 while (p
->next
!= t
->next
)
1336 /* Create a (dummy) PROCESS with NAME, PID, and STATUS, and make it the last
1337 process in jobs[JID]->pipe. Used by the lastpipe code. */
1339 append_process (name
, pid
, status
, jid
)
1347 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1348 t
->next
= (PROCESS
*)NULL
;
1350 /* set process exit status using offset discovered by configure */
1351 t
->status
= (status
& 0xff) << WEXITSTATUS_OFFSET
;
1352 t
->running
= PS_DONE
;
1355 js
.c_reaped
++; /* XXX */
1357 for (p
= jobs
[jid
]->pipe
; p
->next
!= jobs
[jid
]->pipe
; p
= p
->next
)
1360 t
->next
= jobs
[jid
]->pipe
;
1364 /* Take the last job and make it the first job. Must be called with
1367 rotate_the_pipeline ()
1371 if (the_pipeline
->next
== the_pipeline
)
1373 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1378 /* Reverse the order of the processes in the_pipeline. Must be called with
1381 reverse_the_pipeline ()
1385 if (the_pipeline
->next
== the_pipeline
)
1388 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1390 p
->next
= (PROCESS
*)NULL
;
1392 n
= REVERSE_LIST (the_pipeline
, PROCESS
*);
1395 for (p
= the_pipeline
; p
->next
; p
= p
->next
)
1397 p
->next
= the_pipeline
;
1401 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
1402 then it is time to stop mapping, and that is the return value
1403 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
1406 map_over_jobs (func
, arg1
, arg2
)
1407 sh_job_map_func_t
*func
;
1414 if (js
.j_jobslots
== 0)
1417 BLOCK_CHILD (set
, oset
);
1419 /* XXX could use js.j_firstj here */
1420 for (i
= result
= 0; i
< js
.j_jobslots
; i
++)
1423 if (i
< js
.j_firstj
&& jobs
[i
])
1424 itrace("map_over_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1425 if (i
> js
.j_lastj
&& jobs
[i
])
1426 itrace("map_over_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1430 result
= (*func
)(jobs
[i
], arg1
, arg2
, i
);
1436 UNBLOCK_CHILD (oset
);
1441 /* Cause all the jobs in the current pipeline to exit. */
1443 terminate_current_pipeline ()
1445 if (pipeline_pgrp
&& pipeline_pgrp
!= shell_pgrp
)
1447 killpg (pipeline_pgrp
, SIGTERM
);
1448 killpg (pipeline_pgrp
, SIGCONT
);
1452 /* Cause all stopped jobs to exit. */
1454 terminate_stopped_jobs ()
1458 /* XXX could use js.j_firstj here */
1459 for (i
= 0; i
< js
.j_jobslots
; i
++)
1461 if (jobs
[i
] && STOPPED (i
))
1463 killpg (jobs
[i
]->pgrp
, SIGTERM
);
1464 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1469 /* Cause all jobs, running or stopped, to receive a hangup signal. If
1470 a job is marked J_NOHUP, don't send the SIGHUP. */
1476 /* XXX could use js.j_firstj here */
1477 for (i
= 0; i
< js
.j_jobslots
; i
++)
1481 if (jobs
[i
]->flags
& J_NOHUP
)
1483 killpg (jobs
[i
]->pgrp
, SIGHUP
);
1485 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1491 kill_current_pipeline ()
1493 stop_making_children ();
1497 /* Return the pipeline that PID belongs to. Note that the pipeline
1498 doesn't have to belong to a job. Must be called with SIGCHLD blocked.
1499 If JOBP is non-null, return the index of the job containing PID. */
1501 find_pipeline (pid
, alive_only
, jobp
)
1504 int *jobp
; /* index into jobs list or NO_JOB */
1509 /* See if this process is in the pipeline that we are building. */
1517 /* Return it if we found it. Don't ever return a recycled pid. */
1518 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1523 while (p
!= the_pipeline
);
1525 /* Now look in the last process substitution pipeline, since that sets $! */
1526 if (last_procsub_child
)
1528 p
= last_procsub_child
;
1531 /* Return it if we found it. Don't ever return a recycled pid. */
1532 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1537 while (p
!= last_procsub_child
);
1540 job
= find_job (pid
, alive_only
, &p
);
1543 return (job
== NO_JOB
) ? (PROCESS
*)NULL
: jobs
[job
]->pipe
;
1546 /* Return the PROCESS * describing PID. If JOBP is non-null return the index
1547 into the jobs array of the job containing PID. Must be called with
1550 find_process (pid
, alive_only
, jobp
)
1553 int *jobp
; /* index into jobs list or NO_JOB */
1557 p
= find_pipeline (pid
, alive_only
, jobp
);
1558 while (p
&& p
->pid
!= pid
)
1563 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1564 belong to any job. Must be called with SIGCHLD blocked. */
1566 find_job (pid
, alive_only
, procp
)
1574 /* XXX could use js.j_firstj here, and should check js.j_lastj */
1575 for (i
= 0; i
< js
.j_jobslots
; i
++)
1578 if (i
< js
.j_firstj
&& jobs
[i
])
1579 itrace("find_job: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1580 if (i
> js
.j_lastj
&& jobs
[i
])
1581 itrace("find_job: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1589 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1598 while (p
!= jobs
[i
]->pipe
);
1605 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
1606 required by find_job. */
1608 get_job_by_pid (pid
, block
)
1616 BLOCK_CHILD (set
, oset
);
1618 job
= find_job (pid
, 0, NULL
);
1621 UNBLOCK_CHILD (oset
);
1626 /* Print descriptive information about the job with leader pid PID. */
1634 BLOCK_CHILD (set
, oset
);
1636 job
= find_job (pid
, 0, NULL
);
1639 fprintf (stderr
, "[%d] %ld\n", job
+ 1, (long)pid
);
1641 programming_error (_("describe_pid: %ld: no such pid"), (long)pid
);
1643 UNBLOCK_CHILD (oset
);
1655 x
= retcode_name_buffer
;
1656 snprintf (x
, sizeof(retcode_name_buffer
), _("Signal %d"), s
);
1662 printable_job_status (j
, p
, format
)
1672 if (STOPPED (j
) && format
== 0)
1674 if (posixly_correct
== 0 || p
== 0 || (WIFSTOPPED (p
->status
) == 0))
1675 temp
= _("Stopped");
1678 temp
= retcode_name_buffer
;
1679 snprintf (temp
, sizeof(retcode_name_buffer
), _("Stopped(%s)"), signal_name (WSTOPSIG (p
->status
)));
1682 else if (RUNNING (j
))
1683 temp
= _("Running");
1686 if (WIFSTOPPED (p
->status
))
1687 temp
= j_strsignal (WSTOPSIG (p
->status
));
1688 else if (WIFSIGNALED (p
->status
))
1689 temp
= j_strsignal (WTERMSIG (p
->status
));
1690 else if (WIFEXITED (p
->status
))
1692 temp
= retcode_name_buffer
;
1693 es
= WEXITSTATUS (p
->status
);
1696 strncpy (temp
, _("Done"), sizeof (retcode_name_buffer
) - 1);
1697 temp
[sizeof (retcode_name_buffer
) - 1] = '\0';
1699 else if (posixly_correct
)
1700 snprintf (temp
, sizeof(retcode_name_buffer
), _("Done(%d)"), es
);
1702 snprintf (temp
, sizeof(retcode_name_buffer
), _("Exit %d"), es
);
1705 temp
= _("Unknown status");
1711 /* This is the way to print out information on a job if you
1712 know the index. FORMAT is:
1714 JLIST_NORMAL) [1]+ Running emacs
1715 JLIST_LONG ) [1]+ 2378 Running emacs
1716 -1 ) [1]+ 2378 emacs
1718 JLIST_NORMAL) [1]+ Stopped ls | more
1719 JLIST_LONG ) [1]+ 2369 Stopped ls
1722 Just list the pid of the process group leader (really
1725 Use format JLIST_NORMAL, but list only jobs about which
1726 the user has not been notified. */
1728 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1729 the JOBS array corresponding to this pipeline. FORMAT is as described
1730 above. Must be called with SIGCHLD blocked.
1732 If you're printing a pipeline that's not in the jobs array, like the
1733 current pipeline as it's being created, pass -1 for JOB_INDEX */
1735 print_pipeline (p
, job_index
, format
, stream
)
1737 int job_index
, format
;
1740 PROCESS
*first
, *last
, *show
;
1741 int es
, name_padding
;
1748 while (last
->next
!= first
)
1754 fprintf (stream
, format
? " " : " |");
1756 if (format
!= JLIST_STANDARD
)
1757 fprintf (stream
, "%5ld", (long)p
->pid
);
1759 fprintf (stream
, " ");
1761 if (format
> -1 && job_index
>= 0)
1763 show
= format
? p
: last
;
1764 temp
= printable_job_status (job_index
, show
, format
);
1770 if (show
->running
== first
->running
&&
1771 WSTATUS (show
->status
) == WSTATUS (first
->status
))
1775 temp
= (char *)NULL
;
1780 fprintf (stream
, "%s", temp
);
1784 es
= 2; /* strlen ("| ") */
1785 name_padding
= LONGEST_SIGNAL_DESC
- es
;
1787 fprintf (stream
, "%*s", name_padding
, "");
1789 if ((WIFSTOPPED (show
->status
) == 0) &&
1790 (WIFCONTINUED (show
->status
) == 0) &&
1791 WIFCORED (show
->status
))
1792 fprintf (stream
, _("(core dumped) "));
1796 if (p
!= first
&& format
)
1797 fprintf (stream
, "| ");
1800 fprintf (stream
, "%s", p
->command
);
1802 if (p
== last
&& job_index
>= 0)
1804 temp
= current_working_directory ();
1806 if (RUNNING (job_index
) && (IS_FOREGROUND (job_index
) == 0))
1807 fprintf (stream
, " &");
1809 if (strcmp (temp
, jobs
[job_index
]->wd
) != 0)
1811 _(" (wd: %s)"), polite_directory_format (jobs
[job_index
]->wd
));
1814 if (format
|| (p
== last
))
1816 /* We need to add a CR only if this is an interactive shell, and
1817 we're reporting the status of a completed job asynchronously.
1818 We can't really check whether this particular job is being
1819 reported asynchronously, so just add the CR if the shell is
1820 currently interactive and asynchronous notification is enabled. */
1821 if (asynchronous_notification
&& interactive
)
1822 fprintf (stream
, "\r\n");
1824 fprintf (stream
, "\n");
1834 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1835 Must be called with SIGCHLD blocked or queued with queue_sigchld */
1837 pretty_print_job (job_index
, format
, stream
)
1838 int job_index
, format
;
1841 register PROCESS
*p
;
1843 /* Format only pid information about the process group leader? */
1844 if (format
== JLIST_PID_ONLY
)
1846 fprintf (stream
, "%ld\n", (long)jobs
[job_index
]->pipe
->pid
);
1850 if (format
== JLIST_CHANGED_ONLY
)
1852 if (IS_NOTIFIED (job_index
))
1854 format
= JLIST_STANDARD
;
1857 if (format
!= JLIST_NONINTERACTIVE
)
1858 fprintf (stream
, "[%d]%c ", job_index
+ 1,
1859 (job_index
== js
.j_current
) ? '+':
1860 (job_index
== js
.j_previous
) ? '-' : ' ');
1862 if (format
== JLIST_NONINTERACTIVE
)
1863 format
= JLIST_LONG
;
1865 p
= jobs
[job_index
]->pipe
;
1867 print_pipeline (p
, job_index
, format
, stream
);
1869 /* We have printed information about this job. When the job's
1870 status changes, waitchld () sets the notification flag to 0. */
1871 jobs
[job_index
]->flags
|= J_NOTIFIED
;
1875 print_job (job
, format
, state
, job_index
)
1877 int format
, state
, job_index
;
1879 if (state
== -1 || (JOB_STATE
)state
== job
->state
)
1880 pretty_print_job (job_index
, format
, stdout
);
1885 list_one_job (job
, format
, ignore
, job_index
)
1887 int format
, ignore
, job_index
;
1889 pretty_print_job (job_index
, format
, stdout
);
1893 list_stopped_jobs (format
)
1896 cleanup_dead_jobs ();
1897 map_over_jobs (print_job
, format
, (int)JSTOPPED
);
1901 list_running_jobs (format
)
1904 cleanup_dead_jobs ();
1905 map_over_jobs (print_job
, format
, (int)JRUNNING
);
1908 /* List jobs. If FORMAT is non-zero, then the long form of the information
1909 is printed, else just a short version. */
1911 list_all_jobs (format
)
1914 cleanup_dead_jobs ();
1915 map_over_jobs (print_job
, format
, -1);
1918 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1919 COMMAND is just for remembering the name of the command; we don't do
1920 anything else with it. ASYNC_P says what to do with the tty. If
1921 non-zero, then don't give it away. */
1923 make_child (command
, async_p
)
1931 /* XXX - block SIGTERM here and unblock in child after fork resets the
1932 set of pending signals? */
1934 sigaddset (&set
, SIGCHLD
);
1935 sigaddset (&set
, SIGINT
);
1936 sigemptyset (&oset
);
1937 sigprocmask (SIG_BLOCK
, &set
, &oset
);
1943 #if defined (BUFFERED_INPUT)
1944 /* If default_buffered_input is active, we are reading a script. If
1945 the command is asynchronous, we have already duplicated /dev/null
1946 as fd 0, but have not changed the buffered stream corresponding to
1947 the old fd 0. We don't want to sync the stream in this case. */
1948 if (default_buffered_input
!= -1 &&
1949 (!async_p
|| default_buffered_input
> 0))
1950 sync_buffered_stream (default_buffered_input
);
1951 #endif /* BUFFERED_INPUT */
1955 /* Create the child, handle severe errors. Retry on EAGAIN. */
1956 while ((pid
= fork ()) < 0 && errno
== EAGAIN
&& forksleep
< FORKSLEEP_MAX
)
1959 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
1960 /* If we can't create any children, try to reap some dead ones. */
1963 errno
= EAGAIN
; /* restore errno */
1964 sys_error ("fork: retry");
1967 if (sleep (forksleep
) != 0)
1971 if (interrupt_state
)
1973 sigprocmask (SIG_SETMASK
, &set
, (sigset_t
*)NULL
);
1983 /* Kill all of the processes in the current pipeline. */
1984 terminate_current_pipeline ();
1986 /* Discard the current pipeline, if any. */
1988 kill_current_pipeline ();
1990 last_command_exit_value
= EX_NOEXEC
;
1991 throw_to_top_level (); /* Reset signals, etc. */
1996 /* In the child. Give this child the right process group, set the
1997 signals to the default state for a new process. */
2001 #if defined (BUFFERED_INPUT)
2002 /* Close default_buffered_input if it's > 0. We don't close it if it's
2003 0 because that's the file descriptor used when redirecting input,
2004 and it's wrong to close the file in that case. */
2005 unset_bash_input (0);
2006 #endif /* BUFFERED_INPUT */
2008 CLRINTERRUPT
; /* XXX - children have their own interrupt state */
2010 /* Restore top-level signal mask. */
2011 sigprocmask (SIG_SETMASK
, &top_level_mask
, (sigset_t
*)NULL
);
2015 /* All processes in this pipeline belong in the same
2018 if (pipeline_pgrp
== 0) /* This is the first child. */
2019 pipeline_pgrp
= mypid
;
2021 /* Check for running command in backquotes. */
2022 if (pipeline_pgrp
== shell_pgrp
)
2023 ignore_tty_job_signals ();
2025 default_tty_job_signals ();
2027 /* Set the process group before trying to mess with the terminal's
2028 process group. This is mandated by POSIX. */
2029 /* This is in accordance with the Posix 1003.1 standard,
2030 section B.7.2.4, which says that trying to set the terminal
2031 process group with tcsetpgrp() to an unused pgrp value (like
2032 this would have for the first child) is an error. Section
2033 B.4.3.3, p. 237 also covers this, in the context of job control
2035 if (setpgid (mypid
, pipeline_pgrp
) < 0)
2036 sys_error (_("child setpgid (%ld to %ld)"), (long)mypid
, (long)pipeline_pgrp
);
2038 /* By convention (and assumption above), if
2039 pipeline_pgrp == shell_pgrp, we are making a child for
2040 command substitution.
2041 In this case, we don't want to give the terminal to the
2042 shell's process group (we could be in the middle of a
2043 pipeline, for example). */
2044 if (async_p
== 0 && pipeline_pgrp
!= shell_pgrp
&& ((subshell_environment
&(SUBSHELL_ASYNC
|SUBSHELL_PIPE
)) == 0) && running_in_background
== 0)
2045 give_terminal_to (pipeline_pgrp
, 0);
2047 #if defined (PGRP_PIPE)
2048 if (pipeline_pgrp
== mypid
)
2049 pipe_read (pgrp_pipe
);
2052 else /* Without job control... */
2054 if (pipeline_pgrp
== 0)
2055 pipeline_pgrp
= shell_pgrp
;
2057 /* If these signals are set to SIG_DFL, we encounter the curious
2058 situation of an interactive ^Z to a running process *working*
2059 and stopping the process, but being unable to do anything with
2060 that process to change its state. On the other hand, if they
2061 are set to SIG_IGN, jobs started from scripts do not stop when
2062 the shell running the script gets a SIGTSTP and stops. */
2064 default_tty_job_signals ();
2067 #if defined (PGRP_PIPE)
2068 /* Release the process group pipe, since our call to setpgid ()
2069 is done. The last call to sh_closepipe is done in stop_pipeline. */
2070 sh_closepipe (pgrp_pipe
);
2071 #endif /* PGRP_PIPE */
2074 /* Don't set last_asynchronous_pid in the child */
2076 last_asynchronous_pid
= mypid
; /* XXX */
2079 #if defined (RECYCLES_PIDS)
2080 if (last_asynchronous_pid
== mypid
)
2081 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2082 last_asynchronous_pid
= 1;
2087 /* In the parent. Remember the pid of the child just created
2088 as the proper pgrp if this is the first child. */
2092 if (pipeline_pgrp
== 0)
2094 pipeline_pgrp
= pid
;
2095 /* Don't twiddle terminal pgrps in the parent! This is the bug,
2096 not the good thing of twiddling them in the child! */
2097 /* give_terminal_to (pipeline_pgrp, 0); */
2099 /* This is done on the recommendation of the Rationale section of
2100 the POSIX 1003.1 standard, where it discusses job control and
2101 shells. It is done to avoid possible race conditions. (Ref.
2102 1003.1 Rationale, section B.4.3.3, page 236). */
2103 setpgid (pid
, pipeline_pgrp
);
2107 if (pipeline_pgrp
== 0)
2108 pipeline_pgrp
= shell_pgrp
;
2111 /* Place all processes into the jobs array regardless of the
2112 state of job_control. */
2113 add_process (command
, pid
);
2116 last_asynchronous_pid
= pid
;
2117 #if defined (RECYCLES_PIDS)
2118 else if (last_asynchronous_pid
== pid
)
2119 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2120 last_asynchronous_pid
= 1;
2123 /* Delete the saved status for any job containing this PID in case it's
2125 delete_old_job (pid
);
2127 /* Perform the check for pid reuse unconditionally. Some systems reuse
2128 PIDs before giving a process CHILD_MAX/_SC_CHILD_MAX unique ones. */
2129 bgp_delete (pid
); /* new process, discard any saved status */
2131 last_made_pid
= pid
;
2137 /* Unblock SIGINT and SIGCHLD unless creating a pipeline, in which case
2138 SIGCHLD remains blocked until all commands in the pipeline have been
2140 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
2146 /* These two functions are called only in child processes. */
2148 ignore_tty_job_signals ()
2150 set_signal_handler (SIGTSTP
, SIG_IGN
);
2151 set_signal_handler (SIGTTIN
, SIG_IGN
);
2152 set_signal_handler (SIGTTOU
, SIG_IGN
);
2155 /* Reset the tty-generated job control signals to SIG_DFL unless that signal
2156 was ignored at entry to the shell, in which case we need to set it to
2157 SIG_IGN in the child. We can't rely on resetting traps, since the hard
2158 ignored signals can't be trapped. */
2160 default_tty_job_signals ()
2162 if (signal_is_trapped (SIGTSTP
) == 0 && signal_is_hard_ignored (SIGTSTP
))
2163 set_signal_handler (SIGTSTP
, SIG_IGN
);
2165 set_signal_handler (SIGTSTP
, SIG_DFL
);
2167 if (signal_is_trapped (SIGTTIN
) == 0 && signal_is_hard_ignored (SIGTTIN
))
2168 set_signal_handler (SIGTTIN
, SIG_IGN
);
2170 set_signal_handler (SIGTTIN
, SIG_DFL
);
2172 if (signal_is_trapped (SIGTTOU
) == 0 && signal_is_hard_ignored (SIGTTOU
))
2173 set_signal_handler (SIGTTOU
, SIG_IGN
);
2175 set_signal_handler (SIGTTOU
, SIG_DFL
);
2178 /* Called once in a parent process. */
2180 get_original_tty_job_signals ()
2182 static int fetched
= 0;
2186 if (interactive_shell
)
2188 set_original_signal (SIGTSTP
, SIG_DFL
);
2189 set_original_signal (SIGTTIN
, SIG_DFL
);
2190 set_original_signal (SIGTTOU
, SIG_DFL
);
2194 get_original_signal (SIGTSTP
);
2195 get_original_signal (SIGTTIN
);
2196 get_original_signal (SIGTTOU
);
2202 /* When we end a job abnormally, or if we stop a job, we set the tty to the
2203 state kept in here. When a job ends normally, we set the state in here
2204 to the state of the tty. */
2206 static TTYSTRUCT shell_tty_info
;
2208 #if defined (NEW_TTY_DRIVER)
2209 static struct tchars shell_tchars
;
2210 static struct ltchars shell_ltchars
;
2211 #endif /* NEW_TTY_DRIVER */
2213 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
2214 /* Since the BSD tty driver does not allow us to change the tty modes
2215 while simultaneously waiting for output to drain and preserving
2216 typeahead, we have to drain the output ourselves before calling
2217 ioctl. We cheat by finding the length of the output queue, and
2218 using select to wait for an appropriate length of time. This is
2219 a hack, and should be labeled as such (it's a hastily-adapted
2220 mutation of a `usleep' implementation). It's only reason for
2221 existing is the flaw in the BSD tty driver. */
2223 static int ttspeeds
[] =
2225 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
2226 1800, 2400, 4800, 9600, 19200, 38400
2233 register int delay
= ttspeeds
[ospeed
];
2239 while ((ioctl (fd
, TIOCOUTQ
, &n
) == 0) && n
)
2241 if (n
> (delay
/ 100))
2245 n
*= 10; /* 2 bits more for conservativeness. */
2246 tv
.tv_sec
= n
/ delay
;
2247 tv
.tv_usec
= ((n
% delay
) * 1000000) / delay
;
2248 select (fd
, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &tv
);
2254 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
2256 /* Return the fd from which we are actually getting input. */
2257 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
2259 /* Fill the contents of shell_tty_info with the current tty info. */
2268 #if defined (NEW_TTY_DRIVER)
2269 ioctl (tty
, TIOCGETP
, &shell_tty_info
);
2270 ioctl (tty
, TIOCGETC
, &shell_tchars
);
2271 ioctl (tty
, TIOCGLTC
, &shell_ltchars
);
2272 #endif /* NEW_TTY_DRIVER */
2274 #if defined (TERMIO_TTY_DRIVER)
2275 ioctl (tty
, TCGETA
, &shell_tty_info
);
2276 #endif /* TERMIO_TTY_DRIVER */
2278 #if defined (TERMIOS_TTY_DRIVER)
2279 if (tcgetattr (tty
, &shell_tty_info
) < 0)
2282 /* Only print an error message if we're really interactive at
2285 sys_error ("[%ld: %d (%d)] tcgetattr", (long)getpid (), shell_level
, tty
);
2289 #endif /* TERMIOS_TTY_DRIVER */
2290 if (check_window_size
)
2291 get_new_window_size (0, (int *)0, (int *)0);
2296 /* Make the current tty use the state in shell_tty_info. */
2305 #if defined (NEW_TTY_DRIVER)
2306 # if defined (DRAIN_OUTPUT)
2307 draino (tty
, shell_tty_info
.sg_ospeed
);
2308 # endif /* DRAIN_OUTPUT */
2309 ioctl (tty
, TIOCSETN
, &shell_tty_info
);
2310 ioctl (tty
, TIOCSETC
, &shell_tchars
);
2311 ioctl (tty
, TIOCSLTC
, &shell_ltchars
);
2312 #endif /* NEW_TTY_DRIVER */
2314 #if defined (TERMIO_TTY_DRIVER)
2315 ioctl (tty
, TCSETAW
, &shell_tty_info
);
2316 #endif /* TERMIO_TTY_DRIVER */
2318 #if defined (TERMIOS_TTY_DRIVER)
2319 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
2321 /* Only print an error message if we're really interactive at
2324 sys_error ("[%ld: %d (%d)] tcsetattr", (long)getpid (), shell_level
, tty
);
2327 #endif /* TERMIOS_TTY_DRIVER */
2332 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2333 process in that job's pipeline. This is the one whose exit status
2334 counts. Must be called with SIGCHLD blocked or queued. */
2336 find_last_proc (job
, block
)
2340 register PROCESS
*p
;
2344 BLOCK_CHILD (set
, oset
);
2346 p
= jobs
[job
]->pipe
;
2347 while (p
&& p
->next
!= jobs
[job
]->pipe
)
2351 UNBLOCK_CHILD (oset
);
2357 find_last_pid (job
, block
)
2363 p
= find_last_proc (job
, block
);
2364 /* Possible race condition here. */
2368 /* Wait for a particular child of the shell to finish executing.
2369 This low-level function prints an error message if PID is not
2370 a child of this shell. It returns -1 if it fails, or whatever
2371 wait_for returns otherwise. If the child is not found in the
2372 jobs table, it returns 127. If FLAGS doesn't include 1, we
2373 suppress the error message if PID isn't found. */
2376 wait_for_single_pid (pid
, flags
)
2380 register PROCESS
*child
;
2384 BLOCK_CHILD (set
, oset
);
2385 child
= find_pipeline (pid
, 0, (int *)NULL
);
2386 UNBLOCK_CHILD (oset
);
2390 r
= bgp_search (pid
);
2398 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid
);
2404 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2406 BLOCK_CHILD (set
, oset
);
2407 job
= find_job (pid
, 0, NULL
);
2408 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
2409 jobs
[job
]->flags
|= J_NOTIFIED
;
2410 UNBLOCK_CHILD (oset
);
2412 /* If running in posix mode, remove the job from the jobs table immediately */
2413 if (posixly_correct
)
2415 cleanup_dead_jobs ();
2422 /* Wait for all of the background processes started by this shell to finish. */
2424 wait_for_background_pids ()
2426 register int i
, r
, waited_for
;
2430 for (waited_for
= 0;;)
2432 BLOCK_CHILD (set
, oset
);
2434 /* find first running job; if none running in foreground, break */
2435 /* XXX could use js.j_firstj and js.j_lastj here */
2436 for (i
= 0; i
< js
.j_jobslots
; i
++)
2439 if (i
< js
.j_firstj
&& jobs
[i
])
2440 itrace("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
2441 if (i
> js
.j_lastj
&& jobs
[i
])
2442 itrace("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
2444 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
2447 if (i
== js
.j_jobslots
)
2449 UNBLOCK_CHILD (oset
);
2453 /* now wait for the last pid in that job. */
2454 pid
= find_last_pid (i
, 0);
2455 UNBLOCK_CHILD (oset
);
2457 errno
= 0; /* XXX */
2458 r
= wait_for_single_pid (pid
, 1);
2461 /* If we're mistaken about job state, compensate. */
2462 if (errno
== ECHILD
)
2463 mark_all_jobs_as_dead ();
2469 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2470 `wait' is called with no arguments. */
2471 mark_dead_jobs_as_notified (1);
2472 cleanup_dead_jobs ();
2476 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2477 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2478 static SigHandler
*old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2480 static int wait_sigint_received
;
2481 static int child_caught_sigint
;
2482 static int waiting_for_child
;
2484 /* Clean up state after longjmp to wait_intr_buf */
2486 wait_sigint_cleanup ()
2489 waiting_for_child
= 0;
2493 restore_sigint_handler ()
2495 if (old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
2497 set_signal_handler (SIGINT
, old_sigint_handler
);
2498 old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2499 waiting_for_child
= 0;
2503 /* Handle SIGINT while we are waiting for children in a script to exit.
2504 The `wait' builtin should be interruptible, but all others should be
2505 effectively ignored (i.e. not cause the shell to exit). */
2507 wait_sigint_handler (sig
)
2510 SigHandler
*sigint_handler
;
2512 if (interrupt_immediately
||
2513 (this_shell_builtin
&& this_shell_builtin
== wait_builtin
))
2515 last_command_exit_value
= 128+SIGINT
;
2516 restore_sigint_handler ();
2517 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2518 what POSIX.2 says (see builtins/wait.def for more info). */
2519 if (this_shell_builtin
&& this_shell_builtin
== wait_builtin
&&
2520 signal_is_trapped (SIGINT
) &&
2521 ((sigint_handler
= trap_to_sighandler (SIGINT
)) == trap_handler
))
2523 trap_handler (SIGINT
); /* set pending_traps[SIGINT] */
2524 wait_signal_received
= SIGINT
;
2525 if (interrupt_immediately
&& wait_intr_flag
)
2527 interrupt_immediately
= 0;
2528 sh_longjmp (wait_intr_buf
, 1);
2531 /* Let CHECK_WAIT_INTR handle it in wait_for/waitchld */
2534 else if (interrupt_immediately
)
2539 else /* wait_builtin but signal not trapped, treat as interrupt */
2540 kill (getpid (), SIGINT
);
2543 /* XXX - should this be interrupt_state? If it is, the shell will act
2544 as if it got the SIGINT interrupt. */
2545 if (waiting_for_child
)
2546 wait_sigint_received
= 1;
2549 last_command_exit_value
= 128+SIGINT
;
2550 restore_sigint_handler ();
2551 kill (getpid (), SIGINT
);
2554 /* Otherwise effectively ignore the SIGINT and allow the running job to
2560 process_exit_signal (status
)
2563 return (WIFSIGNALED (status
) ? WTERMSIG (status
) : 0);
2567 process_exit_status (status
)
2570 if (WIFSIGNALED (status
))
2571 return (128 + WTERMSIG (status
));
2572 else if (WIFSTOPPED (status
) == 0)
2573 return (WEXITSTATUS (status
));
2575 return (EXECUTION_SUCCESS
);
2579 job_signal_status (job
)
2582 register PROCESS
*p
;
2585 p
= jobs
[job
]->pipe
;
2589 if (WIFSIGNALED(s
) || WIFSTOPPED(s
))
2593 while (p
!= jobs
[job
]->pipe
);
2598 /* Return the exit status of the last process in the pipeline for job JOB.
2599 This is the exit status of the entire job. */
2601 raw_job_exit_status (job
)
2604 register PROCESS
*p
;
2611 p
= jobs
[job
]->pipe
;
2614 if (WSTATUS (p
->status
) != EXECUTION_SUCCESS
)
2615 fail
= WSTATUS(p
->status
);
2618 while (p
!= jobs
[job
]->pipe
);
2619 WSTATUS (ret
) = fail
;
2623 for (p
= jobs
[job
]->pipe
; p
->next
!= jobs
[job
]->pipe
; p
= p
->next
)
2628 /* Return the exit status of job JOB. This is the exit status of the last
2629 (rightmost) process in the job's pipeline, modified if the job was killed
2630 by a signal or stopped. */
2632 job_exit_status (job
)
2635 return (process_exit_status (raw_job_exit_status (job
)));
2639 job_exit_signal (job
)
2642 return (process_exit_signal (raw_job_exit_status (job
)));
2645 #define FIND_CHILD(pid, child) \
2648 child = find_pipeline (pid, 0, (int *)NULL); \
2651 give_terminal_to (shell_pgrp, 0); \
2652 UNBLOCK_CHILD (oset); \
2653 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2654 restore_sigint_handler (); \
2655 return (termination_state = 127); \
2660 /* Wait for pid (one of our children) to terminate, then
2661 return the termination state. Returns 127 if PID is not found in
2662 the jobs table. Returns -1 if waitchld() returns -1, indicating
2663 that there are no unwaited-for child processes. */
2668 int job
, termination_state
, r
;
2670 register PROCESS
*child
;
2673 /* In the case that this code is interrupted, and we longjmp () out of it,
2674 we are relying on the code in throw_to_top_level () to restore the
2675 top-level signal mask. */
2677 BLOCK_CHILD (set
, oset
);
2679 /* Ignore interrupts while waiting for a job run without job control
2680 to finish. We don't want the shell to exit if an interrupt is
2681 received, only if one of the jobs run is killed via SIGINT. If
2682 job control is not set, the job will be run in the same pgrp as
2683 the shell, and the shell will see any signals the job gets. In
2684 fact, we want this set every time the waiting shell and the waited-
2685 for process are in the same process group, including command
2688 /* This is possibly a race condition -- should it go in stop_pipeline? */
2689 wait_sigint_received
= child_caught_sigint
= 0;
2690 if (job_control
== 0 || (subshell_environment
&SUBSHELL_COMSUB
))
2692 SigHandler
*temp_sigint_handler
;
2694 temp_sigint_handler
= set_signal_handler (SIGINT
, wait_sigint_handler
);
2695 if (temp_sigint_handler
== wait_sigint_handler
)
2698 internal_warning ("wait_for: recursively setting old_sigint_handler to wait_sigint_handler: running_trap = %d", running_trap
);
2702 old_sigint_handler
= temp_sigint_handler
;
2703 waiting_for_child
= 0;
2704 if (old_sigint_handler
== SIG_IGN
)
2705 set_signal_handler (SIGINT
, old_sigint_handler
);
2708 termination_state
= last_command_exit_value
;
2710 if (interactive
&& job_control
== 0)
2712 /* Check for terminating signals and exit the shell if we receive one */
2715 /* Check for a trapped signal interrupting the wait builtin and jump out */
2718 /* If we say wait_for (), then we have a record of this child somewhere.
2719 If it and none of its peers are running, don't call waitchld(). */
2725 FIND_CHILD (pid
, child
);
2727 /* If this child is part of a job, then we are really waiting for the
2728 job to finish. Otherwise, we are waiting for the child to finish.
2729 We check for JDEAD in case the job state has been set by waitchld
2730 after receipt of a SIGCHLD. */
2731 if (job
== NO_JOB
) /* XXX -- && pid != ANY_PID ? */
2732 job
= find_job (pid
, 0, NULL
);
2734 /* waitchld() takes care of setting the state of the job. If the job
2735 has already exited before this is called, sigchld_handler will have
2736 called waitchld and the state will be set to JDEAD. */
2738 if (pid
== ANY_PID
|| PRUNNING(child
) || (job
!= NO_JOB
&& RUNNING (job
)))
2740 #if defined (WAITPID_BROKEN) /* SCOv4 */
2741 sigset_t suspend_set
;
2742 sigemptyset (&suspend_set
);
2743 sigsuspend (&suspend_set
);
2744 #else /* !WAITPID_BROKEN */
2745 # if defined (MUST_UNBLOCK_CHLD)
2746 struct sigaction act
, oact
;
2747 sigset_t nullset
, chldset
;
2750 sigemptyset (&nullset
);
2751 sigemptyset (&chldset
);
2752 sigprocmask (SIG_SETMASK
, &nullset
, &chldset
);
2753 act
.sa_handler
= SIG_DFL
;
2754 sigemptyset (&act
.sa_mask
);
2755 sigemptyset (&oact
.sa_mask
);
2757 # if defined (SA_RESTART)
2758 act
.sa_flags
|= SA_RESTART
;
2760 sigaction (SIGCHLD
, &act
, &oact
);
2761 # endif /* MUST_UNBLOCK_CHLD */
2763 waiting_for_child
++;
2764 r
= waitchld (pid
, 1); /* XXX */
2765 waiting_for_child
--;
2767 itrace("wait_for: blocking wait for %d returns %d child = %p", (int)pid
, r
, child
);
2769 # if defined (MUST_UNBLOCK_CHLD)
2770 sigaction (SIGCHLD
, &oact
, (struct sigaction
*)NULL
);
2771 sigprocmask (SIG_SETMASK
, &chldset
, (sigset_t
*)NULL
);
2774 if (r
== -1 && errno
== ECHILD
&& this_shell_builtin
== wait_builtin
)
2776 termination_state
= -1;
2777 /* XXX - restore sigint handler here? */
2778 goto wait_for_return
;
2781 /* If child is marked as running, but waitpid() returns -1/ECHILD,
2782 there is something wrong. Somewhere, wait should have returned
2783 that child's pid. Mark the child as not running and the job,
2784 if it exists, as JDEAD. */
2785 if (r
== -1 && errno
== ECHILD
)
2789 child
->running
= PS_DONE
;
2790 WSTATUS (child
->status
) = 0; /* XXX -- can't find true status */
2792 js
.c_living
= 0; /* no living child processes */
2795 jobs
[job
]->state
= JDEAD
;
2801 termination_state
= -1;
2805 #endif /* WAITPID_BROKEN */
2808 /* If the shell is interactive, and job control is disabled, see
2809 if the foreground process has died due to SIGINT and jump out
2810 of the wait loop if it has. waitchld has already restored the
2811 old SIGINT signal handler. */
2812 if (interactive
&& job_control
== 0)
2814 /* Check for terminating signals and exit the shell if we receive one */
2817 /* Check for a trapped signal interrupting the wait builtin and jump out */
2821 /* XXX - could set child but we don't have a handle on what waitchld
2822 reaps. Leave termination_state alone. */
2823 goto wait_for_return
;
2825 while (PRUNNING (child
) || (job
!= NO_JOB
&& RUNNING (job
)));
2827 /* Restore the original SIGINT signal handler before we return. */
2828 restore_sigint_handler ();
2830 /* The exit state of the command is either the termination state of the
2831 child, or the termination state of the job. If a job, the status
2832 of the last child in the pipeline is the significant one. If the command
2833 or job was terminated by a signal, note that value also. */
2834 termination_state
= (job
!= NO_JOB
) ? job_exit_status (job
)
2835 : (child
? process_exit_status (child
->status
) : EXECUTION_SUCCESS
);
2836 last_command_exit_signal
= (job
!= NO_JOB
) ? job_exit_signal (job
)
2837 : (child
? process_exit_signal (child
->status
) : 0);
2840 if ((job
!= NO_JOB
&& JOBSTATE (job
) == JSTOPPED
) || (child
&& WIFSTOPPED (child
->status
)))
2841 termination_state
= 128 + WSTOPSIG (child
->status
);
2843 if (job
== NO_JOB
|| IS_JOBCONTROL (job
))
2845 /* XXX - under what circumstances is a job not present in the jobs
2846 table (job == NO_JOB)?
2847 1. command substitution
2849 In the case of command substitution, at least, it's probably not
2850 the right thing to give the terminal to the shell's process group,
2851 even though there is code in subst.c:command_substitute to work
2855 $PROMPT_COMMAND execution
2856 process substitution
2860 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp
);
2862 /* Don't modify terminal pgrp if we are running in background or a
2863 subshell. Make sure subst.c:command_substitute uses the same
2864 conditions to determine whether or not it should undo this and
2865 give the terminal to pipeline_pgrp. */
2867 if (running_in_background
== 0 && (subshell_environment
&(SUBSHELL_ASYNC
|SUBSHELL_PIPE
)) == 0)
2868 give_terminal_to (shell_pgrp
, 0);
2871 /* If the command did not exit cleanly, or the job is just
2872 being stopped, then reset the tty state back to what it
2873 was before this command. Reset the tty state and notify
2874 the user of the job termination only if the shell is
2875 interactive. Clean up any dead jobs in either case. */
2878 if (interactive_shell
&& subshell_environment
== 0)
2880 /* This used to use `child->status'. That's wrong, however, for
2881 pipelines. `child' is the first process in the pipeline. It's
2882 likely that the process we want to check for abnormal termination
2883 or stopping is the last process in the pipeline, especially if
2884 it's long-lived and the first process is short-lived. Since we
2885 know we have a job here, we can check all the processes in this
2886 job's pipeline and see if one of them stopped or terminated due
2887 to a signal. We might want to change this later to just check
2888 the last process in the pipeline. If no process exits due to a
2889 signal, S is left as the status of the last job in the pipeline. */
2890 s
= job_signal_status (job
);
2892 if (WIFSIGNALED (s
) || WIFSTOPPED (s
))
2896 /* If the current job was stopped or killed by a signal, and
2897 the user has requested it, get a possibly new window size */
2898 if (check_window_size
&& (job
== js
.j_current
|| IS_FOREGROUND (job
)))
2899 get_new_window_size (0, (int *)0, (int *)0);
2902 #if defined (READLINE)
2903 /* We don't want to do this if we are running a process during
2904 programmable completion. */
2905 if (RL_ISSTATE (RL_STATE_COMPLETING
) == 0)
2909 /* If job control is enabled, the job was started with job
2910 control, the job was the foreground job, and it was killed
2911 by SIGINT, then print a newline to compensate for the kernel
2912 printing the ^C without a trailing newline. */
2913 if (job_control
&& IS_JOBCONTROL (job
) && IS_FOREGROUND (job
) &&
2914 WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
)
2916 /* If SIGINT is not trapped and the shell is in a for, while,
2917 or until loop, act as if the shell received SIGINT as
2918 well, so the loop can be broken. This doesn't call the
2919 SIGINT signal handler; maybe it should. */
2920 if (signal_is_trapped (SIGINT
) == 0 && (loop_level
|| (shell_compatibility_level
> 32 && executing_list
)))
2922 /* Call any SIGINT trap handler if the shell is running a loop, so
2923 the loop can be broken. This seems more useful and matches the
2924 behavior when the shell is running a builtin command in a loop
2925 when it is interrupted. Change ADDINTERRUPT to
2926 trap_handler (SIGINT) to run the trap without interrupting the
2928 else if (signal_is_trapped (SIGINT
) && loop_level
)
2937 else if ((subshell_environment
& (SUBSHELL_COMSUB
|SUBSHELL_PIPE
)) && wait_sigint_received
)
2939 /* If waiting for a job in a subshell started to do command
2940 substitution or to run a pipeline element that consists of
2941 something like a while loop or a for loop, simulate getting
2942 and being killed by the SIGINT to pass the status back to our
2944 if (child_caught_sigint
== 0 && signal_is_trapped (SIGINT
) == 0)
2946 UNBLOCK_CHILD (oset
);
2947 old_sigint_handler
= set_signal_handler (SIGINT
, SIG_DFL
);
2948 if (old_sigint_handler
== SIG_IGN
)
2949 restore_sigint_handler ();
2951 kill (getpid (), SIGINT
);
2954 else if (interactive_shell
== 0 && IS_FOREGROUND (job
) && check_window_size
)
2955 get_new_window_size (0, (int *)0, (int *)0);
2957 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
2958 signal handler path */
2959 if (DEADJOB (job
) && IS_FOREGROUND (job
) /*&& subshell_environment == 0*/)
2962 /* If this job is dead, notify the user of the status. If the shell
2963 is interactive, this will display a message on the terminal. If
2964 the shell is not interactive, make sure we turn on the notify bit
2965 so we don't get an unwanted message about the job's termination,
2966 and so delete_job really clears the slot in the jobs table. */
2967 notify_and_cleanup ();
2972 UNBLOCK_CHILD (oset
);
2974 return (termination_state
);
2977 /* Wait for the last process in the pipeline for JOB. Returns whatever
2978 wait_for returns: the last process's termination state or -1 if there
2979 are no unwaited-for child processes or an error occurs. */
2988 BLOCK_CHILD(set
, oset
);
2989 if (JOBSTATE (job
) == JSTOPPED
)
2990 internal_warning (_("wait_for_job: job %d is stopped"), job
+1);
2992 pid
= find_last_pid (job
, 0);
2993 UNBLOCK_CHILD(oset
);
2996 /* POSIX.2: we can remove the job from the jobs table if we just waited
2998 BLOCK_CHILD (set
, oset
);
2999 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
3000 jobs
[job
]->flags
|= J_NOTIFIED
;
3001 UNBLOCK_CHILD (oset
);
3006 /* Wait for any background job started by this shell to finish. Very
3007 similar to wait_for_background_pids(). Returns the exit status of
3008 the next exiting job, -1 if there are no background jobs. The caller
3009 is responsible for translating -1 into the right return value. */
3014 int i
, r
, waited_for
;
3017 if (jobs_list_frozen
)
3020 /* First see if there are any unnotified dead jobs that we can report on */
3021 BLOCK_CHILD (set
, oset
);
3022 for (i
= 0; i
< js
.j_jobslots
; i
++)
3024 if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
) == 0)
3027 r
= job_exit_status (i
);
3028 notify_of_job_status (); /* XXX */
3030 #if defined (COPROCESS_SUPPORT)
3033 UNBLOCK_CHILD (oset
);
3037 UNBLOCK_CHILD (oset
);
3039 /* At this point, we have no dead jobs in the jobs table. Wait until we
3040 get one, even if it takes multiple pids exiting. */
3041 for (waited_for
= 0;;)
3043 /* Make sure there is a background job to wait for */
3044 BLOCK_CHILD (set
, oset
);
3045 for (i
= 0; i
< js
.j_jobslots
; i
++)
3046 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
3048 if (i
== js
.j_jobslots
)
3050 UNBLOCK_CHILD (oset
);
3054 UNBLOCK_CHILD (oset
);
3061 r
= wait_for (ANY_PID
); /* special sentinel value for wait_for */
3062 if (r
== -1 && errno
== ECHILD
)
3063 mark_all_jobs_as_dead ();
3065 /* Now we see if we have any dead jobs and return the first one */
3066 BLOCK_CHILD (set
, oset
);
3067 for (i
= 0; i
< js
.j_jobslots
; i
++)
3068 if (jobs
[i
] && DEADJOB (i
))
3070 UNBLOCK_CHILD (oset
);
3076 /* Print info about dead jobs, and then delete them from the list
3077 of known jobs. This does not actually delete jobs when the
3078 shell is not interactive, because the dead jobs are not marked
3081 notify_and_cleanup ()
3083 if (jobs_list_frozen
)
3086 if (interactive
|| interactive_shell
== 0 || sourcelevel
)
3087 notify_of_job_status ();
3089 cleanup_dead_jobs ();
3092 /* Make dead jobs disappear from the jobs array without notification.
3093 This is used when the shell is not interactive. */
3097 mark_dead_jobs_as_notified (0);
3098 cleanup_dead_jobs ();
3101 /* Return the next closest (chronologically) job to JOB which is in
3102 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
3103 there is no next recent job. */
3105 most_recent_job_in_state (job
, state
)
3109 register int i
, result
;
3112 BLOCK_CHILD (set
, oset
);
3114 for (result
= NO_JOB
, i
= job
- 1; i
>= 0; i
--)
3116 if (jobs
[i
] && (JOBSTATE (i
) == state
))
3123 UNBLOCK_CHILD (oset
);
3128 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
3131 job_last_stopped (job
)
3134 return (most_recent_job_in_state (job
, JSTOPPED
));
3137 /* Return the newest *running* job older than JOB, or NO_JOB if not
3140 job_last_running (job
)
3143 return (most_recent_job_in_state (job
, JRUNNING
));
3146 /* Make JOB be the current job, and make previous be useful. Must be
3147 called with SIGCHLD blocked. */
3149 set_current_job (job
)
3154 if (js
.j_current
!= job
)
3156 js
.j_previous
= js
.j_current
;
3160 /* First choice for previous job is the old current job. */
3161 if (js
.j_previous
!= js
.j_current
&&
3162 js
.j_previous
!= NO_JOB
&&
3163 jobs
[js
.j_previous
] &&
3164 STOPPED (js
.j_previous
))
3167 /* Second choice: Newest stopped job that is older than
3170 if (STOPPED (js
.j_current
))
3172 candidate
= job_last_stopped (js
.j_current
);
3174 if (candidate
!= NO_JOB
)
3176 js
.j_previous
= candidate
;
3181 /* If we get here, there is either only one stopped job, in which case it is
3182 the current job and the previous job should be set to the newest running
3183 job, or there are only running jobs and the previous job should be set to
3184 the newest running job older than the current job. We decide on which
3185 alternative to use based on whether or not JOBSTATE(js.j_current) is
3188 candidate
= RUNNING (js
.j_current
) ? job_last_running (js
.j_current
)
3189 : job_last_running (js
.j_jobslots
);
3191 if (candidate
!= NO_JOB
)
3193 js
.j_previous
= candidate
;
3197 /* There is only a single job, and it is both `+' and `-'. */
3198 js
.j_previous
= js
.j_current
;
3201 /* Make current_job be something useful, if it isn't already. */
3203 /* Here's the deal: The newest non-running job should be `+', and the
3204 next-newest non-running job should be `-'. If there is only a single
3205 stopped job, the js.j_previous is the newest non-running job. If there
3206 are only running jobs, the newest running job is `+' and the
3207 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
3214 if (js
.j_jobslots
&& js
.j_current
!= NO_JOB
&& jobs
[js
.j_current
] && STOPPED (js
.j_current
))
3215 candidate
= js
.j_current
;
3220 /* First choice: the previous job. */
3221 if (js
.j_previous
!= NO_JOB
&& jobs
[js
.j_previous
] && STOPPED (js
.j_previous
))
3222 candidate
= js
.j_previous
;
3224 /* Second choice: the most recently stopped job. */
3225 if (candidate
== NO_JOB
)
3226 candidate
= job_last_stopped (js
.j_jobslots
);
3228 /* Third choice: the newest running job. */
3229 if (candidate
== NO_JOB
)
3230 candidate
= job_last_running (js
.j_jobslots
);
3233 /* If we found a job to use, then use it. Otherwise, there
3234 are no jobs period. */
3235 if (candidate
!= NO_JOB
)
3236 set_current_job (candidate
);
3238 js
.j_current
= js
.j_previous
= NO_JOB
;
3241 /* Set up the job structures so we know the job and its processes are
3244 set_job_running (job
)
3247 register PROCESS
*p
;
3249 /* Each member of the pipeline is now running. */
3250 p
= jobs
[job
]->pipe
;
3254 if (WIFSTOPPED (p
->status
))
3255 p
->running
= PS_RUNNING
; /* XXX - could be PS_STOPPED */
3258 while (p
!= jobs
[job
]->pipe
);
3260 /* This means that the job is running. */
3261 JOBSTATE (job
) = JRUNNING
;
3264 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
3265 start the job in the background. JOB is a zero-based index into
3266 JOBS. Returns -1 if it is unable to start a job, and the return
3267 status of the job otherwise. */
3269 start_job (job
, foreground
)
3270 int job
, foreground
;
3272 register PROCESS
*p
;
3273 int already_running
;
3276 static TTYSTRUCT save_stty
;
3278 BLOCK_CHILD (set
, oset
);
3282 internal_error (_("%s: job has terminated"), this_command_name
);
3283 UNBLOCK_CHILD (oset
);
3287 already_running
= RUNNING (job
);
3289 if (foreground
== 0 && already_running
)
3291 internal_error (_("%s: job %d already in background"), this_command_name
, job
+ 1);
3292 UNBLOCK_CHILD (oset
);
3293 return (0); /* XPG6/SUSv3 says this is not an error */
3296 wd
= current_working_directory ();
3298 /* You don't know about the state of this job. Do you? */
3299 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3303 set_current_job (job
);
3304 jobs
[job
]->flags
|= J_FOREGROUND
;
3307 /* Tell the outside world what we're doing. */
3308 p
= jobs
[job
]->pipe
;
3310 if (foreground
== 0)
3312 /* POSIX.2 says `bg' doesn't give any indication about current or
3314 if (posixly_correct
== 0)
3315 s
= (job
== js
.j_current
) ? "+ ": ((job
== js
.j_previous
) ? "- " : " ");
3318 printf ("[%d]%s", job
+ 1, s
);
3324 p
->command
? p
->command
: "",
3325 p
->next
!= jobs
[job
]->pipe
? " | " : "");
3328 while (p
!= jobs
[job
]->pipe
);
3330 if (foreground
== 0)
3333 if (strcmp (wd
, jobs
[job
]->wd
) != 0)
3334 printf (" (wd: %s)", polite_directory_format (jobs
[job
]->wd
));
3339 if (already_running
== 0)
3340 set_job_running (job
);
3342 /* Save the tty settings before we start the job in the foreground. */
3346 save_stty
= shell_tty_info
;
3347 /* Give the terminal to this job. */
3348 if (IS_JOBCONTROL (job
))
3349 give_terminal_to (jobs
[job
]->pgrp
, 0);
3352 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3354 /* If the job is already running, then don't bother jump-starting it. */
3355 if (already_running
== 0)
3357 jobs
[job
]->flags
|= J_NOTIFIED
;
3358 killpg (jobs
[job
]->pgrp
, SIGCONT
);
3366 pid
= find_last_pid (job
, 0);
3367 UNBLOCK_CHILD (oset
);
3368 st
= wait_for (pid
);
3369 shell_tty_info
= save_stty
;
3376 UNBLOCK_CHILD (oset
);
3381 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
3382 If PID does belong to a job, and the job is stopped, then CONTinue the
3383 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
3384 then kill the process group associated with PID. */
3386 kill_pid (pid
, sig
, group
)
3390 register PROCESS
*p
;
3391 int job
, result
, negative
;
3397 group
= negative
= 1;
3402 result
= EXECUTION_SUCCESS
;
3405 BLOCK_CHILD (set
, oset
);
3406 p
= find_pipeline (pid
, 0, &job
);
3410 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3412 /* Kill process in backquotes or one started without job control? */
3414 /* If we're passed a pid < -1, just call killpg and see what happens */
3415 if (negative
&& jobs
[job
]->pgrp
== shell_pgrp
)
3416 result
= killpg (pid
, sig
);
3417 /* If we're killing using job control notification, for example,
3418 without job control active, we have to do things ourselves. */
3419 else if (jobs
[job
]->pgrp
== shell_pgrp
)
3421 p
= jobs
[job
]->pipe
;
3424 if (PALIVE (p
) == 0)
3425 continue; /* avoid pid recycling problem */
3427 if (PEXITED (p
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3428 kill (p
->pid
, SIGCONT
);
3431 while (p
!= jobs
[job
]->pipe
);
3435 result
= killpg (jobs
[job
]->pgrp
, sig
);
3436 if (p
&& STOPPED (job
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3437 killpg (jobs
[job
]->pgrp
, SIGCONT
);
3438 /* If we're continuing a stopped job via kill rather than bg or
3439 fg, emulate the `bg' behavior. */
3440 if (p
&& STOPPED (job
) && (sig
== SIGCONT
))
3442 set_job_running (job
);
3443 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3444 jobs
[job
]->flags
|= J_NOTIFIED
;
3449 result
= killpg (pid
, sig
);
3451 UNBLOCK_CHILD (oset
);
3454 result
= kill (pid
, sig
);
3459 /* sigchld_handler () flushes at least one of the children that we are
3460 waiting for. It gets run when we have gotten a SIGCHLD signal. */
3462 sigchld_handler (sig
)
3468 REINSTALL_SIGCHLD_HANDLER
;
3471 if (queue_sigchld
== 0)
3472 n
= waitchld (-1, 0);
3477 /* waitchld() reaps dead or stopped children. It's called by wait_for and
3478 sigchld_handler, and runs until there aren't any children terminating any
3480 If BLOCK is 1, this is to be a blocking wait for a single child, although
3481 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
3482 the number of children reaped, or -1 if there are no unwaited-for child
3485 waitchld (wpid
, block
)
3493 int call_set_current
, last_stopped_job
, job
, children_exited
, waitpid_flags
;
3494 static int wcontinued
= WCONTINUED
; /* run-time fix for glibc problem */
3496 call_set_current
= children_exited
= 0;
3497 last_stopped_job
= NO_JOB
;
3501 /* We don't want to be notified about jobs stopping if job control
3502 is not active. XXX - was interactive_shell instead of job_control */
3503 waitpid_flags
= (job_control
&& subshell_environment
== 0)
3504 ? (WUNTRACED
|wcontinued
)
3506 if (sigchld
|| block
== 0)
3507 waitpid_flags
|= WNOHANG
;
3509 /* Check for terminating signals and exit the shell if we receive one */
3511 /* Check for a trapped signal interrupting the wait builtin and jump out */
3514 if (block
== 1 && queue_sigchld
== 0 && (waitpid_flags
& WNOHANG
) == 0)
3516 internal_warning (_("waitchld: turning on WNOHANG to avoid indefinite block"));
3517 waitpid_flags
|= WNOHANG
;
3520 pid
= WAITPID (-1, &status
, waitpid_flags
);
3523 if (wpid
!= -1 && block
)
3524 itrace("waitchld: blocking waitpid returns %d", pid
);
3528 itrace("waitchld: %s waitpid returns %d", block
?"blocking":"non-blocking", pid
);
3530 /* WCONTINUED may be rejected by waitpid as invalid even when defined */
3531 if (wcontinued
&& pid
< 0 && errno
== EINVAL
)
3534 continue; /* jump back to the test and retry without WCONTINUED */
3537 /* The check for WNOHANG is to make sure we decrement sigchld only
3538 if it was non-zero before we called waitpid. */
3539 if (sigchld
> 0 && (waitpid_flags
& WNOHANG
))
3542 /* If waitpid returns -1 with errno == ECHILD, there are no more
3543 unwaited-for child processes of this shell. */
3544 if (pid
< 0 && errno
== ECHILD
)
3546 if (children_exited
== 0)
3553 itrace("waitchld: waitpid returns %d block = %d children_exited = %d", pid
, block
, children_exited
);
3555 /* If waitpid returns 0, there are running children. If it returns -1,
3556 the only other error POSIX says it can return is EINTR. */
3560 /* If waitpid returns -1/EINTR and the shell saw a SIGINT, then we
3561 assume the child has blocked or handled SIGINT. In that case, we
3562 require the child to actually die due to SIGINT to act on the
3563 SIGINT we received; otherwise we assume the child handled it and
3565 if (pid
< 0 && errno
== EINTR
&& wait_sigint_received
)
3566 child_caught_sigint
= 1;
3569 continue; /* jumps right to the test */
3571 /* Linux kernels appear to signal the parent but not interrupt the
3572 waitpid() (or restart it even without SA_RESTART) on SIGINT, so if
3573 we saw a SIGINT and the process exited or died due to some other
3574 signal, assume the child caught the SIGINT. */
3575 if (wait_sigint_received
&& (WIFSIGNALED (status
) == 0 || WTERMSIG (status
) != SIGINT
))
3576 child_caught_sigint
= 1;
3578 /* If the child process did die due to SIGINT, forget our assumption
3579 that it caught or otherwise handled it. */
3580 if (WIFSIGNALED (status
) && WTERMSIG (status
) == SIGINT
)
3581 child_caught_sigint
= 0;
3583 /* children_exited is used to run traps on SIGCHLD. We don't want to
3584 run the trap if a process is just being continued. */
3585 if (WIFCONTINUED(status
) == 0)
3591 /* Locate our PROCESS for this pid. */
3592 child
= find_process (pid
, 1, &job
); /* want living procs only */
3594 #if defined (COPROCESS_SUPPORT)
3595 coproc_pidchk (pid
, WSTATUS(status
));
3598 /* It is not an error to have a child terminate that we did
3599 not have a record of. This child could have been part of
3600 a pipeline in backquote substitution. Even so, I'm not
3601 sure child is ever non-zero. */
3604 if (WIFEXITED (status
) || WIFSIGNALED (status
))
3609 /* Remember status, and whether or not the process is running. */
3610 child
->status
= status
;
3611 child
->running
= WIFCONTINUED(status
) ? PS_RUNNING
: PS_DONE
;
3613 if (PEXITED (child
))
3623 call_set_current
+= set_job_status_and_cleanup (job
);
3626 last_stopped_job
= job
;
3627 else if (DEADJOB (job
) && last_stopped_job
== job
)
3628 last_stopped_job
= NO_JOB
;
3630 while ((sigchld
|| block
== 0) && pid
> (pid_t
)0);
3632 /* If a job was running and became stopped, then set the current
3633 job. Otherwise, don't change a thing. */
3634 if (call_set_current
)
3636 if (last_stopped_job
!= NO_JOB
)
3637 set_current_job (last_stopped_job
);
3642 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3643 if (job_control
&& children_exited
&&
3644 (signal_is_trapped (SIGCHLD
) || trap_list
[SIGCHLD
] == (char *)IMPOSSIBLE_TRAP_HANDLER
) &&
3645 trap_list
[SIGCHLD
] != (char *)IGNORE_SIG
)
3647 if (posixly_correct
&& this_shell_builtin
&& this_shell_builtin
== wait_builtin
)
3649 interrupt_immediately
= 0;
3650 /* This was trap_handler (SIGCHLD) but that can lose traps if
3651 children_exited > 1 */
3652 queue_sigchld_trap (children_exited
);
3653 wait_signal_received
= SIGCHLD
;
3654 /* If we're in a signal handler, let CHECK_WAIT_INTR pick it up;
3655 run_pending_traps will call run_sigchld_trap later */
3656 if (sigchld
== 0 && wait_intr_flag
)
3657 sh_longjmp (wait_intr_buf
, 1);
3659 /* If not in posix mode and not executing the wait builtin, queue the
3660 signal for later handling. Run the trap immediately if we are
3661 executing the wait builtin, but don't break out of `wait'. */
3662 else if (sigchld
) /* called from signal handler */
3663 queue_sigchld_trap (children_exited
);
3664 else if (signal_in_progress (SIGCHLD
))
3665 queue_sigchld_trap (children_exited
);
3666 else if (trap_list
[SIGCHLD
] == (char *)IMPOSSIBLE_TRAP_HANDLER
)
3667 queue_sigchld_trap (children_exited
);
3668 else if (running_trap
)
3669 queue_sigchld_trap (children_exited
);
3670 else if (this_shell_builtin
== wait_builtin
)
3671 run_sigchld_trap (children_exited
); /* XXX */
3673 queue_sigchld_trap (children_exited
);
3676 /* We have successfully recorded the useful information about this process
3677 that has just changed state. If we notify asynchronously, and the job
3678 that this process belongs to is no longer running, then notify the user
3679 of that fact now. */
3680 if (asynchronous_notification
&& interactive
)
3681 notify_of_job_status ();
3683 return (children_exited
);
3686 /* Set the status of JOB and perform any necessary cleanup if the job is
3689 Currently, the cleanup activity is restricted to handling any SIGINT
3690 received while waiting for a foreground job to finish. */
3692 set_job_status_and_cleanup (job
)
3696 int tstatus
, job_state
, any_stopped
, any_tstped
, call_set_current
;
3697 SigHandler
*temp_handler
;
3699 child
= jobs
[job
]->pipe
;
3700 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3702 call_set_current
= 0;
3705 * COMPUTE JOB STATUS
3708 /* If all children are not running, but any of them is stopped, then
3709 the job is stopped, not dead. */
3710 job_state
= any_stopped
= any_tstped
= 0;
3713 job_state
|= PRUNNING (child
);
3715 if (PEXITED (child
) && (WIFSTOPPED (child
->status
)))
3717 /* Only checking for WIFSTOPPED now, not for PS_DONE */
3718 if (PSTOPPED (child
))
3722 any_tstped
|= job_control
&& (WSTOPSIG (child
->status
) == SIGTSTP
);
3724 child
= child
->next
;
3726 while (child
!= jobs
[job
]->pipe
);
3728 /* If job_state != 0, the job is still running, so don't bother with
3729 setting the process exit status and job state unless we're
3730 transitioning from stopped to running. */
3731 if (job_state
!= 0 && JOBSTATE(job
) != JSTOPPED
)
3738 /* The job is either stopped or dead. Set the state of the job accordingly. */
3741 jobs
[job
]->state
= JSTOPPED
;
3742 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3744 /* Suspending a job with SIGTSTP breaks all active loops. */
3745 if (any_tstped
&& loop_level
)
3746 breaking
= loop_level
;
3748 else if (job_state
!= 0) /* was stopped, now running */
3750 jobs
[job
]->state
= JRUNNING
;
3755 jobs
[job
]->state
= JDEAD
;
3759 if (IS_FOREGROUND (job
))
3763 /* If this job has a cleanup function associated with it, call it
3764 with `cleanarg' as the single argument, then set the function
3765 pointer to NULL so it is not inadvertently called twice. The
3766 cleanup function is responsible for deallocating cleanarg. */
3767 if (jobs
[job
]->j_cleanup
)
3769 (*jobs
[job
]->j_cleanup
) (jobs
[job
]->cleanarg
);
3770 jobs
[job
]->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
3777 * Currently, we just do special things if we got a SIGINT while waiting
3778 * for a foreground job to complete
3781 if (JOBSTATE (job
) == JDEAD
)
3783 /* If we're running a shell script and we get a SIGINT with a
3784 SIGINT trap handler, but the foreground job handles it and
3785 does not exit due to SIGINT, run the trap handler but do not
3786 otherwise act as if we got the interrupt. */
3787 if (wait_sigint_received
&& interactive_shell
== 0 &&
3788 child_caught_sigint
&& IS_FOREGROUND (job
) &&
3789 signal_is_trapped (SIGINT
))
3792 wait_sigint_received
= 0;
3793 last_command_exit_value
= process_exit_status (child
->status
);
3795 old_frozen
= jobs_list_frozen
;
3796 jobs_list_frozen
= 1;
3797 tstatus
= maybe_call_trap_handler (SIGINT
);
3798 jobs_list_frozen
= old_frozen
;
3801 /* If the foreground job is killed by SIGINT when job control is not
3802 active, we need to perform some special handling.
3804 The check of wait_sigint_received is a way to determine if the
3805 SIGINT came from the keyboard (in which case the shell has already
3806 seen it, and wait_sigint_received is non-zero, because keyboard
3807 signals are sent to process groups) or via kill(2) to the foreground
3808 process by another process (or itself). If the shell did receive the
3809 SIGINT, it needs to perform normal SIGINT processing. XXX - should
3810 this change its behavior depending on whether the last command in an
3811 pipeline exited due to SIGINT, or any process in the pipeline? Right
3812 now it does this if any process in the pipeline exits due to SIGINT. */
3813 else if (wait_sigint_received
&&
3814 child_caught_sigint
== 0 &&
3815 IS_FOREGROUND (job
) && IS_JOBCONTROL (job
) == 0)
3819 wait_sigint_received
= 0;
3821 /* If SIGINT is trapped, set the exit status so that the trap
3822 handler can see it. */
3823 if (signal_is_trapped (SIGINT
))
3824 last_command_exit_value
= process_exit_status (child
->status
);
3826 /* If the signal is trapped, let the trap handler get it no matter
3827 what and simply return if the trap handler returns.
3828 maybe_call_trap_handler() may cause dead jobs to be removed from
3829 the job table because of a call to execute_command. We work
3830 around this by setting JOBS_LIST_FROZEN. */
3831 old_frozen
= jobs_list_frozen
;
3832 jobs_list_frozen
= 1;
3833 tstatus
= maybe_call_trap_handler (SIGINT
);
3834 jobs_list_frozen
= old_frozen
;
3835 if (tstatus
== 0 && old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
3837 /* wait_sigint_handler () has already seen SIGINT and
3838 allowed the wait builtin to jump out. We need to
3839 call the original SIGINT handler, if necessary. If
3840 the original handler is SIG_DFL, we need to resend
3841 the signal to ourselves. */
3843 temp_handler
= old_sigint_handler
;
3845 /* Bogus. If we've reset the signal handler as the result
3846 of a trap caught on SIGINT, then old_sigint_handler
3847 will point to trap_handler, which now knows nothing about
3848 SIGINT (if we reset the sighandler to the default).
3849 In this case, we have to fix things up. What a crock. */
3850 if (temp_handler
== trap_handler
&& signal_is_trapped (SIGINT
) == 0)
3851 temp_handler
= trap_to_sighandler (SIGINT
);
3852 restore_sigint_handler ();
3853 if (temp_handler
== SIG_DFL
)
3854 termsig_handler (SIGINT
); /* XXX */
3855 else if (temp_handler
!= SIG_IGN
)
3856 (*temp_handler
) (SIGINT
);
3861 return call_set_current
;
3864 /* Build the array of values for the $PIPESTATUS variable from the set of
3865 exit statuses of all processes in the job J. */
3870 #if defined (ARRAY_VARS)
3872 register PROCESS
*p
;
3874 for (i
= 1, p
= jobs
[j
]->pipe
; p
->next
!= jobs
[j
]->pipe
; p
= p
->next
, i
++)
3879 pstatuses
= (int *)xrealloc (pstatuses
, i
* sizeof (int));
3886 pstatuses
[i
++] = process_exit_status (p
->status
);
3889 while (p
!= jobs
[j
]->pipe
);
3891 pstatuses
[i
] = -1; /* sentinel */
3892 set_pipestatus_array (pstatuses
, i
);
3897 run_sigchld_trap (nchild
)
3903 /* Turn off the trap list during the call to parse_and_execute ()
3904 to avoid potentially infinite recursive calls. Preserve the
3905 values of last_command_exit_value, last_made_pid, and the_pipeline
3906 around the execution of the trap commands. */
3907 trap_command
= savestring (trap_list
[SIGCHLD
]);
3909 begin_unwind_frame ("SIGCHLD trap");
3910 unwind_protect_int (last_command_exit_value
);
3911 unwind_protect_int (last_command_exit_signal
);
3912 unwind_protect_var (last_made_pid
);
3913 unwind_protect_int (interrupt_immediately
);
3914 unwind_protect_int (jobs_list_frozen
);
3915 unwind_protect_pointer (the_pipeline
);
3916 unwind_protect_pointer (subst_assign_varlist
);
3917 unwind_protect_pointer (this_shell_builtin
);
3918 unwind_protect_pointer (temporary_env
);
3920 /* We have to add the commands this way because they will be run
3921 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
3922 to reference freed memory. */
3923 add_unwind_protect (xfree
, trap_command
);
3924 add_unwind_protect (maybe_set_sigchld_trap
, trap_command
);
3926 subst_assign_varlist
= (WORD_LIST
*)NULL
;
3927 the_pipeline
= (PROCESS
*)NULL
;
3928 temporary_env
= 0; /* traps should not run with temporary env */
3930 running_trap
= SIGCHLD
+ 1;
3932 set_impossible_sigchld_trap ();
3933 jobs_list_frozen
= 1;
3934 for (i
= 0; i
< nchild
; i
++)
3937 interrupt_immediately
= 1;
3939 parse_and_execute (savestring (trap_command
), "trap", SEVAL_NOHIST
|SEVAL_RESETLINE
);
3942 run_unwind_frame ("SIGCHLD trap");
3946 /* Function to call when you want to notify people of changes
3947 in job status. This prints out all jobs which are pending
3948 notification to stderr, and marks those printed as already
3949 notified, thus making them candidates for cleanup. */
3951 notify_of_job_status ()
3953 register int job
, termsig
;
3958 if (jobs
== 0 || js
.j_jobslots
== 0)
3964 sigaddset (&set
, SIGCHLD
);
3965 sigaddset (&set
, SIGTTOU
);
3966 sigemptyset (&oset
);
3967 sigprocmask (SIG_BLOCK
, &set
, &oset
);
3972 /* XXX could use js.j_firstj here */
3973 for (job
= 0, dir
= (char *)NULL
; job
< js
.j_jobslots
; job
++)
3975 if (jobs
[job
] && IS_NOTIFIED (job
) == 0)
3977 s
= raw_job_exit_status (job
);
3978 termsig
= WTERMSIG (s
);
3980 /* POSIX.2 says we have to hang onto the statuses of at most the
3981 last CHILD_MAX background processes if the shell is running a
3982 script. If the shell is running a script, either from a file
3983 or standard input, don't print anything unless the job was
3984 killed by a signal. */
3985 if (startup_state
== 0 && WIFSIGNALED (s
) == 0 &&
3986 ((DEADJOB (job
) && IS_FOREGROUND (job
) == 0) || STOPPED (job
)))
3990 /* If job control is disabled, don't print the status messages.
3991 Mark dead jobs as notified so that they get cleaned up. If
3992 startup_state == 2, we were started to run `-c command', so
3993 don't print anything. */
3994 if ((job_control
== 0 && interactive_shell
) || startup_state
== 2)
3996 /* If job control is disabled, don't print the status messages.
3997 Mark dead jobs as notified so that they get cleaned up. If
3998 startup_state == 2 and subshell_environment has the
3999 SUBSHELL_COMSUB bit turned on, we were started to run a command
4000 substitution, so don't print anything. */
4001 if ((job_control
== 0 && interactive_shell
) ||
4002 (startup_state
== 2 && (subshell_environment
& SUBSHELL_COMSUB
)))
4005 /* POSIX.2 compatibility: if the shell is not interactive,
4006 hang onto the job corresponding to the last asynchronous
4007 pid until the user has been notified of its status or does
4009 if (DEADJOB (job
) && (interactive_shell
|| (find_last_pid (job
, 0) != last_asynchronous_pid
)))
4010 jobs
[job
]->flags
|= J_NOTIFIED
;
4014 /* Print info on jobs that are running in the background,
4015 and on foreground jobs that were killed by anything
4016 except SIGINT (and possibly SIGPIPE). */
4017 switch (JOBSTATE (job
))
4020 if (interactive_shell
== 0 && termsig
&& WIFSIGNALED (s
) &&
4021 termsig
!= SIGINT
&&
4022 #if defined (DONT_REPORT_SIGTERM)
4023 termsig
!= SIGTERM
&&
4025 #if defined (DONT_REPORT_SIGPIPE)
4026 termsig
!= SIGPIPE
&&
4028 signal_is_trapped (termsig
) == 0)
4030 /* Don't print `0' for a line number. */
4031 fprintf (stderr
, _("%s: line %d: "), get_name_for_error (), (line_number
== 0) ? 1 : line_number
);
4032 pretty_print_job (job
, JLIST_NONINTERACTIVE
, stderr
);
4034 else if (IS_FOREGROUND (job
))
4036 #if !defined (DONT_REPORT_SIGPIPE)
4037 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
)
4039 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
&& termsig
!= SIGPIPE
)
4042 fprintf (stderr
, "%s", j_strsignal (termsig
));
4045 fprintf (stderr
, _(" (core dumped)"));
4047 fprintf (stderr
, "\n");
4050 else if (job_control
) /* XXX job control test added */
4053 dir
= current_working_directory ();
4054 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
4055 if (dir
&& strcmp (dir
, jobs
[job
]->wd
) != 0)
4057 _("(wd now: %s)\n"), polite_directory_format (dir
));
4060 jobs
[job
]->flags
|= J_NOTIFIED
;
4064 fprintf (stderr
, "\n");
4066 dir
= current_working_directory ();
4067 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
4068 if (dir
&& (strcmp (dir
, jobs
[job
]->wd
) != 0))
4070 _("(wd now: %s)\n"), polite_directory_format (dir
));
4071 jobs
[job
]->flags
|= J_NOTIFIED
;
4079 programming_error ("notify_of_job_status");
4084 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
4089 /* Initialize the job control mechanism, and set up the tty stuff. */
4091 initialize_job_control (force
)
4098 shell_pgrp
= getpgid (0);
4100 if (shell_pgrp
== -1)
4102 sys_error (_("initialize_job_control: getpgrp failed"));
4106 /* We can only have job control if we are interactive unless we force it. */
4107 if (interactive
== 0 && force
== 0)
4110 original_pgrp
= NO_PID
;
4111 shell_tty
= fileno (stderr
);
4112 terminal_pgrp
= tcgetpgrp (shell_tty
); /* for checking later */
4118 /* If forced_interactive is set, we skip the normal check that stderr
4119 is attached to a tty, so we need to check here. If it's not, we
4120 need to see whether we have a controlling tty by opening /dev/tty,
4121 since trying to use job control tty pgrp manipulations on a non-tty
4122 is going to fail. */
4123 if (forced_interactive
&& isatty (fileno (stderr
)) == 0)
4124 shell_tty
= open ("/dev/tty", O_RDWR
|O_NONBLOCK
);
4126 /* Get our controlling terminal. If job_control is set, or
4127 interactive is set, then this is an interactive shell no
4128 matter where fd 2 is directed. */
4129 if (shell_tty
== -1)
4130 shell_tty
= dup (fileno (stderr
)); /* fd 2 */
4132 if (shell_tty
!= -1)
4133 shell_tty
= move_to_high_fd (shell_tty
, 1, -1);
4135 /* Compensate for a bug in systems that compiled the BSD
4136 rlogind with DEBUG defined, like NeXT and Alliant. */
4137 if (shell_pgrp
== 0)
4139 shell_pgrp
= getpid ();
4140 setpgid (0, shell_pgrp
);
4141 if (shell_tty
!= -1)
4142 tcsetpgrp (shell_tty
, shell_pgrp
);
4145 while ((terminal_pgrp
= tcgetpgrp (shell_tty
)) != -1)
4147 if (shell_pgrp
!= terminal_pgrp
)
4151 ottin
= set_signal_handler (SIGTTIN
, SIG_DFL
);
4153 set_signal_handler (SIGTTIN
, ottin
);
4159 if (terminal_pgrp
== -1)
4162 /* Make sure that we are using the new line discipline. */
4163 if (set_new_line_discipline (shell_tty
) < 0)
4165 sys_error (_("initialize_job_control: line discipline"));
4170 original_pgrp
= shell_pgrp
;
4171 shell_pgrp
= getpid ();
4173 if ((original_pgrp
!= shell_pgrp
) && (setpgid (0, shell_pgrp
) < 0))
4175 sys_error (_("initialize_job_control: setpgid"));
4176 shell_pgrp
= original_pgrp
;
4181 /* If (and only if) we just set our process group to our pid,
4182 thereby becoming a process group leader, and the terminal
4183 is not in the same process group as our (new) process group,
4184 then set the terminal's process group to our (new) process
4185 group. If that fails, set our process group back to what it
4186 was originally (so we can still read from the terminal) and
4187 turn off job control. */
4188 if (shell_pgrp
!= original_pgrp
&& shell_pgrp
!= terminal_pgrp
)
4190 if (give_terminal_to (shell_pgrp
, 0) < 0)
4193 setpgid (0, original_pgrp
);
4194 shell_pgrp
= original_pgrp
;
4196 sys_error (_("cannot set terminal process group (%d)"), shell_pgrp
);
4201 if (job_control
&& ((t
= tcgetpgrp (shell_tty
)) == -1 || t
!= shell_pgrp
))
4205 sys_error (_("cannot set terminal process group (%d)"), t
);
4209 if (job_control
== 0)
4210 internal_error (_("no job control in this shell"));
4213 running_in_background
= terminal_pgrp
!= shell_pgrp
;
4215 if (shell_tty
!= fileno (stderr
))
4216 SET_CLOSE_ON_EXEC (shell_tty
);
4218 set_signal_handler (SIGCHLD
, sigchld_handler
);
4220 change_flag ('m', job_control
? '-' : '+');
4225 if (js
.c_childmax
< 0)
4226 js
.c_childmax
= getmaxchild ();
4227 if (js
.c_childmax
< 0)
4228 js
.c_childmax
= DEFAULT_CHILD_MAX
;
4231 if (js
.c_childmax
> MAX_CHILD_MAX
)
4232 js
.c_childmax
= MAX_CHILD_MAX
;
4240 debug_print_pgrps ()
4242 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
4243 (long)original_pgrp
, (long)shell_pgrp
, (long)terminal_pgrp
);
4244 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
4245 shell_tty
, (long)tcgetpgrp (shell_tty
), (long)getpgid(0));
4249 /* Set the line discipline to the best this system has to offer.
4250 Return -1 if this is not possible. */
4252 set_new_line_discipline (tty
)
4255 #if defined (NEW_TTY_DRIVER)
4258 if (ioctl (tty
, TIOCGETD
, &ldisc
) < 0)
4261 if (ldisc
!= NTTYDISC
)
4265 if (ioctl (tty
, TIOCSETD
, &ldisc
) < 0)
4269 #endif /* NEW_TTY_DRIVER */
4271 #if defined (TERMIO_TTY_DRIVER)
4272 # if defined (TERMIO_LDISC) && (NTTYDISC)
4273 if (ioctl (tty
, TCGETA
, &shell_tty_info
) < 0)
4276 if (shell_tty_info
.c_line
!= NTTYDISC
)
4278 shell_tty_info
.c_line
= NTTYDISC
;
4279 if (ioctl (tty
, TCSETAW
, &shell_tty_info
) < 0)
4282 # endif /* TERMIO_LDISC && NTTYDISC */
4284 #endif /* TERMIO_TTY_DRIVER */
4286 #if defined (TERMIOS_TTY_DRIVER)
4287 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
4288 if (tcgetattr (tty
, &shell_tty_info
) < 0)
4291 if (shell_tty_info
.c_line
!= NTTYDISC
)
4293 shell_tty_info
.c_line
= NTTYDISC
;
4294 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
4297 # endif /* TERMIOS_LDISC && NTTYDISC */
4299 #endif /* TERMIOS_TTY_DRIVER */
4301 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
4306 /* Setup this shell to handle C-C, etc. */
4308 initialize_job_signals ()
4312 set_signal_handler (SIGINT
, sigint_sighandler
);
4313 set_signal_handler (SIGTSTP
, SIG_IGN
);
4314 set_signal_handler (SIGTTOU
, SIG_IGN
);
4315 set_signal_handler (SIGTTIN
, SIG_IGN
);
4317 else if (job_control
)
4319 old_tstp
= set_signal_handler (SIGTSTP
, sigstop_sighandler
);
4320 old_ttin
= set_signal_handler (SIGTTIN
, sigstop_sighandler
);
4321 old_ttou
= set_signal_handler (SIGTTOU
, sigstop_sighandler
);
4323 /* Leave disposition unmodified for non-interactive shells without job
4327 /* Here we handle CONT signals. */
4329 sigcont_sighandler (sig
)
4332 initialize_job_signals ();
4333 set_signal_handler (SIGCONT
, old_cont
);
4334 kill (getpid (), SIGCONT
);
4339 /* Here we handle stop signals while we are running not as a login shell. */
4341 sigstop_sighandler (sig
)
4344 set_signal_handler (SIGTSTP
, old_tstp
);
4345 set_signal_handler (SIGTTOU
, old_ttou
);
4346 set_signal_handler (SIGTTIN
, old_ttin
);
4348 old_cont
= set_signal_handler (SIGCONT
, sigcont_sighandler
);
4350 give_terminal_to (shell_pgrp
, 0);
4352 kill (getpid (), sig
);
4357 /* Give the terminal to PGRP. */
4359 give_terminal_to (pgrp
, force
)
4367 if (job_control
|| force
)
4370 sigaddset (&set
, SIGTTOU
);
4371 sigaddset (&set
, SIGTTIN
);
4372 sigaddset (&set
, SIGTSTP
);
4373 sigaddset (&set
, SIGCHLD
);
4374 sigemptyset (&oset
);
4375 sigprocmask (SIG_BLOCK
, &set
, &oset
);
4377 if (tcsetpgrp (shell_tty
, pgrp
) < 0)
4379 /* Maybe we should print an error message? */
4381 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
4382 shell_tty
, (long)getpid(), (long)pgrp
);
4388 terminal_pgrp
= pgrp
;
4389 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
4398 /* Give terminal to NPGRP iff it's currently owned by OPGRP. FLAGS are the
4399 flags to pass to give_terminal_to(). */
4401 maybe_give_terminal_to (opgrp
, npgrp
, flags
)
4407 tpgrp
= tcgetpgrp (shell_tty
);
4408 if (tpgrp
< 0 && errno
== ENOTTY
)
4412 terminal_pgrp
= npgrp
;
4415 else if (tpgrp
!= opgrp
)
4418 internal_warning ("%d: maybe_give_terminal_to: terminal pgrp == %d shell pgrp = %d new pgrp = %d in_background = %d", (int)getpid(), tpgrp
, opgrp
, npgrp
, running_in_background
);
4423 return (give_terminal_to (npgrp
, flags
));
4426 /* Clear out any jobs in the job array. This is intended to be used by
4427 children of the shell, who should not have any job structures as baggage
4428 when they start executing (forking subshells for parenthesized execution
4429 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
4430 is nonzero, only running jobs are removed from the table. */
4432 delete_all_jobs (running_only
)
4438 BLOCK_CHILD (set
, oset
);
4440 /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
4443 js
.j_current
= js
.j_previous
= NO_JOB
;
4445 /* XXX could use js.j_firstj here */
4446 for (i
= 0; i
< js
.j_jobslots
; i
++)
4449 if (i
< js
.j_firstj
&& jobs
[i
])
4450 itrace("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4451 if (i
> js
.j_lastj
&& jobs
[i
])
4452 itrace("delete_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4454 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
4455 /* We don't want to add any of these pids to bgpids. If running_only
4456 is non-zero, we don't want to add running jobs to the list.
4457 If we are interested in all jobs, not just running jobs, and
4458 we are going to clear the bgpids list below (bgp_clear()), we
4459 don't need to bother. */
4460 delete_job (i
, DEL_WARNSTOPPED
|DEL_NOBGPID
);
4462 if (running_only
== 0)
4464 free ((char *)jobs
);
4466 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
4470 if (running_only
== 0)
4473 UNBLOCK_CHILD (oset
);
4476 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
4477 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
4479 nohup_all_jobs (running_only
)
4485 BLOCK_CHILD (set
, oset
);
4489 /* XXX could use js.j_firstj here */
4490 for (i
= 0; i
< js
.j_jobslots
; i
++)
4491 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
4495 UNBLOCK_CHILD (oset
);
4504 /* This really counts all non-dead jobs. */
4505 BLOCK_CHILD (set
, oset
);
4506 /* XXX could use js.j_firstj here */
4507 for (i
= n
= 0; i
< js
.j_jobslots
; i
++)
4510 if (i
< js
.j_firstj
&& jobs
[i
])
4511 itrace("count_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4512 if (i
> js
.j_lastj
&& jobs
[i
])
4513 itrace("count_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4515 if (jobs
[i
] && DEADJOB(i
) == 0)
4518 UNBLOCK_CHILD (oset
);
4523 mark_all_jobs_as_dead ()
4528 if (js
.j_jobslots
== 0)
4531 BLOCK_CHILD (set
, oset
);
4533 /* XXX could use js.j_firstj here */
4534 for (i
= 0; i
< js
.j_jobslots
; i
++)
4537 jobs
[i
]->state
= JDEAD
;
4541 UNBLOCK_CHILD (oset
);
4544 /* Mark all dead jobs as notified, so delete_job () cleans them out
4545 of the job table properly. POSIX.2 says we need to save the
4546 status of the last CHILD_MAX jobs, so we count the number of dead
4547 jobs and mark only enough as notified to save CHILD_MAX statuses. */
4549 mark_dead_jobs_as_notified (force
)
4552 register int i
, ndead
, ndeadproc
;
4555 if (js
.j_jobslots
== 0)
4558 BLOCK_CHILD (set
, oset
);
4560 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
4561 around; just run through the array. */
4564 /* XXX could use js.j_firstj here */
4565 for (i
= 0; i
< js
.j_jobslots
; i
++)
4567 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4568 jobs
[i
]->flags
|= J_NOTIFIED
;
4570 UNBLOCK_CHILD (oset
);
4574 /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
4575 array with the corresponding not marked as notified. This is a better
4576 way to avoid pid aliasing and reuse problems than keeping the POSIX-
4577 mandated CHILD_MAX jobs around. delete_job() takes care of keeping the
4578 bgpids list regulated. */
4580 /* Count the number of dead jobs */
4581 /* XXX could use js.j_firstj here */
4582 for (i
= ndead
= ndeadproc
= 0; i
< js
.j_jobslots
; i
++)
4585 if (i
< js
.j_firstj
&& jobs
[i
])
4586 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4587 if (i
> js
.j_lastj
&& jobs
[i
])
4588 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4590 if (jobs
[i
] && DEADJOB (i
))
4593 ndeadproc
+= processes_in_job (i
);
4599 if (ndeadproc
!= js
.c_reaped
)
4600 itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc
, js
.c_reaped
);
4602 if (ndead
!= js
.j_ndead
)
4603 itrace("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead
, js
.j_ndead
);
4606 if (js
.c_childmax
< 0)
4607 js
.c_childmax
= getmaxchild ();
4608 if (js
.c_childmax
< 0)
4609 js
.c_childmax
= DEFAULT_CHILD_MAX
;
4612 if (js
.c_childmax
> MAX_CHILD_MAX
)
4613 js
.c_childmax
= MAX_CHILD_MAX
;
4616 /* Don't do anything if the number of dead processes is less than CHILD_MAX
4617 and we're not forcing a cleanup. */
4618 if (ndeadproc
<= js
.c_childmax
)
4620 UNBLOCK_CHILD (oset
);
4625 itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js
.c_childmax
, ndead
, ndeadproc
);
4628 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
4629 the list. This isn't exactly right yet; changes need to be made
4630 to stop_pipeline so we don't mark the newer jobs after we've
4631 created CHILD_MAX slots in the jobs array. This needs to be
4632 integrated with a way to keep the jobs array from growing without
4633 bound. Maybe we wrap back around to 0 after we reach some max
4634 limit, and there are sufficient job slots free (keep track of total
4635 size of jobs array (js.j_jobslots) and running count of number of jobs
4636 in jobs array. Then keep a job index corresponding to the `oldest job'
4637 and start this loop there, wrapping around as necessary. In effect,
4638 we turn the list into a circular buffer. */
4639 /* XXX could use js.j_firstj here */
4640 for (i
= 0; i
< js
.j_jobslots
; i
++)
4642 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4645 if (i
< js
.j_firstj
&& jobs
[i
])
4646 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4647 if (i
> js
.j_lastj
&& jobs
[i
])
4648 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4650 /* If marking this job as notified would drop us down below
4651 child_max, don't mark it so we can keep at least child_max
4652 statuses. XXX -- need to check what Posix actually says
4653 about keeping statuses. */
4654 if ((ndeadproc
-= processes_in_job (i
)) <= js
.c_childmax
)
4656 jobs
[i
]->flags
|= J_NOTIFIED
;
4660 UNBLOCK_CHILD (oset
);
4663 /* Here to allow other parts of the shell (like the trap stuff) to
4664 freeze and unfreeze the jobs list. */
4670 o
= jobs_list_frozen
;
4671 jobs_list_frozen
= 1;
4676 unfreeze_jobs_list ()
4678 jobs_list_frozen
= 0;
4681 /* Allow or disallow job control to take place. Returns the old value
4684 set_job_control (arg
)
4692 if (terminal_pgrp
== NO_PID
)
4693 terminal_pgrp
= tcgetpgrp (shell_tty
);
4695 running_in_background
= (terminal_pgrp
!= shell_pgrp
);
4698 if (interactive_shell
== 0 && running_in_background
== 0 && job_control
!= old
)
4701 initialize_job_signals ();
4703 default_tty_job_signals ();
4707 /* If we're turning on job control, reset pipeline_pgrp so make_child will
4708 put new child processes into the right pgrp */
4709 if (job_control
!= old
&& job_control
)
4715 /* Turn off all traces of job control. This is run by children of the shell
4716 which are going to do shellsy things, like wait (), etc. */
4718 without_job_control ()
4720 stop_making_children ();
4722 #if defined (PGRP_PIPE)
4723 sh_closepipe (pgrp_pipe
);
4725 delete_all_jobs (0);
4726 set_job_control (0);
4729 /* If this shell is interactive, terminate all stopped jobs and
4730 restore the original terminal process group. This is done
4731 before the `exec' builtin calls shell_execve. */
4735 if (interactive_shell
|| job_control
) /* XXX - should it be just job_control? */
4737 terminate_stopped_jobs ();
4739 if (original_pgrp
>= 0)
4740 give_terminal_to (original_pgrp
, 1);
4743 if (original_pgrp
>= 0)
4744 setpgid (0, original_pgrp
);
4747 /* Restart job control by closing shell tty and reinitializing. This is
4748 called after an exec fails in an interactive shell and we do not exit. */
4750 restart_job_control ()
4752 if (shell_tty
!= -1)
4754 initialize_job_control (0);
4758 set_maxchild (nchild
)
4761 static int lmaxchild
= -1;
4764 lmaxchild
= getmaxchild ();
4766 lmaxchild
= DEFAULT_CHILD_MAX
;
4768 /* Clamp value we set. Minimum is what Posix requires, maximum is defined
4769 above as MAX_CHILD_MAX. */
4770 if (nchild
< lmaxchild
)
4772 else if (nchild
> MAX_CHILD_MAX
)
4773 nchild
= MAX_CHILD_MAX
;
4775 js
.c_childmax
= nchild
;
4778 /* Set the handler to run when the shell receives a SIGCHLD signal. */
4780 set_sigchld_handler ()
4782 set_signal_handler (SIGCHLD
, sigchld_handler
);
4785 #if defined (PGRP_PIPE)
4786 /* Read from the read end of a pipe. This is how the process group leader
4787 blocks until all of the processes in a pipeline have been made. */
4802 while (read (pp
[0], &ch
, 1) == -1 && errno
== EINTR
)
4807 /* Functional interface closes our local-to-job-control pipes. */
4811 sh_closepipe (pgrp_pipe
);
4815 save_pgrp_pipe (p
, clear
)
4819 p
[0] = pgrp_pipe
[0];
4820 p
[1] = pgrp_pipe
[1];
4822 pgrp_pipe
[0] = pgrp_pipe
[1] = -1;
4826 restore_pgrp_pipe (p
)
4829 pgrp_pipe
[0] = p
[0];
4830 pgrp_pipe
[1] = p
[1];
4833 #endif /* PGRP_PIPE */