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-2017 Free Software Foundation, Inc.
8 This file is part of GNU Bash, the Bourne Again SHell.
10 Bash is free software: you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
15 Bash is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with Bash. If not, see <http://www.gnu.org/licenses/>.
26 #include "bashtypes.h"
32 #if defined (HAVE_UNISTD_H)
36 #include "posixtime.h"
38 #if defined (HAVE_SYS_RESOURCE_H) && defined (HAVE_WAIT3) && !defined (_POSIX_VERSION) && !defined (RLIMTYPE)
39 # include <sys/resource.h>
40 #endif /* !_POSIX_VERSION && HAVE_SYS_RESOURCE_H && HAVE_WAIT3 && !RLIMTYPE */
42 #if defined (HAVE_SYS_FILE_H)
43 # include <sys/file.h>
47 #include <sys/ioctl.h>
48 #if defined (HAVE_SYS_PARAM_H)
49 #include <sys/param.h>
52 #if defined (BUFFERED_INPUT)
56 /* Need to include this up here for *_TTY_DRIVER definitions. */
59 /* Define this if your output is getting swallowed. It's a no-op on
60 machines with the termio or termios tty drivers. */
61 /* #define DRAIN_OUTPUT */
63 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
64 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
66 #endif /* hpux && !TERMIOS_TTY_DRIVER */
73 #include "execute_cmd.h"
78 #include "builtins/builtext.h"
79 #include "builtins/common.h"
81 #if defined (READLINE)
82 # include <readline/readline.h>
89 #if !defined (HAVE_KILLPG)
90 extern int killpg
__P((pid_t
, int));
93 #if !DEFAULT_CHILD_MAX
94 # define DEFAULT_CHILD_MAX 32
98 # define MAX_CHILD_MAX 32768
102 #define MAX_JOBS_IN_ARRAY 4096 /* production */
104 #define MAX_JOBS_IN_ARRAY 128 /* testing */
108 #define PIDSTAT_TABLE_SZ 4096
109 #define BGPIDS_TABLE_SZ 512
111 /* Flag values for second argument to delete_job */
112 #define DEL_WARNSTOPPED 1 /* warn about deleting stopped jobs */
113 #define DEL_NOBGPID 2 /* don't add pgrp leader to bgpids */
115 /* Take care of system dependencies that must be handled when waiting for
116 children. The arguments to the WAITPID macro match those to the Posix.1
117 waitpid() function. */
119 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
120 # define WAITPID(pid, statusp, options) \
121 wait3 ((union wait *)statusp, options, (struct rusage *)0)
123 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
124 # define WAITPID(pid, statusp, options) \
125 waitpid ((pid_t)pid, statusp, options)
127 # if defined (HAVE_WAIT3)
128 # define WAITPID(pid, statusp, options) \
129 wait3 (statusp, options, (struct rusage *)0)
131 # define WAITPID(pid, statusp, options) \
132 wait3 (statusp, options, (int *)0)
133 # endif /* HAVE_WAIT3 */
134 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
135 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
137 /* getpgrp () varies between systems. Even systems that claim to be
138 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
139 #if defined (GETPGRP_VOID)
140 # define getpgid(p) getpgrp ()
142 # define getpgid(p) getpgrp (p)
143 #endif /* !GETPGRP_VOID */
145 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
146 handler for SIGCHLD. */
147 #if defined (MUST_REINSTALL_SIGHANDLERS)
148 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
150 # define REINSTALL_SIGCHLD_HANDLER
151 #endif /* !MUST_REINSTALL_SIGHANDLERS */
153 /* Some systems let waitpid(2) tell callers about stopped children. */
154 #if !defined (WCONTINUED) || defined (WCONTINUED_BROKEN)
156 # define WCONTINUED 0
158 #if !defined (WIFCONTINUED)
159 # define WIFCONTINUED(s) (0)
162 /* The number of additional slots to allocate when we run out. */
165 typedef int sh_job_map_func_t
__P((JOB
*, int, int, int));
167 /* Variables used here but defined in other files. */
168 extern sigset_t top_level_mask
;
169 extern WORD_LIST
*subst_assign_varlist
;
171 extern SigHandler
**original_signals
;
173 extern void set_original_signal
__P((int, SigHandler
*));
175 static struct jobstats zerojs
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
176 struct jobstats js
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
178 ps_index_t pidstat_table
[PIDSTAT_TABLE_SZ
];
179 struct bgpids bgpids
= { 0, 0, 0 };
181 /* The array of known jobs. */
182 JOB
**jobs
= (JOB
**)NULL
;
185 /* The number of slots currently allocated to JOBS. */
189 /* The controlling tty for this shell. */
192 /* The shell's process group. */
193 pid_t shell_pgrp
= NO_PID
;
195 /* The terminal's process group. */
196 pid_t terminal_pgrp
= NO_PID
;
198 /* The process group of the shell's parent. */
199 pid_t original_pgrp
= NO_PID
;
201 /* The process group of the pipeline currently being made. */
202 pid_t pipeline_pgrp
= (pid_t
)0;
204 #if defined (PGRP_PIPE)
205 /* Pipes which each shell uses to communicate with the process group leader
206 until all of the processes in a pipeline have been started. Then the
207 process leader is allowed to continue. */
208 int pgrp_pipe
[2] = { -1, -1 };
211 /* Last child made by the shell. */
212 volatile pid_t last_made_pid
= NO_PID
;
214 /* Pid of the last asynchronous child. */
215 volatile pid_t last_asynchronous_pid
= NO_PID
;
217 /* The pipeline currently being built. */
218 PROCESS
*the_pipeline
= (PROCESS
*)NULL
;
220 /* If this is non-zero, do job control. */
223 /* Are we running in background? (terminal_pgrp != shell_pgrp) */
224 int running_in_background
= 0;
226 /* Call this when you start making children. */
227 int already_making_children
= 0;
229 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
230 exits from get_tty_state(). */
231 int check_window_size
= CHECKWINSIZE_DEFAULT
;
233 PROCESS
*last_procsub_child
= (PROCESS
*)NULL
;
235 /* Functions local to this file. */
237 void debug_print_pgrps (void);
239 static sighandler wait_sigint_handler
__P((int));
240 static sighandler sigchld_handler
__P((int));
241 static sighandler sigcont_sighandler
__P((int));
242 static sighandler sigstop_sighandler
__P((int));
244 static int waitchld
__P((pid_t
, int));
246 static PROCESS
*find_pipeline
__P((pid_t
, int, int *));
247 static PROCESS
*find_process
__P((pid_t
, int, int *));
249 static char *current_working_directory
__P((void));
250 static char *job_working_directory
__P((void));
251 static char *j_strsignal
__P((int));
252 static char *printable_job_status
__P((int, PROCESS
*, int));
254 static PROCESS
*find_last_proc
__P((int, int));
255 static pid_t find_last_pid
__P((int, int));
257 static int set_new_line_discipline
__P((int));
258 static int map_over_jobs
__P((sh_job_map_func_t
*, int, int));
259 static int job_last_stopped
__P((int));
260 static int job_last_running
__P((int));
261 static int most_recent_job_in_state
__P((int, JOB_STATE
));
262 static int find_job
__P((pid_t
, int, PROCESS
**));
263 static int print_job
__P((JOB
*, int, int, int));
264 static int process_exit_status
__P((WAIT
));
265 static int process_exit_signal
__P((WAIT
));
266 static int set_job_status_and_cleanup
__P((int));
268 static WAIT job_signal_status
__P((int));
269 static WAIT raw_job_exit_status
__P((int));
271 static void notify_of_job_status
__P((void));
272 static void reset_job_indices
__P((void));
273 static void cleanup_dead_jobs
__P((void));
274 static int processes_in_job
__P((int));
275 static void realloc_jobs_list
__P((void));
276 static int compact_jobs_list
__P((int));
277 static void add_process
__P((char *, pid_t
));
278 static void print_pipeline
__P((PROCESS
*, int, int, FILE *));
279 static void pretty_print_job
__P((int, int, FILE *));
280 static void set_current_job
__P((int));
281 static void reset_current
__P((void));
282 static void set_job_running
__P((int));
283 static void setjstatus
__P((int));
284 static int maybe_give_terminal_to
__P((pid_t
, pid_t
, int));
285 static void mark_all_jobs_as_dead
__P((void));
286 static void mark_dead_jobs_as_notified
__P((int));
287 static void restore_sigint_handler
__P((void));
288 #if defined (PGRP_PIPE)
289 static void pipe_read
__P((int *));
292 /* Hash table manipulation */
294 static ps_index_t
*pshash_getbucket
__P((pid_t
));
295 static void pshash_delindex
__P((ps_index_t
));
297 /* Saved background process status management */
298 static struct pidstat
*bgp_add
__P((pid_t
, int));
299 static int bgp_delete
__P((pid_t
));
300 static void bgp_clear
__P((void));
301 static int bgp_search
__P((pid_t
));
303 static struct pipeline_saver
*alloc_pipeline_saver
__P((void));
305 static ps_index_t bgp_getindex
__P((void));
306 static void bgp_resize
__P((void)); /* XXX */
308 #if defined (ARRAY_VARS)
309 static int *pstatuses
; /* list of pipeline statuses */
313 /* Used to synchronize between wait_for and other functions and the SIGCHLD
316 static int queue_sigchld
;
318 #define QUEUE_SIGCHLD(os) (os) = sigchld, queue_sigchld++
320 #define UNQUEUE_SIGCHLD(os) \
323 if (queue_sigchld == 0 && os != sigchld) \
327 static SigHandler
*old_tstp
, *old_ttou
, *old_ttin
;
328 static SigHandler
*old_cont
= (SigHandler
*)SIG_DFL
;
330 /* A place to temporarily save the current pipeline. */
331 static struct pipeline_saver
*saved_pipeline
;
332 static int saved_already_making_children
;
334 /* Set this to non-zero whenever you don't want the jobs list to change at
335 all: no jobs deleted and no status change notifications. This is used,
336 for example, when executing SIGCHLD traps, which may run arbitrary
338 static int jobs_list_frozen
;
340 static char retcode_name_buffer
[64];
342 #if !defined (_POSIX_VERSION)
344 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
345 library functions and system calls. */
346 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
347 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
355 /* ioctl will handle setting errno correctly. */
356 if (ioctl (fd
, TIOCGPGRP
, &pgrp
) < 0)
361 #endif /* !_POSIX_VERSION */
363 /* Initialize the global job stats structure and other bookkeeping variables */
370 /* Return the working directory for the current process. Unlike
371 job_working_directory, this does not call malloc (), nor do any
372 of the functions it calls. This is so that it can safely be called
373 from a signal handler. */
375 current_working_directory ()
378 static char d
[PATH_MAX
];
380 dir
= get_string_value ("PWD");
382 if (dir
== 0 && the_current_working_directory
&& no_symbolic_links
)
383 dir
= the_current_working_directory
;
387 dir
= getcwd (d
, sizeof(d
));
392 return (dir
== 0) ? "<unknown>" : dir
;
395 /* Return the working directory for the current process. */
397 job_working_directory ()
401 dir
= get_string_value ("PWD");
403 return (savestring (dir
));
405 dir
= get_working_directory ("job-working-directory");
409 return (savestring ("<unknown>"));
415 if (already_making_children
)
418 already_making_children
= 1;
423 stop_making_children ()
425 already_making_children
= 0;
429 cleanup_the_pipeline ()
434 BLOCK_CHILD (set
, oset
);
435 disposer
= the_pipeline
;
436 the_pipeline
= (PROCESS
*)NULL
;
437 UNBLOCK_CHILD (oset
);
440 discard_pipeline (disposer
);
444 discard_last_procsub_child ()
449 BLOCK_CHILD (set
, oset
);
450 disposer
= last_procsub_child
;
451 last_procsub_child
= (PROCESS
*)NULL
;
452 UNBLOCK_CHILD (oset
);
455 discard_pipeline (disposer
);
458 static struct pipeline_saver
*
459 alloc_pipeline_saver ()
461 struct pipeline_saver
*ret
;
463 ret
= (struct pipeline_saver
*)xmalloc (sizeof (struct pipeline_saver
));
470 save_pipeline (clear
)
474 struct pipeline_saver
*saver
;
476 BLOCK_CHILD (set
, oset
);
477 saver
= alloc_pipeline_saver ();
478 saver
->pipeline
= the_pipeline
;
479 saver
->next
= saved_pipeline
;
480 saved_pipeline
= saver
;
482 the_pipeline
= (PROCESS
*)NULL
;
483 saved_already_making_children
= already_making_children
;
484 UNBLOCK_CHILD (oset
);
488 restore_pipeline (discard
)
491 PROCESS
*old_pipeline
;
493 struct pipeline_saver
*saver
;
495 BLOCK_CHILD (set
, oset
);
496 old_pipeline
= the_pipeline
;
497 the_pipeline
= saved_pipeline
->pipeline
;
498 saver
= saved_pipeline
;
499 saved_pipeline
= saved_pipeline
->next
;
501 already_making_children
= saved_already_making_children
;
502 UNBLOCK_CHILD (oset
);
504 if (discard
&& old_pipeline
)
506 discard_pipeline (old_pipeline
);
507 return ((PROCESS
*)NULL
);
512 /* Start building a pipeline. */
518 cleanup_the_pipeline ();
520 #if defined (PGRP_PIPE)
521 sh_closepipe (pgrp_pipe
);
525 #if defined (PGRP_PIPE)
528 if (pipe (pgrp_pipe
) == -1)
529 sys_error (_("start_pipeline: pgrp pipe"));
534 /* Stop building a pipeline. Install the process list in the job array.
535 This returns the index of the newly installed job.
536 DEFERRED is a command structure to be executed upon satisfactory
537 execution exit of this pipeline. */
539 stop_pipeline (async
, deferred
)
547 BLOCK_CHILD (set
, oset
);
549 #if defined (PGRP_PIPE)
550 /* The parent closes the process group synchronization pipe. */
551 sh_closepipe (pgrp_pipe
);
554 cleanup_dead_jobs ();
556 if (js
.j_jobslots
== 0)
558 js
.j_jobslots
= JOB_SLOTS
;
559 jobs
= (JOB
**)xmalloc (js
.j_jobslots
* sizeof (JOB
*));
561 /* Now blank out these new entries. */
562 for (i
= 0; i
< js
.j_jobslots
; i
++)
563 jobs
[i
] = (JOB
*)NULL
;
565 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
568 /* Scan from the last slot backward, looking for the next free one. */
569 /* XXX - revisit this interactive assumption */
570 /* XXX - this way for now */
573 for (i
= js
.j_jobslots
; i
; i
--)
580 /* This wraps around, but makes it inconvenient to extend the array */
581 for (i
= js
.j_lastj
+1; i
!= js
.j_lastj
; i
++)
583 if (i
>= js
.j_jobslots
)
591 /* This doesn't wrap around yet. */
592 for (i
= js
.j_lastj
? js
.j_lastj
+ 1 : js
.j_lastj
; i
< js
.j_jobslots
; i
++)
598 /* Do we need more room? */
600 /* First try compaction */
601 if ((interactive_shell
== 0 || subshell_environment
) && i
== js
.j_jobslots
&& js
.j_jobslots
>= MAX_JOBS_IN_ARRAY
)
602 i
= compact_jobs_list (0);
604 /* If we can't compact, reallocate */
605 if (i
== js
.j_jobslots
)
607 js
.j_jobslots
+= JOB_SLOTS
;
608 jobs
= (JOB
**)xrealloc (jobs
, (js
.j_jobslots
* sizeof (JOB
*)));
610 for (j
= i
; j
< js
.j_jobslots
; j
++)
611 jobs
[j
] = (JOB
*)NULL
;
614 /* Add the current pipeline to the job list. */
618 int any_running
, any_stopped
, n
;
620 newjob
= (JOB
*)xmalloc (sizeof (JOB
));
622 for (n
= 1, p
= the_pipeline
; p
->next
!= the_pipeline
; n
++, p
= p
->next
)
624 p
->next
= (PROCESS
*)NULL
;
625 newjob
->pipe
= REVERSE_LIST (the_pipeline
, PROCESS
*);
626 for (p
= newjob
->pipe
; p
->next
; p
= p
->next
)
628 p
->next
= newjob
->pipe
;
630 the_pipeline
= (PROCESS
*)NULL
;
631 newjob
->pgrp
= pipeline_pgrp
;
636 newjob
->flags
|= J_PIPEFAIL
;
638 /* Flag to see if in another pgrp. */
640 newjob
->flags
|= J_JOBCONTROL
;
642 /* Set the state of this pipeline. */
644 any_running
= any_stopped
= 0;
647 any_running
|= PRUNNING (p
);
648 any_stopped
|= PSTOPPED (p
);
651 while (p
!= newjob
->pipe
);
653 newjob
->state
= any_running
? JRUNNING
: (any_stopped
? JSTOPPED
: JDEAD
);
654 newjob
->wd
= job_working_directory ();
655 newjob
->deferred
= deferred
;
657 newjob
->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
658 newjob
->cleanarg
= (PTR_T
) NULL
;
661 if (newjob
->state
== JDEAD
&& (newjob
->flags
& J_FOREGROUND
))
663 if (newjob
->state
== JDEAD
)
665 js
.c_reaped
+= n
; /* wouldn't have been done since this was not part of a job */
674 newjob
= (JOB
*)NULL
;
677 js
.j_lastmade
= newjob
;
683 newjob
->flags
&= ~J_FOREGROUND
;
684 newjob
->flags
|= J_ASYNC
;
685 js
.j_lastasync
= newjob
;
693 newjob
->flags
|= J_FOREGROUND
;
695 * !!!!! NOTE !!!!! (chet@po.cwru.edu)
697 * The currently-accepted job control wisdom says to set the
698 * terminal's process group n+1 times in an n-step pipeline:
699 * once in the parent and once in each child. This is where
700 * the parent gives it away.
702 * Don't give the terminal away if this shell is an asynchronous
703 * subshell or if we're a (presumably non-interactive) shell running
707 if (job_control
&& newjob
->pgrp
&& (subshell_environment
&SUBSHELL_ASYNC
) == 0 && running_in_background
== 0)
708 maybe_give_terminal_to (shell_pgrp
, newjob
->pgrp
, 0);
712 stop_making_children ();
713 UNBLOCK_CHILD (oset
);
714 return (newjob
? i
: js
.j_current
);
717 /* Functions to manage the list of exited background pids whose status has
722 The current implementation is a hash table using a single (separate) arena
723 for storage that can be allocated and freed as a unit. The size of the hash
724 table is a multiple of PIDSTAT_TABLE_SZ (4096) and multiple PIDs that hash
725 to the same value are chained through the bucket_next and bucket_prev
726 pointers (basically coalesced hashing for collision resolution).
730 All pid/status storage is done using the circular buffer bgpids.storage.
731 This must contain at least js.c_childmax entries. The circular buffer is
732 used to supply the ordered list Posix requires ("the last CHILD_MAX
733 processes"). To avoid searching the entire storage table for a given PID,
734 the hash table (pidstat_table) holds pointers into the storage arena and
735 uses a doubly-linked list of cells (bucket_next/bucket_prev, also pointers
736 into the arena) to implement collision resolution. */
738 /* The number of elements in bgpids.storage always has to be > js.c_childmax for
739 the circular buffer to work right. */
743 ps_index_t nsize
, nsize_cur
, nsize_max
;
746 if (bgpids
.nalloc
== 0)
748 /* invalidate hash table when bgpids table is reallocated */
749 for (psi
= 0; psi
< PIDSTAT_TABLE_SZ
; psi
++)
750 pidstat_table
[psi
] = NO_PIDSTAT
;
751 nsize
= BGPIDS_TABLE_SZ
; /* should be power of 2 */
755 nsize
= bgpids
.nalloc
;
757 nsize_max
= TYPE_MAXIMUM (ps_index_t
);
758 nsize_cur
= (ps_index_t
)js
.c_childmax
;
759 if (nsize_cur
< 0) /* overflow */
760 nsize_cur
= MAX_CHILD_MAX
;
762 while (nsize
> 0 && nsize
< nsize_cur
) /* > 0 should catch overflow */
764 if (nsize
> nsize_max
|| nsize
<= 0) /* overflow? */
766 if (nsize
> MAX_CHILD_MAX
)
767 nsize
= nsize_max
= MAX_CHILD_MAX
; /* hard cap */
769 if (bgpids
.nalloc
< nsize_cur
&& bgpids
.nalloc
< nsize_max
)
771 bgpids
.storage
= (struct pidstat
*)xrealloc (bgpids
.storage
, nsize
* sizeof (struct pidstat
));
773 for (psi
= bgpids
.nalloc
; psi
< nsize
; psi
++)
774 bgpids
.storage
[psi
].pid
= NO_PID
;
776 bgpids
.nalloc
= nsize
;
779 else if (bgpids
.head
>= bgpids
.nalloc
) /* wrap around */
786 if (bgpids
.nalloc
< (ps_index_t
)js
.c_childmax
|| bgpids
.head
>= bgpids
.nalloc
)
789 pshash_delindex (bgpids
.head
); /* XXX - clear before reusing */
790 return bgpids
.head
++;
794 pshash_getbucket (pid
)
797 unsigned long hash
; /* XXX - u_bits32_t */
799 hash
= pid
* 0x9e370001UL
;
800 return (&pidstat_table
[hash
% PIDSTAT_TABLE_SZ
]);
803 static struct pidstat
*
804 bgp_add (pid
, status
)
808 ps_index_t
*bucket
, psi
;
811 /* bucket == existing chain of pids hashing to same value
812 psi = where were going to put this pid/status */
814 bucket
= pshash_getbucket (pid
); /* index into pidstat_table */
815 psi
= bgp_getindex (); /* bgpids.head, index into storage */
817 /* XXX - what if psi == *bucket? */
821 internal_warning ("hashed pid %d (pid %d) collides with bgpids.head, skipping", psi
, pid
);
823 bgpids
.storage
[psi
].pid
= NO_PID
; /* make sure */
824 psi
= bgp_getindex (); /* skip to next one */
827 ps
= &bgpids
.storage
[psi
];
831 ps
->bucket_next
= *bucket
;
832 ps
->bucket_prev
= NO_PIDSTAT
;
837 if (bgpids
.npid
> js
.c_childmax
)
841 if (ps
->bucket_next
!= NO_PIDSTAT
)
842 bgpids
.storage
[ps
->bucket_next
].bucket_prev
= psi
;
844 *bucket
= psi
; /* set chain head in hash table */
850 pshash_delindex (psi
)
856 ps
= &bgpids
.storage
[psi
];
857 if (ps
->pid
== NO_PID
)
860 if (ps
->bucket_next
!= NO_PIDSTAT
)
861 bgpids
.storage
[ps
->bucket_next
].bucket_prev
= ps
->bucket_prev
;
862 if (ps
->bucket_prev
!= NO_PIDSTAT
)
863 bgpids
.storage
[ps
->bucket_prev
].bucket_next
= ps
->bucket_next
;
866 bucket
= pshash_getbucket (ps
->pid
);
867 *bucket
= ps
->bucket_next
; /* deleting chain head in hash table */
870 /* clear out this cell, in case it gets reused. */
872 ps
->bucket_next
= ps
->bucket_prev
= NO_PIDSTAT
;
879 ps_index_t psi
, orig_psi
;
881 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0 || bgpids
.npid
== 0)
884 /* Search chain using hash to find bucket in pidstat_table */
885 for (orig_psi
= psi
= *(pshash_getbucket (pid
)); psi
!= NO_PIDSTAT
; psi
= bgpids
.storage
[psi
].bucket_next
)
887 if (bgpids
.storage
[psi
].pid
== pid
)
889 if (orig_psi
== bgpids
.storage
[psi
].bucket_next
) /* catch reported bug */
891 internal_warning ("bgp_delete: LOOP: psi (%d) == storage[psi].bucket_next", psi
);
896 if (psi
== NO_PIDSTAT
)
897 return 0; /* not found */
900 itrace("bgp_delete: deleting %d", pid
);
903 pshash_delindex (psi
); /* hash table management */
909 /* Clear out the list of saved statuses */
913 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0)
916 free (bgpids
.storage
);
925 /* Search for PID in the list of saved background pids; return its status if
926 found. If not found, return -1. We hash to the right spot in pidstat_table
927 and follow the bucket chain to the end. */
932 ps_index_t psi
, orig_psi
;
934 if (bgpids
.storage
== 0 || bgpids
.nalloc
== 0 || bgpids
.npid
== 0)
937 /* Search chain using hash to find bucket in pidstat_table */
938 for (orig_psi
= psi
= *(pshash_getbucket (pid
)); psi
!= NO_PIDSTAT
; psi
= bgpids
.storage
[psi
].bucket_next
)
940 if (bgpids
.storage
[psi
].pid
== pid
)
941 return (bgpids
.storage
[psi
].status
);
942 if (orig_psi
== bgpids
.storage
[psi
].bucket_next
) /* catch reported bug */
944 internal_warning ("bgp_search: LOOP: psi (%d) == storage[psi].bucket_next", psi
);
960 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
961 been deleted. The caller should check whether js.j_njobs is 0 before
962 calling this. This wraps around, but the rest of the code does not. At
963 this point, it should not matter. */
969 if (jobs
[js
.j_firstj
] == 0)
972 if (old
>= js
.j_jobslots
)
973 old
= js
.j_jobslots
- 1;
974 while (js
.j_firstj
!= old
)
976 if (js
.j_firstj
>= js
.j_jobslots
)
978 if (jobs
[js
.j_firstj
] || js
.j_firstj
== old
) /* needed if old == 0 */
982 if (js
.j_firstj
== old
)
983 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
985 if (jobs
[js
.j_lastj
] == 0)
990 while (js
.j_lastj
!= old
)
993 js
.j_lastj
= js
.j_jobslots
- 1;
994 if (jobs
[js
.j_lastj
] || js
.j_lastj
== old
) /* needed if old == js.j_jobslots */
998 if (js
.j_lastj
== old
)
999 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
1003 /* Delete all DEAD jobs that the user had received notification about. */
1005 cleanup_dead_jobs ()
1011 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1016 /* XXX could use js.j_firstj and js.j_lastj here */
1017 for (i
= 0; i
< js
.j_jobslots
; i
++)
1020 if (i
< js
.j_firstj
&& jobs
[i
])
1021 itrace("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1022 if (i
> js
.j_lastj
&& jobs
[i
])
1023 itrace("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1026 if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
))
1030 #if defined (PROCESS_SUBSTITUTION)
1031 if (last_procsub_child
&& last_procsub_child
->running
== PS_DONE
)
1033 bgp_add (last_procsub_child
->pid
, process_exit_status (last_procsub_child
->status
)); /* XXX */
1034 discard
= last_procsub_child
;
1035 last_procsub_child
= (PROCESS
*)NULL
;
1036 discard_pipeline (discard
);
1040 #if defined (COPROCESS_SUPPORT)
1044 UNQUEUE_SIGCHLD(os
);
1048 processes_in_job (job
)
1052 register PROCESS
*p
;
1055 p
= jobs
[job
]->pipe
;
1061 while (p
!= jobs
[job
]->pipe
);
1067 delete_old_job (pid
)
1073 job
= find_job (pid
, 0, &p
);
1077 itrace ("delete_old_job: found pid %d in job %d with state %d", pid
, job
, jobs
[job
]->state
);
1079 if (JOBSTATE (job
) == JDEAD
)
1080 delete_job (job
, DEL_NOBGPID
);
1084 internal_warning (_("forked pid %d appears in running job %d"), pid
, job
+1);
1092 /* Reallocate and compress the jobs list. This returns with a jobs array
1093 whose size is a multiple of JOB_SLOTS and can hold the current number of
1094 jobs. Heuristics are used to minimize the number of new reallocs. */
1096 realloc_jobs_list ()
1099 int nsize
, i
, j
, ncur
, nprev
;
1102 ncur
= nprev
= NO_JOB
;
1103 nsize
= ((js
.j_njobs
+ JOB_SLOTS
- 1) / JOB_SLOTS
);
1105 i
= js
.j_njobs
% JOB_SLOTS
;
1106 if (i
== 0 || i
> (JOB_SLOTS
>> 1))
1109 BLOCK_CHILD (set
, oset
);
1110 nlist
= (js
.j_jobslots
== nsize
) ? jobs
: (JOB
**) xmalloc (nsize
* sizeof (JOB
*));
1112 js
.c_reaped
= js
.j_ndead
= 0;
1113 for (i
= j
= 0; i
< js
.j_jobslots
; i
++)
1116 if (i
== js
.j_current
)
1118 if (i
== js
.j_previous
)
1120 nlist
[j
++] = jobs
[i
];
1121 if (jobs
[i
]->state
== JDEAD
)
1124 js
.c_reaped
+= processes_in_job (i
);
1129 itrace ("realloc_jobs_list: resize jobs list from %d to %d", js
.j_jobslots
, nsize
);
1130 itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js
.j_lastj
, (j
> 0) ? j
- 1 : 0);
1131 itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js
.j_njobs
, j
);
1132 itrace ("realloc_jobs_list: js.j_ndead %d js.c_reaped %d", js
.j_ndead
, js
.c_reaped
);
1136 js
.j_lastj
= (j
> 0) ? j
- 1 : 0;
1138 js
.j_jobslots
= nsize
;
1140 /* Zero out remaining slots in new jobs list */
1141 for ( ; j
< nsize
; j
++)
1142 nlist
[j
] = (JOB
*)NULL
;
1151 js
.j_current
= ncur
;
1152 if (nprev
!= NO_JOB
)
1153 js
.j_previous
= nprev
;
1155 /* Need to reset these */
1156 if (js
.j_current
== NO_JOB
|| js
.j_previous
== NO_JOB
|| js
.j_current
> js
.j_lastj
|| js
.j_previous
> js
.j_lastj
)
1160 itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js
.j_current
, js
.j_previous
);
1163 UNBLOCK_CHILD (oset
);
1166 /* Compact the jobs list by removing dead jobs. Assume that we have filled
1167 the jobs array to some predefined maximum. Called when the shell is not
1168 the foreground process (subshell_environment != 0). Returns the first
1169 available slot in the compacted list. If that value is js.j_jobslots, then
1170 the list needs to be reallocated. The jobs array may be in new memory if
1171 this returns > 0 and < js.j_jobslots. FLAGS is reserved for future use. */
1173 compact_jobs_list (flags
)
1176 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1177 return js
.j_jobslots
;
1180 realloc_jobs_list ();
1183 itrace("compact_jobs_list: returning %d", (js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
1186 return ((js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
1189 /* Delete the job at INDEX from the job list. Must be called
1190 with SIGCHLD blocked. */
1192 delete_job (job_index
, dflags
)
1193 int job_index
, dflags
;
1199 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1202 if ((dflags
& DEL_WARNSTOPPED
) && subshell_environment
== 0 && STOPPED (job_index
))
1203 internal_warning (_("deleting stopped job %d with process group %ld"), job_index
+1, (long)jobs
[job_index
]->pgrp
);
1204 temp
= jobs
[job_index
];
1208 if ((dflags
& DEL_NOBGPID
) == 0 && (temp
->flags
& (J_ASYNC
|J_FOREGROUND
)) == J_ASYNC
)
1210 proc
= find_last_proc (job_index
, 0);
1212 bgp_add (proc
->pid
, process_exit_status (proc
->status
));
1215 jobs
[job_index
] = (JOB
*)NULL
;
1216 if (temp
== js
.j_lastmade
)
1218 else if (temp
== js
.j_lastasync
)
1222 ndel
= discard_pipeline (temp
->pipe
);
1224 js
.c_injobs
-= ndel
;
1225 if (temp
->state
== JDEAD
)
1227 js
.c_reaped
-= ndel
;
1229 if (js
.c_reaped
< 0)
1232 itrace("delete_job (%d pgrp %d): js.c_reaped (%d) < 0 ndel = %d js.j_ndead = %d", job_index
, temp
->pgrp
, js
.c_reaped
, ndel
, js
.j_ndead
);
1239 dispose_command (temp
->deferred
);
1244 if (js
.j_njobs
== 0)
1245 js
.j_firstj
= js
.j_lastj
= 0;
1246 else if (jobs
[js
.j_firstj
] == 0 || jobs
[js
.j_lastj
] == 0)
1247 reset_job_indices ();
1249 if (job_index
== js
.j_current
|| job_index
== js
.j_previous
)
1253 /* Must be called with SIGCHLD blocked. */
1255 nohup_job (job_index
)
1260 if (js
.j_jobslots
== 0)
1263 if (temp
= jobs
[job_index
])
1264 temp
->flags
|= J_NOHUP
;
1267 /* Get rid of the data structure associated with a process chain. */
1269 discard_pipeline (chain
)
1270 register PROCESS
*chain
;
1272 register PROCESS
*this, *next
;
1280 FREE (this->command
);
1285 while (this != chain
);
1290 /* Add this process to the chain being built in the_pipeline.
1291 NAME is the command string that will be exec'ed later.
1292 PID is the process id of the child. */
1294 add_process (name
, pid
)
1300 #if defined (RECYCLES_PIDS)
1302 p
= find_process (pid
, 0, &j
);
1307 internal_warning (_("add_process: process %5ld (%s) in the_pipeline"), (long)p
->pid
, p
->command
);
1310 internal_warning (_("add_process: pid %5ld (%s) marked as still alive"), (long)p
->pid
, p
->command
);
1311 p
->running
= PS_RECYCLED
; /* mark as recycled */
1315 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1316 t
->next
= the_pipeline
;
1318 WSTATUS (t
->status
) = 0;
1319 t
->running
= PS_RUNNING
;
1328 while (p
->next
!= t
->next
)
1334 /* Create a (dummy) PROCESS with NAME, PID, and STATUS, and make it the last
1335 process in jobs[JID]->pipe. Used by the lastpipe code. */
1337 append_process (name
, pid
, status
, jid
)
1345 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1346 t
->next
= (PROCESS
*)NULL
;
1348 /* set process exit status using offset discovered by configure */
1349 t
->status
= (status
& 0xff) << WEXITSTATUS_OFFSET
;
1350 t
->running
= PS_DONE
;
1353 js
.c_reaped
++; /* XXX */
1355 for (p
= jobs
[jid
]->pipe
; p
->next
!= jobs
[jid
]->pipe
; p
= p
->next
)
1358 t
->next
= jobs
[jid
]->pipe
;
1362 /* Take the last job and make it the first job. Must be called with
1365 rotate_the_pipeline ()
1369 if (the_pipeline
->next
== the_pipeline
)
1371 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1376 /* Reverse the order of the processes in the_pipeline. Must be called with
1379 reverse_the_pipeline ()
1383 if (the_pipeline
->next
== the_pipeline
)
1386 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1388 p
->next
= (PROCESS
*)NULL
;
1390 n
= REVERSE_LIST (the_pipeline
, PROCESS
*);
1393 for (p
= the_pipeline
; p
->next
; p
= p
->next
)
1395 p
->next
= the_pipeline
;
1399 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
1400 then it is time to stop mapping, and that is the return value
1401 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
1404 map_over_jobs (func
, arg1
, arg2
)
1405 sh_job_map_func_t
*func
;
1412 if (js
.j_jobslots
== 0)
1415 BLOCK_CHILD (set
, oset
);
1417 /* XXX could use js.j_firstj here */
1418 for (i
= result
= 0; i
< js
.j_jobslots
; i
++)
1421 if (i
< js
.j_firstj
&& jobs
[i
])
1422 itrace("map_over_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1423 if (i
> js
.j_lastj
&& jobs
[i
])
1424 itrace("map_over_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1428 result
= (*func
)(jobs
[i
], arg1
, arg2
, i
);
1434 UNBLOCK_CHILD (oset
);
1439 /* Cause all the jobs in the current pipeline to exit. */
1441 terminate_current_pipeline ()
1443 if (pipeline_pgrp
&& pipeline_pgrp
!= shell_pgrp
)
1445 killpg (pipeline_pgrp
, SIGTERM
);
1446 killpg (pipeline_pgrp
, SIGCONT
);
1450 /* Cause all stopped jobs to exit. */
1452 terminate_stopped_jobs ()
1456 /* XXX could use js.j_firstj here */
1457 for (i
= 0; i
< js
.j_jobslots
; i
++)
1459 if (jobs
[i
] && STOPPED (i
))
1461 killpg (jobs
[i
]->pgrp
, SIGTERM
);
1462 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1467 /* Cause all jobs, running or stopped, to receive a hangup signal. If
1468 a job is marked J_NOHUP, don't send the SIGHUP. */
1474 /* XXX could use js.j_firstj here */
1475 for (i
= 0; i
< js
.j_jobslots
; i
++)
1479 if (jobs
[i
]->flags
& J_NOHUP
)
1481 killpg (jobs
[i
]->pgrp
, SIGHUP
);
1483 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1489 kill_current_pipeline ()
1491 stop_making_children ();
1495 /* Return the pipeline that PID belongs to. Note that the pipeline
1496 doesn't have to belong to a job. Must be called with SIGCHLD blocked.
1497 If JOBP is non-null, return the index of the job containing PID. */
1499 find_pipeline (pid
, alive_only
, jobp
)
1502 int *jobp
; /* index into jobs list or NO_JOB */
1507 /* See if this process is in the pipeline that we are building. */
1515 /* Return it if we found it. Don't ever return a recycled pid. */
1516 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1521 while (p
!= the_pipeline
);
1523 /* Now look in the last process substitution pipeline, since that sets $! */
1524 if (last_procsub_child
)
1526 p
= last_procsub_child
;
1529 /* Return it if we found it. Don't ever return a recycled pid. */
1530 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1535 while (p
!= last_procsub_child
);
1538 job
= find_job (pid
, alive_only
, &p
);
1541 return (job
== NO_JOB
) ? (PROCESS
*)NULL
: jobs
[job
]->pipe
;
1544 /* Return the PROCESS * describing PID. If JOBP is non-null return the index
1545 into the jobs array of the job containing PID. Must be called with
1548 find_process (pid
, alive_only
, jobp
)
1551 int *jobp
; /* index into jobs list or NO_JOB */
1555 p
= find_pipeline (pid
, alive_only
, jobp
);
1556 while (p
&& p
->pid
!= pid
)
1561 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1562 belong to any job. Must be called with SIGCHLD blocked. */
1564 find_job (pid
, alive_only
, procp
)
1572 /* XXX could use js.j_firstj here, and should check js.j_lastj */
1573 for (i
= 0; i
< js
.j_jobslots
; i
++)
1576 if (i
< js
.j_firstj
&& jobs
[i
])
1577 itrace("find_job: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1578 if (i
> js
.j_lastj
&& jobs
[i
])
1579 itrace("find_job: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1587 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1596 while (p
!= jobs
[i
]->pipe
);
1603 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
1604 required by find_job. */
1606 get_job_by_pid (pid
, block
)
1614 BLOCK_CHILD (set
, oset
);
1616 job
= find_job (pid
, 0, NULL
);
1619 UNBLOCK_CHILD (oset
);
1624 /* Print descriptive information about the job with leader pid PID. */
1632 BLOCK_CHILD (set
, oset
);
1634 job
= find_job (pid
, 0, NULL
);
1637 fprintf (stderr
, "[%d] %ld\n", job
+ 1, (long)pid
);
1639 programming_error (_("describe_pid: %ld: no such pid"), (long)pid
);
1641 UNBLOCK_CHILD (oset
);
1653 x
= retcode_name_buffer
;
1654 snprintf (x
, sizeof(retcode_name_buffer
), _("Signal %d"), s
);
1660 printable_job_status (j
, p
, format
)
1670 if (STOPPED (j
) && format
== 0)
1672 if (posixly_correct
== 0 || p
== 0 || (WIFSTOPPED (p
->status
) == 0))
1673 temp
= _("Stopped");
1676 temp
= retcode_name_buffer
;
1677 snprintf (temp
, sizeof(retcode_name_buffer
), _("Stopped(%s)"), signal_name (WSTOPSIG (p
->status
)));
1680 else if (RUNNING (j
))
1681 temp
= _("Running");
1684 if (WIFSTOPPED (p
->status
))
1685 temp
= j_strsignal (WSTOPSIG (p
->status
));
1686 else if (WIFSIGNALED (p
->status
))
1687 temp
= j_strsignal (WTERMSIG (p
->status
));
1688 else if (WIFEXITED (p
->status
))
1690 temp
= retcode_name_buffer
;
1691 es
= WEXITSTATUS (p
->status
);
1694 strncpy (temp
, _("Done"), sizeof (retcode_name_buffer
) - 1);
1695 temp
[sizeof (retcode_name_buffer
) - 1] = '\0';
1697 else if (posixly_correct
)
1698 snprintf (temp
, sizeof(retcode_name_buffer
), _("Done(%d)"), es
);
1700 snprintf (temp
, sizeof(retcode_name_buffer
), _("Exit %d"), es
);
1703 temp
= _("Unknown status");
1709 /* This is the way to print out information on a job if you
1710 know the index. FORMAT is:
1712 JLIST_NORMAL) [1]+ Running emacs
1713 JLIST_LONG ) [1]+ 2378 Running emacs
1714 -1 ) [1]+ 2378 emacs
1716 JLIST_NORMAL) [1]+ Stopped ls | more
1717 JLIST_LONG ) [1]+ 2369 Stopped ls
1720 Just list the pid of the process group leader (really
1723 Use format JLIST_NORMAL, but list only jobs about which
1724 the user has not been notified. */
1726 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1727 the JOBS array corresponding to this pipeline. FORMAT is as described
1728 above. Must be called with SIGCHLD blocked.
1730 If you're printing a pipeline that's not in the jobs array, like the
1731 current pipeline as it's being created, pass -1 for JOB_INDEX */
1733 print_pipeline (p
, job_index
, format
, stream
)
1735 int job_index
, format
;
1738 PROCESS
*first
, *last
, *show
;
1739 int es
, name_padding
;
1746 while (last
->next
!= first
)
1752 fprintf (stream
, format
? " " : " |");
1754 if (format
!= JLIST_STANDARD
)
1755 fprintf (stream
, "%5ld", (long)p
->pid
);
1757 fprintf (stream
, " ");
1759 if (format
> -1 && job_index
>= 0)
1761 show
= format
? p
: last
;
1762 temp
= printable_job_status (job_index
, show
, format
);
1768 if (show
->running
== first
->running
&&
1769 WSTATUS (show
->status
) == WSTATUS (first
->status
))
1773 temp
= (char *)NULL
;
1778 fprintf (stream
, "%s", temp
);
1782 es
= 2; /* strlen ("| ") */
1783 name_padding
= LONGEST_SIGNAL_DESC
- es
;
1785 fprintf (stream
, "%*s", name_padding
, "");
1787 if ((WIFSTOPPED (show
->status
) == 0) &&
1788 (WIFCONTINUED (show
->status
) == 0) &&
1789 WIFCORED (show
->status
))
1790 fprintf (stream
, _("(core dumped) "));
1794 if (p
!= first
&& format
)
1795 fprintf (stream
, "| ");
1798 fprintf (stream
, "%s", p
->command
);
1800 if (p
== last
&& job_index
>= 0)
1802 temp
= current_working_directory ();
1804 if (RUNNING (job_index
) && (IS_FOREGROUND (job_index
) == 0))
1805 fprintf (stream
, " &");
1807 if (strcmp (temp
, jobs
[job_index
]->wd
) != 0)
1809 _(" (wd: %s)"), polite_directory_format (jobs
[job_index
]->wd
));
1812 if (format
|| (p
== last
))
1814 /* We need to add a CR only if this is an interactive shell, and
1815 we're reporting the status of a completed job asynchronously.
1816 We can't really check whether this particular job is being
1817 reported asynchronously, so just add the CR if the shell is
1818 currently interactive and asynchronous notification is enabled. */
1819 if (asynchronous_notification
&& interactive
)
1820 fprintf (stream
, "\r\n");
1822 fprintf (stream
, "\n");
1832 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1833 Must be called with SIGCHLD blocked or queued with queue_sigchld */
1835 pretty_print_job (job_index
, format
, stream
)
1836 int job_index
, format
;
1839 register PROCESS
*p
;
1841 /* Format only pid information about the process group leader? */
1842 if (format
== JLIST_PID_ONLY
)
1844 fprintf (stream
, "%ld\n", (long)jobs
[job_index
]->pipe
->pid
);
1848 if (format
== JLIST_CHANGED_ONLY
)
1850 if (IS_NOTIFIED (job_index
))
1852 format
= JLIST_STANDARD
;
1855 if (format
!= JLIST_NONINTERACTIVE
)
1856 fprintf (stream
, "[%d]%c ", job_index
+ 1,
1857 (job_index
== js
.j_current
) ? '+':
1858 (job_index
== js
.j_previous
) ? '-' : ' ');
1860 if (format
== JLIST_NONINTERACTIVE
)
1861 format
= JLIST_LONG
;
1863 p
= jobs
[job_index
]->pipe
;
1865 print_pipeline (p
, job_index
, format
, stream
);
1867 /* We have printed information about this job. When the job's
1868 status changes, waitchld () sets the notification flag to 0. */
1869 jobs
[job_index
]->flags
|= J_NOTIFIED
;
1873 print_job (job
, format
, state
, job_index
)
1875 int format
, state
, job_index
;
1877 if (state
== -1 || (JOB_STATE
)state
== job
->state
)
1878 pretty_print_job (job_index
, format
, stdout
);
1883 list_one_job (job
, format
, ignore
, job_index
)
1885 int format
, ignore
, job_index
;
1887 pretty_print_job (job_index
, format
, stdout
);
1891 list_stopped_jobs (format
)
1894 cleanup_dead_jobs ();
1895 map_over_jobs (print_job
, format
, (int)JSTOPPED
);
1899 list_running_jobs (format
)
1902 cleanup_dead_jobs ();
1903 map_over_jobs (print_job
, format
, (int)JRUNNING
);
1906 /* List jobs. If FORMAT is non-zero, then the long form of the information
1907 is printed, else just a short version. */
1909 list_all_jobs (format
)
1912 cleanup_dead_jobs ();
1913 map_over_jobs (print_job
, format
, -1);
1916 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1917 COMMAND is just for remembering the name of the command; we don't do
1918 anything else with it. ASYNC_P says what to do with the tty. If
1919 non-zero, then don't give it away. */
1921 make_child (command
, async_p
)
1929 /* XXX - block SIGTERM here and unblock in child after fork resets the
1930 set of pending signals? */
1932 sigaddset (&set
, SIGCHLD
);
1933 sigaddset (&set
, SIGINT
);
1934 sigemptyset (&oset
);
1935 sigprocmask (SIG_BLOCK
, &set
, &oset
);
1941 #if defined (BUFFERED_INPUT)
1942 /* If default_buffered_input is active, we are reading a script. If
1943 the command is asynchronous, we have already duplicated /dev/null
1944 as fd 0, but have not changed the buffered stream corresponding to
1945 the old fd 0. We don't want to sync the stream in this case. */
1946 if (default_buffered_input
!= -1 &&
1947 (!async_p
|| default_buffered_input
> 0))
1948 sync_buffered_stream (default_buffered_input
);
1949 #endif /* BUFFERED_INPUT */
1953 /* Create the child, handle severe errors. Retry on EAGAIN. */
1954 while ((pid
= fork ()) < 0 && errno
== EAGAIN
&& forksleep
< FORKSLEEP_MAX
)
1957 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
1958 /* If we can't create any children, try to reap some dead ones. */
1961 errno
= EAGAIN
; /* restore errno */
1962 sys_error ("fork: retry");
1965 if (sleep (forksleep
) != 0)
1969 if (interrupt_state
)
1971 sigprocmask (SIG_SETMASK
, &set
, (sigset_t
*)NULL
);
1981 /* Kill all of the processes in the current pipeline. */
1982 terminate_current_pipeline ();
1984 /* Discard the current pipeline, if any. */
1986 kill_current_pipeline ();
1988 last_command_exit_value
= EX_NOEXEC
;
1989 throw_to_top_level (); /* Reset signals, etc. */
1994 /* In the child. Give this child the right process group, set the
1995 signals to the default state for a new process. */
1998 /* If this ends up being changed to modify or use `command' in the
1999 child process, go back and change callers who free `command' in
2000 the child process when this returns. */
2002 #if defined (BUFFERED_INPUT)
2003 /* Close default_buffered_input if it's > 0. We don't close it if it's
2004 0 because that's the file descriptor used when redirecting input,
2005 and it's wrong to close the file in that case. */
2006 unset_bash_input (0);
2007 #endif /* BUFFERED_INPUT */
2009 CLRINTERRUPT
; /* XXX - children have their own interrupt state */
2011 /* Restore top-level signal mask. */
2012 sigprocmask (SIG_SETMASK
, &top_level_mask
, (sigset_t
*)NULL
);
2016 /* All processes in this pipeline belong in the same
2019 if (pipeline_pgrp
== 0) /* This is the first child. */
2020 pipeline_pgrp
= mypid
;
2022 /* Check for running command in backquotes. */
2023 if (pipeline_pgrp
== shell_pgrp
)
2024 ignore_tty_job_signals ();
2026 default_tty_job_signals ();
2028 /* Set the process group before trying to mess with the terminal's
2029 process group. This is mandated by POSIX. */
2030 /* This is in accordance with the Posix 1003.1 standard,
2031 section B.7.2.4, which says that trying to set the terminal
2032 process group with tcsetpgrp() to an unused pgrp value (like
2033 this would have for the first child) is an error. Section
2034 B.4.3.3, p. 237 also covers this, in the context of job control
2036 if (setpgid (mypid
, pipeline_pgrp
) < 0)
2037 sys_error (_("child setpgid (%ld to %ld)"), (long)mypid
, (long)pipeline_pgrp
);
2039 /* By convention (and assumption above), if
2040 pipeline_pgrp == shell_pgrp, we are making a child for
2041 command substitution.
2042 In this case, we don't want to give the terminal to the
2043 shell's process group (we could be in the middle of a
2044 pipeline, for example). */
2045 if (async_p
== 0 && pipeline_pgrp
!= shell_pgrp
&& ((subshell_environment
&(SUBSHELL_ASYNC
|SUBSHELL_PIPE
)) == 0) && running_in_background
== 0)
2046 give_terminal_to (pipeline_pgrp
, 0);
2048 #if defined (PGRP_PIPE)
2049 if (pipeline_pgrp
== mypid
)
2050 pipe_read (pgrp_pipe
);
2053 else /* Without job control... */
2055 if (pipeline_pgrp
== 0)
2056 pipeline_pgrp
= shell_pgrp
;
2058 /* If these signals are set to SIG_DFL, we encounter the curious
2059 situation of an interactive ^Z to a running process *working*
2060 and stopping the process, but being unable to do anything with
2061 that process to change its state. On the other hand, if they
2062 are set to SIG_IGN, jobs started from scripts do not stop when
2063 the shell running the script gets a SIGTSTP and stops. */
2065 default_tty_job_signals ();
2068 #if defined (PGRP_PIPE)
2069 /* Release the process group pipe, since our call to setpgid ()
2070 is done. The last call to sh_closepipe is done in stop_pipeline. */
2071 sh_closepipe (pgrp_pipe
);
2072 #endif /* PGRP_PIPE */
2075 /* Don't set last_asynchronous_pid in the child */
2077 last_asynchronous_pid
= mypid
; /* XXX */
2080 #if defined (RECYCLES_PIDS)
2081 if (last_asynchronous_pid
== mypid
)
2082 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2083 last_asynchronous_pid
= 1;
2088 /* In the parent. Remember the pid of the child just created
2089 as the proper pgrp if this is the first child. */
2093 if (pipeline_pgrp
== 0)
2095 pipeline_pgrp
= pid
;
2096 /* Don't twiddle terminal pgrps in the parent! This is the bug,
2097 not the good thing of twiddling them in the child! */
2098 /* give_terminal_to (pipeline_pgrp, 0); */
2100 /* This is done on the recommendation of the Rationale section of
2101 the POSIX 1003.1 standard, where it discusses job control and
2102 shells. It is done to avoid possible race conditions. (Ref.
2103 1003.1 Rationale, section B.4.3.3, page 236). */
2104 setpgid (pid
, pipeline_pgrp
);
2108 if (pipeline_pgrp
== 0)
2109 pipeline_pgrp
= shell_pgrp
;
2112 /* Place all processes into the jobs array regardless of the
2113 state of job_control. */
2114 add_process (command
, pid
);
2117 last_asynchronous_pid
= pid
;
2118 #if defined (RECYCLES_PIDS)
2119 else if (last_asynchronous_pid
== pid
)
2120 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2121 last_asynchronous_pid
= 1;
2124 /* Delete the saved status for any job containing this PID in case it's
2126 delete_old_job (pid
);
2128 /* Perform the check for pid reuse unconditionally. Some systems reuse
2129 PIDs before giving a process CHILD_MAX/_SC_CHILD_MAX unique ones. */
2130 bgp_delete (pid
); /* new process, discard any saved status */
2132 last_made_pid
= pid
;
2138 /* Unblock SIGINT and SIGCHLD unless creating a pipeline, in which case
2139 SIGCHLD remains blocked until all commands in the pipeline have been
2141 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
2147 /* These two functions are called only in child processes. */
2149 ignore_tty_job_signals ()
2151 set_signal_handler (SIGTSTP
, SIG_IGN
);
2152 set_signal_handler (SIGTTIN
, SIG_IGN
);
2153 set_signal_handler (SIGTTOU
, SIG_IGN
);
2156 /* Reset the tty-generated job control signals to SIG_DFL unless that signal
2157 was ignored at entry to the shell, in which case we need to set it to
2158 SIG_IGN in the child. We can't rely on resetting traps, since the hard
2159 ignored signals can't be trapped. */
2161 default_tty_job_signals ()
2163 if (signal_is_trapped (SIGTSTP
) == 0 && signal_is_hard_ignored (SIGTSTP
))
2164 set_signal_handler (SIGTSTP
, SIG_IGN
);
2166 set_signal_handler (SIGTSTP
, SIG_DFL
);
2168 if (signal_is_trapped (SIGTTIN
) == 0 && signal_is_hard_ignored (SIGTTIN
))
2169 set_signal_handler (SIGTTIN
, SIG_IGN
);
2171 set_signal_handler (SIGTTIN
, SIG_DFL
);
2173 if (signal_is_trapped (SIGTTOU
) == 0 && signal_is_hard_ignored (SIGTTOU
))
2174 set_signal_handler (SIGTTOU
, SIG_IGN
);
2176 set_signal_handler (SIGTTOU
, SIG_DFL
);
2179 /* Called once in a parent process. */
2181 get_original_tty_job_signals ()
2183 static int fetched
= 0;
2187 if (interactive_shell
)
2189 set_original_signal (SIGTSTP
, SIG_DFL
);
2190 set_original_signal (SIGTTIN
, SIG_DFL
);
2191 set_original_signal (SIGTTOU
, SIG_DFL
);
2195 get_original_signal (SIGTSTP
);
2196 get_original_signal (SIGTTIN
);
2197 get_original_signal (SIGTTOU
);
2203 /* When we end a job abnormally, or if we stop a job, we set the tty to the
2204 state kept in here. When a job ends normally, we set the state in here
2205 to the state of the tty. */
2207 static TTYSTRUCT shell_tty_info
;
2209 #if defined (NEW_TTY_DRIVER)
2210 static struct tchars shell_tchars
;
2211 static struct ltchars shell_ltchars
;
2212 #endif /* NEW_TTY_DRIVER */
2214 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
2215 /* Since the BSD tty driver does not allow us to change the tty modes
2216 while simultaneously waiting for output to drain and preserving
2217 typeahead, we have to drain the output ourselves before calling
2218 ioctl. We cheat by finding the length of the output queue, and
2219 using select to wait for an appropriate length of time. This is
2220 a hack, and should be labeled as such (it's a hastily-adapted
2221 mutation of a `usleep' implementation). It's only reason for
2222 existing is the flaw in the BSD tty driver. */
2224 static int ttspeeds
[] =
2226 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
2227 1800, 2400, 4800, 9600, 19200, 38400
2234 register int delay
= ttspeeds
[ospeed
];
2240 while ((ioctl (fd
, TIOCOUTQ
, &n
) == 0) && n
)
2242 if (n
> (delay
/ 100))
2246 n
*= 10; /* 2 bits more for conservativeness. */
2247 tv
.tv_sec
= n
/ delay
;
2248 tv
.tv_usec
= ((n
% delay
) * 1000000) / delay
;
2249 select (fd
, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &tv
);
2255 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
2257 /* Return the fd from which we are actually getting input. */
2258 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
2260 /* Fill the contents of shell_tty_info with the current tty info. */
2269 #if defined (NEW_TTY_DRIVER)
2270 ioctl (tty
, TIOCGETP
, &shell_tty_info
);
2271 ioctl (tty
, TIOCGETC
, &shell_tchars
);
2272 ioctl (tty
, TIOCGLTC
, &shell_ltchars
);
2273 #endif /* NEW_TTY_DRIVER */
2275 #if defined (TERMIO_TTY_DRIVER)
2276 ioctl (tty
, TCGETA
, &shell_tty_info
);
2277 #endif /* TERMIO_TTY_DRIVER */
2279 #if defined (TERMIOS_TTY_DRIVER)
2280 if (tcgetattr (tty
, &shell_tty_info
) < 0)
2283 /* Only print an error message if we're really interactive at
2286 sys_error ("[%ld: %d (%d)] tcgetattr", (long)getpid (), shell_level
, tty
);
2290 #endif /* TERMIOS_TTY_DRIVER */
2291 if (check_window_size
)
2292 get_new_window_size (0, (int *)0, (int *)0);
2297 /* Make the current tty use the state in shell_tty_info. */
2306 #if defined (NEW_TTY_DRIVER)
2307 # if defined (DRAIN_OUTPUT)
2308 draino (tty
, shell_tty_info
.sg_ospeed
);
2309 # endif /* DRAIN_OUTPUT */
2310 ioctl (tty
, TIOCSETN
, &shell_tty_info
);
2311 ioctl (tty
, TIOCSETC
, &shell_tchars
);
2312 ioctl (tty
, TIOCSLTC
, &shell_ltchars
);
2313 #endif /* NEW_TTY_DRIVER */
2315 #if defined (TERMIO_TTY_DRIVER)
2316 ioctl (tty
, TCSETAW
, &shell_tty_info
);
2317 #endif /* TERMIO_TTY_DRIVER */
2319 #if defined (TERMIOS_TTY_DRIVER)
2320 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
2322 /* Only print an error message if we're really interactive at
2325 sys_error ("[%ld: %d (%d)] tcsetattr", (long)getpid (), shell_level
, tty
);
2328 #endif /* TERMIOS_TTY_DRIVER */
2333 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2334 process in that job's pipeline. This is the one whose exit status
2335 counts. Must be called with SIGCHLD blocked or queued. */
2337 find_last_proc (job
, block
)
2341 register PROCESS
*p
;
2345 BLOCK_CHILD (set
, oset
);
2347 p
= jobs
[job
]->pipe
;
2348 while (p
&& p
->next
!= jobs
[job
]->pipe
)
2352 UNBLOCK_CHILD (oset
);
2358 find_last_pid (job
, block
)
2364 p
= find_last_proc (job
, block
);
2365 /* Possible race condition here. */
2369 /* Wait for a particular child of the shell to finish executing.
2370 This low-level function prints an error message if PID is not
2371 a child of this shell. It returns -1 if it fails, or whatever
2372 wait_for returns otherwise. If the child is not found in the
2373 jobs table, it returns 127. If FLAGS doesn't include JWAIT_PERROR,
2374 we suppress the error message if PID isn't found. */
2377 wait_for_single_pid (pid
, flags
)
2381 register PROCESS
*child
;
2385 BLOCK_CHILD (set
, oset
);
2386 child
= find_pipeline (pid
, 0, (int *)NULL
);
2387 UNBLOCK_CHILD (oset
);
2391 r
= bgp_search (pid
);
2398 if (flags
& JWAIT_PERROR
)
2399 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid
);
2407 if ((flags
& JWAIT_FORCE
) == 0)
2410 BLOCK_CHILD (set
, oset
);
2411 alive
= PALIVE (child
);
2412 UNBLOCK_CHILD (oset
);
2416 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2418 BLOCK_CHILD (set
, oset
);
2419 job
= find_job (pid
, 0, NULL
);
2420 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
2421 jobs
[job
]->flags
|= J_NOTIFIED
;
2422 UNBLOCK_CHILD (oset
);
2424 /* If running in posix mode, remove the job from the jobs table immediately */
2425 if (posixly_correct
)
2427 cleanup_dead_jobs ();
2434 /* Wait for all of the background processes started by this shell to finish. */
2436 wait_for_background_pids ()
2439 int any_stopped
, check_async
;
2443 for (any_stopped
= 0, check_async
= 1;;)
2445 BLOCK_CHILD (set
, oset
);
2447 /* find first running job; if none running in foreground, break */
2448 /* XXX could use js.j_firstj and js.j_lastj here */
2449 for (i
= 0; i
< js
.j_jobslots
; i
++)
2452 if (i
< js
.j_firstj
&& jobs
[i
])
2453 itrace("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
2454 if (i
> js
.j_lastj
&& jobs
[i
])
2455 itrace("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
2457 if (jobs
[i
] && STOPPED (i
))
2459 builtin_warning ("job %d[%d] stopped", i
+1, find_last_pid (i
, 0));
2463 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
2466 if (i
== js
.j_jobslots
)
2468 UNBLOCK_CHILD (oset
);
2472 /* now wait for the last pid in that job. */
2473 pid
= find_last_pid (i
, 0);
2474 UNBLOCK_CHILD (oset
);
2476 errno
= 0; /* XXX */
2477 r
= wait_for_single_pid (pid
, JWAIT_PERROR
);
2478 if (r
== -1 && errno
== ECHILD
)
2480 /* If we're mistaken about job state, compensate. */
2482 mark_all_jobs_as_dead ();
2486 #if defined (PROCESS_SUBSTITUTION)
2487 if (last_procsub_child
&& last_procsub_child
->pid
!= NO_PID
)
2488 r
= wait_for (last_procsub_child
->pid
);
2492 /* We don't want to wait indefinitely if we have stopped children. */
2493 if (any_stopped
== 0)
2495 /* Check whether or not we have any unreaped children. */
2496 while ((r
= wait_for (ANY_PID
)) >= 0)
2505 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2506 `wait' is called with no arguments. */
2507 mark_dead_jobs_as_notified (1);
2508 cleanup_dead_jobs ();
2512 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2513 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2514 static SigHandler
*old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2516 static int wait_sigint_received
;
2517 static int child_caught_sigint
;
2518 static int waiting_for_child
;
2520 /* Clean up state after longjmp to wait_intr_buf */
2522 wait_sigint_cleanup ()
2525 waiting_for_child
= 0;
2529 restore_sigint_handler ()
2531 if (old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
2533 set_signal_handler (SIGINT
, old_sigint_handler
);
2534 old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2535 waiting_for_child
= 0;
2539 /* Handle SIGINT while we are waiting for children in a script to exit.
2540 The `wait' builtin should be interruptible, but all others should be
2541 effectively ignored (i.e. not cause the shell to exit). */
2543 wait_sigint_handler (sig
)
2546 SigHandler
*sigint_handler
;
2548 if (interrupt_immediately
||
2549 (this_shell_builtin
&& this_shell_builtin
== wait_builtin
))
2551 last_command_exit_value
= 128+SIGINT
;
2552 restore_sigint_handler ();
2553 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2554 what POSIX.2 says (see builtins/wait.def for more info). */
2555 if (this_shell_builtin
&& this_shell_builtin
== wait_builtin
&&
2556 signal_is_trapped (SIGINT
) &&
2557 ((sigint_handler
= trap_to_sighandler (SIGINT
)) == trap_handler
))
2559 trap_handler (SIGINT
); /* set pending_traps[SIGINT] */
2560 wait_signal_received
= SIGINT
;
2561 if (interrupt_immediately
&& wait_intr_flag
)
2563 interrupt_immediately
= 0;
2564 sh_longjmp (wait_intr_buf
, 1);
2567 /* Let CHECK_WAIT_INTR handle it in wait_for/waitchld */
2570 else if (interrupt_immediately
)
2575 else /* wait_builtin but signal not trapped, treat as interrupt */
2576 kill (getpid (), SIGINT
);
2579 /* XXX - should this be interrupt_state? If it is, the shell will act
2580 as if it got the SIGINT interrupt. */
2581 if (waiting_for_child
)
2582 wait_sigint_received
= 1;
2585 last_command_exit_value
= 128+SIGINT
;
2586 restore_sigint_handler ();
2587 kill (getpid (), SIGINT
);
2590 /* Otherwise effectively ignore the SIGINT and allow the running job to
2596 process_exit_signal (status
)
2599 return (WIFSIGNALED (status
) ? WTERMSIG (status
) : 0);
2603 process_exit_status (status
)
2606 if (WIFSIGNALED (status
))
2607 return (128 + WTERMSIG (status
));
2608 else if (WIFSTOPPED (status
) == 0)
2609 return (WEXITSTATUS (status
));
2611 return (EXECUTION_SUCCESS
);
2615 job_signal_status (job
)
2618 register PROCESS
*p
;
2621 p
= jobs
[job
]->pipe
;
2625 if (WIFSIGNALED(s
) || WIFSTOPPED(s
))
2629 while (p
!= jobs
[job
]->pipe
);
2634 /* Return the exit status of the last process in the pipeline for job JOB.
2635 This is the exit status of the entire job. */
2637 raw_job_exit_status (job
)
2640 register PROCESS
*p
;
2647 if (jobs
[job
]->flags
& J_PIPEFAIL
)
2651 p
= jobs
[job
]->pipe
;
2654 if (WSTATUS (p
->status
) != EXECUTION_SUCCESS
)
2655 fail
= WSTATUS(p
->status
);
2658 while (p
!= jobs
[job
]->pipe
);
2659 WSTATUS (ret
) = fail
;
2663 for (p
= jobs
[job
]->pipe
; p
->next
!= jobs
[job
]->pipe
; p
= p
->next
)
2668 /* Return the exit status of job JOB. This is the exit status of the last
2669 (rightmost) process in the job's pipeline, modified if the job was killed
2670 by a signal or stopped. */
2672 job_exit_status (job
)
2675 return (process_exit_status (raw_job_exit_status (job
)));
2679 job_exit_signal (job
)
2682 return (process_exit_signal (raw_job_exit_status (job
)));
2685 #define FIND_CHILD(pid, child) \
2688 child = find_pipeline (pid, 0, (int *)NULL); \
2691 give_terminal_to (shell_pgrp, 0); \
2692 UNBLOCK_CHILD (oset); \
2693 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2694 restore_sigint_handler (); \
2695 return (termination_state = 127); \
2700 /* Wait for pid (one of our children) to terminate, then
2701 return the termination state. Returns 127 if PID is not found in
2702 the jobs table. Returns -1 if waitchld() returns -1, indicating
2703 that there are no unwaited-for child processes. */
2708 int job
, termination_state
, r
;
2710 register PROCESS
*child
;
2713 /* In the case that this code is interrupted, and we longjmp () out of it,
2714 we are relying on the code in throw_to_top_level () to restore the
2715 top-level signal mask. */
2717 BLOCK_CHILD (set
, oset
);
2719 /* Ignore interrupts while waiting for a job run without job control
2720 to finish. We don't want the shell to exit if an interrupt is
2721 received, only if one of the jobs run is killed via SIGINT. If
2722 job control is not set, the job will be run in the same pgrp as
2723 the shell, and the shell will see any signals the job gets. In
2724 fact, we want this set every time the waiting shell and the waited-
2725 for process are in the same process group, including command
2728 /* This is possibly a race condition -- should it go in stop_pipeline? */
2729 wait_sigint_received
= child_caught_sigint
= 0;
2730 if (job_control
== 0 || (subshell_environment
&SUBSHELL_COMSUB
))
2732 SigHandler
*temp_sigint_handler
;
2734 temp_sigint_handler
= set_signal_handler (SIGINT
, wait_sigint_handler
);
2735 if (temp_sigint_handler
== wait_sigint_handler
)
2738 internal_warning ("wait_for: recursively setting old_sigint_handler to wait_sigint_handler: running_trap = %d", running_trap
);
2742 old_sigint_handler
= temp_sigint_handler
;
2743 waiting_for_child
= 0;
2744 if (old_sigint_handler
== SIG_IGN
)
2745 set_signal_handler (SIGINT
, old_sigint_handler
);
2748 termination_state
= last_command_exit_value
;
2750 if (interactive
&& job_control
== 0)
2752 /* Check for terminating signals and exit the shell if we receive one */
2755 /* Check for a trapped signal interrupting the wait builtin and jump out */
2758 /* If we say wait_for (), then we have a record of this child somewhere.
2759 If it and none of its peers are running, don't call waitchld(). */
2765 FIND_CHILD (pid
, child
);
2767 /* If this child is part of a job, then we are really waiting for the
2768 job to finish. Otherwise, we are waiting for the child to finish.
2769 We check for JDEAD in case the job state has been set by waitchld
2770 after receipt of a SIGCHLD. */
2771 if (job
== NO_JOB
&& pid
!= ANY_PID
) /* XXX -- && pid != ANY_PID ? */
2772 job
= find_job (pid
, 0, NULL
);
2774 /* waitchld() takes care of setting the state of the job. If the job
2775 has already exited before this is called, sigchld_handler will have
2776 called waitchld and the state will be set to JDEAD. */
2778 if (pid
== ANY_PID
|| PRUNNING(child
) || (job
!= NO_JOB
&& RUNNING (job
)))
2780 #if defined (WAITPID_BROKEN) /* SCOv4 */
2781 sigset_t suspend_set
;
2782 sigemptyset (&suspend_set
);
2783 sigsuspend (&suspend_set
);
2784 #else /* !WAITPID_BROKEN */
2785 # if defined (MUST_UNBLOCK_CHLD)
2786 struct sigaction act
, oact
;
2787 sigset_t nullset
, chldset
;
2790 sigemptyset (&nullset
);
2791 sigemptyset (&chldset
);
2792 sigprocmask (SIG_SETMASK
, &nullset
, &chldset
);
2793 act
.sa_handler
= SIG_DFL
;
2794 sigemptyset (&act
.sa_mask
);
2795 sigemptyset (&oact
.sa_mask
);
2797 # if defined (SA_RESTART)
2798 act
.sa_flags
|= SA_RESTART
;
2800 sigaction (SIGCHLD
, &act
, &oact
);
2801 # endif /* MUST_UNBLOCK_CHLD */
2803 waiting_for_child
++;
2804 r
= waitchld (pid
, 1); /* XXX */
2805 waiting_for_child
--;
2807 itrace("wait_for: blocking wait for %d returns %d child = %p", (int)pid
, r
, child
);
2809 # if defined (MUST_UNBLOCK_CHLD)
2810 sigaction (SIGCHLD
, &oact
, (struct sigaction
*)NULL
);
2811 sigprocmask (SIG_SETMASK
, &chldset
, (sigset_t
*)NULL
);
2814 if (r
== -1 && errno
== ECHILD
&& this_shell_builtin
== wait_builtin
)
2816 termination_state
= -1;
2817 /* XXX - restore sigint handler here */
2818 restore_sigint_handler ();
2819 goto wait_for_return
;
2822 /* If child is marked as running, but waitpid() returns -1/ECHILD,
2823 there is something wrong. Somewhere, wait should have returned
2824 that child's pid. Mark the child as not running and the job,
2825 if it exists, as JDEAD. */
2826 if (r
== -1 && errno
== ECHILD
)
2830 child
->running
= PS_DONE
;
2831 WSTATUS (child
->status
) = 0; /* XXX -- can't find true status */
2833 js
.c_living
= 0; /* no living child processes */
2836 jobs
[job
]->state
= JDEAD
;
2842 termination_state
= -1;
2846 #endif /* WAITPID_BROKEN */
2849 /* If the shell is interactive, and job control is disabled, see
2850 if the foreground process has died due to SIGINT and jump out
2851 of the wait loop if it has. waitchld has already restored the
2852 old SIGINT signal handler. */
2853 if (interactive
&& job_control
== 0)
2855 /* Check for terminating signals and exit the shell if we receive one */
2858 /* Check for a trapped signal interrupting the wait builtin and jump out */
2863 /* XXX - could set child but we don't have a handle on what waitchld
2864 reaps. Leave termination_state alone. */
2865 restore_sigint_handler ();
2866 goto wait_for_return
;
2869 while (PRUNNING (child
) || (job
!= NO_JOB
&& RUNNING (job
)));
2871 /* Restore the original SIGINT signal handler before we return. */
2872 restore_sigint_handler ();
2874 /* The exit state of the command is either the termination state of the
2875 child, or the termination state of the job. If a job, the status
2876 of the last child in the pipeline is the significant one. If the command
2877 or job was terminated by a signal, note that value also. */
2878 termination_state
= (job
!= NO_JOB
) ? job_exit_status (job
)
2879 : (child
? process_exit_status (child
->status
) : EXECUTION_SUCCESS
);
2880 last_command_exit_signal
= (job
!= NO_JOB
) ? job_exit_signal (job
)
2881 : (child
? process_exit_signal (child
->status
) : 0);
2884 if ((job
!= NO_JOB
&& JOBSTATE (job
) == JSTOPPED
) || (child
&& WIFSTOPPED (child
->status
)))
2885 termination_state
= 128 + WSTOPSIG (child
->status
);
2887 if (job
== NO_JOB
|| IS_JOBCONTROL (job
))
2889 /* XXX - under what circumstances is a job not present in the jobs
2890 table (job == NO_JOB)?
2891 1. command substitution
2893 In the case of command substitution, at least, it's probably not
2894 the right thing to give the terminal to the shell's process group,
2895 even though there is code in subst.c:command_substitute to work
2899 $PROMPT_COMMAND execution
2900 process substitution
2904 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp
);
2906 /* Don't modify terminal pgrp if we are running in background or a
2907 subshell. Make sure subst.c:command_substitute uses the same
2908 conditions to determine whether or not it should undo this and
2909 give the terminal to pipeline_pgrp. */
2911 if (running_in_background
== 0 && (subshell_environment
&(SUBSHELL_ASYNC
|SUBSHELL_PIPE
)) == 0)
2912 give_terminal_to (shell_pgrp
, 0);
2915 /* If the command did not exit cleanly, or the job is just
2916 being stopped, then reset the tty state back to what it
2917 was before this command. Reset the tty state and notify
2918 the user of the job termination only if the shell is
2919 interactive. Clean up any dead jobs in either case. */
2922 if (interactive_shell
&& subshell_environment
== 0)
2924 /* This used to use `child->status'. That's wrong, however, for
2925 pipelines. `child' is the first process in the pipeline. It's
2926 likely that the process we want to check for abnormal termination
2927 or stopping is the last process in the pipeline, especially if
2928 it's long-lived and the first process is short-lived. Since we
2929 know we have a job here, we can check all the processes in this
2930 job's pipeline and see if one of them stopped or terminated due
2931 to a signal. We might want to change this later to just check
2932 the last process in the pipeline. If no process exits due to a
2933 signal, S is left as the status of the last job in the pipeline. */
2934 s
= job_signal_status (job
);
2936 if (WIFSIGNALED (s
) || WIFSTOPPED (s
))
2940 /* If the current job was stopped or killed by a signal, and
2941 the user has requested it, get a possibly new window size */
2942 if (check_window_size
&& (job
== js
.j_current
|| IS_FOREGROUND (job
)))
2943 get_new_window_size (0, (int *)0, (int *)0);
2946 #if defined (READLINE)
2947 /* We don't want to do this if we are running a process during
2948 programmable completion. */
2949 if (RL_ISSTATE (RL_STATE_COMPLETING
) == 0)
2953 /* If job control is enabled, the job was started with job
2954 control, the job was the foreground job, and it was killed
2955 by SIGINT, then print a newline to compensate for the kernel
2956 printing the ^C without a trailing newline. */
2957 if (job_control
&& IS_JOBCONTROL (job
) && IS_FOREGROUND (job
) &&
2958 WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
)
2960 /* If SIGINT is not trapped and the shell is in a for, while,
2961 or until loop, act as if the shell received SIGINT as
2962 well, so the loop can be broken. This doesn't call the
2963 SIGINT signal handler; maybe it should. */
2964 if (signal_is_trapped (SIGINT
) == 0 && (loop_level
|| (shell_compatibility_level
> 32 && executing_list
)))
2966 /* Call any SIGINT trap handler if the shell is running a loop, so
2967 the loop can be broken. This seems more useful and matches the
2968 behavior when the shell is running a builtin command in a loop
2969 when it is interrupted. Change ADDINTERRUPT to
2970 trap_handler (SIGINT) to run the trap without interrupting the
2972 else if (signal_is_trapped (SIGINT
) && loop_level
)
2974 /* If an interactive shell with job control enabled is sourcing
2975 a file, allow the interrupt to terminate the file sourcing. */
2976 else if (interactive_shell
&& signal_is_trapped (SIGINT
) == 0 && sourcelevel
)
2985 else if ((subshell_environment
& (SUBSHELL_COMSUB
|SUBSHELL_PIPE
)) && wait_sigint_received
)
2987 /* If waiting for a job in a subshell started to do command
2988 substitution or to run a pipeline element that consists of
2989 something like a while loop or a for loop, simulate getting
2990 and being killed by the SIGINT to pass the status back to our
2992 if (child_caught_sigint
== 0 && signal_is_trapped (SIGINT
) == 0)
2994 UNBLOCK_CHILD (oset
);
2995 old_sigint_handler
= set_signal_handler (SIGINT
, SIG_DFL
);
2996 if (old_sigint_handler
== SIG_IGN
)
2997 restore_sigint_handler ();
2999 kill (getpid (), SIGINT
);
3002 else if (interactive_shell
== 0 && subshell_environment
== 0 && IS_FOREGROUND (job
))
3004 s
= job_signal_status (job
);
3006 /* If we are non-interactive, but job control is enabled, and the job
3007 died due to SIGINT, pretend we got the SIGINT */
3008 if (job_control
&& IS_JOBCONTROL (job
) && WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
)
3010 ADDINTERRUPT
; /* For now */
3013 if (check_window_size
)
3014 get_new_window_size (0, (int *)0, (int *)0);
3017 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
3018 signal handler path */
3019 if (DEADJOB (job
) && IS_FOREGROUND (job
) /*&& subshell_environment == 0*/)
3022 /* If this job is dead, notify the user of the status. If the shell
3023 is interactive, this will display a message on the terminal. If
3024 the shell is not interactive, make sure we turn on the notify bit
3025 so we don't get an unwanted message about the job's termination,
3026 and so delete_job really clears the slot in the jobs table. */
3027 notify_and_cleanup ();
3032 UNBLOCK_CHILD (oset
);
3034 return (termination_state
);
3037 /* Wait for the last process in the pipeline for JOB. Returns whatever
3038 wait_for returns: the last process's termination state or -1 if there
3039 are no unwaited-for child processes or an error occurs. If FLAGS
3040 includes JWAIT_FORCE, we wait for the job to terminate, no just change
3043 wait_for_job (job
, flags
)
3050 BLOCK_CHILD(set
, oset
);
3051 state
= JOBSTATE (job
);
3052 if (state
== JSTOPPED
)
3053 internal_warning (_("wait_for_job: job %d is stopped"), job
+1);
3055 pid
= find_last_pid (job
, 0);
3056 UNBLOCK_CHILD(oset
);
3061 if (r
== -1 && errno
== ECHILD
)
3062 mark_all_jobs_as_dead ();
3064 if ((flags
& JWAIT_FORCE
) == 0)
3067 BLOCK_CHILD (set
, oset
);
3068 state
= (job
!= NO_JOB
&& jobs
[job
]) ? JOBSTATE (job
) : JDEAD
;
3069 UNBLOCK_CHILD (oset
);
3071 while (state
!= JDEAD
);
3073 /* POSIX.2: we can remove the job from the jobs table if we just waited
3075 BLOCK_CHILD (set
, oset
);
3076 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
3077 jobs
[job
]->flags
|= J_NOTIFIED
;
3078 UNBLOCK_CHILD (oset
);
3083 /* Wait for any background job started by this shell to finish. Very
3084 similar to wait_for_background_pids(). Returns the exit status of
3085 the next exiting job, -1 if there are no background jobs. The caller
3086 is responsible for translating -1 into the right return value. */
3088 wait_for_any_job (flags
)
3095 if (jobs_list_frozen
)
3098 /* First see if there are any unnotified dead jobs that we can report on */
3099 BLOCK_CHILD (set
, oset
);
3100 for (i
= 0; i
< js
.j_jobslots
; i
++)
3102 if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
) == 0)
3105 r
= job_exit_status (i
);
3106 notify_of_job_status (); /* XXX */
3108 #if defined (COPROCESS_SUPPORT)
3111 UNBLOCK_CHILD (oset
);
3115 UNBLOCK_CHILD (oset
);
3117 /* At this point, we have no dead jobs in the jobs table. Wait until we
3118 get one, even if it takes multiple pids exiting. */
3121 /* Make sure there is a background job to wait for */
3122 BLOCK_CHILD (set
, oset
);
3123 for (i
= 0; i
< js
.j_jobslots
; i
++)
3124 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
3126 if (i
== js
.j_jobslots
)
3128 UNBLOCK_CHILD (oset
);
3132 UNBLOCK_CHILD (oset
);
3139 r
= wait_for (ANY_PID
); /* special sentinel value for wait_for */
3140 if (r
== -1 && errno
== ECHILD
)
3141 mark_all_jobs_as_dead ();
3143 /* Now we see if we have any dead jobs and return the first one */
3144 BLOCK_CHILD (set
, oset
);
3145 for (i
= 0; i
< js
.j_jobslots
; i
++)
3146 if (jobs
[i
] && DEADJOB (i
))
3148 UNBLOCK_CHILD (oset
);
3154 /* Print info about dead jobs, and then delete them from the list
3155 of known jobs. This does not actually delete jobs when the
3156 shell is not interactive, because the dead jobs are not marked
3159 notify_and_cleanup ()
3161 if (jobs_list_frozen
)
3164 if (interactive
|| interactive_shell
== 0 || sourcelevel
)
3165 notify_of_job_status ();
3167 cleanup_dead_jobs ();
3170 /* Make dead jobs disappear from the jobs array without notification.
3171 This is used when the shell is not interactive. */
3175 mark_dead_jobs_as_notified (0);
3176 cleanup_dead_jobs ();
3179 /* Return the next closest (chronologically) job to JOB which is in
3180 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
3181 there is no next recent job. */
3183 most_recent_job_in_state (job
, state
)
3187 register int i
, result
;
3190 BLOCK_CHILD (set
, oset
);
3192 for (result
= NO_JOB
, i
= job
- 1; i
>= 0; i
--)
3194 if (jobs
[i
] && (JOBSTATE (i
) == state
))
3201 UNBLOCK_CHILD (oset
);
3206 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
3209 job_last_stopped (job
)
3212 return (most_recent_job_in_state (job
, JSTOPPED
));
3215 /* Return the newest *running* job older than JOB, or NO_JOB if not
3218 job_last_running (job
)
3221 return (most_recent_job_in_state (job
, JRUNNING
));
3224 /* Make JOB be the current job, and make previous be useful. Must be
3225 called with SIGCHLD blocked. */
3227 set_current_job (job
)
3232 if (js
.j_current
!= job
)
3234 js
.j_previous
= js
.j_current
;
3238 /* First choice for previous job is the old current job. */
3239 if (js
.j_previous
!= js
.j_current
&&
3240 js
.j_previous
!= NO_JOB
&&
3241 jobs
[js
.j_previous
] &&
3242 STOPPED (js
.j_previous
))
3245 /* Second choice: Newest stopped job that is older than
3248 if (STOPPED (js
.j_current
))
3250 candidate
= job_last_stopped (js
.j_current
);
3252 if (candidate
!= NO_JOB
)
3254 js
.j_previous
= candidate
;
3259 /* If we get here, there is either only one stopped job, in which case it is
3260 the current job and the previous job should be set to the newest running
3261 job, or there are only running jobs and the previous job should be set to
3262 the newest running job older than the current job. We decide on which
3263 alternative to use based on whether or not JOBSTATE(js.j_current) is
3266 candidate
= RUNNING (js
.j_current
) ? job_last_running (js
.j_current
)
3267 : job_last_running (js
.j_jobslots
);
3269 if (candidate
!= NO_JOB
)
3271 js
.j_previous
= candidate
;
3275 /* There is only a single job, and it is both `+' and `-'. */
3276 js
.j_previous
= js
.j_current
;
3279 /* Make current_job be something useful, if it isn't already. */
3281 /* Here's the deal: The newest non-running job should be `+', and the
3282 next-newest non-running job should be `-'. If there is only a single
3283 stopped job, the js.j_previous is the newest non-running job. If there
3284 are only running jobs, the newest running job is `+' and the
3285 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
3292 if (js
.j_jobslots
&& js
.j_current
!= NO_JOB
&& jobs
[js
.j_current
] && STOPPED (js
.j_current
))
3293 candidate
= js
.j_current
;
3298 /* First choice: the previous job. */
3299 if (js
.j_previous
!= NO_JOB
&& jobs
[js
.j_previous
] && STOPPED (js
.j_previous
))
3300 candidate
= js
.j_previous
;
3302 /* Second choice: the most recently stopped job. */
3303 if (candidate
== NO_JOB
)
3304 candidate
= job_last_stopped (js
.j_jobslots
);
3306 /* Third choice: the newest running job. */
3307 if (candidate
== NO_JOB
)
3308 candidate
= job_last_running (js
.j_jobslots
);
3311 /* If we found a job to use, then use it. Otherwise, there
3312 are no jobs period. */
3313 if (candidate
!= NO_JOB
)
3314 set_current_job (candidate
);
3316 js
.j_current
= js
.j_previous
= NO_JOB
;
3319 /* Set up the job structures so we know the job and its processes are
3322 set_job_running (job
)
3325 register PROCESS
*p
;
3327 /* Each member of the pipeline is now running. */
3328 p
= jobs
[job
]->pipe
;
3332 if (WIFSTOPPED (p
->status
))
3333 p
->running
= PS_RUNNING
; /* XXX - could be PS_STOPPED */
3336 while (p
!= jobs
[job
]->pipe
);
3338 /* This means that the job is running. */
3339 JOBSTATE (job
) = JRUNNING
;
3342 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
3343 start the job in the background. JOB is a zero-based index into
3344 JOBS. Returns -1 if it is unable to start a job, and the return
3345 status of the job otherwise. */
3347 start_job (job
, foreground
)
3348 int job
, foreground
;
3350 register PROCESS
*p
;
3351 int already_running
;
3354 static TTYSTRUCT save_stty
;
3356 BLOCK_CHILD (set
, oset
);
3360 internal_error (_("%s: job has terminated"), this_command_name
);
3361 UNBLOCK_CHILD (oset
);
3365 already_running
= RUNNING (job
);
3367 if (foreground
== 0 && already_running
)
3369 internal_error (_("%s: job %d already in background"), this_command_name
, job
+ 1);
3370 UNBLOCK_CHILD (oset
);
3371 return (0); /* XPG6/SUSv3 says this is not an error */
3374 wd
= current_working_directory ();
3376 /* You don't know about the state of this job. Do you? */
3377 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3381 set_current_job (job
);
3382 jobs
[job
]->flags
|= J_FOREGROUND
;
3385 /* Tell the outside world what we're doing. */
3386 p
= jobs
[job
]->pipe
;
3388 if (foreground
== 0)
3390 /* POSIX.2 says `bg' doesn't give any indication about current or
3392 if (posixly_correct
== 0)
3393 s
= (job
== js
.j_current
) ? "+ ": ((job
== js
.j_previous
) ? "- " : " ");
3396 printf ("[%d]%s", job
+ 1, s
);
3402 p
->command
? p
->command
: "",
3403 p
->next
!= jobs
[job
]->pipe
? " | " : "");
3406 while (p
!= jobs
[job
]->pipe
);
3408 if (foreground
== 0)
3411 if (strcmp (wd
, jobs
[job
]->wd
) != 0)
3412 printf (" (wd: %s)", polite_directory_format (jobs
[job
]->wd
));
3417 if (already_running
== 0)
3418 set_job_running (job
);
3420 /* Save the tty settings before we start the job in the foreground. */
3424 save_stty
= shell_tty_info
;
3425 /* Give the terminal to this job. */
3426 if (IS_JOBCONTROL (job
))
3427 give_terminal_to (jobs
[job
]->pgrp
, 0);
3430 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3432 /* If the job is already running, then don't bother jump-starting it. */
3433 if (already_running
== 0)
3435 jobs
[job
]->flags
|= J_NOTIFIED
;
3436 killpg (jobs
[job
]->pgrp
, SIGCONT
);
3444 pid
= find_last_pid (job
, 0);
3445 UNBLOCK_CHILD (oset
);
3446 st
= wait_for (pid
);
3447 shell_tty_info
= save_stty
;
3454 UNBLOCK_CHILD (oset
);
3459 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
3460 If PID does belong to a job, and the job is stopped, then CONTinue the
3461 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
3462 then kill the process group associated with PID. */
3464 kill_pid (pid
, sig
, group
)
3468 register PROCESS
*p
;
3469 int job
, result
, negative
;
3475 group
= negative
= 1;
3480 result
= EXECUTION_SUCCESS
;
3483 BLOCK_CHILD (set
, oset
);
3484 p
= find_pipeline (pid
, 0, &job
);
3488 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3490 /* Kill process in backquotes or one started without job control? */
3492 /* If we're passed a pid < -1, just call killpg and see what happens */
3493 if (negative
&& jobs
[job
]->pgrp
== shell_pgrp
)
3494 result
= killpg (pid
, sig
);
3495 /* If we're killing using job control notification, for example,
3496 without job control active, we have to do things ourselves. */
3497 else if (jobs
[job
]->pgrp
== shell_pgrp
)
3499 p
= jobs
[job
]->pipe
;
3502 if (PALIVE (p
) == 0)
3503 continue; /* avoid pid recycling problem */
3505 if (PEXITED (p
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3506 kill (p
->pid
, SIGCONT
);
3509 while (p
!= jobs
[job
]->pipe
);
3513 result
= killpg (jobs
[job
]->pgrp
, sig
);
3514 if (p
&& STOPPED (job
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3515 killpg (jobs
[job
]->pgrp
, SIGCONT
);
3516 /* If we're continuing a stopped job via kill rather than bg or
3517 fg, emulate the `bg' behavior. */
3518 if (p
&& STOPPED (job
) && (sig
== SIGCONT
))
3520 set_job_running (job
);
3521 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3522 jobs
[job
]->flags
|= J_NOTIFIED
;
3527 result
= killpg (pid
, sig
);
3529 UNBLOCK_CHILD (oset
);
3532 result
= kill (pid
, sig
);
3537 /* sigchld_handler () flushes at least one of the children that we are
3538 waiting for. It gets run when we have gotten a SIGCHLD signal. */
3540 sigchld_handler (sig
)
3546 REINSTALL_SIGCHLD_HANDLER
;
3549 if (queue_sigchld
== 0)
3550 n
= waitchld (-1, 0);
3555 /* waitchld() reaps dead or stopped children. It's called by wait_for and
3556 sigchld_handler, and runs until there aren't any children terminating any
3558 If BLOCK is 1, this is to be a blocking wait for a single child, although
3559 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
3560 the number of children reaped, or -1 if there are no unwaited-for child
3563 waitchld (wpid
, block
)
3572 int call_set_current
, last_stopped_job
, job
, children_exited
, waitpid_flags
;
3573 static int wcontinued
= WCONTINUED
; /* run-time fix for glibc problem */
3575 call_set_current
= children_exited
= 0;
3576 last_stopped_job
= NO_JOB
;
3580 /* We don't want to be notified about jobs stopping if job control
3581 is not active. XXX - was interactive_shell instead of job_control */
3582 waitpid_flags
= (job_control
&& subshell_environment
== 0)
3583 ? (WUNTRACED
|wcontinued
)
3585 if (sigchld
|| block
== 0)
3586 waitpid_flags
|= WNOHANG
;
3588 /* Check for terminating signals and exit the shell if we receive one */
3590 /* Check for a trapped signal interrupting the wait builtin and jump out */
3593 if (block
== 1 && queue_sigchld
== 0 && (waitpid_flags
& WNOHANG
) == 0)
3595 internal_warning (_("waitchld: turning on WNOHANG to avoid indefinite block"));
3596 waitpid_flags
|= WNOHANG
;
3599 pid
= WAITPID (-1, &status
, waitpid_flags
);
3602 if (wpid
!= -1 && block
)
3603 itrace("waitchld: blocking waitpid returns %d", pid
);
3607 itrace("waitchld: %s waitpid returns %d", block
?"blocking":"non-blocking", pid
);
3609 /* WCONTINUED may be rejected by waitpid as invalid even when defined */
3610 if (wcontinued
&& pid
< 0 && errno
== EINVAL
)
3613 continue; /* jump back to the test and retry without WCONTINUED */
3616 /* The check for WNOHANG is to make sure we decrement sigchld only
3617 if it was non-zero before we called waitpid. */
3618 if (sigchld
> 0 && (waitpid_flags
& WNOHANG
))
3621 /* If waitpid returns -1 with errno == ECHILD, there are no more
3622 unwaited-for child processes of this shell. */
3623 if (pid
< 0 && errno
== ECHILD
)
3625 if (children_exited
== 0)
3632 itrace("waitchld: waitpid returns %d block = %d children_exited = %d", pid
, block
, children_exited
);
3634 /* If waitpid returns 0, there are running children. If it returns -1,
3635 the only other error POSIX says it can return is EINTR. */
3639 /* If waitpid returns -1/EINTR and the shell saw a SIGINT, then we
3640 assume the child has blocked or handled SIGINT. In that case, we
3641 require the child to actually die due to SIGINT to act on the
3642 SIGINT we received; otherwise we assume the child handled it and
3644 if (pid
< 0 && errno
== EINTR
&& wait_sigint_received
)
3645 child_caught_sigint
= 1;
3648 continue; /* jumps right to the test */
3650 /* Linux kernels appear to signal the parent but not interrupt the
3651 waitpid() (or restart it even without SA_RESTART) on SIGINT, so if
3652 we saw a SIGINT and the process exited or died due to some other
3653 signal, assume the child caught the SIGINT. */
3654 if (wait_sigint_received
&& (WIFSIGNALED (status
) == 0 || WTERMSIG (status
) != SIGINT
))
3655 child_caught_sigint
= 1;
3657 /* If the child process did die due to SIGINT, forget our assumption
3658 that it caught or otherwise handled it. */
3659 if (WIFSIGNALED (status
) && WTERMSIG (status
) == SIGINT
)
3660 child_caught_sigint
= 0;
3662 /* children_exited is used to run traps on SIGCHLD. We don't want to
3663 run the trap if a process is just being continued. */
3664 if (WIFCONTINUED(status
) == 0)
3670 /* Locate our PROCESS for this pid. */
3671 child
= find_process (pid
, 1, &job
); /* want living procs only */
3673 #if defined (COPROCESS_SUPPORT)
3674 coproc_pidchk (pid
, WSTATUS(status
));
3677 #if defined (PROCESS_SUBSTITUTION)
3678 /* Only manipulate the list of process substitutions while SIGCHLD
3680 if ((ind
= find_procsub_child (pid
)) >= 0)
3681 set_procsub_status (ind
, pid
, WSTATUS (status
));
3682 /* XXX - save in bgpids list? */
3685 /* It is not an error to have a child terminate that we did
3686 not have a record of. This child could have been part of
3687 a pipeline in backquote substitution. Even so, I'm not
3688 sure child is ever non-zero. */
3691 if (WIFEXITED (status
) || WIFSIGNALED (status
))
3696 /* Remember status, and whether or not the process is running. */
3697 child
->status
= status
;
3698 child
->running
= WIFCONTINUED(status
) ? PS_RUNNING
: PS_DONE
;
3700 if (PEXITED (child
))
3710 call_set_current
+= set_job_status_and_cleanup (job
);
3713 last_stopped_job
= job
;
3714 else if (DEADJOB (job
) && last_stopped_job
== job
)
3715 last_stopped_job
= NO_JOB
;
3717 while ((sigchld
|| block
== 0) && pid
> (pid_t
)0);
3719 /* If a job was running and became stopped, then set the current
3720 job. Otherwise, don't change a thing. */
3721 if (call_set_current
)
3723 if (last_stopped_job
!= NO_JOB
)
3724 set_current_job (last_stopped_job
);
3729 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3730 if (children_exited
&&
3731 (signal_is_trapped (SIGCHLD
) || trap_list
[SIGCHLD
] == (char *)IMPOSSIBLE_TRAP_HANDLER
) &&
3732 trap_list
[SIGCHLD
] != (char *)IGNORE_SIG
)
3734 if (posixly_correct
&& this_shell_builtin
&& this_shell_builtin
== wait_builtin
)
3736 interrupt_immediately
= 0;
3737 /* This was trap_handler (SIGCHLD) but that can lose traps if
3738 children_exited > 1 */
3739 queue_sigchld_trap (children_exited
);
3740 wait_signal_received
= SIGCHLD
;
3741 /* If we're in a signal handler, let CHECK_WAIT_INTR pick it up;
3742 run_pending_traps will call run_sigchld_trap later */
3743 if (sigchld
== 0 && wait_intr_flag
)
3744 sh_longjmp (wait_intr_buf
, 1);
3746 /* If not in posix mode and not executing the wait builtin, queue the
3747 signal for later handling. Run the trap immediately if we are
3748 executing the wait builtin, but don't break out of `wait'. */
3749 else if (sigchld
) /* called from signal handler */
3750 queue_sigchld_trap (children_exited
);
3751 else if (signal_in_progress (SIGCHLD
))
3752 queue_sigchld_trap (children_exited
);
3753 else if (trap_list
[SIGCHLD
] == (char *)IMPOSSIBLE_TRAP_HANDLER
)
3754 queue_sigchld_trap (children_exited
);
3755 else if (running_trap
)
3756 queue_sigchld_trap (children_exited
);
3757 else if (this_shell_builtin
== wait_builtin
)
3758 run_sigchld_trap (children_exited
); /* XXX */
3760 queue_sigchld_trap (children_exited
);
3763 /* We have successfully recorded the useful information about this process
3764 that has just changed state. If we notify asynchronously, and the job
3765 that this process belongs to is no longer running, then notify the user
3766 of that fact now. */
3767 if (asynchronous_notification
&& interactive
)
3768 notify_of_job_status ();
3770 return (children_exited
);
3773 /* Set the status of JOB and perform any necessary cleanup if the job is
3776 Currently, the cleanup activity is restricted to handling any SIGINT
3777 received while waiting for a foreground job to finish. */
3779 set_job_status_and_cleanup (job
)
3783 int tstatus
, job_state
, any_stopped
, any_tstped
, call_set_current
;
3784 SigHandler
*temp_handler
;
3786 child
= jobs
[job
]->pipe
;
3787 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3789 call_set_current
= 0;
3792 * COMPUTE JOB STATUS
3795 /* If all children are not running, but any of them is stopped, then
3796 the job is stopped, not dead. */
3797 job_state
= any_stopped
= any_tstped
= 0;
3800 job_state
|= PRUNNING (child
);
3802 if (PEXITED (child
) && (WIFSTOPPED (child
->status
)))
3804 /* Only checking for WIFSTOPPED now, not for PS_DONE */
3805 if (PSTOPPED (child
))
3809 any_tstped
|= job_control
&& (WSTOPSIG (child
->status
) == SIGTSTP
);
3811 child
= child
->next
;
3813 while (child
!= jobs
[job
]->pipe
);
3815 /* If job_state != 0, the job is still running, so don't bother with
3816 setting the process exit status and job state unless we're
3817 transitioning from stopped to running. */
3818 if (job_state
!= 0 && JOBSTATE(job
) != JSTOPPED
)
3825 /* The job is either stopped or dead. Set the state of the job accordingly. */
3828 jobs
[job
]->state
= JSTOPPED
;
3829 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3831 /* Suspending a job with SIGTSTP breaks all active loops. */
3832 if (any_tstped
&& loop_level
)
3833 breaking
= loop_level
;
3835 else if (job_state
!= 0) /* was stopped, now running */
3837 jobs
[job
]->state
= JRUNNING
;
3842 jobs
[job
]->state
= JDEAD
;
3846 if (IS_FOREGROUND (job
))
3850 /* If this job has a cleanup function associated with it, call it
3851 with `cleanarg' as the single argument, then set the function
3852 pointer to NULL so it is not inadvertently called twice. The
3853 cleanup function is responsible for deallocating cleanarg. */
3854 if (jobs
[job
]->j_cleanup
)
3856 (*jobs
[job
]->j_cleanup
) (jobs
[job
]->cleanarg
);
3857 jobs
[job
]->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
3864 * Currently, we just do special things if we got a SIGINT while waiting
3865 * for a foreground job to complete
3868 if (JOBSTATE (job
) == JDEAD
)
3870 /* If we're running a shell script and we get a SIGINT with a
3871 SIGINT trap handler, but the foreground job handles it and
3872 does not exit due to SIGINT, run the trap handler but do not
3873 otherwise act as if we got the interrupt. */
3874 if (wait_sigint_received
&& interactive_shell
== 0 &&
3875 child_caught_sigint
&& IS_FOREGROUND (job
) &&
3876 signal_is_trapped (SIGINT
))
3879 wait_sigint_received
= 0;
3880 last_command_exit_value
= process_exit_status (child
->status
);
3882 old_frozen
= jobs_list_frozen
;
3883 jobs_list_frozen
= 1;
3884 tstatus
= maybe_call_trap_handler (SIGINT
);
3885 jobs_list_frozen
= old_frozen
;
3888 /* If the foreground job is killed by SIGINT when job control is not
3889 active, we need to perform some special handling.
3891 The check of wait_sigint_received is a way to determine if the
3892 SIGINT came from the keyboard (in which case the shell has already
3893 seen it, and wait_sigint_received is non-zero, because keyboard
3894 signals are sent to process groups) or via kill(2) to the foreground
3895 process by another process (or itself). If the shell did receive the
3896 SIGINT, it needs to perform normal SIGINT processing. XXX - should
3897 this change its behavior depending on whether the last command in an
3898 pipeline exited due to SIGINT, or any process in the pipeline? Right
3899 now it does this if any process in the pipeline exits due to SIGINT. */
3900 else if (wait_sigint_received
&&
3901 child_caught_sigint
== 0 &&
3902 IS_FOREGROUND (job
) && IS_JOBCONTROL (job
) == 0)
3906 wait_sigint_received
= 0;
3908 /* If SIGINT is trapped, set the exit status so that the trap
3909 handler can see it. */
3910 if (signal_is_trapped (SIGINT
))
3911 last_command_exit_value
= process_exit_status (child
->status
);
3913 /* If the signal is trapped, let the trap handler get it no matter
3914 what and simply return if the trap handler returns.
3915 maybe_call_trap_handler() may cause dead jobs to be removed from
3916 the job table because of a call to execute_command. We work
3917 around this by setting JOBS_LIST_FROZEN. */
3918 old_frozen
= jobs_list_frozen
;
3919 jobs_list_frozen
= 1;
3920 tstatus
= maybe_call_trap_handler (SIGINT
);
3921 jobs_list_frozen
= old_frozen
;
3922 if (tstatus
== 0 && old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
3924 /* wait_sigint_handler () has already seen SIGINT and
3925 allowed the wait builtin to jump out. We need to
3926 call the original SIGINT handler, if necessary. If
3927 the original handler is SIG_DFL, we need to resend
3928 the signal to ourselves. */
3930 temp_handler
= old_sigint_handler
;
3932 /* Bogus. If we've reset the signal handler as the result
3933 of a trap caught on SIGINT, then old_sigint_handler
3934 will point to trap_handler, which now knows nothing about
3935 SIGINT (if we reset the sighandler to the default).
3936 In this case, we have to fix things up. What a crock. */
3937 if (temp_handler
== trap_handler
&& signal_is_trapped (SIGINT
) == 0)
3938 temp_handler
= trap_to_sighandler (SIGINT
);
3939 restore_sigint_handler ();
3940 if (temp_handler
== SIG_DFL
)
3941 termsig_handler (SIGINT
); /* XXX */
3942 else if (temp_handler
!= SIG_IGN
)
3943 (*temp_handler
) (SIGINT
);
3948 return call_set_current
;
3951 /* Build the array of values for the $PIPESTATUS variable from the set of
3952 exit statuses of all processes in the job J. */
3957 #if defined (ARRAY_VARS)
3959 register PROCESS
*p
;
3961 for (i
= 1, p
= jobs
[j
]->pipe
; p
->next
!= jobs
[j
]->pipe
; p
= p
->next
, i
++)
3966 pstatuses
= (int *)xrealloc (pstatuses
, i
* sizeof (int));
3973 pstatuses
[i
++] = process_exit_status (p
->status
);
3976 while (p
!= jobs
[j
]->pipe
);
3978 pstatuses
[i
] = -1; /* sentinel */
3979 set_pipestatus_array (pstatuses
, i
);
3984 run_sigchld_trap (nchild
)
3990 /* Turn off the trap list during the call to parse_and_execute ()
3991 to avoid potentially infinite recursive calls. Preserve the
3992 values of last_command_exit_value, last_made_pid, and the_pipeline
3993 around the execution of the trap commands. */
3994 trap_command
= savestring (trap_list
[SIGCHLD
]);
3996 begin_unwind_frame ("SIGCHLD trap");
3997 unwind_protect_int (last_command_exit_value
);
3998 unwind_protect_int (last_command_exit_signal
);
3999 unwind_protect_var (last_made_pid
);
4000 unwind_protect_int (interrupt_immediately
);
4001 unwind_protect_int (jobs_list_frozen
);
4002 unwind_protect_pointer (the_pipeline
);
4003 unwind_protect_pointer (subst_assign_varlist
);
4004 unwind_protect_pointer (this_shell_builtin
);
4005 unwind_protect_pointer (temporary_env
);
4007 /* We have to add the commands this way because they will be run
4008 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
4009 to reference freed memory. */
4010 add_unwind_protect (xfree
, trap_command
);
4011 add_unwind_protect (maybe_set_sigchld_trap
, trap_command
);
4013 subst_assign_varlist
= (WORD_LIST
*)NULL
;
4014 the_pipeline
= (PROCESS
*)NULL
;
4015 temporary_env
= 0; /* traps should not run with temporary env */
4017 running_trap
= SIGCHLD
+ 1;
4019 set_impossible_sigchld_trap ();
4020 jobs_list_frozen
= 1;
4021 for (i
= 0; i
< nchild
; i
++)
4024 interrupt_immediately
= 1;
4026 parse_and_execute (savestring (trap_command
), "trap", SEVAL_NOHIST
|SEVAL_RESETLINE
);
4029 run_unwind_frame ("SIGCHLD trap");
4033 /* Function to call when you want to notify people of changes
4034 in job status. This prints out all jobs which are pending
4035 notification to stderr, and marks those printed as already
4036 notified, thus making them candidates for cleanup. */
4038 notify_of_job_status ()
4040 register int job
, termsig
;
4045 if (jobs
== 0 || js
.j_jobslots
== 0)
4051 sigaddset (&set
, SIGCHLD
);
4052 sigaddset (&set
, SIGTTOU
);
4053 sigemptyset (&oset
);
4054 sigprocmask (SIG_BLOCK
, &set
, &oset
);
4059 /* XXX could use js.j_firstj here */
4060 for (job
= 0, dir
= (char *)NULL
; job
< js
.j_jobslots
; job
++)
4062 if (jobs
[job
] && IS_NOTIFIED (job
) == 0)
4064 s
= raw_job_exit_status (job
);
4065 termsig
= WTERMSIG (s
);
4067 /* POSIX.2 says we have to hang onto the statuses of at most the
4068 last CHILD_MAX background processes if the shell is running a
4069 script. If the shell is running a script, either from a file
4070 or standard input, don't print anything unless the job was
4071 killed by a signal. */
4072 if (startup_state
== 0 && WIFSIGNALED (s
) == 0 &&
4073 ((DEADJOB (job
) && IS_FOREGROUND (job
) == 0) || STOPPED (job
)))
4076 /* If job control is disabled, don't print the status messages.
4077 Mark dead jobs as notified so that they get cleaned up. If
4078 startup_state == 2 and subshell_environment has the
4079 SUBSHELL_COMSUB bit turned on, we were started to run a command
4080 substitution, so don't print anything.
4081 Otherwise, if the shell is not interactive, POSIX says that `jobs'
4082 is the only way to notify of job status. */
4084 if ((job_control
== 0 && interactive_shell
) ||
4085 (startup_state
== 2 && (subshell_environment
& SUBSHELL_COMSUB
)))
4086 #else /* TAG:bash-5.1 */
4087 if ((job_control
== 0 && interactive_shell
) ||
4088 (startup_state
== 2 && (subshell_environment
& SUBSHELL_COMSUB
)) ||
4089 (startup_state
== 2 && posixly_correct
&& (subshell_environment
& SUBSHELL_COMSUB
) == 0))
4092 /* POSIX.2 compatibility: if the shell is not interactive,
4093 hang onto the job corresponding to the last asynchronous
4094 pid until the user has been notified of its status or does
4096 if (DEADJOB (job
) && (interactive_shell
|| (find_last_pid (job
, 0) != last_asynchronous_pid
)))
4097 jobs
[job
]->flags
|= J_NOTIFIED
;
4101 /* Print info on jobs that are running in the background,
4102 and on foreground jobs that were killed by anything
4103 except SIGINT (and possibly SIGPIPE). */
4104 switch (JOBSTATE (job
))
4107 if (interactive_shell
== 0 && termsig
&& WIFSIGNALED (s
) &&
4108 termsig
!= SIGINT
&&
4109 #if defined (DONT_REPORT_SIGTERM)
4110 termsig
!= SIGTERM
&&
4112 #if defined (DONT_REPORT_SIGPIPE)
4113 termsig
!= SIGPIPE
&&
4115 signal_is_trapped (termsig
) == 0)
4117 /* Don't print `0' for a line number. */
4118 fprintf (stderr
, _("%s: line %d: "), get_name_for_error (), (line_number
== 0) ? 1 : line_number
);
4119 pretty_print_job (job
, JLIST_NONINTERACTIVE
, stderr
);
4121 else if (IS_FOREGROUND (job
))
4123 #if !defined (DONT_REPORT_SIGPIPE)
4124 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
)
4126 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
&& termsig
!= SIGPIPE
)
4129 fprintf (stderr
, "%s", j_strsignal (termsig
));
4132 fprintf (stderr
, _(" (core dumped)"));
4134 fprintf (stderr
, "\n");
4137 else if (job_control
) /* XXX job control test added */
4140 dir
= current_working_directory ();
4141 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
4142 if (dir
&& strcmp (dir
, jobs
[job
]->wd
) != 0)
4144 _("(wd now: %s)\n"), polite_directory_format (dir
));
4147 jobs
[job
]->flags
|= J_NOTIFIED
;
4151 fprintf (stderr
, "\n");
4153 dir
= current_working_directory ();
4154 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
4155 if (dir
&& (strcmp (dir
, jobs
[job
]->wd
) != 0))
4157 _("(wd now: %s)\n"), polite_directory_format (dir
));
4158 jobs
[job
]->flags
|= J_NOTIFIED
;
4166 programming_error ("notify_of_job_status");
4171 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
4176 /* Initialize the job control mechanism, and set up the tty stuff. */
4178 initialize_job_control (force
)
4182 int t_errno
, tty_sigs
;
4185 shell_pgrp
= getpgid (0);
4187 if (shell_pgrp
== -1)
4189 sys_error (_("initialize_job_control: getpgrp failed"));
4193 /* We can only have job control if we are interactive unless we force it. */
4194 if (interactive
== 0 && force
== 0)
4197 original_pgrp
= NO_PID
;
4198 shell_tty
= fileno (stderr
);
4199 terminal_pgrp
= tcgetpgrp (shell_tty
); /* for checking later */
4205 /* If forced_interactive is set, we skip the normal check that stderr
4206 is attached to a tty, so we need to check here. If it's not, we
4207 need to see whether we have a controlling tty by opening /dev/tty,
4208 since trying to use job control tty pgrp manipulations on a non-tty
4209 is going to fail. */
4210 if (forced_interactive
&& isatty (fileno (stderr
)) == 0)
4211 shell_tty
= open ("/dev/tty", O_RDWR
|O_NONBLOCK
);
4213 /* Get our controlling terminal. If job_control is set, or
4214 interactive is set, then this is an interactive shell no
4215 matter where fd 2 is directed. */
4216 if (shell_tty
== -1)
4217 shell_tty
= dup (fileno (stderr
)); /* fd 2 */
4219 if (shell_tty
!= -1)
4220 shell_tty
= move_to_high_fd (shell_tty
, 1, -1);
4222 /* Compensate for a bug in systems that compiled the BSD
4223 rlogind with DEBUG defined, like NeXT and Alliant. */
4224 if (shell_pgrp
== 0)
4226 shell_pgrp
= getpid ();
4227 setpgid (0, shell_pgrp
);
4228 if (shell_tty
!= -1)
4229 tcsetpgrp (shell_tty
, shell_pgrp
);
4233 while ((terminal_pgrp
= tcgetpgrp (shell_tty
)) != -1)
4235 if (shell_pgrp
!= terminal_pgrp
)
4240 ottin
= set_signal_handler (SIGTTIN
, SIG_DFL
);
4242 set_signal_handler (SIGTTIN
, ottin
);
4243 if (tty_sigs
++ > 16)
4245 sys_error (_("initialize_job_control: no job control in background"));
4247 original_pgrp
= terminal_pgrp
; /* for eventual give_terminal_to */
4255 if (terminal_pgrp
== -1)
4258 /* Make sure that we are using the new line discipline. */
4259 if (set_new_line_discipline (shell_tty
) < 0)
4261 sys_error (_("initialize_job_control: line discipline"));
4266 original_pgrp
= shell_pgrp
;
4267 shell_pgrp
= getpid ();
4269 if ((original_pgrp
!= shell_pgrp
) && (setpgid (0, shell_pgrp
) < 0))
4271 sys_error (_("initialize_job_control: setpgid"));
4272 shell_pgrp
= original_pgrp
;
4277 /* If (and only if) we just set our process group to our pid,
4278 thereby becoming a process group leader, and the terminal
4279 is not in the same process group as our (new) process group,
4280 then set the terminal's process group to our (new) process
4281 group. If that fails, set our process group back to what it
4282 was originally (so we can still read from the terminal) and
4283 turn off job control. */
4284 if (shell_pgrp
!= original_pgrp
&& shell_pgrp
!= terminal_pgrp
)
4286 if (give_terminal_to (shell_pgrp
, 0) < 0)
4289 setpgid (0, original_pgrp
);
4290 shell_pgrp
= original_pgrp
;
4292 sys_error (_("cannot set terminal process group (%d)"), shell_pgrp
);
4297 if (job_control
&& ((t
= tcgetpgrp (shell_tty
)) == -1 || t
!= shell_pgrp
))
4301 sys_error (_("cannot set terminal process group (%d)"), t
);
4305 if (job_control
== 0)
4306 internal_error (_("no job control in this shell"));
4310 running_in_background
= terminal_pgrp
!= shell_pgrp
;
4312 if (shell_tty
!= fileno (stderr
))
4313 SET_CLOSE_ON_EXEC (shell_tty
);
4315 set_signal_handler (SIGCHLD
, sigchld_handler
);
4317 change_flag ('m', job_control
? '-' : '+');
4322 if (js
.c_childmax
< 0)
4323 js
.c_childmax
= getmaxchild ();
4324 if (js
.c_childmax
< 0)
4325 js
.c_childmax
= DEFAULT_CHILD_MAX
;
4328 if (js
.c_childmax
> MAX_CHILD_MAX
)
4329 js
.c_childmax
= MAX_CHILD_MAX
;
4337 debug_print_pgrps ()
4339 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
4340 (long)original_pgrp
, (long)shell_pgrp
, (long)terminal_pgrp
);
4341 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
4342 shell_tty
, (long)tcgetpgrp (shell_tty
), (long)getpgid(0));
4346 /* Set the line discipline to the best this system has to offer.
4347 Return -1 if this is not possible. */
4349 set_new_line_discipline (tty
)
4352 #if defined (NEW_TTY_DRIVER)
4355 if (ioctl (tty
, TIOCGETD
, &ldisc
) < 0)
4358 if (ldisc
!= NTTYDISC
)
4362 if (ioctl (tty
, TIOCSETD
, &ldisc
) < 0)
4366 #endif /* NEW_TTY_DRIVER */
4368 #if defined (TERMIO_TTY_DRIVER)
4369 # if defined (TERMIO_LDISC) && (NTTYDISC)
4370 if (ioctl (tty
, TCGETA
, &shell_tty_info
) < 0)
4373 if (shell_tty_info
.c_line
!= NTTYDISC
)
4375 shell_tty_info
.c_line
= NTTYDISC
;
4376 if (ioctl (tty
, TCSETAW
, &shell_tty_info
) < 0)
4379 # endif /* TERMIO_LDISC && NTTYDISC */
4381 #endif /* TERMIO_TTY_DRIVER */
4383 #if defined (TERMIOS_TTY_DRIVER)
4384 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
4385 if (tcgetattr (tty
, &shell_tty_info
) < 0)
4388 if (shell_tty_info
.c_line
!= NTTYDISC
)
4390 shell_tty_info
.c_line
= NTTYDISC
;
4391 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
4394 # endif /* TERMIOS_LDISC && NTTYDISC */
4396 #endif /* TERMIOS_TTY_DRIVER */
4398 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
4403 /* Setup this shell to handle C-C, etc. */
4405 initialize_job_signals ()
4409 set_signal_handler (SIGINT
, sigint_sighandler
);
4410 set_signal_handler (SIGTSTP
, SIG_IGN
);
4411 set_signal_handler (SIGTTOU
, SIG_IGN
);
4412 set_signal_handler (SIGTTIN
, SIG_IGN
);
4414 else if (job_control
)
4416 old_tstp
= set_signal_handler (SIGTSTP
, sigstop_sighandler
);
4417 old_ttin
= set_signal_handler (SIGTTIN
, sigstop_sighandler
);
4418 old_ttou
= set_signal_handler (SIGTTOU
, sigstop_sighandler
);
4420 /* Leave disposition unmodified for non-interactive shells without job
4424 /* Here we handle CONT signals. */
4426 sigcont_sighandler (sig
)
4429 initialize_job_signals ();
4430 set_signal_handler (SIGCONT
, old_cont
);
4431 kill (getpid (), SIGCONT
);
4436 /* Here we handle stop signals while we are running not as a login shell. */
4438 sigstop_sighandler (sig
)
4441 set_signal_handler (SIGTSTP
, old_tstp
);
4442 set_signal_handler (SIGTTOU
, old_ttou
);
4443 set_signal_handler (SIGTTIN
, old_ttin
);
4445 old_cont
= set_signal_handler (SIGCONT
, sigcont_sighandler
);
4447 give_terminal_to (shell_pgrp
, 0);
4449 kill (getpid (), sig
);
4454 /* Give the terminal to PGRP. */
4456 give_terminal_to (pgrp
, force
)
4464 if (job_control
|| force
)
4467 sigaddset (&set
, SIGTTOU
);
4468 sigaddset (&set
, SIGTTIN
);
4469 sigaddset (&set
, SIGTSTP
);
4470 sigaddset (&set
, SIGCHLD
);
4471 sigemptyset (&oset
);
4472 sigprocmask (SIG_BLOCK
, &set
, &oset
);
4474 if (tcsetpgrp (shell_tty
, pgrp
) < 0)
4476 /* Maybe we should print an error message? */
4478 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
4479 shell_tty
, (long)getpid(), (long)pgrp
);
4485 terminal_pgrp
= pgrp
;
4486 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
4495 /* Give terminal to NPGRP iff it's currently owned by OPGRP. FLAGS are the
4496 flags to pass to give_terminal_to(). */
4498 maybe_give_terminal_to (opgrp
, npgrp
, flags
)
4504 tpgrp
= tcgetpgrp (shell_tty
);
4505 if (tpgrp
< 0 && errno
== ENOTTY
)
4509 terminal_pgrp
= npgrp
;
4512 else if (tpgrp
!= opgrp
)
4515 internal_warning ("%d: maybe_give_terminal_to: terminal pgrp == %d shell pgrp = %d new pgrp = %d in_background = %d", (int)getpid(), tpgrp
, opgrp
, npgrp
, running_in_background
);
4520 return (give_terminal_to (npgrp
, flags
));
4523 /* Clear out any jobs in the job array. This is intended to be used by
4524 children of the shell, who should not have any job structures as baggage
4525 when they start executing (forking subshells for parenthesized execution
4526 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
4527 is nonzero, only running jobs are removed from the table. */
4529 delete_all_jobs (running_only
)
4535 BLOCK_CHILD (set
, oset
);
4537 /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
4540 js
.j_current
= js
.j_previous
= NO_JOB
;
4542 /* XXX could use js.j_firstj here */
4543 for (i
= 0; i
< js
.j_jobslots
; i
++)
4546 if (i
< js
.j_firstj
&& jobs
[i
])
4547 itrace("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4548 if (i
> js
.j_lastj
&& jobs
[i
])
4549 itrace("delete_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4551 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
4552 /* We don't want to add any of these pids to bgpids. If running_only
4553 is non-zero, we don't want to add running jobs to the list.
4554 If we are interested in all jobs, not just running jobs, and
4555 we are going to clear the bgpids list below (bgp_clear()), we
4556 don't need to bother. */
4557 delete_job (i
, DEL_WARNSTOPPED
|DEL_NOBGPID
);
4559 if (running_only
== 0)
4561 free ((char *)jobs
);
4563 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
4567 if (running_only
== 0)
4570 UNBLOCK_CHILD (oset
);
4573 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
4574 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
4576 nohup_all_jobs (running_only
)
4582 BLOCK_CHILD (set
, oset
);
4586 /* XXX could use js.j_firstj here */
4587 for (i
= 0; i
< js
.j_jobslots
; i
++)
4588 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
4592 UNBLOCK_CHILD (oset
);
4601 /* This really counts all non-dead jobs. */
4602 BLOCK_CHILD (set
, oset
);
4603 /* XXX could use js.j_firstj here */
4604 for (i
= n
= 0; i
< js
.j_jobslots
; i
++)
4607 if (i
< js
.j_firstj
&& jobs
[i
])
4608 itrace("count_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4609 if (i
> js
.j_lastj
&& jobs
[i
])
4610 itrace("count_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4612 if (jobs
[i
] && DEADJOB(i
) == 0)
4615 UNBLOCK_CHILD (oset
);
4620 mark_all_jobs_as_dead ()
4625 if (js
.j_jobslots
== 0)
4628 BLOCK_CHILD (set
, oset
);
4630 /* XXX could use js.j_firstj here */
4631 for (i
= 0; i
< js
.j_jobslots
; i
++)
4634 jobs
[i
]->state
= JDEAD
;
4638 UNBLOCK_CHILD (oset
);
4641 /* Mark all dead jobs as notified, so delete_job () cleans them out
4642 of the job table properly. POSIX.2 says we need to save the
4643 status of the last CHILD_MAX jobs, so we count the number of dead
4644 jobs and mark only enough as notified to save CHILD_MAX statuses. */
4646 mark_dead_jobs_as_notified (force
)
4649 register int i
, ndead
, ndeadproc
;
4652 if (js
.j_jobslots
== 0)
4655 BLOCK_CHILD (set
, oset
);
4657 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
4658 around; just run through the array. */
4661 /* XXX could use js.j_firstj here */
4662 for (i
= 0; i
< js
.j_jobslots
; i
++)
4664 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4665 jobs
[i
]->flags
|= J_NOTIFIED
;
4667 UNBLOCK_CHILD (oset
);
4671 /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
4672 array with the corresponding not marked as notified. This is a better
4673 way to avoid pid aliasing and reuse problems than keeping the POSIX-
4674 mandated CHILD_MAX jobs around. delete_job() takes care of keeping the
4675 bgpids list regulated. */
4677 /* Count the number of dead jobs */
4678 /* XXX could use js.j_firstj here */
4679 for (i
= ndead
= ndeadproc
= 0; i
< js
.j_jobslots
; i
++)
4682 if (i
< js
.j_firstj
&& jobs
[i
])
4683 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4684 if (i
> js
.j_lastj
&& jobs
[i
])
4685 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4687 if (jobs
[i
] && DEADJOB (i
))
4690 ndeadproc
+= processes_in_job (i
);
4696 if (ndeadproc
!= js
.c_reaped
)
4697 itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc
, js
.c_reaped
);
4699 if (ndead
!= js
.j_ndead
)
4700 itrace("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead
, js
.j_ndead
);
4703 if (js
.c_childmax
< 0)
4704 js
.c_childmax
= getmaxchild ();
4705 if (js
.c_childmax
< 0)
4706 js
.c_childmax
= DEFAULT_CHILD_MAX
;
4709 if (js
.c_childmax
> MAX_CHILD_MAX
)
4710 js
.c_childmax
= MAX_CHILD_MAX
;
4713 /* Don't do anything if the number of dead processes is less than CHILD_MAX
4714 and we're not forcing a cleanup. */
4715 if (ndeadproc
<= js
.c_childmax
)
4717 UNBLOCK_CHILD (oset
);
4722 itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js
.c_childmax
, ndead
, ndeadproc
);
4725 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
4726 the list. This isn't exactly right yet; changes need to be made
4727 to stop_pipeline so we don't mark the newer jobs after we've
4728 created CHILD_MAX slots in the jobs array. This needs to be
4729 integrated with a way to keep the jobs array from growing without
4730 bound. Maybe we wrap back around to 0 after we reach some max
4731 limit, and there are sufficient job slots free (keep track of total
4732 size of jobs array (js.j_jobslots) and running count of number of jobs
4733 in jobs array. Then keep a job index corresponding to the `oldest job'
4734 and start this loop there, wrapping around as necessary. In effect,
4735 we turn the list into a circular buffer. */
4736 /* XXX could use js.j_firstj here */
4737 for (i
= 0; i
< js
.j_jobslots
; i
++)
4739 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4742 if (i
< js
.j_firstj
&& jobs
[i
])
4743 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4744 if (i
> js
.j_lastj
&& jobs
[i
])
4745 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4747 /* If marking this job as notified would drop us down below
4748 child_max, don't mark it so we can keep at least child_max
4749 statuses. XXX -- need to check what Posix actually says
4750 about keeping statuses. */
4751 if ((ndeadproc
-= processes_in_job (i
)) <= js
.c_childmax
)
4753 jobs
[i
]->flags
|= J_NOTIFIED
;
4757 UNBLOCK_CHILD (oset
);
4760 /* Here to allow other parts of the shell (like the trap stuff) to
4761 freeze and unfreeze the jobs list. */
4767 o
= jobs_list_frozen
;
4768 jobs_list_frozen
= 1;
4773 unfreeze_jobs_list ()
4775 jobs_list_frozen
= 0;
4779 set_jobs_list_frozen (s
)
4782 jobs_list_frozen
= s
;
4785 /* Allow or disallow job control to take place. Returns the old value
4788 set_job_control (arg
)
4796 if (terminal_pgrp
== NO_PID
)
4797 terminal_pgrp
= tcgetpgrp (shell_tty
);
4799 running_in_background
= (terminal_pgrp
!= shell_pgrp
);
4802 if (interactive_shell
== 0 && running_in_background
== 0 && job_control
!= old
)
4805 initialize_job_signals ();
4807 default_tty_job_signals ();
4811 /* If we're turning on job control, reset pipeline_pgrp so make_child will
4812 put new child processes into the right pgrp */
4813 if (job_control
!= old
&& job_control
)
4819 /* Turn off all traces of job control. This is run by children of the shell
4820 which are going to do shellsy things, like wait (), etc. */
4822 without_job_control ()
4824 stop_making_children ();
4826 #if defined (PGRP_PIPE)
4827 sh_closepipe (pgrp_pipe
);
4829 delete_all_jobs (0);
4830 set_job_control (0);
4833 /* If this shell is interactive, terminate all stopped jobs and
4834 restore the original terminal process group. This is done
4835 before the `exec' builtin calls shell_execve. */
4840 terminate_stopped_jobs ();
4842 if (original_pgrp
>= 0 && terminal_pgrp
!= original_pgrp
)
4843 give_terminal_to (original_pgrp
, 1);
4845 if (original_pgrp
>= 0 && setpgid (0, original_pgrp
) == 0)
4846 shell_pgrp
= original_pgrp
;
4849 /* Restart job control by closing shell tty and reinitializing. This is
4850 called after an exec fails in an interactive shell and we do not exit. */
4852 restart_job_control ()
4854 if (shell_tty
!= -1)
4856 initialize_job_control (0);
4860 set_maxchild (nchild
)
4863 static int lmaxchild
= -1;
4866 lmaxchild
= getmaxchild ();
4868 lmaxchild
= DEFAULT_CHILD_MAX
;
4870 /* Clamp value we set. Minimum is what Posix requires, maximum is defined
4871 above as MAX_CHILD_MAX. */
4872 if (nchild
< lmaxchild
)
4874 else if (nchild
> MAX_CHILD_MAX
)
4875 nchild
= MAX_CHILD_MAX
;
4877 js
.c_childmax
= nchild
;
4880 /* Set the handler to run when the shell receives a SIGCHLD signal. */
4882 set_sigchld_handler ()
4884 set_signal_handler (SIGCHLD
, sigchld_handler
);
4887 #if defined (PGRP_PIPE)
4888 /* Read from the read end of a pipe. This is how the process group leader
4889 blocks until all of the processes in a pipeline have been made. */
4904 while (read (pp
[0], &ch
, 1) == -1 && errno
== EINTR
)
4909 /* Functional interface closes our local-to-job-control pipes. */
4913 sh_closepipe (pgrp_pipe
);
4917 save_pgrp_pipe (p
, clear
)
4921 p
[0] = pgrp_pipe
[0];
4922 p
[1] = pgrp_pipe
[1];
4924 pgrp_pipe
[0] = pgrp_pipe
[1] = -1;
4928 restore_pgrp_pipe (p
)
4931 pgrp_pipe
[0] = p
[0];
4932 pgrp_pipe
[1] = p
[1];
4935 #endif /* PGRP_PIPE */