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-2024 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>
54 /* Need to include this up here for *_TTY_DRIVER definitions. */
57 /* Define this if your output is getting swallowed. It's a no-op on
58 machines with the termio or termios tty drivers. */
59 /* #define DRAIN_OUTPUT */
61 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
62 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
64 #endif /* hpux && !TERMIOS_TTY_DRIVER */
71 #include "execute_cmd.h"
76 #include "builtins/builtext.h"
77 #include "builtins/common.h"
79 #if defined (READLINE)
80 # include <readline/readline.h>
87 #if !defined (HAVE_KILLPG)
88 extern int killpg (pid_t
, int);
91 #if !DEFAULT_CHILD_MAX
92 # define DEFAULT_CHILD_MAX 4096
96 # define MAX_CHILD_MAX 32768
100 #define MAX_JOBS_IN_ARRAY 4096 /* production */
102 #define MAX_JOBS_IN_ARRAY 128 /* testing */
106 #define PIDSTAT_TABLE_SZ 4096
107 #define BGPIDS_TABLE_SZ 512
109 /* Flag values for second argument to delete_job */
110 #define DEL_WARNSTOPPED 1 /* warn about deleting stopped jobs */
111 #define DEL_NOBGPID 2 /* don't add pgrp leader to bgpids */
113 /* Take care of system dependencies that must be handled when waiting for
114 children. The arguments to the WAITPID macro match those to the Posix.1
115 waitpid() function. */
117 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
118 # define WAITPID(pid, statusp, options) \
119 wait3 ((union wait *)statusp, options, (struct rusage *)0)
121 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
122 # define WAITPID(pid, statusp, options) \
123 waitpid ((pid_t)pid, statusp, options)
125 # if defined (HAVE_WAIT3)
126 # define WAITPID(pid, statusp, options) \
127 wait3 (statusp, options, (struct rusage *)0)
129 # define WAITPID(pid, statusp, options) \
130 wait3 (statusp, options, (int *)0)
131 # endif /* HAVE_WAIT3 */
132 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
133 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
135 /* getpgrp () varies between systems. Even systems that claim to be
136 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
137 #if defined (GETPGRP_VOID)
138 # define getpgid(p) getpgrp ()
140 # define getpgid(p) getpgrp (p)
141 #endif /* !GETPGRP_VOID */
143 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
144 handler for SIGCHLD. */
145 #if defined (MUST_REINSTALL_SIGHANDLERS)
146 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
148 # define REINSTALL_SIGCHLD_HANDLER
149 #endif /* !MUST_REINSTALL_SIGHANDLERS */
151 /* Some systems let waitpid(2) tell callers about stopped children. */
152 #if !defined (WCONTINUED) || defined (WCONTINUED_BROKEN)
154 # define WCONTINUED 0
156 #if !defined (WIFCONTINUED)
157 # define WIFCONTINUED(s) (0)
160 /* The number of additional slots to allocate when we run out. */
163 typedef int sh_job_map_func_t (JOB
*, int, int, int);
165 /* Variables used here but defined in other files. */
166 extern WORD_LIST
*subst_assign_varlist
;
168 extern SigHandler
**original_signals
;
170 extern void set_original_signal (int, SigHandler
*);
172 static struct jobstats zerojs
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
173 struct jobstats js
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
175 ps_index_t pidstat_table
[PIDSTAT_TABLE_SZ
];
176 struct bgpids bgpids
= { 0, 0, 0, 0 };
178 struct procchain procsubs
= { 0, 0, 0 };
180 /* The array of known jobs. */
181 JOB
**jobs
= (JOB
**)NULL
;
184 /* The number of slots currently allocated to JOBS. */
188 /* The controlling tty for this shell. */
191 /* The shell's process group. */
192 pid_t shell_pgrp
= NO_PID
;
194 /* The terminal's process group. */
195 pid_t terminal_pgrp
= NO_PID
;
197 /* The process group of the shell's parent. */
198 pid_t original_pgrp
= NO_PID
;
200 /* The process group of the pipeline currently being made. */
201 pid_t pipeline_pgrp
= (pid_t
)0;
203 #if defined (PGRP_PIPE)
204 /* Pipes which each shell uses to communicate with the process group leader
205 until all of the processes in a pipeline have been started. Then the
206 process leader is allowed to continue. */
207 int pgrp_pipe
[2] = { -1, -1 };
210 /* Last child made by the shell. */
211 volatile pid_t last_made_pid
= NO_PID
;
213 /* Pid of the last asynchronous child. */
214 volatile pid_t last_asynchronous_pid
= NO_PID
;
216 /* The pipeline currently being built. */
217 PROCESS
*the_pipeline
= (PROCESS
*)NULL
;
219 /* If this is non-zero, do job control. */
222 /* Are we running in background? (terminal_pgrp != shell_pgrp) */
223 int running_in_background
= 0;
225 /* Call this when you start making children. */
226 int already_making_children
= 0;
228 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
229 exits from get_tty_state(). */
230 int check_window_size
= CHECKWINSIZE_DEFAULT
;
232 PROCESS
*last_procsub_child
= (PROCESS
*)NULL
;
234 /* Functions local to this file. */
236 void debug_print_pgrps (void);
238 static sighandler
wait_sigint_handler (int);
239 static sighandler
sigchld_handler (int);
240 static sighandler
sigcont_sighandler (int);
241 static sighandler
sigstop_sighandler (int);
243 static int waitchld (pid_t
, int);
245 static PROCESS
*find_pid_in_pipeline (pid_t
, PROCESS
*, int);
246 static PROCESS
*find_pipeline (pid_t
, int, int *);
247 static PROCESS
*find_process (pid_t
, int, int *);
249 static char *current_working_directory (void);
250 static char *job_working_directory (void);
251 static char *j_strsignal (int);
252 static char *printable_job_status (int, PROCESS
*, int);
254 static PROCESS
*find_last_proc (int, int);
255 static pid_t
find_last_pid (int, int);
257 static int set_new_line_discipline (int);
258 static int map_over_jobs (sh_job_map_func_t
*, int, int);
259 static int job_last_stopped (int);
260 static int job_last_running (int);
261 static int most_recent_job_in_state (int, JOB_STATE
);
262 static int find_job (pid_t
, int, PROCESS
**);
263 static int print_job (JOB
*, int, int, int);
264 static int process_exit_status (WAIT
);
265 static int process_exit_signal (WAIT
);
266 static int set_job_status_and_cleanup (int);
268 static WAIT
job_signal_status (int);
269 static WAIT
raw_job_exit_status (int);
271 static int job_killed_by_signal (int);
273 static void notify_of_job_status (void);
274 static void reset_job_indices (void);
275 static void cleanup_dead_jobs (void);
276 static int processes_in_job (int);
277 static void realloc_jobs_list (void);
278 static int compact_jobs_list (int);
279 static void add_process (char *, pid_t
);
280 static void print_pipeline (PROCESS
*, int, int, FILE *);
281 static void pretty_print_job (int, int, FILE *);
282 static void set_current_job (int);
283 static void reset_current (void);
284 static void set_job_running (int);
285 static void setjstatus (int);
286 static int maybe_give_terminal_to (pid_t
, pid_t
, int);
287 static void mark_all_jobs_as_dead (void);
288 static void mark_dead_jobs_as_notified (int);
289 static void restore_sigint_handler (void);
290 #if defined (PGRP_PIPE)
291 static void pipe_read (int *);
294 /* Hash table manipulation */
296 static ps_index_t
*pshash_getbucket (pid_t
);
297 static void pshash_delindex (ps_index_t
);
299 /* Saved background process status management */
300 static struct pidstat
*bgp_add (pid_t
, int);
301 static int bgp_delete (pid_t
);
302 static void bgp_clear (void);
303 static int bgp_search (pid_t
);
305 static struct pipeline_saver
*alloc_pipeline_saver (void);
307 static ps_index_t
bgp_getindex (void);
308 static void bgp_resize (void); /* XXX */
310 #if defined (ARRAY_VARS)
311 static int *pstatuses
; /* list of pipeline statuses */
315 /* Used to synchronize between wait_for and other functions and the SIGCHLD
318 static int queue_sigchld
;
320 #define QUEUE_SIGCHLD(os) (os) = sigchld, queue_sigchld++
322 /* We set queue_sigchld around the call to waitchld to protect data structures
323 from a SIGCHLD arriving while waitchld is executing. */
324 #define UNQUEUE_SIGCHLD(os) \
327 if (queue_sigchld == 0 && os != sigchld) \
335 static SigHandler
*old_tstp
, *old_ttou
, *old_ttin
;
336 static SigHandler
*old_cont
= (SigHandler
*)SIG_DFL
;
338 /* A place to temporarily save the current pipeline. */
339 static struct pipeline_saver
*saved_pipeline
;
341 /* Set this to non-zero whenever you don't want the jobs list to change at
342 all: no jobs deleted and no status change notifications. This is used,
343 for example, when executing SIGCHLD traps, which may run arbitrary
345 static int jobs_list_frozen
;
347 static char retcode_name_buffer
[64];
349 #if !defined (_POSIX_VERSION)
351 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
352 library functions and system calls. */
353 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
354 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
361 /* ioctl will handle setting errno correctly. */
362 if (ioctl (fd
, TIOCGPGRP
, &pgrp
) < 0)
367 #endif /* !_POSIX_VERSION */
369 /* Initialize the global job stats structure and other bookkeeping variables */
371 init_job_stats (void)
376 /* Return the working directory for the current process. Unlike
377 job_working_directory, this does not call malloc (), nor do any
378 of the functions it calls. This is so that it can safely be called
379 from a signal handler. */
381 current_working_directory (void)
384 static char d
[PATH_MAX
];
386 dir
= get_string_value ("PWD");
388 if (dir
== 0 && the_current_working_directory
&& no_symbolic_links
)
389 dir
= the_current_working_directory
;
393 dir
= getcwd (d
, sizeof(d
));
398 return (dir
== 0) ? "<unknown>" : dir
;
401 /* Return the working directory for the current process. */
403 job_working_directory (void)
407 dir
= get_string_value ("PWD");
409 return (savestring (dir
));
411 dir
= get_working_directory ("job-working-directory");
415 return (savestring ("<unknown>"));
419 making_children (void)
421 if (already_making_children
)
424 already_making_children
= 1;
429 stop_making_children (void)
431 already_making_children
= 0;
435 cleanup_the_pipeline (void)
440 BLOCK_CHILD (set
, oset
);
441 disposer
= the_pipeline
;
442 the_pipeline
= (PROCESS
*)NULL
;
443 UNBLOCK_CHILD (oset
);
446 discard_pipeline (disposer
);
449 /* Not used right now */
451 discard_last_procsub_child (void)
456 BLOCK_CHILD (set
, oset
);
457 disposer
= last_procsub_child
;
458 last_procsub_child
= (PROCESS
*)NULL
;
459 UNBLOCK_CHILD (oset
);
462 discard_pipeline (disposer
);
465 static struct pipeline_saver
*
466 alloc_pipeline_saver (void)
468 struct pipeline_saver
*ret
;
470 ret
= (struct pipeline_saver
*)xmalloc (sizeof (struct pipeline_saver
));
472 ret
->already_making_children
= 0;
478 save_pipeline (int clear
)
481 struct pipeline_saver
*saver
;
483 BLOCK_CHILD (set
, oset
);
484 saver
= alloc_pipeline_saver ();
485 saver
->pipeline
= the_pipeline
;
486 saver
->already_making_children
= already_making_children
;
487 saver
->next
= saved_pipeline
;
488 saved_pipeline
= saver
;
490 the_pipeline
= (PROCESS
*)NULL
;
491 UNBLOCK_CHILD (oset
);
495 restore_pipeline (int discard
)
497 PROCESS
*old_pipeline
;
499 struct pipeline_saver
*saver
;
501 BLOCK_CHILD (set
, oset
);
502 old_pipeline
= the_pipeline
;
503 the_pipeline
= saved_pipeline
->pipeline
;
504 already_making_children
= saved_pipeline
->already_making_children
;
505 saver
= saved_pipeline
;
506 saved_pipeline
= saved_pipeline
->next
;
508 UNBLOCK_CHILD (oset
);
510 if (discard
&& old_pipeline
)
512 discard_pipeline (old_pipeline
);
513 return ((PROCESS
*)NULL
);
518 /* Start building a pipeline. */
520 start_pipeline (void)
524 cleanup_the_pipeline ();
525 /* If job_control == 0, pipeline_pgrp will always be equal to shell_pgrp;
526 if job_control != 0, pipeline_pgrp == shell_pgrp for command and
527 process substitution, in which case we want it to be the same as
528 shell_pgrp for the lifetime of this shell instance. */
529 if (pipeline_pgrp
!= shell_pgrp
)
531 #if defined (PGRP_PIPE)
532 sh_closepipe (pgrp_pipe
);
536 #if defined (PGRP_PIPE)
539 if (pipe (pgrp_pipe
) == -1)
540 sys_error (_("start_pipeline: pgrp pipe"));
545 /* Stop building a pipeline. Install the process list in the job array.
546 This returns the index of the newly installed job.
547 DEFERRED is a command structure to be executed upon satisfactory
548 execution exit of this pipeline. */
550 stop_pipeline (int async
, COMMAND
*deferred
)
556 BLOCK_CHILD (set
, oset
);
558 #if defined (PGRP_PIPE)
559 /* The parent closes the process group synchronization pipe. */
560 sh_closepipe (pgrp_pipe
);
563 cleanup_dead_jobs ();
565 if (js
.j_jobslots
== 0)
567 js
.j_jobslots
= JOB_SLOTS
;
568 jobs
= (JOB
**)xmalloc (js
.j_jobslots
* sizeof (JOB
*));
570 /* Now blank out these new entries. */
571 for (i
= 0; i
< js
.j_jobslots
; i
++)
572 jobs
[i
] = (JOB
*)NULL
;
574 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
577 /* Scan from the last slot backward, looking for the next free one. */
578 /* XXX - revisit this interactive assumption */
579 /* XXX - this way for now */
582 for (i
= js
.j_jobslots
; i
; i
--)
589 /* This wraps around, but makes it inconvenient to extend the array */
590 for (i
= js
.j_lastj
+1; i
!= js
.j_lastj
; i
++)
592 if (i
>= js
.j_jobslots
)
600 /* This doesn't wrap around yet. */
601 for (i
= js
.j_lastj
? js
.j_lastj
+ 1 : js
.j_lastj
; i
< js
.j_jobslots
; i
++)
607 /* Do we need more room? */
609 /* First try compaction */
610 if ((interactive_shell
== 0 || subshell_environment
) && i
== js
.j_jobslots
&& js
.j_jobslots
>= MAX_JOBS_IN_ARRAY
)
611 i
= compact_jobs_list (0);
613 /* If we can't compact, reallocate */
614 if (i
== js
.j_jobslots
)
616 js
.j_jobslots
+= JOB_SLOTS
;
617 jobs
= (JOB
**)xrealloc (jobs
, (js
.j_jobslots
* sizeof (JOB
*)));
619 for (j
= i
; j
< js
.j_jobslots
; j
++)
620 jobs
[j
] = (JOB
*)NULL
;
623 /* Add the current pipeline to the job list. */
627 int any_running
, any_stopped
, n
;
629 newjob
= (JOB
*)xmalloc (sizeof (JOB
));
631 for (n
= 1, p
= the_pipeline
; p
->next
!= the_pipeline
; n
++, p
= p
->next
)
633 p
->next
= (PROCESS
*)NULL
;
634 newjob
->pipe
= REVERSE_LIST (the_pipeline
, PROCESS
*);
635 for (p
= newjob
->pipe
; p
->next
; p
= p
->next
)
637 p
->next
= newjob
->pipe
;
639 the_pipeline
= (PROCESS
*)NULL
;
640 newjob
->pgrp
= pipeline_pgrp
;
642 /* Invariant: if the shell is executing a command substitution,
643 pipeline_pgrp == shell_pgrp. Other parts of the shell assume this. */
644 if (pipeline_pgrp
!= shell_pgrp
)
649 newjob
->flags
|= J_PIPEFAIL
;
651 /* Flag to see if in another pgrp. */
653 newjob
->flags
|= J_JOBCONTROL
;
655 /* Set the state of this pipeline. */
657 any_running
= any_stopped
= 0;
660 any_running
|= PRUNNING (p
);
661 any_stopped
|= PSTOPPED (p
);
664 while (p
!= newjob
->pipe
);
666 newjob
->state
= any_running
? JRUNNING
: (any_stopped
? JSTOPPED
: JDEAD
);
667 newjob
->wd
= job_working_directory ();
668 newjob
->deferred
= deferred
;
670 newjob
->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
671 newjob
->cleanarg
= (PTR_T
) NULL
;
674 if (newjob
->state
== JDEAD
&& (newjob
->flags
& J_FOREGROUND
))
676 if (newjob
->state
== JDEAD
)
678 js
.c_reaped
+= n
; /* wouldn't have been done since this was not part of a job */
687 newjob
= (JOB
*)NULL
;
690 js
.j_lastmade
= newjob
;
696 newjob
->flags
&= ~J_FOREGROUND
;
697 newjob
->flags
|= J_ASYNC
;
698 js
.j_lastasync
= newjob
;
706 newjob
->flags
|= J_FOREGROUND
;
708 * !!!!! NOTE !!!!! (chet@po.cwru.edu)
710 * The currently-accepted job control wisdom says to set the
711 * terminal's process group n+1 times in an n-step pipeline:
712 * once in the parent and once in each child. This is where
713 * the parent gives it away.
715 * Don't give the terminal away if this shell is an asynchronous
716 * subshell or if we're a (presumably non-interactive) shell running
720 /* 09/08/2023 - rely on child processes to set the terminal pgrp */
722 if (job_control
&& newjob
->pgrp
&& (subshell_environment
&SUBSHELL_ASYNC
) == 0 && running_in_background
== 0)
723 maybe_give_terminal_to (shell_pgrp
, newjob
->pgrp
, 0);
728 stop_making_children ();
729 UNBLOCK_CHILD (oset
);
730 return (newjob
? i
: js
.j_current
);
733 /* Functions to manage the list of exited background pids whose status has
738 The current implementation is a hash table using a single (separate) arena
739 for storage that can be allocated and freed as a unit. The size of the hash
740 table is a multiple of PIDSTAT_TABLE_SZ (4096) and multiple PIDs that hash
741 to the same value are chained through the bucket_next and bucket_prev
742 pointers (basically coalesced hashing for collision resolution).
746 All pid/status storage is done using the circular buffer bgpids.storage.
747 This must contain at least js.c_childmax entries. The circular buffer is
748 used to supply the ordered list Posix requires ("the last CHILD_MAX
749 processes"). To avoid searching the entire storage table for a given PID,
750 the hash table (pidstat_table) holds pointers into the storage arena and
751 uses a doubly-linked list of cells (bucket_next/bucket_prev, also pointers
752 into the arena) to implement collision resolution. */
754 /* The number of elements in bgpids.storage always has to be > js.c_childmax for
755 the circular buffer to work right. */
759 ps_index_t nsize
, nsize_cur
, nsize_max
;
762 if (bgpids
.nalloc
== 0)
764 /* invalidate hash table when bgpids table is reallocated */
765 for (psi
= 0; psi
< PIDSTAT_TABLE_SZ
; psi
++)
766 pidstat_table
[psi
] = NO_PIDSTAT
;
767 nsize
= BGPIDS_TABLE_SZ
; /* should be power of 2 */
771 nsize
= bgpids
.nalloc
;
773 nsize_max
= TYPE_MAXIMUM (ps_index_t
);
774 nsize_cur
= (ps_index_t
)js
.c_childmax
;
775 if (nsize_cur
< 0) /* overflow */
776 nsize_cur
= MAX_CHILD_MAX
;
778 while (nsize
> 0 && nsize
< nsize_cur
) /* > 0 should catch overflow */
780 if (nsize
> nsize_max
|| nsize
<= 0) /* overflow? */
782 if (nsize
> MAX_CHILD_MAX
)
783 nsize
= nsize_max
= MAX_CHILD_MAX
; /* hard cap */
785 if (bgpids
.nalloc
< nsize_cur
&& bgpids
.nalloc
< nsize_max
)
787 bgpids
.storage
= (struct pidstat
*)xrealloc (bgpids
.storage
, nsize
* sizeof (struct pidstat
));
789 for (psi
= bgpids
.nalloc
; psi
< nsize
; psi
++)
790 bgpids
.storage
[psi
].pid
= NO_PID
;
792 bgpids
.nalloc
= nsize
;
795 else if (bgpids
.head
>= bgpids
.nalloc
) /* wrap around */
802 if (bgpids
.nalloc
< (ps_index_t
)js
.c_childmax
|| bgpids
.head
>= bgpids
.nalloc
)
805 pshash_delindex (bgpids
.head
); /* XXX - clear before reusing */
806 return bgpids
.head
++;
810 pshash_getbucket (pid_t pid
)
812 unsigned long hash
; /* XXX - u_bits32_t */
814 hash
= pid
* 0x9e370001UL
;
815 return (&pidstat_table
[hash
% PIDSTAT_TABLE_SZ
]);
818 static struct pidstat
*
819 bgp_add (pid_t pid
, int status
)
821 ps_index_t
*bucket
, psi
;
824 /* bucket == existing chain of pids hashing to same value
825 psi = where were going to put this pid/status */
827 bucket
= pshash_getbucket (pid
); /* index into pidstat_table */
828 psi
= bgp_getindex (); /* bgpids.head, index into storage */
830 /* XXX - what if psi == *bucket? */
833 internal_debug ("hashed pid %d (pid %d) collides with bgpids.head, skipping", psi
, pid
);
834 bgpids
.storage
[psi
].pid
= NO_PID
; /* make sure */
835 psi
= bgp_getindex (); /* skip to next one */
838 ps
= &bgpids
.storage
[psi
];
842 ps
->bucket_next
= *bucket
;
843 ps
->bucket_prev
= NO_PIDSTAT
;
848 if (bgpids
.npid
> js
.c_childmax
)
852 if (ps
->bucket_next
!= NO_PIDSTAT
)
853 bgpids
.storage
[ps
->bucket_next
].bucket_prev
= psi
;
855 *bucket
= psi
; /* set chain head in hash table */
861 pshash_delindex (ps_index_t psi
)
866 ps
= &bgpids
.storage
[psi
];
867 if (ps
->pid
== NO_PID
)
870 if (ps
->bucket_next
!= NO_PIDSTAT
)
871 bgpids
.storage
[ps
->bucket_next
].bucket_prev
= ps
->bucket_prev
;
872 if (ps
->bucket_prev
!= NO_PIDSTAT
)
873 bgpids
.storage
[ps
->bucket_prev
].bucket_next
= ps
->bucket_next
;
876 bucket
= pshash_getbucket (ps
->pid
);
877 *bucket
= ps
->bucket_next
; /* deleting chain head in hash table */
880 /* clear out this cell, in case it gets reused. */
882 ps
->bucket_next
= ps
->bucket_prev
= NO_PIDSTAT
;
886 bgp_delete (pid_t pid
)
888 ps_index_t psi
, orig_psi
;
890 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0 || bgpids
.npid
== 0)
893 /* Search chain using hash to find bucket in pidstat_table */
894 for (orig_psi
= psi
= *(pshash_getbucket (pid
)); psi
!= NO_PIDSTAT
; psi
= bgpids
.storage
[psi
].bucket_next
)
896 if (bgpids
.storage
[psi
].pid
== pid
)
898 if (orig_psi
== bgpids
.storage
[psi
].bucket_next
) /* catch reported bug */
900 internal_warning (_("bgp_delete: LOOP: psi (%d) == storage[psi].bucket_next"), psi
);
905 if (psi
== NO_PIDSTAT
)
906 return 0; /* not found */
909 itrace("bgp_delete: deleting %d", pid
);
912 pshash_delindex (psi
); /* hash table management */
918 /* Clear out the list of saved statuses */
922 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0)
925 free (bgpids
.storage
);
934 /* Search for PID in the list of saved background pids; return its status if
935 found. If not found, return -1. We hash to the right spot in pidstat_table
936 and follow the bucket chain to the end. */
938 bgp_search (pid_t pid
)
940 ps_index_t psi
, orig_psi
;
942 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0 || bgpids
.npid
== 0)
945 /* Search chain using hash to find bucket in pidstat_table */
946 for (orig_psi
= psi
= *(pshash_getbucket (pid
)); psi
!= NO_PIDSTAT
; psi
= bgpids
.storage
[psi
].bucket_next
)
948 if (bgpids
.storage
[psi
].pid
== pid
)
949 return (bgpids
.storage
[psi
].status
);
950 if (orig_psi
== bgpids
.storage
[psi
].bucket_next
) /* catch reported bug */
952 internal_warning (_("bgp_search: LOOP: psi (%d) == storage[psi].bucket_next"), psi
);
968 /* External interface to bgp_add/bgp_search/bgp_delete; takes care of blocking
969 and unblocking SIGCHLD if needed. If retrieve_proc_status or delete_proc_status
970 is called with BLOCK non-zero, the caller must block and unblock SIGCHLD. */
973 save_proc_status (pid_t pid
, int status
)
977 BLOCK_CHILD (set
, oset
);
978 bgp_add (pid
, status
);
979 UNBLOCK_CHILD (oset
);
983 retrieve_proc_status (pid_t pid
, int block
)
989 BLOCK_CHILD (set
, oset
);
990 r
= bgp_search (pid
);
992 UNBLOCK_CHILD (oset
);
997 delete_proc_status (pid_t pid
, int block
)
1002 BLOCK_CHILD (set
, oset
);
1005 UNBLOCK_CHILD (oset
);
1008 #if defined (PROCESS_SUBSTITUTION)
1009 /* Functions to add and remove PROCESS * children from the list of running
1010 asynchronous process substitutions. The list is currently a simple singly
1011 linked list of PROCESS *, so it works with the set of callers that want
1012 a child. subst.c:process_substitute adds to the list, the various wait*
1013 functions manipulate child->running and child->status, and processes are
1014 eventually removed from the list and added to the bgpids table. */
1017 procsub_free (PROCESS
*p
)
1024 procsub_add (PROCESS
*p
)
1028 BLOCK_CHILD (set
, oset
);
1029 if (procsubs
.head
== 0)
1031 procsubs
.head
= procsubs
.end
= p
;
1036 procsubs
.end
->next
= p
;
1040 UNBLOCK_CHILD (oset
);
1046 procsub_search (pid_t pid
)
1051 BLOCK_CHILD (set
, oset
);
1052 for (p
= procsubs
.head
; p
; p
= p
->next
)
1055 UNBLOCK_CHILD (oset
);
1061 procsub_delete (pid_t pid
)
1066 BLOCK_CHILD (set
, oset
);
1067 for (p
= prev
= procsubs
.head
; p
; prev
= p
, p
= p
->next
)
1070 prev
->next
= p
->next
;
1076 UNBLOCK_CHILD (oset
);
1080 if (p
== procsubs
.head
)
1081 procsubs
.head
= procsubs
.head
->next
;
1082 else if (p
== procsubs
.end
)
1083 procsubs
.end
= prev
;
1086 if (procsubs
.nproc
== 0)
1087 procsubs
.head
= procsubs
.end
= 0;
1088 else if (procsubs
.nproc
== 1) /* XXX */
1089 procsubs
.end
= procsubs
.head
;
1091 /* this can't be called anywhere in a signal handling path */
1092 bgp_add (p
->pid
, process_exit_status (p
->status
));
1093 UNBLOCK_CHILD (oset
);
1098 procsub_waitpid (pid_t pid
)
1103 p
= procsub_search (pid
);
1106 if (p
->running
== PS_DONE
)
1108 r
= wait_for (p
->pid
, 0);
1109 return (r
); /* defer removing until later */
1113 procsub_waitall (void)
1118 for (p
= procsubs
.head
; p
; p
= p
->next
)
1120 if (p
->running
== PS_DONE
)
1122 r
= wait_for (p
->pid
, 0);
1127 procsub_clear (void)
1132 BLOCK_CHILD (set
, oset
);
1134 for (ps
= procsubs
.head
; ps
; )
1140 procsubs
.head
= procsubs
.end
= 0;
1142 UNBLOCK_CHILD (oset
);
1145 /* Must be called with SIGCHLD blocked. */
1147 procsub_prune (void)
1149 PROCESS
*ohead
, *oend
, *ps
, *p
;
1152 if (procsubs
.nproc
== 0)
1155 ohead
= procsubs
.head
;
1156 oend
= procsubs
.end
;
1157 onproc
= procsubs
.nproc
;
1159 procsubs
.head
= procsubs
.end
= 0;
1162 for (p
= ohead
; p
; )
1166 if (p
->running
== PS_DONE
)
1168 bgp_add (p
->pid
, process_exit_status (p
->status
));
1178 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
1179 been deleted. The caller should check whether js.j_njobs is 0 before
1180 calling this. This wraps around, but the rest of the code does not. At
1181 this point, it should not matter. */
1183 reset_job_indices (void)
1187 if (jobs
[js
.j_firstj
] == 0)
1189 old
= js
.j_firstj
++;
1190 if (old
>= js
.j_jobslots
)
1191 old
= js
.j_jobslots
- 1;
1192 while (js
.j_firstj
!= old
)
1194 if (js
.j_firstj
>= js
.j_jobslots
)
1196 if (jobs
[js
.j_firstj
] || js
.j_firstj
== old
) /* needed if old == 0 */
1200 if (js
.j_firstj
== old
)
1201 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
1203 if (jobs
[js
.j_lastj
] == 0)
1208 while (js
.j_lastj
!= old
)
1211 js
.j_lastj
= js
.j_jobslots
- 1;
1212 if (jobs
[js
.j_lastj
] || js
.j_lastj
== old
) /* needed if old == js.j_jobslots */
1216 if (js
.j_lastj
== old
)
1217 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
1221 /* Delete all DEAD jobs that the user had received notification about. */
1223 cleanup_dead_jobs (void)
1228 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1233 /* XXX could use js.j_firstj and js.j_lastj here */
1234 for (i
= 0; i
< js
.j_jobslots
; i
++)
1236 if (i
< js
.j_firstj
&& jobs
[i
])
1237 INTERNAL_DEBUG (("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
1238 if (i
> js
.j_lastj
&& jobs
[i
])
1239 INTERNAL_DEBUG(("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
1241 if (jobs
[i
] == 0 || DEADJOB (i
) == 0)
1242 continue; /* not a candidate */
1243 else if (IS_NOTIFIED (i
))
1244 delete_job (i
, 0); /* already notified */
1245 else if (IS_FOREGROUND (i
) && job_killed_by_signal (i
) == 0)
1246 delete_job (i
, 0); /* we won't notify about this */
1249 #if defined (PROCESS_SUBSTITUTION)
1251 last_procsub_child
= (PROCESS
*)NULL
;
1254 #if defined (COPROCESS_SUPPORT)
1258 UNQUEUE_SIGCHLD(os
);
1262 processes_in_job (int job
)
1265 register PROCESS
*p
;
1268 p
= jobs
[job
]->pipe
;
1274 while (p
!= jobs
[job
]->pipe
);
1280 delete_old_job (pid_t pid
)
1285 job
= find_job (pid
, 0, &p
);
1288 INTERNAL_DEBUG (("delete_old_job: found pid %d in job %d with state %d", pid
, job
, jobs
[job
]->state
));
1289 if (JOBSTATE (job
) == JDEAD
)
1290 delete_job (job
, DEL_NOBGPID
);
1293 internal_debug (_("forked pid %d appears in running job %d"), pid
, job
+1);
1300 /* Reallocate and compress the jobs list. This returns with a jobs array
1301 whose size is a multiple of JOB_SLOTS and can hold the current number of
1302 jobs. Heuristics are used to minimize the number of new reallocs. */
1304 realloc_jobs_list (void)
1307 int nsize
, i
, j
, ncur
, nprev
;
1310 ncur
= nprev
= NO_JOB
;
1311 nsize
= ((js
.j_njobs
+ JOB_SLOTS
- 1) / JOB_SLOTS
);
1313 i
= js
.j_njobs
% JOB_SLOTS
;
1314 if (i
== 0 || i
> (JOB_SLOTS
>> 1))
1317 BLOCK_CHILD (set
, oset
);
1318 nlist
= (js
.j_jobslots
== nsize
) ? jobs
: (JOB
**) xmalloc (nsize
* sizeof (JOB
*));
1320 js
.c_reaped
= js
.j_ndead
= 0;
1321 for (i
= j
= 0; i
< js
.j_jobslots
; i
++)
1324 if (i
== js
.j_current
)
1326 if (i
== js
.j_previous
)
1328 nlist
[j
++] = jobs
[i
];
1329 if (jobs
[i
]->state
== JDEAD
)
1332 js
.c_reaped
+= processes_in_job (i
);
1337 itrace ("realloc_jobs_list: resize jobs list from %d to %d", js
.j_jobslots
, nsize
);
1338 itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js
.j_lastj
, (j
> 0) ? j
- 1 : 0);
1339 itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js
.j_njobs
, j
);
1340 itrace ("realloc_jobs_list: js.j_ndead %d js.c_reaped %d", js
.j_ndead
, js
.c_reaped
);
1344 js
.j_lastj
= (j
> 0) ? j
- 1 : 0;
1346 js
.j_jobslots
= nsize
;
1348 /* Zero out remaining slots in new jobs list */
1349 for ( ; j
< nsize
; j
++)
1350 nlist
[j
] = (JOB
*)NULL
;
1359 js
.j_current
= ncur
;
1360 if (nprev
!= NO_JOB
)
1361 js
.j_previous
= nprev
;
1363 /* Need to reset these */
1364 if (js
.j_current
== NO_JOB
|| js
.j_previous
== NO_JOB
|| js
.j_current
> js
.j_lastj
|| js
.j_previous
> js
.j_lastj
)
1368 itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js
.j_current
, js
.j_previous
);
1371 UNBLOCK_CHILD (oset
);
1374 /* Compact the jobs list by removing dead jobs. Assume that we have filled
1375 the jobs array to some predefined maximum. Called when the shell is not
1376 the foreground process (subshell_environment != 0). Returns the first
1377 available slot in the compacted list. If that value is js.j_jobslots, then
1378 the list needs to be reallocated. The jobs array may be in new memory if
1379 this returns > 0 and < js.j_jobslots. FLAGS is reserved for future use. */
1381 compact_jobs_list (int flags
)
1383 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1384 return js
.j_jobslots
;
1387 realloc_jobs_list ();
1390 itrace("compact_jobs_list: returning %d", (js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
1393 return ((js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
1396 /* Delete the job at INDEX from the job list. Must be called
1397 with SIGCHLD blocked. */
1399 delete_job (int job_index
, int dflags
)
1405 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1408 if ((dflags
& DEL_WARNSTOPPED
) && subshell_environment
== 0 && STOPPED (job_index
))
1409 internal_warning (_("deleting stopped job %d with process group %ld"), job_index
+1, (long)jobs
[job_index
]->pgrp
);
1410 temp
= jobs
[job_index
];
1414 if ((dflags
& DEL_NOBGPID
) == 0 && (temp
->flags
& (J_ASYNC
|J_FOREGROUND
)) == J_ASYNC
)
1416 proc
= find_last_proc (job_index
, 0);
1418 bgp_add (proc
->pid
, process_exit_status (proc
->status
));
1421 jobs
[job_index
] = (JOB
*)NULL
;
1422 if (temp
== js
.j_lastmade
)
1424 else if (temp
== js
.j_lastasync
)
1428 ndel
= discard_pipeline (temp
->pipe
);
1430 js
.c_injobs
-= ndel
;
1431 if (temp
->state
== JDEAD
)
1433 /* XXX - save_pipeline and restore_pipeline (e.g., for DEBUG trap) can
1434 mess with this total. */
1435 js
.c_reaped
-= ndel
; /* assumes proc hadn't been reaped earlier */
1437 if (js
.c_reaped
< 0)
1439 INTERNAL_DEBUG (("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
));
1445 dispose_command (temp
->deferred
);
1450 if (js
.j_njobs
== 0)
1451 js
.j_firstj
= js
.j_lastj
= 0;
1452 else if (jobs
[js
.j_firstj
] == 0 || jobs
[js
.j_lastj
] == 0)
1453 reset_job_indices ();
1455 if (job_index
== js
.j_current
|| job_index
== js
.j_previous
)
1459 /* Must be called with SIGCHLD blocked. */
1461 nohup_job (int job_index
)
1465 if (js
.j_jobslots
== 0)
1468 if (temp
= jobs
[job_index
])
1469 temp
->flags
|= J_NOHUP
;
1472 /* Get rid of the data structure associated with a process chain. */
1474 discard_pipeline (PROCESS
*chain
)
1476 register PROCESS
*this, *next
;
1484 FREE (this->command
);
1489 while (this != chain
);
1494 /* Add this process to the chain being built in the_pipeline.
1495 NAME is the command string that will be exec'ed later.
1496 PID is the process id of the child. */
1498 add_process (char *name
, pid_t pid
)
1502 #if defined (RECYCLES_PIDS)
1504 p
= find_process (pid
, 0, &j
);
1508 internal_debug ("add_process: process %5ld (%s) in the_pipeline", (long)p
->pid
, p
->command
);
1510 internal_warning (_("add_process: pid %5ld (%s) marked as still alive"), (long)p
->pid
, p
->command
);
1511 p
->running
= PS_RECYCLED
; /* mark as recycled */
1515 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1516 t
->next
= the_pipeline
;
1518 WSTATUS (t
->status
) = 0;
1519 t
->running
= PS_RUNNING
;
1528 while (p
->next
!= t
->next
)
1534 /* Create a (dummy) PROCESS with NAME, PID, and STATUS, and make it the last
1535 process in jobs[JID]->pipe. Used by the lastpipe code. */
1537 append_process (char *name
, pid_t pid
, int status
, int jid
)
1541 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1542 t
->next
= (PROCESS
*)NULL
;
1544 /* set process exit status using offset discovered by configure */
1545 t
->status
= (status
& 0xff) << WEXITSTATUS_OFFSET
;
1546 t
->running
= PS_DONE
;
1549 js
.c_reaped
++; /* XXX */
1551 for (p
= jobs
[jid
]->pipe
; p
->next
!= jobs
[jid
]->pipe
; p
= p
->next
)
1554 t
->next
= jobs
[jid
]->pipe
;
1558 /* Take the last job and make it the first job. Must be called with
1561 rotate_the_pipeline (void)
1565 if (the_pipeline
->next
== the_pipeline
)
1567 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1572 /* Reverse the order of the processes in the_pipeline. Must be called with
1575 reverse_the_pipeline (void)
1579 if (the_pipeline
->next
== the_pipeline
)
1582 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1584 p
->next
= (PROCESS
*)NULL
;
1586 n
= REVERSE_LIST (the_pipeline
, PROCESS
*);
1589 for (p
= the_pipeline
; p
->next
; p
= p
->next
)
1591 p
->next
= the_pipeline
;
1595 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
1596 then it is time to stop mapping, and that is the return value
1597 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
1600 map_over_jobs (sh_job_map_func_t
*func
, int arg1
, int arg2
)
1606 if (js
.j_jobslots
== 0)
1609 BLOCK_CHILD (set
, oset
);
1611 /* XXX could use js.j_firstj here */
1612 for (i
= result
= 0; i
< js
.j_jobslots
; i
++)
1614 if (i
< js
.j_firstj
&& jobs
[i
])
1615 INTERNAL_DEBUG (("map_over_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
1616 if (i
> js
.j_lastj
&& jobs
[i
])
1617 INTERNAL_DEBUG (("map_over_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
1621 result
= (*func
)(jobs
[i
], arg1
, arg2
, i
);
1627 UNBLOCK_CHILD (oset
);
1632 /* Cause all the jobs in the current pipeline to exit. */
1634 terminate_current_pipeline (void)
1638 if (pipeline_pgrp
&& pipeline_pgrp
!= shell_pgrp
)
1640 killpg (pipeline_pgrp
, SIGTERM
);
1641 killpg (pipeline_pgrp
, SIGCONT
);
1642 killpg (pipeline_pgrp
, SIGKILL
);
1644 else if (pipeline_pgrp
&& pipeline_pgrp
== shell_pgrp
&& (p
= the_pipeline
))
1648 kill (p
->pid
, SIGTERM
);
1649 kill (p
->pid
, SIGCONT
);
1650 kill (p
->pid
, SIGKILL
);
1653 while (p
!= the_pipeline
);
1657 /* Cause all stopped jobs to exit. */
1659 terminate_stopped_jobs (void)
1663 /* XXX could use js.j_firstj here */
1664 for (i
= 0; i
< js
.j_jobslots
; i
++)
1666 if (jobs
[i
] && STOPPED (i
))
1668 killpg (jobs
[i
]->pgrp
, SIGTERM
);
1669 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1674 /* Cause all jobs, running or stopped, to receive a hangup signal. If
1675 a job is marked J_NOHUP, don't send the SIGHUP. */
1677 hangup_all_jobs (void)
1681 /* XXX could use js.j_firstj here */
1682 for (i
= 0; i
< js
.j_jobslots
; i
++)
1686 if (jobs
[i
]->flags
& J_NOHUP
)
1688 killpg (jobs
[i
]->pgrp
, SIGHUP
);
1690 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1696 kill_current_pipeline (void)
1698 stop_making_children ();
1703 find_pid_in_pipeline (pid_t pid
, PROCESS
*pipeline
, int alive_only
)
1710 /* Return it if we found it. Don't ever return a recycled pid. */
1711 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1716 while (p
!= pipeline
);
1717 return ((PROCESS
*)NULL
);
1720 /* Return the pipeline that PID belongs to. Note that the pipeline
1721 doesn't have to belong to a job. Must be called with SIGCHLD blocked.
1722 If JOBP is non-null, return the index of the job containing PID, or
1723 NO_JOB if PID doesn't belong to an existing job. */
1725 find_pipeline (pid_t pid
, int alive_only
, int *jobp
)
1729 struct pipeline_saver
*save
;
1731 /* See if this process is in the pipeline that we are building. */
1732 p
= (PROCESS
*)NULL
;
1736 if (the_pipeline
&& (p
= find_pid_in_pipeline (pid
, the_pipeline
, alive_only
)))
1739 /* Is this process in a saved pipeline? */
1740 for (save
= saved_pipeline
; save
; save
= save
->next
)
1741 if (save
->pipeline
&& (p
= find_pid_in_pipeline (pid
, save
->pipeline
, alive_only
)))
1744 #if defined (PROCESS_SUBSTITUTION)
1745 if (procsubs
.nproc
> 0 && (p
= procsub_search (pid
)) && ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1749 job
= find_job (pid
, alive_only
, &p
);
1752 return (job
== NO_JOB
) ? (PROCESS
*)NULL
: jobs
[job
]->pipe
;
1755 /* Return the PROCESS * describing PID. If JOBP is non-null return the index
1756 into the jobs array of the job containing PID or NO_JOB. Must be called
1757 with SIGCHLD blocked. */
1759 find_process (pid_t pid
, int alive_only
, int *jobp
)
1763 p
= find_pipeline (pid
, alive_only
, jobp
);
1764 while (p
&& p
->pid
!= pid
)
1769 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1770 belong to any job. Must be called with SIGCHLD blocked. */
1772 find_job (pid_t pid
, int alive_only
, PROCESS
**procp
)
1777 /* XXX could use js.j_firstj here, and should check js.j_lastj */
1778 for (i
= 0; i
< js
.j_jobslots
; i
++)
1780 if (i
< js
.j_firstj
&& jobs
[i
])
1781 INTERNAL_DEBUG (("find_job: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
1782 if (i
> js
.j_lastj
&& jobs
[i
])
1783 INTERNAL_DEBUG (("find_job: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
1791 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1800 while (p
!= jobs
[i
]->pipe
);
1807 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
1808 required by find_job. */
1810 get_job_by_pid (pid_t pid
, int block
, PROCESS
**procp
)
1816 BLOCK_CHILD (set
, oset
);
1818 job
= find_job (pid
, 0, procp
);
1821 UNBLOCK_CHILD (oset
);
1826 /* Print descriptive information about the job with leader pid PID. */
1828 describe_pid (pid_t pid
)
1833 BLOCK_CHILD (set
, oset
);
1835 job
= find_job (pid
, 0, NULL
);
1838 fprintf (stderr
, "[%d] %ld\n", job
+ 1, (long)pid
);
1840 programming_error (_("describe_pid: %ld: no such pid"), (long)pid
);
1842 UNBLOCK_CHILD (oset
);
1853 x
= retcode_name_buffer
;
1854 snprintf (x
, sizeof(retcode_name_buffer
), _("Signal %d"), s
);
1860 printable_job_status (int j
, PROCESS
*p
, int format
)
1867 if (STOPPED (j
) && format
== 0)
1869 if (posixly_correct
== 0 || p
== 0 || (WIFSTOPPED (p
->status
) == 0))
1870 temp
= _("Stopped");
1873 temp
= retcode_name_buffer
;
1874 snprintf (temp
, sizeof(retcode_name_buffer
), _("Stopped(%s)"), signal_name (WSTOPSIG (p
->status
)));
1877 else if (RUNNING (j
))
1878 temp
= _("Running");
1881 if (WIFSTOPPED (p
->status
))
1882 temp
= j_strsignal (WSTOPSIG (p
->status
));
1883 else if (WIFSIGNALED (p
->status
))
1884 temp
= j_strsignal (WTERMSIG (p
->status
));
1885 else if (WIFEXITED (p
->status
))
1887 temp
= retcode_name_buffer
;
1888 es
= WEXITSTATUS (p
->status
);
1891 strncpy (temp
, _("Done"), sizeof (retcode_name_buffer
) - 1);
1892 temp
[sizeof (retcode_name_buffer
) - 1] = '\0';
1894 else if (posixly_correct
)
1895 snprintf (temp
, sizeof(retcode_name_buffer
), _("Done(%d)"), es
);
1897 snprintf (temp
, sizeof(retcode_name_buffer
), _("Exit %d"), es
);
1900 temp
= _("Unknown status");
1906 /* This is the way to print out information on a job if you
1907 know the index. FORMAT is:
1909 JLIST_NORMAL) [1]+ Running emacs
1910 JLIST_LONG ) [1]+ 2378 Running emacs
1911 -1 ) [1]+ 2378 emacs
1913 JLIST_NORMAL) [1]+ Stopped ls | more
1914 JLIST_LONG ) [1]+ 2369 Stopped ls
1917 Just list the pid of the process group leader (really
1920 Use format JLIST_NORMAL, but list only jobs about which
1921 the user has not been notified. */
1923 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1924 the JOBS array corresponding to this pipeline. FORMAT is as described
1925 above. Must be called with SIGCHLD blocked.
1927 If you're printing a pipeline that's not in the jobs array, like the
1928 current pipeline as it's being created, pass -1 for JOB_INDEX */
1930 print_pipeline (PROCESS
*p
, int job_index
, int format
, FILE *stream
)
1932 PROCESS
*first
, *last
, *show
;
1933 int es
, name_padding
;
1940 while (last
->next
!= first
)
1946 fprintf (stream
, format
? " " : " |");
1948 if (format
!= JLIST_STANDARD
)
1949 fprintf (stream
, "%5ld", (long)p
->pid
);
1951 fprintf (stream
, " ");
1953 if (format
> -1 && job_index
>= 0)
1955 show
= format
? p
: last
;
1956 temp
= printable_job_status (job_index
, show
, format
);
1962 if (show
->running
== first
->running
&&
1963 WSTATUS (show
->status
) == WSTATUS (first
->status
))
1967 temp
= (char *)NULL
;
1972 fprintf (stream
, "%s", temp
);
1976 es
= 2; /* strlen ("| ") */
1977 name_padding
= LONGEST_SIGNAL_DESC
- es
;
1979 fprintf (stream
, "%*s", name_padding
, "");
1981 if ((WIFSTOPPED (show
->status
) == 0) &&
1982 (WIFCONTINUED (show
->status
) == 0) &&
1983 WIFCORED (show
->status
))
1984 fprintf (stream
, _("(core dumped) "));
1988 if (p
!= first
&& format
)
1989 fprintf (stream
, "| ");
1992 fprintf (stream
, "%s", p
->command
);
1994 if (p
== last
&& job_index
>= 0)
1996 temp
= current_working_directory ();
1998 if (RUNNING (job_index
) && (IS_FOREGROUND (job_index
) == 0))
1999 fprintf (stream
, " &");
2001 if (strcmp (temp
, jobs
[job_index
]->wd
) != 0)
2003 _(" (wd: %s)"), polite_directory_format (jobs
[job_index
]->wd
));
2006 if (format
|| (p
== last
))
2008 /* We need to add a CR only if this is an interactive shell, and
2009 we're reporting the status of a completed job asynchronously.
2010 We can't really check whether this particular job is being
2011 reported asynchronously, so just add the CR if the shell is
2012 currently interactive and asynchronous notification is enabled. */
2013 if (asynchronous_notification
&& interactive
)
2014 putc ('\r', stream
);
2015 fprintf (stream
, "\n");
2025 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
2026 Must be called with SIGCHLD blocked or queued with queue_sigchld */
2028 pretty_print_job (int job_index
, int format
, FILE *stream
)
2030 register PROCESS
*p
;
2032 /* Format only pid information about the process group leader? */
2033 if (format
== JLIST_PID_ONLY
)
2035 fprintf (stream
, "%ld\n", (long)jobs
[job_index
]->pipe
->pid
);
2039 if (format
== JLIST_CHANGED_ONLY
)
2041 if (IS_NOTIFIED (job_index
))
2043 format
= JLIST_STANDARD
;
2046 if (format
!= JLIST_NONINTERACTIVE
)
2047 fprintf (stream
, "[%d]%c ", job_index
+ 1,
2048 (job_index
== js
.j_current
) ? '+':
2049 (job_index
== js
.j_previous
) ? '-' : ' ');
2051 if (format
== JLIST_NONINTERACTIVE
)
2052 format
= JLIST_LONG
;
2054 p
= jobs
[job_index
]->pipe
;
2056 print_pipeline (p
, job_index
, format
, stream
);
2058 /* We have printed information about this job. When the job's
2059 status changes, waitchld () sets the notification flag to 0. */
2060 jobs
[job_index
]->flags
|= J_NOTIFIED
;
2064 print_job (JOB
*job
, int format
, int state
, int job_index
)
2066 if (state
== -1 || (JOB_STATE
)state
== job
->state
)
2067 pretty_print_job (job_index
, format
, stdout
);
2072 list_one_job (JOB
*job
, int format
, int ignore
, int job_index
)
2074 pretty_print_job (job_index
, format
, stdout
);
2075 cleanup_dead_jobs ();
2079 list_stopped_jobs (int format
)
2081 cleanup_dead_jobs ();
2082 map_over_jobs (print_job
, format
, (int)JSTOPPED
);
2086 list_running_jobs (int format
)
2088 cleanup_dead_jobs ();
2089 map_over_jobs (print_job
, format
, (int)JRUNNING
);
2092 /* List jobs. If FORMAT is non-zero, then the long form of the information
2093 is printed, else just a short version. */
2095 list_all_jobs (int format
)
2097 cleanup_dead_jobs ();
2098 map_over_jobs (print_job
, format
, -1);
2101 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
2102 COMMAND is just for remembering the name of the command; we don't do
2103 anything else with it. ASYNC_P says what to do with the tty. If
2104 non-zero, then don't give it away. */
2106 make_child (char *command
, int flags
)
2109 unsigned int forksleep
;
2110 sigset_t set
, oset
, oset_copy
;
2114 sigemptyset (&oset_copy
);
2115 sigprocmask (SIG_BLOCK
, (sigset_t
*)NULL
, &oset_copy
);
2116 sigaddset (&oset_copy
, SIGTERM
);
2118 /* Block SIGTERM here and unblock in child after fork resets the
2119 set of pending signals. */
2121 sigaddset (&set
, SIGCHLD
);
2122 sigaddset (&set
, SIGINT
);
2123 sigaddset (&set
, SIGTERM
);
2125 sigemptyset (&oset
);
2126 sigprocmask (SIG_BLOCK
, &set
, &oset
);
2128 /* Blocked in the parent, child will receive it after unblocking SIGTERM */
2129 if (interactive_shell
)
2130 oterm
= set_signal_handler (SIGTERM
, SIG_DFL
);
2134 async_p
= (flags
& FORK_ASYNC
);
2137 /* If default_buffered_input is active, we are reading a script. If
2138 the command is asynchronous, we have already duplicated /dev/null
2139 as fd 0, but have not changed the buffered stream corresponding to
2140 the old fd 0. We don't want to sync the stream in this case. */
2141 if (default_buffered_input
!= -1 && (!async_p
|| default_buffered_input
> 0))
2142 sync_buffered_stream (default_buffered_input
);
2144 /* Create the child, handle severe errors. Retry on EAGAIN. */
2145 while ((pid
= fork ()) < 0 && errno
== EAGAIN
&& forksleep
< FORKSLEEP_MAX
)
2148 /* keep SIGTERM blocked until we reset the handler to SIG_IGN */
2149 sigprocmask (SIG_SETMASK
, &oset_copy
, (sigset_t
*)NULL
);
2150 /* If we can't create any children, try to reap some dead ones. */
2153 errno
= EAGAIN
; /* restore errno */
2154 sys_error ("fork: retry");
2156 if (sleep (forksleep
) != 0)
2160 if (interrupt_state
)
2162 sigprocmask (SIG_SETMASK
, &set
, (sigset_t
*)NULL
);
2166 if (interactive_shell
)
2167 set_signal_handler (SIGTERM
, oterm
);
2173 /* Kill all of the processes in the current pipeline. */
2174 terminate_current_pipeline ();
2176 /* Discard the current pipeline, if any. */
2178 kill_current_pipeline ();
2180 set_exit_status (EX_NOEXEC
);
2181 throw_to_top_level (); /* Reset signals, etc. */
2186 /* In the child. Give this child the right process group, set the
2187 signals to the default state for a new process. */
2190 subshell_environment
|= SUBSHELL_IGNTRAP
;
2192 /* If this ends up being changed to modify or use `command' in the
2193 child process, go back and change callers who free `command' in
2194 the child process when this returns. */
2197 /* Close default_buffered_input if it's > 0. We don't close it if it's
2198 0 because that's the file descriptor used when redirecting input,
2199 and it's wrong to close the file in that case. */
2200 unset_bash_input (0);
2202 CLRINTERRUPT
; /* XXX - children have their own interrupt state */
2204 /* Restore top-level signal mask, including unblocking SIGTERM */
2209 /* All processes in this pipeline belong in the same
2212 if (pipeline_pgrp
== 0) /* This is the first child. */
2213 pipeline_pgrp
= mypid
;
2215 /* Check for running command in backquotes. */
2216 if (pipeline_pgrp
== shell_pgrp
)
2217 ignore_tty_job_signals ();
2219 default_tty_job_signals ();
2221 /* Set the process group before trying to mess with the terminal's
2222 process group. This is mandated by POSIX. */
2223 /* This is in accordance with the Posix 1003.1 standard,
2224 section B.7.2.4, which says that trying to set the terminal
2225 process group with tcsetpgrp() to an unused pgrp value (like
2226 this would have for the first child) is an error. Section
2227 B.4.3.3, p. 237 also covers this, in the context of job control
2229 if (setpgid (mypid
, pipeline_pgrp
) < 0)
2230 sys_error (_("child setpgid (%ld to %ld)"), (long)mypid
, (long)pipeline_pgrp
);
2232 /* By convention (and assumption above), if
2233 pipeline_pgrp == shell_pgrp, we are making a child for
2234 command substitution.
2235 In this case, we don't want to give the terminal to the
2236 shell's process group (we could be in the middle of a
2237 pipeline, for example). */
2238 if ((flags
& FORK_NOTERM
) == 0 && async_p
== 0 && pipeline_pgrp
!= shell_pgrp
&& ((subshell_environment
&(SUBSHELL_ASYNC
|SUBSHELL_PIPE
)) == 0) && running_in_background
== 0)
2239 give_terminal_to (pipeline_pgrp
, 0);
2241 #if defined (PGRP_PIPE)
2242 if (pipeline_pgrp
== mypid
)
2243 pipe_read (pgrp_pipe
);
2246 else /* Without job control... */
2248 if (pipeline_pgrp
== 0)
2249 pipeline_pgrp
= shell_pgrp
;
2251 /* If these signals are set to SIG_DFL, we encounter the curious
2252 situation of an interactive ^Z to a running process *working*
2253 and stopping the process, but being unable to do anything with
2254 that process to change its state. On the other hand, if they
2255 are set to SIG_IGN, jobs started from scripts do not stop when
2256 the shell running the script gets a SIGTSTP and stops. */
2258 default_tty_job_signals ();
2261 #if defined (PGRP_PIPE)
2262 /* Release the process group pipe, since our call to setpgid ()
2263 is done. The last call to sh_closepipe is done in stop_pipeline. */
2264 sh_closepipe (pgrp_pipe
);
2265 #endif /* PGRP_PIPE */
2267 /* Don't set last_asynchronous_pid in the child */
2269 #if defined (RECYCLES_PIDS)
2270 if (last_asynchronous_pid
== mypid
)
2271 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2272 last_asynchronous_pid
= 1;
2277 /* In the parent. Remember the pid of the child just created
2278 as the proper pgrp if this is the first child. */
2282 if (pipeline_pgrp
== 0)
2284 pipeline_pgrp
= pid
;
2285 /* Don't twiddle terminal pgrps in the parent! This is the bug,
2286 not the good thing of twiddling them in the child! */
2287 /* give_terminal_to (pipeline_pgrp, 0); */
2289 /* This is done on the recommendation of the Rationale section of
2290 the POSIX 1003.1 standard, where it discusses job control and
2291 shells. It is done to avoid possible race conditions. (Ref.
2292 1003.1 Rationale, section B.4.3.3, page 236). */
2293 setpgid (pid
, pipeline_pgrp
);
2297 if (pipeline_pgrp
== 0)
2298 pipeline_pgrp
= shell_pgrp
;
2301 /* Place all processes into the jobs array regardless of the
2302 state of job_control. */
2303 add_process (command
, pid
);
2306 last_asynchronous_pid
= pid
;
2307 #if defined (RECYCLES_PIDS)
2308 else if (last_asynchronous_pid
== pid
)
2309 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2310 last_asynchronous_pid
= 1;
2313 /* Delete the saved status for any job containing this PID in case it's
2315 delete_old_job (pid
);
2317 /* Perform the check for pid reuse unconditionally. Some systems reuse
2318 PIDs before giving a process CHILD_MAX/_SC_CHILD_MAX unique ones. */
2319 bgp_delete (pid
); /* new process, discard any saved status */
2321 last_made_pid
= pid
;
2327 /* Unblock SIGTERM, SIGINT, and SIGCHLD unless creating a pipeline, in
2328 which case SIGCHLD remains blocked until all commands in the pipeline
2329 have been created (execute_cmd.c:execute_pipeline()). */
2330 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
2336 /* These two functions are called only in child processes. */
2338 ignore_tty_job_signals (void)
2340 set_signal_handler (SIGTSTP
, SIG_IGN
);
2341 set_signal_handler (SIGTTIN
, SIG_IGN
);
2342 set_signal_handler (SIGTTOU
, SIG_IGN
);
2345 /* Reset the tty-generated job control signals to SIG_DFL unless that signal
2346 was ignored at entry to the shell, in which case we need to set it to
2347 SIG_IGN in the child. We can't rely on resetting traps, since the hard
2348 ignored signals can't be trapped. */
2350 default_tty_job_signals (void)
2352 if (signal_is_trapped (SIGTSTP
) == 0 && signal_is_hard_ignored (SIGTSTP
))
2353 set_signal_handler (SIGTSTP
, SIG_IGN
);
2355 set_signal_handler (SIGTSTP
, SIG_DFL
);
2357 if (signal_is_trapped (SIGTTIN
) == 0 && signal_is_hard_ignored (SIGTTIN
))
2358 set_signal_handler (SIGTTIN
, SIG_IGN
);
2360 set_signal_handler (SIGTTIN
, SIG_DFL
);
2362 if (signal_is_trapped (SIGTTOU
) == 0 && signal_is_hard_ignored (SIGTTOU
))
2363 set_signal_handler (SIGTTOU
, SIG_IGN
);
2365 set_signal_handler (SIGTTOU
, SIG_DFL
);
2368 /* Called once in a parent process. */
2370 get_original_tty_job_signals (void)
2372 static int fetched
= 0;
2376 if (interactive_shell
)
2378 set_original_signal (SIGTSTP
, SIG_DFL
);
2379 set_original_signal (SIGTTIN
, SIG_DFL
);
2380 set_original_signal (SIGTTOU
, SIG_DFL
);
2384 get_original_signal (SIGTSTP
);
2385 get_original_signal (SIGTTIN
);
2386 get_original_signal (SIGTTOU
);
2392 /* When we end a job abnormally, or if we stop a job, we set the tty to the
2393 state kept in here. When a job ends normally, we set the state in here
2394 to the state of the tty. */
2396 static TTYSTRUCT shell_tty_info
;
2398 #if defined (NEW_TTY_DRIVER)
2399 static struct tchars shell_tchars
;
2400 static struct ltchars shell_ltchars
;
2401 #endif /* NEW_TTY_DRIVER */
2403 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
2404 /* Since the BSD tty driver does not allow us to change the tty modes
2405 while simultaneously waiting for output to drain and preserving
2406 typeahead, we have to drain the output ourselves before calling
2407 ioctl. We cheat by finding the length of the output queue, and
2408 using select to wait for an appropriate length of time. This is
2409 a hack, and should be labeled as such (it's a hastily-adapted
2410 mutation of a `usleep' implementation). It's only reason for
2411 existing is the flaw in the BSD tty driver. */
2413 static int ttspeeds
[] =
2415 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
2416 1800, 2400, 4800, 9600, 19200, 38400
2420 draino (int fd
, int ospeed
)
2422 register int delay
= ttspeeds
[ospeed
];
2428 while ((ioctl (fd
, TIOCOUTQ
, &n
) == 0) && n
)
2430 if (n
> (delay
/ 100))
2434 n
*= 10; /* 2 bits more for conservativeness. */
2435 tv
.tv_sec
= n
/ delay
;
2436 tv
.tv_usec
= ((n
% delay
) * 1000000) / delay
;
2437 select (fd
, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &tv
);
2443 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
2445 /* Return the fd from which we are actually getting input. */
2446 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
2448 /* Fill the contents of shell_tty_info with the current tty info. */
2450 get_tty_state (void)
2457 #if defined (NEW_TTY_DRIVER)
2458 ioctl (tty
, TIOCGETP
, &shell_tty_info
);
2459 ioctl (tty
, TIOCGETC
, &shell_tchars
);
2460 ioctl (tty
, TIOCGLTC
, &shell_ltchars
);
2461 #endif /* NEW_TTY_DRIVER */
2463 #if defined (TERMIO_TTY_DRIVER)
2464 ioctl (tty
, TCGETA
, &shell_tty_info
);
2465 #endif /* TERMIO_TTY_DRIVER */
2467 #if defined (TERMIOS_TTY_DRIVER)
2468 if (tcgetattr (tty
, &shell_tty_info
) < 0)
2471 /* Only print an error message if we're really interactive at
2474 sys_error ("[%ld: %d (%d)] tcgetattr", (long)getpid (), shell_level
, tty
);
2478 #endif /* TERMIOS_TTY_DRIVER */
2479 if (check_window_size
)
2480 get_new_window_size (0, (int *)0, (int *)0);
2485 /* Make the current tty use the state in shell_tty_info. */
2487 set_tty_state (void)
2494 #if defined (NEW_TTY_DRIVER)
2495 # if defined (DRAIN_OUTPUT)
2496 draino (tty
, shell_tty_info
.sg_ospeed
);
2497 # endif /* DRAIN_OUTPUT */
2498 ioctl (tty
, TIOCSETN
, &shell_tty_info
);
2499 ioctl (tty
, TIOCSETC
, &shell_tchars
);
2500 ioctl (tty
, TIOCSLTC
, &shell_ltchars
);
2501 #endif /* NEW_TTY_DRIVER */
2503 #if defined (TERMIO_TTY_DRIVER)
2504 ioctl (tty
, TCSETAW
, &shell_tty_info
);
2505 #endif /* TERMIO_TTY_DRIVER */
2507 #if defined (TERMIOS_TTY_DRIVER)
2508 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
2510 /* Only print an error message if we're really interactive at
2513 sys_error ("[%ld: %d (%d)] tcsetattr", (long)getpid (), shell_level
, tty
);
2516 #endif /* TERMIOS_TTY_DRIVER */
2521 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2522 process in that job's pipeline. This is the one whose exit status
2523 counts. Must be called with SIGCHLD blocked or queued. */
2525 find_last_proc (int job
, int block
)
2527 register PROCESS
*p
;
2531 BLOCK_CHILD (set
, oset
);
2533 p
= jobs
[job
]->pipe
;
2534 while (p
&& p
->next
!= jobs
[job
]->pipe
)
2538 UNBLOCK_CHILD (oset
);
2544 find_last_pid (int job
, int block
)
2548 p
= find_last_proc (job
, block
);
2549 /* Possible race condition here. */
2553 /* Wait for a particular child of the shell to finish executing.
2554 This low-level function prints an error message if PID is not
2555 a child of this shell. It returns -1 if it fails, or whatever
2556 wait_for returns otherwise. If the child is not found in the
2557 jobs table, it returns 127. If FLAGS doesn't include JWAIT_PERROR,
2558 we suppress the error message if PID isn't found. */
2561 wait_for_single_pid (pid_t pid
, int flags
)
2563 register PROCESS
*child
;
2567 BLOCK_CHILD (set
, oset
);
2568 child
= find_pipeline (pid
, 0, (int *)NULL
);
2569 UNBLOCK_CHILD (oset
);
2573 r
= bgp_search (pid
);
2580 if (flags
& JWAIT_PERROR
)
2581 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid
);
2588 r
= wait_for (pid
, 0);
2589 if ((flags
& JWAIT_FORCE
) == 0)
2592 BLOCK_CHILD (set
, oset
);
2593 alive
= PALIVE (child
);
2594 UNBLOCK_CHILD (oset
);
2598 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2600 BLOCK_CHILD (set
, oset
);
2601 job
= find_job (pid
, 0, NULL
);
2602 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
2603 jobs
[job
]->flags
|= J_NOTIFIED
;
2604 UNBLOCK_CHILD (oset
);
2606 /* If running in posix mode, remove the job from the jobs table immediately */
2607 if (posixly_correct
)
2609 cleanup_dead_jobs ();
2613 /* Check for a trapped signal interrupting the wait builtin and jump out */
2619 /* Wait for all of the background processes started by this shell to finish. */
2621 wait_for_background_pids (struct procstat
*ps
)
2624 int any_stopped
, check_async
, njobs
;
2628 for (njobs
= any_stopped
= 0, check_async
= 1;;)
2630 BLOCK_CHILD (set
, oset
);
2632 /* find first running job; if none running in foreground, break */
2633 /* XXX could use js.j_firstj and js.j_lastj here */
2634 for (i
= 0; i
< js
.j_jobslots
; i
++)
2636 if (i
< js
.j_firstj
&& jobs
[i
])
2637 INTERNAL_DEBUG (("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
2638 if (i
> js
.j_lastj
&& jobs
[i
])
2639 INTERNAL_DEBUG (("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
2641 if (jobs
[i
] && STOPPED (i
))
2643 builtin_warning ("job %d[%d] stopped", i
+1, find_last_pid (i
, 0));
2647 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
2650 if (i
== js
.j_jobslots
)
2652 UNBLOCK_CHILD (oset
);
2656 /* now wait for the last pid in that job. */
2657 pid
= find_last_pid (i
, 0);
2658 UNBLOCK_CHILD (oset
);
2660 errno
= 0; /* XXX */
2661 r
= wait_for_single_pid (pid
, JWAIT_PERROR
);
2665 ps
->status
= (r
< 0 || r
> 256) ? 127 : r
;
2667 if (r
== -1 && errno
== ECHILD
)
2669 /* If we're mistaken about job state, compensate. */
2671 mark_all_jobs_as_dead ();
2676 #if defined (PROCESS_SUBSTITUTION)
2677 if (last_procsub_child
&& last_procsub_child
->pid
!= NO_PID
&& last_procsub_child
->pid
== last_asynchronous_pid
)
2678 procsub_waitpid (last_procsub_child
->pid
);
2679 reap_procsubs (); /* closes fd */
2682 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2683 `wait' is called with no arguments. */
2684 mark_dead_jobs_as_notified (1);
2685 cleanup_dead_jobs (); /* calls procsub_prune */
2691 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2692 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2693 static SigHandler
*old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2695 /* The current SIGINT handler as set by restore_sigint_handler. Only valid
2696 immediately after restore_sigint_handler, used for continuations. */
2697 static SigHandler
*cur_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2699 static int wait_sigint_received
;
2700 static int child_caught_sigint
;
2702 int waiting_for_child
;
2704 /* Clean up state after longjmp to wait_intr_buf */
2706 wait_sigint_cleanup (void)
2709 waiting_for_child
= 0;
2710 restore_sigint_handler ();
2714 restore_sigint_handler (void)
2716 cur_sigint_handler
= old_sigint_handler
;
2717 if (old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
2719 set_signal_handler (SIGINT
, old_sigint_handler
);
2720 old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2721 waiting_for_child
= 0;
2725 /* Handle SIGINT while we are waiting for children in a script to exit.
2726 The `wait' builtin should be interruptible, but all others should be
2727 effectively ignored (i.e. not cause the shell to exit). */
2729 wait_sigint_handler (int sig
)
2731 SigHandler
*sigint_handler
;
2733 if (this_shell_builtin
&& this_shell_builtin
== wait_builtin
)
2735 set_exit_status (128+SIGINT
);
2736 restore_sigint_handler ();
2737 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2738 what POSIX.2 says (see builtins/wait.def for more info). */
2739 if (signal_is_trapped (SIGINT
) &&
2740 ((sigint_handler
= trap_to_sighandler (SIGINT
)) == trap_handler
))
2742 trap_handler (SIGINT
); /* set pending_traps[SIGINT] */
2743 wait_signal_received
= SIGINT
;
2745 sh_longjmp (wait_intr_buf
, 1);
2747 /* Let CHECK_WAIT_INTR handle it in wait_for/waitchld */
2750 else /* wait_builtin but signal not trapped, treat as interrupt */
2751 kill (getpid (), SIGINT
);
2754 /* XXX - should this be interrupt_state? If it is, the shell will act
2755 as if it got the SIGINT interrupt. */
2756 if (waiting_for_child
)
2757 wait_sigint_received
= 1;
2760 set_exit_status (128+SIGINT
);
2761 restore_sigint_handler ();
2762 if (cur_sigint_handler
== INVALID_SIGNAL_HANDLER
)
2763 set_sigint_handler (); /* XXX - only do this in one place */
2764 kill (getpid (), SIGINT
);
2767 /* Otherwise effectively ignore the SIGINT and allow the running job to
2773 process_exit_signal (WAIT status
)
2775 return (WIFSIGNALED (status
) ? WTERMSIG (status
) : 0);
2779 process_exit_status (WAIT status
)
2781 if (WIFSIGNALED (status
))
2782 return (128 + WTERMSIG (status
));
2783 else if (WIFSTOPPED (status
) == 0)
2784 return (WEXITSTATUS (status
));
2786 return (EXECUTION_SUCCESS
);
2790 job_signal_status (int job
)
2792 register PROCESS
*p
;
2795 p
= jobs
[job
]->pipe
;
2799 if (WIFSIGNALED(s
) || WIFSTOPPED(s
))
2803 while (p
!= jobs
[job
]->pipe
);
2808 /* Return the exit status of the last process in the pipeline for job JOB.
2809 This is the exit status of the entire job. */
2811 raw_job_exit_status (int job
)
2813 register PROCESS
*p
;
2817 if (jobs
[job
]->flags
& J_PIPEFAIL
)
2820 p
= jobs
[job
]->pipe
;
2823 if (WSTATUS (p
->status
) != EXECUTION_SUCCESS
)
2824 fail
= WSTATUS(p
->status
);
2827 while (p
!= jobs
[job
]->pipe
);
2828 WSTATUS (ret
) = fail
;
2832 for (p
= jobs
[job
]->pipe
; p
->next
!= jobs
[job
]->pipe
; p
= p
->next
)
2837 /* Return the exit status of job JOB. This is the exit status of the last
2838 (rightmost) process in the job's pipeline, modified if the job was killed
2839 by a signal or stopped. */
2841 job_exit_status (int job
)
2843 return (process_exit_status (raw_job_exit_status (job
)));
2847 job_exit_signal (int job
)
2849 return (process_exit_signal (raw_job_exit_status (job
)));
2853 job_killed_by_signal (int job
)
2857 termsig
= job_exit_signal (job
);
2858 #if !defined (DONT_REPORT_SIGPIPE)
2859 return (termsig
&& termsig
!= SIGINT
);
2861 return (termsig
&& termsig
!= SIGINT
&& termsig
!= SIGPIPE
);
2865 #define FIND_CHILD(pid, child) \
2868 child = find_pipeline (pid, 0, (int *)NULL); \
2871 give_terminal_to (shell_pgrp, 0); \
2872 UNBLOCK_CHILD (oset); \
2873 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2874 restore_sigint_handler (); \
2875 return (termination_state = 127); \
2880 /* Wait for pid (one of our children) to terminate, then
2881 return the termination state. Returns 127 if PID is not found in
2882 the jobs table. Returns -1 if waitchld() returns -1, indicating
2883 that there are no unwaited-for child processes. */
2885 wait_for (pid_t pid
, int flags
)
2887 int job
, termination_state
, r
;
2889 register PROCESS
*child
;
2892 /* In the case that this code is interrupted, and we longjmp () out of it,
2893 we are relying on the code in throw_to_top_level () to restore the
2894 top-level signal mask. */
2896 BLOCK_CHILD (set
, oset
);
2898 /* Ignore interrupts while waiting for a job run without job control
2899 to finish. We don't want the shell to exit if an interrupt is
2900 received, only if one of the jobs run is killed via SIGINT. If
2901 job control is not set, the job will be run in the same pgrp as
2902 the shell, and the shell will see any signals the job gets. In
2903 fact, we want this set every time the waiting shell and the waited-
2904 for process are in the same process group, including command
2907 /* This is possibly a race condition -- should it go in stop_pipeline? */
2908 wait_sigint_received
= child_caught_sigint
= 0;
2909 if (job_control
== 0 || (subshell_environment
&SUBSHELL_COMSUB
))
2911 SigHandler
*temp_sigint_handler
;
2913 temp_sigint_handler
= old_sigint_handler
;
2914 old_sigint_handler
= set_signal_handler (SIGINT
, wait_sigint_handler
);
2915 if (old_sigint_handler
== wait_sigint_handler
)
2917 internal_debug ("wait_for: recursively setting old_sigint_handler to wait_sigint_handler: running_trap = %d", running_trap
);
2918 old_sigint_handler
= temp_sigint_handler
;
2920 waiting_for_child
= 0;
2921 if (old_sigint_handler
== SIG_IGN
)
2922 set_signal_handler (SIGINT
, old_sigint_handler
);
2925 termination_state
= last_command_exit_value
;
2927 if (interactive
&& job_control
== 0)
2929 /* Check for terminating signals and exit the shell if we receive one */
2932 /* Check for a trapped signal interrupting the wait builtin and jump out */
2935 /* If we say wait_for (), then we have a record of this child somewhere.
2936 If it and none of its peers are running, don't call waitchld(). */
2942 FIND_CHILD (pid
, child
);
2944 /* If this child is part of a job, then we are really waiting for the
2945 job to finish. Otherwise, we are waiting for the child to finish.
2946 We check for JDEAD in case the job state has been set by waitchld
2947 after receipt of a SIGCHLD. */
2948 if (job
== NO_JOB
&& pid
!= ANY_PID
) /* XXX -- && pid != ANY_PID ? */
2949 job
= find_job (pid
, 0, NULL
);
2951 /* waitchld() takes care of setting the state of the job. If the job
2952 has already exited before this is called, sigchld_handler will have
2953 called waitchld and the state will be set to JDEAD. */
2955 if (pid
== ANY_PID
|| PRUNNING(child
) || (job
!= NO_JOB
&& RUNNING (job
)))
2960 old_waiting
= waiting_for_child
;
2961 waiting_for_child
= 1;
2962 /* XXX - probably not strictly necessary but we want to catch
2963 everything that happened before we switch the behavior of
2964 trap_handler to longjmp on a trapped signal (waiting_for_child) */
2966 r
= waitchld (pid
, 1); /* XXX */
2967 waiting_for_child
= old_waiting
;
2969 itrace("wait_for: blocking wait for %d returns %d child = %p", (int)pid
, r
, child
);
2972 if (r
== -1 && errno
== ECHILD
&& this_shell_builtin
== wait_builtin
)
2974 termination_state
= -1;
2975 /* XXX - restore sigint handler here */
2976 restore_sigint_handler ();
2977 goto wait_for_return
;
2980 /* If child is marked as running, but waitpid() returns -1/ECHILD,
2981 there is something wrong. Somewhere, wait should have returned
2982 that child's pid. Mark the child as not running and the job,
2983 if it exists, as JDEAD. */
2984 if (r
== -1 && errno
== ECHILD
)
2988 child
->running
= PS_DONE
;
2989 WSTATUS (child
->status
) = 0; /* XXX -- can't find true status */
2991 js
.c_living
= 0; /* no living child processes */
2994 jobs
[job
]->state
= JDEAD
;
3000 termination_state
= -1;
3006 /* If the shell is interactive, and job control is disabled, see
3007 if the foreground process has died due to SIGINT and jump out
3008 of the wait loop if it has. waitchld has already restored the
3009 old SIGINT signal handler. */
3010 if (interactive
&& job_control
== 0)
3012 /* Check for terminating signals and exit the shell if we receive one */
3015 /* Check for a trapped signal interrupting the wait builtin and jump out */
3020 /* XXX - could set child but we don't have a handle on what waitchld
3021 reaps. Leave termination_state alone. */
3022 restore_sigint_handler ();
3023 goto wait_for_return
;
3026 while (PRUNNING (child
) || (job
!= NO_JOB
&& RUNNING (job
)));
3028 /* Restore the original SIGINT signal handler before we return. */
3029 restore_sigint_handler ();
3031 /* The exit state of the command is either the termination state of the
3032 child, or the termination state of the job. If a job, the status
3033 of the last child in the pipeline is the significant one. If the command
3034 or job was terminated by a signal, note that value also. */
3035 termination_state
= (job
!= NO_JOB
) ? job_exit_status (job
)
3036 : (child
? process_exit_status (child
->status
) : EXECUTION_SUCCESS
);
3037 last_command_exit_signal
= (job
!= NO_JOB
) ? job_exit_signal (job
)
3038 : (child
? process_exit_signal (child
->status
) : 0);
3041 if ((job
!= NO_JOB
&& JOBSTATE (job
) == JSTOPPED
) || (child
&& WIFSTOPPED (child
->status
)))
3042 termination_state
= 128 + WSTOPSIG (child
->status
);
3044 if (job
== NO_JOB
|| IS_JOBCONTROL (job
))
3046 /* XXX - under what circumstances is a job not present in the jobs
3047 table (job == NO_JOB)?
3048 1. command substitution
3050 In the case of command substitution, at least, it's probably not
3051 the right thing to give the terminal to the shell's process group,
3052 even though there is code in subst.c:command_substitute to work
3056 $PROMPT_COMMAND execution
3057 process substitution
3061 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp
);
3063 /* Don't modify terminal pgrp if we are running in background or a
3064 subshell. Make sure subst.c:command_substitute uses the same
3065 conditions to determine whether or not it should undo this and
3066 give the terminal to pipeline_pgrp. We don't give the terminal
3067 back to shell_pgrp if an async job in the background exits because
3068 we never gave it to that job in the first place. An async job in
3069 the foreground is one we started in the background and foregrounded
3070 with `fg', and gave it the terminal. */
3071 if ((flags
& JWAIT_NOTERM
) == 0 && running_in_background
== 0 &&
3072 (job
== NO_JOB
|| IS_ASYNC (job
) == 0 || IS_FOREGROUND (job
)) &&
3073 (subshell_environment
& (SUBSHELL_ASYNC
|SUBSHELL_PIPE
)) == 0)
3074 give_terminal_to (shell_pgrp
, 0);
3077 /* If the command did not exit cleanly, or the job is just
3078 being stopped, then reset the tty state back to what it
3079 was before this command. Reset the tty state and notify
3080 the user of the job termination only if the shell is
3081 interactive. Clean up any dead jobs in either case. */
3084 if (interactive_shell
&& subshell_environment
== 0)
3086 /* This used to use `child->status'. That's wrong, however, for
3087 pipelines. `child' is the first process in the pipeline. It's
3088 likely that the process we want to check for abnormal termination
3089 or stopping is the last process in the pipeline, especially if
3090 it's long-lived and the first process is short-lived. Since we
3091 know we have a job here, we can check all the processes in this
3092 job's pipeline and see if one of them stopped or terminated due
3093 to a signal. We might want to change this later to just check
3094 the last process in the pipeline. If no process exits due to a
3095 signal, S is left as the status of the last job in the pipeline. */
3096 s
= job_signal_status (job
);
3098 if (WIFSIGNALED (s
) || WIFSTOPPED (s
))
3102 /* If the current job was stopped or killed by a signal, and
3103 the user has requested it, get a possibly new window size */
3104 if (check_window_size
&& (job
== js
.j_current
|| IS_FOREGROUND (job
)))
3105 get_new_window_size (0, (int *)0, (int *)0);
3108 #if defined (READLINE)
3109 /* We don't want to get the entire tty state if we are running
3110 while readline is active or has changed the terminal, but we
3111 can handle window size changes during programmable completion,
3112 traps while readline is active, or a command bound using
3114 if (RL_ISSTATE(RL_STATE_COMPLETING
|RL_STATE_DISPATCHING
|RL_STATE_TERMPREPPED
) != 0)
3116 if (check_window_size
)
3117 get_new_window_size (0, (int *)0, (int *)0);
3123 /* If job control is enabled, the job was started with job
3124 control, the job was the foreground job, and it was killed
3125 by SIGINT, then print a newline to compensate for the kernel
3126 printing the ^C without a trailing newline. */
3127 if (job_control
&& IS_JOBCONTROL (job
) && IS_FOREGROUND (job
) &&
3128 WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
)
3130 /* If SIGINT is not trapped and the shell is in a for, while,
3131 until, or arithmetic for loop, or is executing a compound list,
3132 act as if the shell received SIGINT as well, so the loop or
3133 list can be broken. This doesn't call the SIGINT signal
3134 handler; maybe it should. */
3135 if (signal_is_trapped (SIGINT
) == 0 && interrupt_execution
)
3137 /* Call any SIGINT trap handler if the shell is running a loop, so
3138 the loop can be broken. This seems more useful and matches the
3139 behavior when the shell is running a builtin command in a loop
3140 when it is interrupted. Change ADDINTERRUPT to
3141 trap_handler (SIGINT) to run the trap without interrupting the
3143 else if (signal_is_trapped (SIGINT
) && loop_level
)
3145 /* If an interactive shell with job control enabled is sourcing
3146 a file, allow the interrupt to terminate the file sourcing. */
3147 else if (interactive_shell
&& signal_is_trapped (SIGINT
) == 0 && sourcelevel
)
3156 else if ((subshell_environment
& (SUBSHELL_COMSUB
|SUBSHELL_PIPE
)) && wait_sigint_received
)
3158 /* If waiting for a job in a subshell started to do command
3159 substitution or to run a pipeline element that consists of
3160 something like a while loop or a for loop, simulate getting
3161 and being killed by the SIGINT to pass the status back to our
3163 if (child_caught_sigint
== 0 && signal_is_trapped (SIGINT
) == 0)
3165 UNBLOCK_CHILD (oset
);
3166 old_sigint_handler
= set_signal_handler (SIGINT
, SIG_DFL
);
3167 if (old_sigint_handler
== SIG_IGN
)
3168 restore_sigint_handler ();
3170 kill (getpid (), SIGINT
);
3173 else if (interactive_shell
== 0 && subshell_environment
== 0 && IS_FOREGROUND (job
))
3175 s
= job_signal_status (job
);
3177 /* If we are non-interactive, but job control is enabled, and the job
3178 died due to SIGINT, pretend we got the SIGINT */
3179 if (job_control
&& IS_JOBCONTROL (job
) && WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
)
3181 ADDINTERRUPT
; /* For now */
3184 if (check_window_size
)
3185 get_new_window_size (0, (int *)0, (int *)0);
3187 else if (interactive_shell
&& interactive
== 0 && check_window_size
&&
3188 (subshell_environment
& (SUBSHELL_PAREN
|SUBSHELL_ASYNC
)) == SUBSHELL_PAREN
&&
3189 IS_FOREGROUND (job
))
3190 /* Make checkwinsize work in foreground subshells started from
3191 interactive shells. */
3192 get_new_window_size (0, (int *)0, (int *)0);
3194 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
3195 signal handler path */
3196 if (DEADJOB (job
) && IS_FOREGROUND (job
) /*&& subshell_environment == 0*/)
3199 /* If this job is dead, notify the user of the status. If the shell
3200 is interactive, this will display a message on the terminal. If
3201 the shell is not interactive, make sure we turn on the notify bit
3202 so we don't get an unwanted message about the job's termination,
3203 and so delete_job really clears the slot in the jobs table. */
3204 notify_and_cleanup ();
3209 UNBLOCK_CHILD (oset
);
3211 return (termination_state
);
3214 /* Wait for the last process in the pipeline for JOB. Returns whatever
3215 wait_for returns: the last process's termination state or -1 if there
3216 are no unwaited-for child processes or an error occurs. If FLAGS
3217 includes JWAIT_FORCE, we wait for the job to terminate, no just change
3220 wait_for_job (int job
, int flags
, struct procstat
*ps
)
3226 BLOCK_CHILD(set
, oset
);
3227 state
= JOBSTATE (job
);
3228 if (state
== JSTOPPED
)
3229 internal_warning (_("wait_for_job: job %d is stopped"), job
+1);
3231 pid
= find_last_pid (job
, 0);
3232 UNBLOCK_CHILD(oset
);
3236 r
= wait_for (pid
, 0);
3237 if (r
== -1 && errno
== ECHILD
)
3238 mark_all_jobs_as_dead ();
3242 if ((flags
& JWAIT_FORCE
) == 0)
3245 BLOCK_CHILD (set
, oset
);
3246 state
= (job
!= NO_JOB
&& jobs
[job
]) ? JOBSTATE (job
) : JDEAD
;
3247 UNBLOCK_CHILD (oset
);
3249 while (state
!= JDEAD
);
3251 /* POSIX.2: we can remove the job from the jobs table if we just waited
3253 BLOCK_CHILD (set
, oset
);
3254 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
3255 jobs
[job
]->flags
|= J_NOTIFIED
;
3256 UNBLOCK_CHILD (oset
);
3261 ps
->status
= (r
< 0) ? 127 : r
;
3266 /* Wait for any background job started by this shell to finish. Very
3267 similar to wait_for_background_pids(). Returns the exit status of
3268 the next exiting job, -1 if there are no background jobs. The caller
3269 is responsible for translating -1 into the right return value. RPID,
3270 if non-null, gets the pid of the job's process leader. */
3272 wait_for_any_job (int flags
, struct procstat
*ps
)
3278 /* Allow funsubs to run this, but don't remove jobs from the jobs table. */
3279 if (jobs_list_frozen
&& executing_funsub
== 0)
3282 /* First see if there are any unnotified dead jobs that we can report on */
3283 BLOCK_CHILD (set
, oset
);
3284 for (i
= 0; i
< js
.j_jobslots
; i
++)
3286 if ((flags
& JWAIT_WAITING
) && jobs
[i
] && IS_WAITING (i
) == 0)
3287 continue; /* if we don't want it, skip it */
3288 if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
) == 0 && IS_FOREGROUND (i
) == 0)
3291 r
= job_exit_status (i
);
3292 pid
= find_last_pid (i
, 0);
3298 if (jobs_list_frozen
== 0) /* must be running a funsub to get here */
3300 notify_of_job_status (); /* XXX */
3301 #if 1 /* TAG: bash-5.3 kre@munnari.oz.au 01/30/2024 */
3302 delete_job (i
, posixly_correct
? DEL_NOBGPID
: 0);
3308 jobs
[i
]->flags
|= J_NOTIFIED
; /* clean up later */
3309 #if defined (COPROCESS_SUPPORT)
3312 UNBLOCK_CHILD (oset
);
3316 UNBLOCK_CHILD (oset
);
3318 /* At this point, we have no dead jobs in the jobs table. Wait until we
3319 get one, even if it takes multiple pids exiting. */
3322 /* Make sure there is a background job to wait for */
3323 BLOCK_CHILD (set
, oset
);
3324 for (i
= 0; i
< js
.j_jobslots
; i
++)
3326 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
3328 /* It's possible for there to be a dead job that was reaped when
3329 SIGCHLD was unblocked before this loop started. */
3330 else if ((flags
& JWAIT_WAITING
) && jobs
[i
] && IS_WAITING (i
) == 0)
3332 else if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
) == 0 && IS_FOREGROUND (i
) == 0)
3336 if (i
== js
.j_jobslots
)
3338 UNBLOCK_CHILD (oset
);
3342 UNBLOCK_CHILD (oset
);
3349 r
= wait_for (ANY_PID
, 0); /* special sentinel value for wait_for */
3350 if (r
== -1 && errno
== ECHILD
)
3351 mark_all_jobs_as_dead ();
3353 /* Now we see if we have any dead jobs and return the first one */
3354 BLOCK_CHILD (set
, oset
);
3355 for (i
= 0; i
< js
.j_jobslots
; i
++)
3357 if ((flags
& JWAIT_WAITING
) && jobs
[i
] && IS_WAITING (i
) == 0)
3358 continue; /* if we don't want it, skip it */
3359 if (jobs
[i
] && DEADJOB (i
))
3362 UNBLOCK_CHILD (oset
);
3368 /* Print info about dead jobs, and then delete them from the list
3369 of known jobs. This does not actually delete jobs when the
3370 shell is not interactive, because the dead jobs are not marked
3373 notify_and_cleanup (void)
3375 if (jobs_list_frozen
)
3378 if (interactive
|| interactive_shell
== 0 || sourcelevel
)
3379 notify_of_job_status ();
3381 cleanup_dead_jobs ();
3384 /* Make dead jobs disappear from the jobs array without notification.
3385 This is used when the shell is not interactive. */
3387 reap_dead_jobs (void)
3389 mark_dead_jobs_as_notified (0);
3390 cleanup_dead_jobs ();
3393 /* Return the next closest (chronologically) job to JOB which is in
3394 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
3395 there is no next recent job. */
3397 most_recent_job_in_state (int job
, JOB_STATE state
)
3399 register int i
, result
;
3402 BLOCK_CHILD (set
, oset
);
3404 for (result
= NO_JOB
, i
= job
- 1; i
>= 0; i
--)
3406 if (jobs
[i
] && (JOBSTATE (i
) == state
))
3413 UNBLOCK_CHILD (oset
);
3418 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
3421 job_last_stopped (int job
)
3423 return (most_recent_job_in_state (job
, JSTOPPED
));
3426 /* Return the newest *running* job older than JOB, or NO_JOB if not
3429 job_last_running (int job
)
3431 return (most_recent_job_in_state (job
, JRUNNING
));
3434 /* Make JOB be the current job, and make previous be useful. Must be
3435 called with SIGCHLD blocked. */
3437 set_current_job (int job
)
3441 if (js
.j_current
!= job
)
3443 js
.j_previous
= js
.j_current
;
3447 /* First choice for previous job is the old current job. */
3448 if (js
.j_previous
!= js
.j_current
&&
3449 js
.j_previous
!= NO_JOB
&&
3450 jobs
[js
.j_previous
] &&
3451 STOPPED (js
.j_previous
))
3454 /* Second choice: Newest stopped job that is older than
3457 if (STOPPED (js
.j_current
))
3459 candidate
= job_last_stopped (js
.j_current
);
3461 if (candidate
!= NO_JOB
)
3463 js
.j_previous
= candidate
;
3468 /* If we get here, there is either only one stopped job, in which case it is
3469 the current job and the previous job should be set to the newest running
3470 job, or there are only running jobs and the previous job should be set to
3471 the newest running job older than the current job. We decide on which
3472 alternative to use based on whether or not JOBSTATE(js.j_current) is
3475 candidate
= RUNNING (js
.j_current
) ? job_last_running (js
.j_current
)
3476 : job_last_running (js
.j_jobslots
);
3478 if (candidate
!= NO_JOB
)
3480 js
.j_previous
= candidate
;
3484 /* There is only a single job, and it is both `+' and `-'. */
3485 js
.j_previous
= js
.j_current
;
3488 /* Make current_job be something useful, if it isn't already. */
3490 /* Here's the deal: The newest non-running job should be `+', and the
3491 next-newest non-running job should be `-'. If there is only a single
3492 stopped job, the js.j_previous is the newest non-running job. If there
3493 are only running jobs, the newest running job is `+' and the
3494 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
3497 reset_current (void)
3501 if (js
.j_jobslots
&& js
.j_current
!= NO_JOB
&& jobs
[js
.j_current
] && STOPPED (js
.j_current
))
3502 candidate
= js
.j_current
;
3507 /* First choice: the previous job. */
3508 if (js
.j_previous
!= NO_JOB
&& jobs
[js
.j_previous
] && STOPPED (js
.j_previous
))
3509 candidate
= js
.j_previous
;
3511 /* Second choice: the most recently stopped job. */
3512 if (candidate
== NO_JOB
)
3513 candidate
= job_last_stopped (js
.j_jobslots
);
3515 /* Third choice: the newest running job. */
3516 if (candidate
== NO_JOB
)
3517 candidate
= job_last_running (js
.j_jobslots
);
3520 /* If we found a job to use, then use it. Otherwise, there
3521 are no jobs period. */
3522 if (candidate
!= NO_JOB
)
3523 set_current_job (candidate
);
3525 js
.j_current
= js
.j_previous
= NO_JOB
;
3528 /* Set up the job structures so we know the job and its processes are
3531 set_job_running (int job
)
3533 register PROCESS
*p
;
3535 /* Each member of the pipeline is now running. */
3536 p
= jobs
[job
]->pipe
;
3540 if (WIFSTOPPED (p
->status
))
3541 p
->running
= PS_RUNNING
; /* XXX - could be PS_STOPPED */
3544 while (p
!= jobs
[job
]->pipe
);
3546 /* This means that the job is running. */
3547 JOBSTATE (job
) = JRUNNING
;
3550 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
3551 start the job in the background. JOB is a zero-based index into
3552 JOBS. Returns -1 if it is unable to start a job, and the return
3553 status of the job otherwise. */
3555 start_job (int job
, int foreground
)
3557 register PROCESS
*p
;
3558 int already_running
;
3561 static TTYSTRUCT save_stty
;
3563 BLOCK_CHILD (set
, oset
);
3565 if ((subshell_environment
& SUBSHELL_COMSUB
) && (pipeline_pgrp
== shell_pgrp
))
3567 internal_error (_("%s: no current jobs"), this_command_name
);
3568 UNBLOCK_CHILD (oset
);
3574 internal_error (_("%s: job has terminated"), this_command_name
);
3575 UNBLOCK_CHILD (oset
);
3579 already_running
= RUNNING (job
);
3581 if (foreground
== 0 && already_running
)
3583 internal_error (_("%s: job %d already in background"), this_command_name
, job
+ 1);
3584 UNBLOCK_CHILD (oset
);
3585 return (0); /* XPG6/SUSv3 says this is not an error */
3588 wd
= current_working_directory ();
3590 /* You don't know about the state of this job. Do you? */
3591 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3595 set_current_job (job
);
3596 jobs
[job
]->flags
|= J_FOREGROUND
;
3599 /* Tell the outside world what we're doing. */
3600 p
= jobs
[job
]->pipe
;
3602 if (foreground
== 0)
3604 /* POSIX.2 says `bg' doesn't give any indication about current or
3606 if (posixly_correct
== 0)
3607 s
= (job
== js
.j_current
) ? "+ ": ((job
== js
.j_previous
) ? "- " : " ");
3610 printf ("[%d]%s", job
+ 1, s
);
3616 p
->command
? p
->command
: "",
3617 p
->next
!= jobs
[job
]->pipe
? " | " : "");
3620 while (p
!= jobs
[job
]->pipe
);
3622 if (foreground
== 0)
3625 if (strcmp (wd
, jobs
[job
]->wd
) != 0)
3626 printf (" (wd: %s)", polite_directory_format (jobs
[job
]->wd
));
3631 if (already_running
== 0)
3632 jobs
[job
]->flags
|= J_NOTIFIED
;
3634 /* Save the tty settings before we start the job in the foreground. */
3638 save_stty
= shell_tty_info
;
3639 jobs
[job
]->flags
&= ~J_ASYNC
; /* no longer async */
3640 /* Give the terminal to this job. */
3641 if (IS_JOBCONTROL (job
))
3642 give_terminal_to (jobs
[job
]->pgrp
, 0);
3646 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3647 jobs
[job
]->flags
|= J_ASYNC
; /* running in background now */
3650 /* Change job state to running only if the kill SIGCONT succeeds or if kill
3651 says the process has terminated so we clean it up later. */
3652 if (killpg (jobs
[job
]->pgrp
, SIGCONT
) >= 0 || errno
== ESRCH
)
3653 set_job_running (job
);
3660 pid
= find_last_pid (job
, 0);
3661 UNBLOCK_CHILD (oset
);
3662 st
= wait_for (pid
, 0);
3663 shell_tty_info
= save_stty
;
3670 UNBLOCK_CHILD (oset
);
3675 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
3676 If PID does belong to a job, and the job is stopped, then CONTinue the
3677 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
3678 then kill the process group associated with PID. */
3680 kill_pid (pid_t pid
, int sig
, int group
)
3682 register PROCESS
*p
;
3683 int job
, result
, negative
;
3689 group
= negative
= 1;
3694 result
= EXECUTION_SUCCESS
;
3697 BLOCK_CHILD (set
, oset
);
3698 p
= find_pipeline (pid
, 0, &job
);
3702 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3704 /* Kill process in backquotes or one started without job control? */
3706 /* If we're passed a pid < -1, just call killpg and see what happens */
3707 if (negative
&& jobs
[job
]->pgrp
== shell_pgrp
)
3708 result
= killpg (pid
, sig
);
3709 /* If we're killing using job control notification, for example,
3710 without job control active, we have to do things ourselves. */
3711 else if (jobs
[job
]->pgrp
== shell_pgrp
) /* XXX - IS_JOBCONTROL(job) == 0? */
3713 p
= jobs
[job
]->pipe
;
3716 if (PALIVE (p
) == 0)
3717 continue; /* avoid pid recycling problem */
3719 if (PEXITED (p
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3720 kill (p
->pid
, SIGCONT
);
3723 while (p
!= jobs
[job
]->pipe
);
3727 result
= killpg (jobs
[job
]->pgrp
, sig
);
3728 if (p
&& STOPPED (job
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3729 killpg (jobs
[job
]->pgrp
, SIGCONT
);
3730 /* If we're continuing a stopped job via kill rather than bg or
3731 fg, emulate the `bg' behavior. */
3732 if (p
&& STOPPED (job
) && (sig
== SIGCONT
))
3734 set_job_running (job
);
3735 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3736 jobs
[job
]->flags
|= J_NOTIFIED
;
3741 result
= killpg (pid
, sig
);
3743 UNBLOCK_CHILD (oset
);
3746 result
= kill (pid
, sig
);
3751 /* sigchld_handler () flushes at least one of the children that we are
3752 waiting for. It gets run when we have gotten a SIGCHLD signal. */
3754 sigchld_handler (int sig
)
3759 REINSTALL_SIGCHLD_HANDLER
;
3762 if (queue_sigchld
== 0)
3763 n
= waitchld (-1, 0);
3768 /* waitchld() reaps dead or stopped children. It's called by wait_for and
3769 sigchld_handler, and runs until there aren't any children terminating any
3771 If BLOCK is 1, this is to be a blocking wait for a single child, although
3772 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
3773 the number of children reaped, or -1 if there are no unwaited-for child
3776 waitchld (pid_t wpid
, int block
)
3783 int call_set_current
, last_stopped_job
, job
, children_exited
, waitpid_flags
;
3784 static int wcontinued
= WCONTINUED
; /* run-time fix for glibc problem */
3786 call_set_current
= children_exited
= 0;
3787 last_stopped_job
= NO_JOB
;
3791 /* We don't want to be notified about jobs stopping if job control
3792 is not active. XXX - was interactive_shell instead of job_control */
3793 waitpid_flags
= (job_control
&& subshell_environment
== 0)
3794 ? (WUNTRACED
|wcontinued
)
3796 if (sigchld
|| block
== 0)
3797 waitpid_flags
|= WNOHANG
;
3799 /* Check for terminating signals and exit the shell if we receive one */
3801 /* Check for a trapped signal interrupting the wait builtin and jump out */
3804 if (block
== 1 && queue_sigchld
== 0 && (waitpid_flags
& WNOHANG
) == 0)
3806 internal_warning (_("waitchld: turning on WNOHANG to avoid indefinite block"));
3807 waitpid_flags
|= WNOHANG
;
3810 pid
= WAITPID (-1, &status
, waitpid_flags
);
3813 if (wpid
!= -1 && block
)
3814 itrace("waitchld: blocking waitpid returns %d", pid
);
3818 itrace("waitchld: %s waitpid returns %d", block
?"blocking":"non-blocking", pid
);
3820 /* WCONTINUED may be rejected by waitpid as invalid even when defined */
3821 if (wcontinued
&& pid
< 0 && errno
== EINVAL
)
3824 continue; /* jump back to the test and retry without WCONTINUED */
3827 /* The check for WNOHANG is to make sure we decrement sigchld only
3828 if it was non-zero before we called waitpid. */
3829 if (sigchld
> 0 && (waitpid_flags
& WNOHANG
))
3832 /* If waitpid returns -1 with errno == ECHILD, there are no more
3833 unwaited-for child processes of this shell. */
3834 if (pid
< 0 && errno
== ECHILD
)
3836 if (children_exited
== 0)
3843 itrace("waitchld: waitpid returns %d block = %d children_exited = %d", pid
, block
, children_exited
);
3845 /* If waitpid returns 0, there are running children. If it returns -1,
3846 the only other error POSIX says it can return is EINTR. */
3850 /* If waitpid returns -1/EINTR and the shell saw a SIGINT, then we
3851 assume the child has blocked or handled SIGINT. In that case, we
3852 require the child to actually die due to SIGINT to act on the
3853 SIGINT we received; otherwise we assume the child handled it and
3855 if (pid
< 0 && errno
== EINTR
&& wait_sigint_received
)
3856 child_caught_sigint
= 1;
3859 continue; /* jumps right to the test */
3861 /* Linux kernels appear to signal the parent but not interrupt the
3862 waitpid() (or restart it even without SA_RESTART) on SIGINT, so if
3863 we saw a SIGINT and the process exited or died due to some other
3864 signal, assume the child caught the SIGINT. */
3865 if (wait_sigint_received
&& (WIFSIGNALED (status
) == 0 || WTERMSIG (status
) != SIGINT
))
3866 child_caught_sigint
= 1;
3868 /* If the child process did die due to SIGINT, forget our assumption
3869 that it caught or otherwise handled it. */
3870 if (WIFSIGNALED (status
) && WTERMSIG (status
) == SIGINT
)
3871 child_caught_sigint
= 0;
3873 /* children_exited is used to run traps on SIGCHLD. We don't want to
3874 run the trap if a process is just being continued. */
3875 if (WIFCONTINUED(status
) == 0)
3881 /* Locate our PROCESS for this pid. */
3882 child
= find_process (pid
, 1, &job
); /* want living procs only */
3884 #if defined (COPROCESS_SUPPORT)
3885 coproc_pidchk (pid
, WSTATUS(status
));
3888 #if defined (PROCESS_SUBSTITUTION)
3889 /* Only manipulate the list of process substitutions while SIGCHLD
3890 is blocked. We only use this as a hint that we can remove FIFOs
3891 or close file descriptors corresponding to terminated process
3893 if ((ind
= find_procsub_child (pid
)) >= 0)
3894 set_procsub_status (ind
, pid
, WSTATUS (status
));
3897 /* It is not an error to have a child terminate that we did
3898 not have a record of. This child could have been part of
3899 a pipeline in backquote substitution. Even so, I'm not
3900 sure child is ever non-zero. */
3903 if (WIFEXITED (status
) || WIFSIGNALED (status
))
3908 /* Remember status, and whether or not the process is running. */
3909 child
->status
= status
;
3910 child
->running
= WIFCONTINUED(status
) ? PS_RUNNING
: PS_DONE
;
3912 if (PEXITED (child
))
3922 call_set_current
+= set_job_status_and_cleanup (job
);
3925 last_stopped_job
= job
;
3926 else if (DEADJOB (job
) && last_stopped_job
== job
)
3927 last_stopped_job
= NO_JOB
;
3929 while ((sigchld
|| block
== 0) && pid
> (pid_t
)0);
3931 /* If a job was running and became stopped, then set the current
3932 job. Otherwise, don't change a thing. */
3933 if (call_set_current
)
3935 if (last_stopped_job
!= NO_JOB
)
3936 set_current_job (last_stopped_job
);
3941 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3942 if (children_exited
&&
3943 (signal_is_trapped (SIGCHLD
) || trap_list
[SIGCHLD
] == (char *)IMPOSSIBLE_TRAP_HANDLER
) &&
3944 trap_list
[SIGCHLD
] != (char *)IGNORE_SIG
)
3946 if (posixly_correct
&& this_shell_builtin
&& this_shell_builtin
== wait_builtin
)
3948 /* This was trap_handler (SIGCHLD) but that can lose traps if
3949 children_exited > 1 */
3950 queue_sigchld_trap (children_exited
);
3951 wait_signal_received
= SIGCHLD
;
3952 /* If we're in a signal handler, let CHECK_WAIT_INTR pick it up;
3953 run_pending_traps will call run_sigchld_trap later */
3954 if (sigchld
== 0 && wait_intr_flag
)
3955 sh_longjmp (wait_intr_buf
, 1);
3957 /* If not in posix mode and not executing the wait builtin, queue the
3958 signal for later handling. Run the trap immediately if we are
3959 executing the wait builtin, but don't break out of `wait'. */
3960 else if (sigchld
) /* called from signal handler */
3961 queue_sigchld_trap (children_exited
);
3962 else if (signal_in_progress (SIGCHLD
))
3963 queue_sigchld_trap (children_exited
);
3964 else if (trap_list
[SIGCHLD
] == (char *)IMPOSSIBLE_TRAP_HANDLER
)
3965 queue_sigchld_trap (children_exited
);
3966 else if (running_trap
)
3967 queue_sigchld_trap (children_exited
);
3968 else if (this_shell_builtin
== wait_builtin
)
3971 o
= jobs_list_frozen
;
3972 jobs_list_frozen
= 1;
3973 run_sigchld_trap (children_exited
); /* XXX */
3974 jobs_list_frozen
= o
;
3977 queue_sigchld_trap (children_exited
);
3980 /* We have successfully recorded the useful information about this process
3981 that has just changed state. If we notify asynchronously, and the job
3982 that this process belongs to is no longer running, then notify the user
3983 of that fact now. */
3984 if (asynchronous_notification
&& interactive
&& executing_builtin
== 0)
3985 notify_of_job_status ();
3987 return (children_exited
);
3990 /* Set the status of JOB and perform any necessary cleanup if the job is
3993 Currently, the cleanup activity is restricted to handling any SIGINT
3994 received while waiting for a foreground job to finish. */
3996 set_job_status_and_cleanup (int job
)
3999 int tstatus
, job_state
, any_stopped
, any_tstped
, call_set_current
;
4000 SigHandler
*temp_handler
;
4002 child
= jobs
[job
]->pipe
;
4003 jobs
[job
]->flags
&= ~J_NOTIFIED
;
4005 call_set_current
= 0;
4008 * COMPUTE JOB STATUS
4011 /* If all children are not running, but any of them is stopped, then
4012 the job is stopped, not dead. */
4013 job_state
= any_stopped
= any_tstped
= 0;
4016 job_state
|= PRUNNING (child
);
4018 if (PEXITED (child
) && (WIFSTOPPED (child
->status
)))
4020 /* Only checking for WIFSTOPPED now, not for PS_DONE */
4021 if (PSTOPPED (child
))
4025 any_tstped
|= job_control
&& (WSTOPSIG (child
->status
) == SIGTSTP
);
4027 child
= child
->next
;
4029 while (child
!= jobs
[job
]->pipe
);
4031 /* If job_state != 0, the job is still running, so don't bother with
4032 setting the process exit status and job state unless we're
4033 transitioning from stopped to running. */
4034 if (job_state
!= 0 && JOBSTATE(job
) != JSTOPPED
)
4041 /* The job is either stopped or dead. Set the state of the job accordingly. */
4044 jobs
[job
]->state
= JSTOPPED
;
4045 jobs
[job
]->flags
&= ~J_FOREGROUND
;
4047 /* Suspending a job with SIGTSTP breaks all active loops. */
4048 if (any_tstped
&& loop_level
)
4049 breaking
= loop_level
;
4051 else if (job_state
!= 0) /* was stopped, now running */
4053 jobs
[job
]->state
= JRUNNING
;
4058 jobs
[job
]->state
= JDEAD
;
4062 if (IS_FOREGROUND (job
))
4066 /* If this job has a cleanup function associated with it, call it
4067 with `cleanarg' as the single argument, then set the function
4068 pointer to NULL so it is not inadvertently called twice. The
4069 cleanup function is responsible for deallocating cleanarg. */
4070 if (jobs
[job
]->j_cleanup
)
4072 (*jobs
[job
]->j_cleanup
) (jobs
[job
]->cleanarg
);
4073 jobs
[job
]->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
4080 * Currently, we just do special things if we got a SIGINT while waiting
4081 * for a foreground job to complete
4084 if (JOBSTATE (job
) == JDEAD
)
4086 /* If we're running a shell script and we get a SIGINT with a
4087 SIGINT trap handler, but the foreground job handles it and
4088 does not exit due to SIGINT, run the trap handler but do not
4089 otherwise act as if we got the interrupt. */
4090 if (wait_sigint_received
&& interactive_shell
== 0 &&
4091 child_caught_sigint
&& IS_FOREGROUND (job
) &&
4092 signal_is_trapped (SIGINT
))
4095 wait_sigint_received
= 0;
4096 last_command_exit_value
= process_exit_status (child
->status
);
4098 old_frozen
= jobs_list_frozen
;
4099 jobs_list_frozen
= 1;
4100 tstatus
= maybe_call_trap_handler (SIGINT
);
4101 jobs_list_frozen
= old_frozen
;
4104 /* If the foreground job is killed by SIGINT when job control is not
4105 active, we need to perform some special handling.
4107 The check of wait_sigint_received is a way to determine if the
4108 SIGINT came from the keyboard (in which case the shell has already
4109 seen it, and wait_sigint_received is non-zero, because keyboard
4110 signals are sent to process groups) or via kill(2) to the foreground
4111 process by another process (or itself). If the shell did receive the
4112 SIGINT, it needs to perform normal SIGINT processing. XXX - should
4113 this change its behavior depending on whether the last command in an
4114 pipeline exited due to SIGINT, or any process in the pipeline? Right
4115 now it does this if any process in the pipeline exits due to SIGINT. */
4116 else if (wait_sigint_received
&&
4117 child_caught_sigint
== 0 &&
4118 IS_FOREGROUND (job
) && IS_JOBCONTROL (job
) == 0)
4122 wait_sigint_received
= 0;
4124 /* If SIGINT is trapped, set the exit status so that the trap
4125 handler can see it. */
4126 if (signal_is_trapped (SIGINT
))
4127 last_command_exit_value
= process_exit_status (child
->status
);
4129 /* If the signal is trapped, let the trap handler get it no matter
4130 what and simply return if the trap handler returns.
4131 maybe_call_trap_handler() may cause dead jobs to be removed from
4132 the job table because of a call to execute_command. We work
4133 around this by setting JOBS_LIST_FROZEN. */
4134 old_frozen
= jobs_list_frozen
;
4135 jobs_list_frozen
= 1;
4136 tstatus
= maybe_call_trap_handler (SIGINT
);
4137 jobs_list_frozen
= old_frozen
;
4138 if (tstatus
== 0 && old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
4140 /* wait_sigint_handler () has already seen SIGINT and
4141 allowed the wait builtin to jump out. We need to
4142 call the original SIGINT handler, if necessary. If
4143 the original handler is SIG_DFL, we need to resend
4144 the signal to ourselves. */
4146 temp_handler
= old_sigint_handler
;
4148 /* Bogus. If we've reset the signal handler as the result
4149 of a trap caught on SIGINT, then old_sigint_handler
4150 will point to trap_handler, which now knows nothing about
4151 SIGINT (if we reset the sighandler to the default).
4152 In this case, we have to fix things up. What a crock. */
4153 if (temp_handler
== trap_handler
&& signal_is_trapped (SIGINT
) == 0)
4154 temp_handler
= trap_to_sighandler (SIGINT
);
4155 restore_sigint_handler ();
4156 if (temp_handler
== SIG_DFL
)
4157 termsig_handler (SIGINT
); /* XXX */
4158 else if (temp_handler
!= SIG_IGN
)
4159 (*temp_handler
) (SIGINT
);
4164 return call_set_current
;
4167 /* Build the array of values for the $PIPESTATUS variable from the set of
4168 exit statuses of all processes in the job J. */
4172 #if defined (ARRAY_VARS)
4174 register PROCESS
*p
;
4176 for (i
= 1, p
= jobs
[j
]->pipe
; p
->next
!= jobs
[j
]->pipe
; p
= p
->next
, i
++)
4181 pstatuses
= (int *)xrealloc (pstatuses
, i
* sizeof (int));
4188 pstatuses
[i
++] = process_exit_status (p
->status
);
4191 while (p
!= jobs
[j
]->pipe
);
4193 pstatuses
[i
] = -1; /* sentinel */
4194 set_pipestatus_array (pstatuses
, i
);
4199 run_sigchld_trap (int nchild
)
4204 /* Turn off the trap list during the call to parse_and_execute ()
4205 to avoid potentially infinite recursive calls. Preserve the
4206 values of last_command_exit_value, last_made_pid, and the_pipeline
4207 around the execution of the trap commands. */
4208 trap_command
= savestring (trap_list
[SIGCHLD
]);
4210 begin_unwind_frame ("SIGCHLD trap");
4211 unwind_protect_int (last_command_exit_value
);
4212 unwind_protect_int (last_command_exit_signal
);
4213 unwind_protect_var (last_made_pid
);
4214 unwind_protect_int (jobs_list_frozen
);
4215 unwind_protect_pointer (the_pipeline
);
4216 unwind_protect_pointer (subst_assign_varlist
);
4217 unwind_protect_pointer (this_shell_builtin
);
4218 unwind_protect_pointer (temporary_env
);
4220 /* We have to add the commands this way because they will be run
4221 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
4222 to reference freed memory. */
4223 add_unwind_protect (xfree
, trap_command
);
4224 add_unwind_protect (uw_maybe_set_sigchld_trap
, trap_command
);
4226 subst_assign_varlist
= (WORD_LIST
*)NULL
;
4227 the_pipeline
= (PROCESS
*)NULL
;
4228 temporary_env
= 0; /* traps should not run with temporary env */
4230 running_trap
= SIGCHLD
+ 1;
4232 set_impossible_sigchld_trap ();
4233 for (i
= 0; i
< nchild
; i
++)
4235 parse_and_execute (savestring (trap_command
), "trap", SEVAL_NOHIST
|SEVAL_RESETLINE
|SEVAL_NOOPTIMIZE
);
4238 run_unwind_frame ("SIGCHLD trap");
4242 /* Function to call when you want to notify people of changes
4243 in job status. This prints out all jobs which are pending
4244 notification to stderr, and marks those printed as already
4245 notified, thus making them candidates for cleanup. */
4247 notify_of_job_status (void)
4249 register int job
, termsig
;
4254 if (jobs
== 0 || js
.j_jobslots
== 0)
4260 sigaddset (&set
, SIGCHLD
);
4261 sigaddset (&set
, SIGTTOU
);
4262 sigemptyset (&oset
);
4263 sigprocmask (SIG_BLOCK
, &set
, &oset
);
4268 /* XXX could use js.j_firstj here */
4269 for (job
= 0, dir
= NULL
; job
< js
.j_jobslots
; job
++)
4271 if (jobs
[job
] && IS_NOTIFIED (job
) == 0)
4273 s
= raw_job_exit_status (job
);
4274 termsig
= WTERMSIG (s
);
4276 /* POSIX.2 says we have to hang onto the statuses of at most the
4277 last CHILD_MAX background processes if the shell is running a
4278 script. If the shell is running a script, either from a file
4279 or standard input, don't print anything unless the job was
4280 killed by a signal. */
4281 if (startup_state
== 0 && WIFSIGNALED (s
) == 0 &&
4282 ((DEADJOB (job
) && IS_FOREGROUND (job
) == 0) || STOPPED (job
)))
4285 /* If job control is disabled, don't print the status messages.
4286 Mark dead jobs as notified so that they get cleaned up. If
4287 startup_state == 2 and subshell_environment has the
4288 SUBSHELL_COMSUB bit turned on, we were started to run a command
4289 substitution, so don't print anything.
4290 Otherwise, if the shell is not interactive, POSIX says that `jobs'
4291 is the only way to notify of job status. */
4292 if ((job_control
== 0 && interactive_shell
) ||
4293 (startup_state
== 2 && (subshell_environment
& SUBSHELL_COMSUB
)) ||
4294 (startup_state
== 2 && posixly_correct
&& (subshell_environment
& SUBSHELL_COMSUB
) == 0))
4296 /* POSIX.2 compatibility: if the shell is not interactive,
4297 hang onto the job corresponding to the last asynchronous
4298 pid until the user has been notified of its status or does
4300 if (DEADJOB (job
) && (interactive_shell
|| (find_last_pid (job
, 0) != last_asynchronous_pid
)))
4301 jobs
[job
]->flags
|= J_NOTIFIED
;
4305 /* Print info on jobs that are running in the background,
4306 and on foreground jobs that were killed by anything
4307 except SIGINT (and possibly SIGPIPE). */
4308 switch (JOBSTATE (job
))
4311 if (interactive_shell
== 0 && termsig
&& WIFSIGNALED (s
) &&
4312 termsig
!= SIGINT
&&
4313 #if defined (DONT_REPORT_SIGTERM)
4314 termsig
!= SIGTERM
&&
4316 #if defined (DONT_REPORT_SIGPIPE)
4317 termsig
!= SIGPIPE
&&
4319 signal_is_trapped (termsig
) == 0)
4321 /* Don't print `0' for a line number. */
4322 fprintf (stderr
, _("%s: line %d: "), get_name_for_error (), (line_number
== 0) ? 1 : line_number
);
4323 pretty_print_job (job
, JLIST_NONINTERACTIVE
, stderr
);
4325 else if (IS_FOREGROUND (job
))
4327 #if !defined (DONT_REPORT_SIGPIPE)
4328 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
)
4330 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
&& termsig
!= SIGPIPE
)
4333 fprintf (stderr
, "%s", j_strsignal (termsig
));
4336 fprintf (stderr
, _(" (core dumped)"));
4338 fprintf (stderr
, "\n");
4340 jobs
[job
]->flags
|= J_NOTIFIED
;
4342 else if (job_control
)
4345 dir
= current_working_directory ();
4346 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
4347 if (dir
&& strcmp (dir
, jobs
[job
]->wd
) != 0)
4349 _("(wd now: %s)\n"), polite_directory_format (dir
));
4352 /* This is where we set J_NOTIFIED for background jobs in
4353 non-interactive shells without job control enabled that are
4354 killed by SIGINT or SIGTERM (DONT_REPORT_SIGTERM) or SIGPIPE
4355 (DONT_REPORT_SIGPIPE) as long as those signals are not
4356 trapped, or that exit cleanly.
4357 Interactive shells without job control enabled are handled
4359 /* XXX - if we want to arrange to keep these jobs in the jobs
4360 list, instead of making them eligible to move to bgpids,
4361 this is where to change things. */
4362 jobs
[job
]->flags
|= J_NOTIFIED
;
4366 fprintf (stderr
, "\n");
4368 dir
= current_working_directory ();
4369 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
4370 if (dir
&& (strcmp (dir
, jobs
[job
]->wd
) != 0))
4372 _("(wd now: %s)\n"), polite_directory_format (dir
));
4373 jobs
[job
]->flags
|= J_NOTIFIED
;
4381 programming_error ("notify_of_job_status");
4386 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
4391 /* Initialize the job control mechanism, and set up the tty stuff. */
4393 initialize_job_control (int force
)
4396 int t_errno
, tty_sigs
;
4399 shell_pgrp
= getpgid (0);
4401 if (shell_pgrp
== -1)
4403 sys_error (_("initialize_job_control: getpgrp failed"));
4407 /* We can only have job control if we are interactive unless we force it. */
4408 if (interactive
== 0 && force
== 0)
4411 original_pgrp
= NO_PID
;
4412 shell_tty
= fileno (stderr
);
4413 terminal_pgrp
= tcgetpgrp (shell_tty
); /* for checking later */
4419 /* If forced_interactive is set, we skip the normal check that stderr
4420 is attached to a tty, so we need to check here. If it's not, we
4421 need to see whether we have a controlling tty by opening /dev/tty,
4422 since trying to use job control tty pgrp manipulations on a non-tty
4423 is going to fail. */
4424 if (forced_interactive
&& isatty (fileno (stderr
)) == 0)
4425 shell_tty
= open ("/dev/tty", O_RDWR
|O_NONBLOCK
);
4427 /* Get our controlling terminal. If job_control is set, or
4428 interactive is set, then this is an interactive shell no
4429 matter where fd 2 is directed. */
4430 if (shell_tty
== -1)
4431 shell_tty
= dup (fileno (stderr
)); /* fd 2 */
4433 if (shell_tty
!= -1)
4434 shell_tty
= move_to_high_fd (shell_tty
, 1, -1);
4436 /* Compensate for a bug in systems that compiled the BSD
4437 rlogind with DEBUG defined, like NeXT and Alliant. */
4438 if (shell_pgrp
== 0)
4440 shell_pgrp
= getpid ();
4441 setpgid (0, shell_pgrp
);
4442 if (shell_tty
!= -1)
4443 tcsetpgrp (shell_tty
, shell_pgrp
);
4447 while ((terminal_pgrp
= tcgetpgrp (shell_tty
)) != -1)
4449 if (shell_pgrp
!= terminal_pgrp
)
4454 ottin
= set_signal_handler (SIGTTIN
, SIG_DFL
);
4456 set_signal_handler (SIGTTIN
, ottin
);
4457 if (tty_sigs
++ > 16)
4459 sys_error (_("initialize_job_control: no job control in background"));
4461 original_pgrp
= terminal_pgrp
; /* for eventual give_terminal_to */
4469 if (terminal_pgrp
== -1)
4472 /* Make sure that we are using the new line discipline. */
4473 if (set_new_line_discipline (shell_tty
) < 0)
4475 sys_error (_("initialize_job_control: line discipline"));
4480 original_pgrp
= shell_pgrp
;
4481 shell_pgrp
= getpid ();
4483 if ((original_pgrp
!= shell_pgrp
) && (setpgid (0, shell_pgrp
) < 0))
4485 sys_error (_("initialize_job_control: setpgid"));
4486 shell_pgrp
= original_pgrp
;
4491 /* If (and only if) we just set our process group to our pid,
4492 thereby becoming a process group leader, and the terminal
4493 is not in the same process group as our (new) process group,
4494 then set the terminal's process group to our (new) process
4495 group. If that fails, set our process group back to what it
4496 was originally (so we can still read from the terminal) and
4497 turn off job control. */
4498 if (shell_pgrp
!= original_pgrp
&& shell_pgrp
!= terminal_pgrp
)
4500 if (give_terminal_to (shell_pgrp
, 0) < 0)
4503 setpgid (0, original_pgrp
);
4504 shell_pgrp
= original_pgrp
;
4506 sys_error (_("cannot set terminal process group (%d)"), shell_pgrp
);
4511 if (job_control
&& ((t
= tcgetpgrp (shell_tty
)) == -1 || t
!= shell_pgrp
))
4515 sys_error (_("cannot set terminal process group (%d)"), t
);
4519 if (job_control
== 0)
4520 internal_error (_("no job control in this shell"));
4524 running_in_background
= terminal_pgrp
!= shell_pgrp
;
4526 if (shell_tty
!= fileno (stderr
))
4527 SET_CLOSE_ON_EXEC (shell_tty
);
4529 set_signal_handler (SIGCHLD
, sigchld_handler
);
4531 change_flag ('m', job_control
? '-' : '+');
4543 debug_print_pgrps (void)
4545 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
4546 (long)original_pgrp
, (long)shell_pgrp
, (long)terminal_pgrp
);
4547 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
4548 shell_tty
, (long)tcgetpgrp (shell_tty
), (long)getpgid(0));
4549 itrace("pipeline_pgrp -> %ld", (long)pipeline_pgrp
);
4553 /* Set the line discipline to the best this system has to offer.
4554 Return -1 if this is not possible. */
4556 set_new_line_discipline (int tty
)
4558 #if defined (NEW_TTY_DRIVER)
4561 if (ioctl (tty
, TIOCGETD
, &ldisc
) < 0)
4564 if (ldisc
!= NTTYDISC
)
4568 if (ioctl (tty
, TIOCSETD
, &ldisc
) < 0)
4572 #endif /* NEW_TTY_DRIVER */
4574 #if defined (TERMIO_TTY_DRIVER)
4575 # if defined (TERMIO_LDISC) && (NTTYDISC)
4576 if (ioctl (tty
, TCGETA
, &shell_tty_info
) < 0)
4579 if (shell_tty_info
.c_line
!= NTTYDISC
)
4581 shell_tty_info
.c_line
= NTTYDISC
;
4582 if (ioctl (tty
, TCSETAW
, &shell_tty_info
) < 0)
4585 # endif /* TERMIO_LDISC && NTTYDISC */
4587 #endif /* TERMIO_TTY_DRIVER */
4589 #if defined (TERMIOS_TTY_DRIVER)
4590 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
4591 if (tcgetattr (tty
, &shell_tty_info
) < 0)
4594 if (shell_tty_info
.c_line
!= NTTYDISC
)
4596 shell_tty_info
.c_line
= NTTYDISC
;
4597 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
4600 # endif /* TERMIOS_LDISC && NTTYDISC */
4602 #endif /* TERMIOS_TTY_DRIVER */
4604 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
4609 /* Setup this shell to handle C-C, etc. */
4611 initialize_job_signals (void)
4615 set_signal_handler (SIGINT
, sigint_sighandler
);
4616 set_signal_handler (SIGTSTP
, SIG_IGN
);
4617 set_signal_handler (SIGTTOU
, SIG_IGN
);
4618 set_signal_handler (SIGTTIN
, SIG_IGN
);
4620 else if (job_control
)
4622 old_tstp
= set_signal_handler (SIGTSTP
, sigstop_sighandler
);
4623 old_ttin
= set_signal_handler (SIGTTIN
, sigstop_sighandler
);
4624 old_ttou
= set_signal_handler (SIGTTOU
, sigstop_sighandler
);
4626 /* Leave disposition unmodified for non-interactive shells without job
4630 /* Here we handle CONT signals. */
4632 sigcont_sighandler (int sig
)
4634 initialize_job_signals ();
4635 set_signal_handler (SIGCONT
, old_cont
);
4636 kill (getpid (), SIGCONT
);
4641 /* Here we handle stop signals while we are running not as a login shell. */
4643 sigstop_sighandler (int sig
)
4645 set_signal_handler (SIGTSTP
, old_tstp
);
4646 set_signal_handler (SIGTTOU
, old_ttou
);
4647 set_signal_handler (SIGTTIN
, old_ttin
);
4649 old_cont
= set_signal_handler (SIGCONT
, sigcont_sighandler
);
4651 give_terminal_to (shell_pgrp
, 0);
4653 kill (getpid (), sig
);
4658 /* Give the terminal to PGRP. */
4660 give_terminal_to (pid_t pgrp
, int force
)
4666 if (job_control
|| force
)
4669 sigaddset (&set
, SIGTTOU
);
4670 sigaddset (&set
, SIGTTIN
);
4671 sigaddset (&set
, SIGTSTP
);
4672 sigaddset (&set
, SIGCHLD
);
4673 sigemptyset (&oset
);
4674 sigprocmask (SIG_BLOCK
, &set
, &oset
);
4676 if (tcsetpgrp (shell_tty
, pgrp
) < 0)
4678 /* Maybe we should print an error message? */
4680 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
4681 shell_tty
, (long)getpid(), (long)pgrp
);
4687 terminal_pgrp
= pgrp
;
4688 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
4697 /* Give terminal to NPGRP iff it's currently owned by OPGRP. FLAGS are the
4698 flags to pass to give_terminal_to(). */
4700 maybe_give_terminal_to (pid_t opgrp
, pid_t npgrp
, int flags
)
4704 tpgrp
= tcgetpgrp (shell_tty
);
4705 if (tpgrp
< 0 && errno
== ENOTTY
)
4709 terminal_pgrp
= npgrp
;
4712 else if (tpgrp
!= opgrp
)
4714 internal_debug ("%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
);
4718 return (give_terminal_to (npgrp
, flags
));
4721 /* Clear out any jobs in the job array. This is intended to be used by
4722 children of the shell, who should not have any job structures as baggage
4723 when they start executing (forking subshells for parenthesized execution
4724 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
4725 is nonzero, only running jobs are removed from the table. */
4727 delete_all_jobs (int running_only
)
4732 BLOCK_CHILD (set
, oset
);
4734 /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
4737 js
.j_current
= js
.j_previous
= NO_JOB
;
4739 /* XXX could use js.j_firstj here */
4740 for (i
= 0; i
< js
.j_jobslots
; i
++)
4742 if (i
< js
.j_firstj
&& jobs
[i
])
4743 INTERNAL_DEBUG (("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
4744 if (i
> js
.j_lastj
&& jobs
[i
])
4745 INTERNAL_DEBUG (("delete_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
4747 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
4748 /* We don't want to add any of these pids to bgpids. If running_only
4749 is non-zero, we don't want to add running jobs to the list.
4750 If we are interested in all jobs, not just running jobs, and
4751 we are going to clear the bgpids list below (bgp_clear()), we
4752 don't need to bother. */
4753 delete_job (i
, DEL_WARNSTOPPED
|DEL_NOBGPID
);
4755 if (running_only
== 0)
4757 free ((char *)jobs
);
4759 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= js
.j_ndead
= 0;
4760 js
.c_reaped
= js
.c_injobs
= js
.c_living
= 0;
4764 if (running_only
== 0)
4767 UNBLOCK_CHILD (oset
);
4770 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
4771 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
4773 nohup_all_jobs (int running_only
)
4778 BLOCK_CHILD (set
, oset
);
4782 /* XXX could use js.j_firstj here */
4783 for (i
= 0; i
< js
.j_jobslots
; i
++)
4784 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
4788 UNBLOCK_CHILD (oset
);
4792 count_all_jobs (void)
4797 /* This really counts all non-dead jobs. */
4798 BLOCK_CHILD (set
, oset
);
4799 /* XXX could use js.j_firstj here */
4800 for (i
= n
= 0; i
< js
.j_jobslots
; i
++)
4802 if (i
< js
.j_firstj
&& jobs
[i
])
4803 INTERNAL_DEBUG (("count_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
4804 if (i
> js
.j_lastj
&& jobs
[i
])
4805 INTERNAL_DEBUG (("count_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
4807 if (jobs
[i
] && DEADJOB(i
) == 0)
4810 UNBLOCK_CHILD (oset
);
4815 mark_all_jobs_as_dead (void)
4820 if (js
.j_jobslots
== 0)
4823 BLOCK_CHILD (set
, oset
);
4825 /* XXX could use js.j_firstj here */
4826 for (i
= js
.j_ndead
= 0; i
< js
.j_jobslots
; i
++)
4829 jobs
[i
]->state
= JDEAD
;
4833 UNBLOCK_CHILD (oset
);
4836 /* Mark all dead jobs as notified, so delete_job () cleans them out
4837 of the job table properly. POSIX.2 says we need to save the
4838 status of the last CHILD_MAX jobs, so we count the number of dead
4839 jobs and mark only enough as notified to save CHILD_MAX statuses. */
4841 mark_dead_jobs_as_notified (int force
)
4843 register int i
, ndead
, ndeadproc
;
4846 if (js
.j_jobslots
== 0)
4849 BLOCK_CHILD (set
, oset
);
4851 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
4852 around; just run through the array. */
4855 /* XXX could use js.j_firstj here */
4856 for (i
= 0; i
< js
.j_jobslots
; i
++)
4858 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4859 jobs
[i
]->flags
|= J_NOTIFIED
;
4861 UNBLOCK_CHILD (oset
);
4865 /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
4866 array with the corresponding not marked as notified. This is a better
4867 way to avoid pid aliasing and reuse problems than keeping the POSIX-
4868 mandated CHILD_MAX jobs around. delete_job() takes care of keeping the
4869 bgpids list regulated. */
4871 /* Count the number of dead jobs */
4872 /* XXX could use js.j_firstj here */
4873 for (i
= ndead
= ndeadproc
= 0; i
< js
.j_jobslots
; i
++)
4875 if (i
< js
.j_firstj
&& jobs
[i
])
4876 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
4877 if (i
> js
.j_lastj
&& jobs
[i
])
4878 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
4880 if (jobs
[i
] && DEADJOB (i
))
4883 ndeadproc
+= processes_in_job (i
);
4888 if (ndeadproc
!= js
.c_reaped
)
4889 itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc
, js
.c_reaped
);
4891 if (ndead
!= js
.j_ndead
)
4892 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead
, js
.j_ndead
));
4894 if (js
.c_childmax
< 0)
4897 /* Don't do anything if the number of dead processes is less than CHILD_MAX
4898 and we're not forcing a cleanup. */
4899 if (ndeadproc
<= js
.c_childmax
)
4901 UNBLOCK_CHILD (oset
);
4906 itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js
.c_childmax
, ndead
, ndeadproc
);
4909 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
4910 the list. This isn't exactly right yet; changes need to be made
4911 to stop_pipeline so we don't mark the newer jobs after we've
4912 created CHILD_MAX slots in the jobs array. This needs to be
4913 integrated with a way to keep the jobs array from growing without
4914 bound. Maybe we wrap back around to 0 after we reach some max
4915 limit, and there are sufficient job slots free (keep track of total
4916 size of jobs array (js.j_jobslots) and running count of number of jobs
4917 in jobs array. Then keep a job index corresponding to the `oldest job'
4918 and start this loop there, wrapping around as necessary. In effect,
4919 we turn the list into a circular buffer. */
4920 /* XXX could use js.j_firstj here */
4921 for (i
= 0; i
< js
.j_jobslots
; i
++)
4923 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4925 if (i
< js
.j_firstj
&& jobs
[i
])
4926 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
));
4927 if (i
> js
.j_lastj
&& jobs
[i
])
4928 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
));
4930 /* If marking this job as notified would drop us down below
4931 child_max, don't mark it so we can keep at least child_max
4932 statuses. XXX -- need to check what Posix actually says
4933 about keeping statuses. */
4934 if ((ndeadproc
-= processes_in_job (i
)) <= js
.c_childmax
)
4936 jobs
[i
]->flags
|= J_NOTIFIED
;
4940 UNBLOCK_CHILD (oset
);
4943 /* Here to allow other parts of the shell (like the trap stuff) to
4944 freeze and unfreeze the jobs list. */
4946 freeze_jobs_list (void)
4950 o
= jobs_list_frozen
;
4951 jobs_list_frozen
= 1;
4956 unfreeze_jobs_list (void)
4960 o
= jobs_list_frozen
;
4961 jobs_list_frozen
= 0;
4966 set_jobs_list_frozen (int s
)
4968 jobs_list_frozen
= s
;
4972 jobs_list_frozen_status (void)
4974 return jobs_list_frozen
;
4977 /* Allow or disallow job control to take place. Returns the old value
4980 set_job_control (int arg
)
4987 if (terminal_pgrp
== NO_PID
&& shell_tty
>= 0)
4988 terminal_pgrp
= tcgetpgrp (shell_tty
);
4990 /* If we're turning on job control we're going to want to know the shell's
4992 if (job_control
!= old
&& job_control
)
4993 shell_pgrp
= getpgid (0);
4995 running_in_background
= (terminal_pgrp
!= shell_pgrp
);
4998 if (interactive_shell
== 0 && running_in_background
== 0 && job_control
!= old
)
5001 initialize_job_signals ();
5003 default_tty_job_signals ();
5007 /* If we're turning on job control, reset pipeline_pgrp so make_child will
5008 put new child processes into the right pgrp */
5009 if (job_control
!= old
&& job_control
)
5015 /* Turn off all traces of job control. This is run by children of the shell
5016 which are going to do shellsy things, like wait (), etc. */
5018 without_job_control (void)
5020 stop_making_children ();
5022 #if defined (PGRP_PIPE)
5023 sh_closepipe (pgrp_pipe
);
5025 delete_all_jobs (0);
5026 set_job_control (0);
5027 original_pgrp
= NO_PID
;
5030 /* If this shell is interactive, terminate all stopped jobs and
5031 restore the original terminal process group. This is done
5032 before the `exec' builtin calls shell_execve. */
5034 end_job_control (void)
5037 terminate_stopped_jobs ();
5039 if (original_pgrp
>= 0 && terminal_pgrp
!= original_pgrp
)
5040 give_terminal_to (original_pgrp
, 1);
5042 if (original_pgrp
>= 0 && setpgid (0, original_pgrp
) == 0)
5043 shell_pgrp
= original_pgrp
;
5047 job_control_active_p (void)
5049 return (job_control
&& original_pgrp
!= shell_pgrp
&& shell_pgrp
== terminal_pgrp
);
5052 /* Restart job control by closing shell tty and reinitializing. This is
5053 called after an exec fails in an interactive shell and we do not exit. */
5055 restart_job_control (void)
5057 if (shell_tty
!= -1)
5059 initialize_job_control (0);
5062 /* Set the maximum number of background children we keep track of to NCHILD.
5063 If the caller passes NCHILD as 0 or -1, this ends up setting it to
5064 LMAXCHILD, which is initialized the first time through. */
5066 set_maxchild (int nchild
)
5068 static int lmaxchild
= -1;
5070 /* Initialize once. */
5074 lmaxchild
= getmaxchild ();
5075 if (lmaxchild
< 0 && errno
== 0)
5076 lmaxchild
= MAX_CHILD_MAX
; /* assume unlimited */
5079 lmaxchild
= DEFAULT_CHILD_MAX
;
5081 /* Clamp value we set. Minimum is what Posix requires, maximum is defined
5082 above as MAX_CHILD_MAX. */
5083 if (nchild
< lmaxchild
)
5085 else if (nchild
> MAX_CHILD_MAX
)
5086 nchild
= MAX_CHILD_MAX
;
5088 js
.c_childmax
= nchild
;
5091 /* Set the handler to run when the shell receives a SIGCHLD signal. */
5093 set_sigchld_handler (void)
5095 set_signal_handler (SIGCHLD
, sigchld_handler
);
5098 #if defined (PGRP_PIPE)
5099 /* Read from the read end of a pipe. This is how the process group leader
5100 blocks until all of the processes in a pipeline have been made. */
5114 while (read (pp
[0], &ch
, 1) == -1 && errno
== EINTR
)
5119 /* Functional interface closes our local-to-job-control pipes. */
5121 close_pgrp_pipe (void)
5123 sh_closepipe (pgrp_pipe
);
5127 save_pgrp_pipe (int *p
, int clear
)
5129 p
[0] = pgrp_pipe
[0];
5130 p
[1] = pgrp_pipe
[1];
5132 pgrp_pipe
[0] = pgrp_pipe
[1] = -1;
5136 restore_pgrp_pipe (int *p
)
5138 pgrp_pipe
[0] = p
[0];
5139 pgrp_pipe
[1] = p
[1];
5142 #endif /* PGRP_PIPE */