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-2011 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 #ifdef HAVE_SYS_PARAM_H
49 #include <sys/param.h>
52 #if defined (BUFFERED_INPUT)
56 /* Need to include this up here for *_TTY_DRIVER definitions. */
59 /* Define this if your output is getting swallowed. It's a no-op on
60 machines with the termio or termios tty drivers. */
61 /* #define DRAIN_OUTPUT */
63 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
64 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
66 #endif /* hpux && !TERMIOS_TTY_DRIVER */
72 #include "execute_cmd.h"
75 #include "builtins/builtext.h"
76 #include "builtins/common.h"
82 #if !defined (HAVE_KILLPG)
83 extern int killpg
__P((pid_t
, int));
86 #define DEFAULT_CHILD_MAX 32
88 #define MAX_JOBS_IN_ARRAY 4096 /* production */
90 #define MAX_JOBS_IN_ARRAY 128 /* testing */
93 /* Flag values for second argument to delete_job */
94 #define DEL_WARNSTOPPED 1 /* warn about deleting stopped jobs */
95 #define DEL_NOBGPID 2 /* don't add pgrp leader to bgpids */
97 /* Take care of system dependencies that must be handled when waiting for
98 children. The arguments to the WAITPID macro match those to the Posix.1
99 waitpid() function. */
101 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
102 # define WAITPID(pid, statusp, options) \
103 wait3 ((union wait *)statusp, options, (struct rusage *)0)
105 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
106 # define WAITPID(pid, statusp, options) \
107 waitpid ((pid_t)pid, statusp, options)
109 # if defined (HAVE_WAIT3)
110 # define WAITPID(pid, statusp, options) \
111 wait3 (statusp, options, (struct rusage *)0)
113 # define WAITPID(pid, statusp, options) \
114 wait3 (statusp, options, (int *)0)
115 # endif /* HAVE_WAIT3 */
116 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
117 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
119 /* getpgrp () varies between systems. Even systems that claim to be
120 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
121 #if defined (GETPGRP_VOID)
122 # define getpgid(p) getpgrp ()
124 # define getpgid(p) getpgrp (p)
125 #endif /* !GETPGRP_VOID */
127 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
128 handler for SIGCHLD. */
129 #if defined (MUST_REINSTALL_SIGHANDLERS)
130 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
132 # define REINSTALL_SIGCHLD_HANDLER
133 #endif /* !MUST_REINSTALL_SIGHANDLERS */
135 /* Some systems let waitpid(2) tell callers about stopped children. */
136 #if !defined (WCONTINUED) || defined (WCONTINUED_BROKEN)
138 # define WCONTINUED 0
140 #if !defined (WIFCONTINUED)
141 # define WIFCONTINUED(s) (0)
144 /* The number of additional slots to allocate when we run out. */
147 typedef int sh_job_map_func_t
__P((JOB
*, int, int, int));
149 /* Variables used here but defined in other files. */
150 extern int subshell_environment
, line_number
;
151 extern int posixly_correct
, shell_level
;
152 extern int last_command_exit_value
, last_command_exit_signal
;
153 extern int loop_level
, breaking
;
154 extern int executing_list
;
155 extern int sourcelevel
;
156 extern int running_trap
;
157 extern sh_builtin_func_t
*this_shell_builtin
;
158 extern char *shell_name
, *this_command_name
;
159 extern sigset_t top_level_mask
;
160 extern procenv_t wait_intr_buf
;
161 extern int wait_signal_received
;
162 extern WORD_LIST
*subst_assign_varlist
;
164 static struct jobstats zerojs
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
165 struct jobstats js
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
167 struct bgpids bgpids
= { 0, 0, 0 };
169 /* The array of known jobs. */
170 JOB
**jobs
= (JOB
**)NULL
;
173 /* The number of slots currently allocated to JOBS. */
177 /* The controlling tty for this shell. */
180 /* The shell's process group. */
181 pid_t shell_pgrp
= NO_PID
;
183 /* The terminal's process group. */
184 pid_t terminal_pgrp
= NO_PID
;
186 /* The process group of the shell's parent. */
187 pid_t original_pgrp
= NO_PID
;
189 /* The process group of the pipeline currently being made. */
190 pid_t pipeline_pgrp
= (pid_t
)0;
192 #if defined (PGRP_PIPE)
193 /* Pipes which each shell uses to communicate with the process group leader
194 until all of the processes in a pipeline have been started. Then the
195 process leader is allowed to continue. */
196 int pgrp_pipe
[2] = { -1, -1 };
200 /* The job which is current; i.e. the one that `%+' stands for. */
201 int current_job
= NO_JOB
;
203 /* The previous job; i.e. the one that `%-' stands for. */
204 int previous_job
= NO_JOB
;
207 /* Last child made by the shell. */
208 pid_t last_made_pid
= NO_PID
;
210 /* Pid of the last asynchronous child. */
211 pid_t last_asynchronous_pid
= NO_PID
;
213 /* The pipeline currently being built. */
214 PROCESS
*the_pipeline
= (PROCESS
*)NULL
;
216 /* If this is non-zero, do job control. */
219 /* Call this when you start making children. */
220 int already_making_children
= 0;
222 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
223 exits from get_tty_state(). */
224 int check_window_size
;
226 /* Functions local to this file. */
228 static sighandler wait_sigint_handler
__P((int));
229 static sighandler sigchld_handler
__P((int));
230 static sighandler sigcont_sighandler
__P((int));
231 static sighandler sigstop_sighandler
__P((int));
233 static int waitchld
__P((pid_t
, int));
235 static PROCESS
*find_pipeline
__P((pid_t
, int, int *));
236 static PROCESS
*find_process
__P((pid_t
, int, int *));
238 static char *current_working_directory
__P((void));
239 static char *job_working_directory
__P((void));
240 static char *j_strsignal
__P((int));
241 static char *printable_job_status
__P((int, PROCESS
*, int));
243 static PROCESS
*find_last_proc
__P((int, int));
244 static pid_t find_last_pid
__P((int, int));
246 static int set_new_line_discipline
__P((int));
247 static int map_over_jobs
__P((sh_job_map_func_t
*, int, int));
248 static int job_last_stopped
__P((int));
249 static int job_last_running
__P((int));
250 static int most_recent_job_in_state
__P((int, JOB_STATE
));
251 static int find_job
__P((pid_t
, int, PROCESS
**));
252 static int print_job
__P((JOB
*, int, int, int));
253 static int process_exit_status
__P((WAIT
));
254 static int process_exit_signal
__P((WAIT
));
255 static int set_job_status_and_cleanup
__P((int));
257 static WAIT job_signal_status
__P((int));
258 static WAIT raw_job_exit_status
__P((int));
260 static void notify_of_job_status
__P((void));
261 static void reset_job_indices
__P((void));
262 static void cleanup_dead_jobs
__P((void));
263 static int processes_in_job
__P((int));
264 static void realloc_jobs_list
__P((void));
265 static int compact_jobs_list
__P((int));
266 static int discard_pipeline
__P((PROCESS
*));
267 static void add_process
__P((char *, pid_t
));
268 static void print_pipeline
__P((PROCESS
*, int, int, FILE *));
269 static void pretty_print_job
__P((int, int, FILE *));
270 static void set_current_job
__P((int));
271 static void reset_current
__P((void));
272 static void set_job_running
__P((int));
273 static void setjstatus
__P((int));
274 static int maybe_give_terminal_to
__P((pid_t
, pid_t
, int));
275 static void mark_all_jobs_as_dead
__P((void));
276 static void mark_dead_jobs_as_notified
__P((int));
277 static void restore_sigint_handler
__P((void));
278 #if defined (PGRP_PIPE)
279 static void pipe_read
__P((int *));
282 static struct pidstat
*bgp_alloc
__P((pid_t
, int));
283 static struct pidstat
*bgp_add
__P((pid_t
, int));
284 static int bgp_delete
__P((pid_t
));
285 static void bgp_clear
__P((void));
286 static int bgp_search
__P((pid_t
));
287 static void bgp_prune
__P((void));
289 #if defined (ARRAY_VARS)
290 static int *pstatuses
; /* list of pipeline statuses */
294 /* Used to synchronize between wait_for and other functions and the SIGCHLD
297 static int queue_sigchld
;
299 #define QUEUE_SIGCHLD(os) (os) = sigchld, queue_sigchld++
301 #define UNQUEUE_SIGCHLD(os) \
304 if (queue_sigchld == 0 && os != sigchld) \
308 static SigHandler
*old_tstp
, *old_ttou
, *old_ttin
;
309 static SigHandler
*old_cont
= (SigHandler
*)SIG_DFL
;
311 /* A place to temporarily save the current pipeline. */
312 static PROCESS
*saved_pipeline
;
313 static int saved_already_making_children
;
315 /* Set this to non-zero whenever you don't want the jobs list to change at
316 all: no jobs deleted and no status change notifications. This is used,
317 for example, when executing SIGCHLD traps, which may run arbitrary
319 static int jobs_list_frozen
;
321 static char retcode_name_buffer
[64];
323 /* flags to detect pid wraparound */
324 static pid_t first_pid
= NO_PID
;
325 static int pid_wrap
= -1;
327 #if !defined (_POSIX_VERSION)
329 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
330 library functions and system calls. */
331 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
332 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
340 /* ioctl will handle setting errno correctly. */
341 if (ioctl (fd
, TIOCGPGRP
, &pgrp
) < 0)
346 #endif /* !_POSIX_VERSION */
348 /* Initialize the global job stats structure and other bookkeeping variables */
357 /* Return the working directory for the current process. Unlike
358 job_working_directory, this does not call malloc (), nor do any
359 of the functions it calls. This is so that it can safely be called
360 from a signal handler. */
362 current_working_directory ()
365 static char d
[PATH_MAX
];
367 dir
= get_string_value ("PWD");
369 if (dir
== 0 && the_current_working_directory
&& no_symbolic_links
)
370 dir
= the_current_working_directory
;
374 dir
= getcwd (d
, sizeof(d
));
379 return (dir
== 0) ? "<unknown>" : dir
;
382 /* Return the working directory for the current process. */
384 job_working_directory ()
388 dir
= get_string_value ("PWD");
390 return (savestring (dir
));
392 dir
= get_working_directory ("job-working-directory");
396 return (savestring ("<unknown>"));
402 if (already_making_children
)
405 already_making_children
= 1;
410 stop_making_children ()
412 already_making_children
= 0;
416 cleanup_the_pipeline ()
421 BLOCK_CHILD (set
, oset
);
422 disposer
= the_pipeline
;
423 the_pipeline
= (PROCESS
*)NULL
;
424 UNBLOCK_CHILD (oset
);
427 discard_pipeline (disposer
);
431 save_pipeline (clear
)
434 saved_pipeline
= the_pipeline
;
436 the_pipeline
= (PROCESS
*)NULL
;
437 saved_already_making_children
= already_making_children
;
441 restore_pipeline (discard
)
444 PROCESS
*old_pipeline
;
446 old_pipeline
= the_pipeline
;
447 the_pipeline
= saved_pipeline
;
448 already_making_children
= saved_already_making_children
;
449 if (discard
&& old_pipeline
)
450 discard_pipeline (old_pipeline
);
453 /* Start building a pipeline. */
459 cleanup_the_pipeline ();
461 #if defined (PGRP_PIPE)
462 sh_closepipe (pgrp_pipe
);
466 #if defined (PGRP_PIPE)
469 if (pipe (pgrp_pipe
) == -1)
470 sys_error (_("start_pipeline: pgrp pipe"));
475 /* Stop building a pipeline. Install the process list in the job array.
476 This returns the index of the newly installed job.
477 DEFERRED is a command structure to be executed upon satisfactory
478 execution exit of this pipeline. */
480 stop_pipeline (async
, deferred
)
488 BLOCK_CHILD (set
, oset
);
490 #if defined (PGRP_PIPE)
491 /* The parent closes the process group synchronization pipe. */
492 sh_closepipe (pgrp_pipe
);
495 cleanup_dead_jobs ();
497 if (js
.j_jobslots
== 0)
499 js
.j_jobslots
= JOB_SLOTS
;
500 jobs
= (JOB
**)xmalloc (js
.j_jobslots
* sizeof (JOB
*));
502 /* Now blank out these new entries. */
503 for (i
= 0; i
< js
.j_jobslots
; i
++)
504 jobs
[i
] = (JOB
*)NULL
;
506 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
509 /* Scan from the last slot backward, looking for the next free one. */
510 /* XXX - revisit this interactive assumption */
511 /* XXX - this way for now */
514 for (i
= js
.j_jobslots
; i
; i
--)
521 /* This wraps around, but makes it inconvenient to extend the array */
522 for (i
= js
.j_lastj
+1; i
!= js
.j_lastj
; i
++)
524 if (i
>= js
.j_jobslots
)
532 /* This doesn't wrap around yet. */
533 for (i
= js
.j_lastj
? js
.j_lastj
+ 1 : js
.j_lastj
; i
< js
.j_jobslots
; i
++)
539 /* Do we need more room? */
541 /* First try compaction */
542 if ((interactive_shell
== 0 || subshell_environment
) && i
== js
.j_jobslots
&& js
.j_jobslots
>= MAX_JOBS_IN_ARRAY
)
543 i
= compact_jobs_list (0);
545 /* If we can't compact, reallocate */
546 if (i
== js
.j_jobslots
)
548 js
.j_jobslots
+= JOB_SLOTS
;
549 jobs
= (JOB
**)xrealloc (jobs
, (js
.j_jobslots
* sizeof (JOB
*)));
551 for (j
= i
; j
< js
.j_jobslots
; j
++)
552 jobs
[j
] = (JOB
*)NULL
;
555 /* Add the current pipeline to the job list. */
559 int any_running
, any_stopped
, n
;
561 newjob
= (JOB
*)xmalloc (sizeof (JOB
));
563 for (n
= 1, p
= the_pipeline
; p
->next
!= the_pipeline
; n
++, p
= p
->next
)
565 p
->next
= (PROCESS
*)NULL
;
566 newjob
->pipe
= REVERSE_LIST (the_pipeline
, PROCESS
*);
567 for (p
= newjob
->pipe
; p
->next
; p
= p
->next
)
569 p
->next
= newjob
->pipe
;
571 the_pipeline
= (PROCESS
*)NULL
;
572 newjob
->pgrp
= pipeline_pgrp
;
577 /* Flag to see if in another pgrp. */
579 newjob
->flags
|= J_JOBCONTROL
;
581 /* Set the state of this pipeline. */
583 any_running
= any_stopped
= 0;
586 any_running
|= PRUNNING (p
);
587 any_stopped
|= PSTOPPED (p
);
590 while (p
!= newjob
->pipe
);
592 newjob
->state
= any_running
? JRUNNING
: (any_stopped
? JSTOPPED
: JDEAD
);
593 newjob
->wd
= job_working_directory ();
594 newjob
->deferred
= deferred
;
596 newjob
->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
597 newjob
->cleanarg
= (PTR_T
) NULL
;
600 if (newjob
->state
== JDEAD
&& (newjob
->flags
& J_FOREGROUND
))
602 if (newjob
->state
== JDEAD
)
604 js
.c_reaped
+= n
; /* wouldn't have been done since this was not part of a job */
613 newjob
= (JOB
*)NULL
;
616 js
.j_lastmade
= newjob
;
622 newjob
->flags
&= ~J_FOREGROUND
;
623 newjob
->flags
|= J_ASYNC
;
624 js
.j_lastasync
= newjob
;
632 newjob
->flags
|= J_FOREGROUND
;
634 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
636 * The currently-accepted job control wisdom says to set the
637 * terminal's process group n+1 times in an n-step pipeline:
638 * once in the parent and once in each child. This is where
639 * the parent gives it away.
641 * Don't give the terminal away if this shell is an asynchronous
645 if (job_control
&& newjob
->pgrp
&& (subshell_environment
&SUBSHELL_ASYNC
) == 0)
646 maybe_give_terminal_to (shell_pgrp
, newjob
->pgrp
, 0);
650 stop_making_children ();
651 UNBLOCK_CHILD (oset
);
652 return (newjob
? i
: js
.j_current
);
655 /* Functions to manage the list of exited background pids whose status has
658 static struct pidstat
*
659 bgp_alloc (pid
, status
)
665 ps
= (struct pidstat
*)xmalloc (sizeof (struct pidstat
));
668 ps
->next
= (struct pidstat
*)0;
672 static struct pidstat
*
673 bgp_add (pid
, status
)
679 ps
= bgp_alloc (pid
, status
);
681 if (bgpids
.list
== 0)
683 bgpids
.list
= bgpids
.end
= ps
;
684 bgpids
.npid
= 0; /* just to make sure */
688 bgpids
.end
->next
= ps
;
693 if (bgpids
.npid
> js
.c_childmax
)
703 struct pidstat
*prev
, *p
;
705 for (prev
= p
= bgpids
.list
; p
; prev
= p
, p
= p
->next
)
708 prev
->next
= p
->next
; /* remove from list */
713 return 0; /* not found */
716 itrace("bgp_delete: deleting %d", pid
);
719 /* Housekeeping in the border cases. */
720 if (p
== bgpids
.list
)
721 bgpids
.list
= bgpids
.list
->next
;
722 else if (p
== bgpids
.end
)
726 if (bgpids
.npid
== 0)
727 bgpids
.list
= bgpids
.end
= 0;
728 else if (bgpids
.npid
== 1)
729 bgpids
.end
= bgpids
.list
; /* just to make sure */
735 /* Clear out the list of saved statuses */
739 struct pidstat
*ps
, *p
;
741 for (ps
= bgpids
.list
; ps
; )
747 bgpids
.list
= bgpids
.end
= 0;
751 /* Search for PID in the list of saved background pids; return its status if
752 found. If not found, return -1. */
759 for (ps
= bgpids
.list
; ps
; ps
= ps
->next
)
770 while (bgpids
.npid
> js
.c_childmax
)
773 bgpids
.list
= bgpids
.list
->next
;
779 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
780 been deleted. The caller should check whether js.j_njobs is 0 before
781 calling this. This wraps around, but the rest of the code does not. At
782 this point, it should not matter. */
788 if (jobs
[js
.j_firstj
] == 0)
791 if (old
>= js
.j_jobslots
)
792 old
= js
.j_jobslots
- 1;
793 while (js
.j_firstj
!= old
)
795 if (js
.j_firstj
>= js
.j_jobslots
)
797 if (jobs
[js
.j_firstj
] || js
.j_firstj
== old
) /* needed if old == 0 */
801 if (js
.j_firstj
== old
)
802 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
804 if (jobs
[js
.j_lastj
] == 0)
809 while (js
.j_lastj
!= old
)
812 js
.j_lastj
= js
.j_jobslots
- 1;
813 if (jobs
[js
.j_lastj
] || js
.j_lastj
== old
) /* needed if old == js.j_jobslots */
817 if (js
.j_lastj
== old
)
818 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
822 /* Delete all DEAD jobs that the user had received notification about. */
829 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
834 /* XXX could use js.j_firstj and js.j_lastj here */
835 for (i
= 0; i
< js
.j_jobslots
; i
++)
838 if (i
< js
.j_firstj
&& jobs
[i
])
839 itrace("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
840 if (i
> js
.j_lastj
&& jobs
[i
])
841 itrace("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
844 if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
))
848 #if defined (COPROCESS_SUPPORT)
856 processes_in_job (job
)
869 while (p
!= jobs
[job
]->pipe
);
881 job
= find_job (pid
, 0, &p
);
885 itrace ("delete_old_job: found pid %d in job %d with state %d", pid
, job
, jobs
[job
]->state
);
887 if (JOBSTATE (job
) == JDEAD
)
888 delete_job (job
, DEL_NOBGPID
);
891 internal_warning (_("forked pid %d appears in running job %d"), pid
, job
);
898 /* Reallocate and compress the jobs list. This returns with a jobs array
899 whose size is a multiple of JOB_SLOTS and can hold the current number of
900 jobs. Heuristics are used to minimize the number of new reallocs. */
905 int nsize
, i
, j
, ncur
, nprev
;
908 ncur
= nprev
= NO_JOB
;
909 nsize
= ((js
.j_njobs
+ JOB_SLOTS
- 1) / JOB_SLOTS
);
911 i
= js
.j_njobs
% JOB_SLOTS
;
912 if (i
== 0 || i
> (JOB_SLOTS
>> 1))
915 BLOCK_CHILD (set
, oset
);
916 nlist
= (js
.j_jobslots
== nsize
) ? jobs
: (JOB
**) xmalloc (nsize
* sizeof (JOB
*));
918 js
.c_reaped
= js
.j_ndead
= 0;
919 for (i
= j
= 0; i
< js
.j_jobslots
; i
++)
922 if (i
== js
.j_current
)
924 if (i
== js
.j_previous
)
926 nlist
[j
++] = jobs
[i
];
927 if (jobs
[i
]->state
== JDEAD
)
930 js
.c_reaped
+= processes_in_job (i
);
935 itrace ("realloc_jobs_list: resize jobs list from %d to %d", js
.j_jobslots
, nsize
);
936 itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js
.j_lastj
, (j
> 0) ? j
- 1 : 0);
937 itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js
.j_njobs
, j
);
938 itrace ("realloc_jobs_list: js.j_ndead %d js.c_reaped %d", js
.j_ndead
, js
.c_reaped
);
942 js
.j_lastj
= (j
> 0) ? j
- 1 : 0;
944 js
.j_jobslots
= nsize
;
946 /* Zero out remaining slots in new jobs list */
947 for ( ; j
< nsize
; j
++)
948 nlist
[j
] = (JOB
*)NULL
;
959 js
.j_previous
= nprev
;
961 /* Need to reset these */
962 if (js
.j_current
== NO_JOB
|| js
.j_previous
== NO_JOB
|| js
.j_current
> js
.j_lastj
|| js
.j_previous
> js
.j_lastj
)
966 itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js
.j_current
, js
.j_previous
);
969 UNBLOCK_CHILD (oset
);
972 /* Compact the jobs list by removing dead jobs. Assumed that we have filled
973 the jobs array to some predefined maximum. Called when the shell is not
974 the foreground process (subshell_environment != 0). Returns the first
975 available slot in the compacted list. If that value is js.j_jobslots, then
976 the list needs to be reallocated. The jobs array may be in new memory if
977 this returns > 0 and < js.j_jobslots. FLAGS is reserved for future use. */
979 compact_jobs_list (flags
)
982 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
983 return js
.j_jobslots
;
986 realloc_jobs_list ();
989 itrace("compact_jobs_list: returning %d", (js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
992 return ((js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
995 /* Delete the job at INDEX from the job list. Must be called
996 with SIGCHLD blocked. */
998 delete_job (job_index
, dflags
)
999 int job_index
, dflags
;
1005 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
1008 if ((dflags
& DEL_WARNSTOPPED
) && subshell_environment
== 0 && STOPPED (job_index
))
1009 internal_warning (_("deleting stopped job %d with process group %ld"), job_index
+1, (long)jobs
[job_index
]->pgrp
);
1010 temp
= jobs
[job_index
];
1014 if ((dflags
& DEL_NOBGPID
) == 0)
1016 proc
= find_last_proc (job_index
, 0);
1017 /* Could do this just for J_ASYNC jobs, but we save all. */
1019 bgp_add (proc
->pid
, process_exit_status (proc
->status
));
1022 jobs
[job_index
] = (JOB
*)NULL
;
1023 if (temp
== js
.j_lastmade
)
1025 else if (temp
== js
.j_lastasync
)
1029 ndel
= discard_pipeline (temp
->pipe
);
1031 js
.c_injobs
-= ndel
;
1032 if (temp
->state
== JDEAD
)
1034 js
.c_reaped
-= ndel
;
1036 if (js
.c_reaped
< 0)
1039 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
);
1046 dispose_command (temp
->deferred
);
1051 if (js
.j_njobs
== 0)
1052 js
.j_firstj
= js
.j_lastj
= 0;
1053 else if (jobs
[js
.j_firstj
] == 0 || jobs
[js
.j_lastj
] == 0)
1054 reset_job_indices ();
1056 if (job_index
== js
.j_current
|| job_index
== js
.j_previous
)
1060 /* Must be called with SIGCHLD blocked. */
1062 nohup_job (job_index
)
1067 if (js
.j_jobslots
== 0)
1070 if (temp
= jobs
[job_index
])
1071 temp
->flags
|= J_NOHUP
;
1074 /* Get rid of the data structure associated with a process chain. */
1076 discard_pipeline (chain
)
1077 register PROCESS
*chain
;
1079 register PROCESS
*this, *next
;
1087 FREE (this->command
);
1092 while (this != chain
);
1097 /* Add this process to the chain being built in the_pipeline.
1098 NAME is the command string that will be exec'ed later.
1099 PID is the process id of the child. */
1101 add_process (name
, pid
)
1107 #if defined (RECYCLES_PIDS)
1109 p
= find_process (pid
, 0, &j
);
1114 internal_warning (_("add_process: process %5ld (%s) in the_pipeline"), (long)p
->pid
, p
->command
);
1117 internal_warning (_("add_process: pid %5ld (%s) marked as still alive"), (long)p
->pid
, p
->command
);
1118 p
->running
= PS_RECYCLED
; /* mark as recycled */
1122 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1123 t
->next
= the_pipeline
;
1125 WSTATUS (t
->status
) = 0;
1126 t
->running
= PS_RUNNING
;
1135 while (p
->next
!= t
->next
)
1141 /* Create a (dummy) PROCESS with NAME, PID, and STATUS, and make it the last
1142 process in jobs[JID]->pipe. Used by the lastpipe code. */
1144 append_process (name
, pid
, status
, jid
)
1152 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1153 t
->next
= (PROCESS
*)NULL
;
1155 /* set process exit status using offset discovered by configure */
1156 t
->status
= (status
& 0xff) << WEXITSTATUS_OFFSET
;
1157 t
->running
= PS_DONE
;
1160 js
.c_reaped
++; /* XXX */
1162 for (p
= jobs
[jid
]->pipe
; p
->next
!= jobs
[jid
]->pipe
; p
= p
->next
)
1165 t
->next
= jobs
[jid
]->pipe
;
1169 /* Take the last job and make it the first job. Must be called with
1172 rotate_the_pipeline ()
1176 if (the_pipeline
->next
== the_pipeline
)
1178 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1183 /* Reverse the order of the processes in the_pipeline. Must be called with
1186 reverse_the_pipeline ()
1190 if (the_pipeline
->next
== the_pipeline
)
1193 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1195 p
->next
= (PROCESS
*)NULL
;
1197 n
= REVERSE_LIST (the_pipeline
, PROCESS
*);
1200 for (p
= the_pipeline
; p
->next
; p
= p
->next
)
1202 p
->next
= the_pipeline
;
1206 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
1207 then it is time to stop mapping, and that is the return value
1208 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
1211 map_over_jobs (func
, arg1
, arg2
)
1212 sh_job_map_func_t
*func
;
1219 if (js
.j_jobslots
== 0)
1222 BLOCK_CHILD (set
, oset
);
1224 /* XXX could use js.j_firstj here */
1225 for (i
= result
= 0; i
< js
.j_jobslots
; i
++)
1228 if (i
< js
.j_firstj
&& jobs
[i
])
1229 itrace("map_over_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1230 if (i
> js
.j_lastj
&& jobs
[i
])
1231 itrace("map_over_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1235 result
= (*func
)(jobs
[i
], arg1
, arg2
, i
);
1241 UNBLOCK_CHILD (oset
);
1246 /* Cause all the jobs in the current pipeline to exit. */
1248 terminate_current_pipeline ()
1250 if (pipeline_pgrp
&& pipeline_pgrp
!= shell_pgrp
)
1252 killpg (pipeline_pgrp
, SIGTERM
);
1253 killpg (pipeline_pgrp
, SIGCONT
);
1257 /* Cause all stopped jobs to exit. */
1259 terminate_stopped_jobs ()
1263 /* XXX could use js.j_firstj here */
1264 for (i
= 0; i
< js
.j_jobslots
; i
++)
1266 if (jobs
[i
] && STOPPED (i
))
1268 killpg (jobs
[i
]->pgrp
, SIGTERM
);
1269 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1274 /* Cause all jobs, running or stopped, to receive a hangup signal. If
1275 a job is marked J_NOHUP, don't send the SIGHUP. */
1281 /* XXX could use js.j_firstj here */
1282 for (i
= 0; i
< js
.j_jobslots
; i
++)
1286 if (jobs
[i
]->flags
& J_NOHUP
)
1288 killpg (jobs
[i
]->pgrp
, SIGHUP
);
1290 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1296 kill_current_pipeline ()
1298 stop_making_children ();
1302 /* Return the pipeline that PID belongs to. Note that the pipeline
1303 doesn't have to belong to a job. Must be called with SIGCHLD blocked.
1304 If JOBP is non-null, return the index of the job containing PID. */
1306 find_pipeline (pid
, alive_only
, jobp
)
1309 int *jobp
; /* index into jobs list or NO_JOB */
1314 /* See if this process is in the pipeline that we are building. */
1322 /* Return it if we found it. Don't ever return a recycled pid. */
1323 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1328 while (p
!= the_pipeline
);
1331 job
= find_job (pid
, alive_only
, &p
);
1334 return (job
== NO_JOB
) ? (PROCESS
*)NULL
: jobs
[job
]->pipe
;
1337 /* Return the PROCESS * describing PID. If JOBP is non-null return the index
1338 into the jobs array of the job containing PID. Must be called with
1341 find_process (pid
, alive_only
, jobp
)
1344 int *jobp
; /* index into jobs list or NO_JOB */
1348 p
= find_pipeline (pid
, alive_only
, jobp
);
1349 while (p
&& p
->pid
!= pid
)
1354 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1355 belong to any job. Must be called with SIGCHLD blocked. */
1357 find_job (pid
, alive_only
, procp
)
1365 /* XXX could use js.j_firstj here, and should check js.j_lastj */
1366 for (i
= 0; i
< js
.j_jobslots
; i
++)
1369 if (i
< js
.j_firstj
&& jobs
[i
])
1370 itrace("find_job: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1371 if (i
> js
.j_lastj
&& jobs
[i
])
1372 itrace("find_job: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1380 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1389 while (p
!= jobs
[i
]->pipe
);
1396 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
1397 required by find_job. */
1399 get_job_by_pid (pid
, block
)
1407 BLOCK_CHILD (set
, oset
);
1409 job
= find_job (pid
, 0, NULL
);
1412 UNBLOCK_CHILD (oset
);
1417 /* Print descriptive information about the job with leader pid PID. */
1425 BLOCK_CHILD (set
, oset
);
1427 job
= find_job (pid
, 0, NULL
);
1430 fprintf (stderr
, "[%d] %ld\n", job
+ 1, (long)pid
);
1432 programming_error (_("describe_pid: %ld: no such pid"), (long)pid
);
1434 UNBLOCK_CHILD (oset
);
1446 x
= retcode_name_buffer
;
1447 sprintf (x
, _("Signal %d"), s
);
1453 printable_job_status (j
, p
, format
)
1463 if (STOPPED (j
) && format
== 0)
1465 if (posixly_correct
== 0 || p
== 0 || (WIFSTOPPED (p
->status
) == 0))
1466 temp
= _("Stopped");
1469 temp
= retcode_name_buffer
;
1470 sprintf (temp
, _("Stopped(%s)"), signal_name (WSTOPSIG (p
->status
)));
1473 else if (RUNNING (j
))
1474 temp
= _("Running");
1477 if (WIFSTOPPED (p
->status
))
1478 temp
= j_strsignal (WSTOPSIG (p
->status
));
1479 else if (WIFSIGNALED (p
->status
))
1480 temp
= j_strsignal (WTERMSIG (p
->status
));
1481 else if (WIFEXITED (p
->status
))
1483 temp
= retcode_name_buffer
;
1484 es
= WEXITSTATUS (p
->status
);
1486 strcpy (temp
, _("Done"));
1487 else if (posixly_correct
)
1488 sprintf (temp
, _("Done(%d)"), es
);
1490 sprintf (temp
, _("Exit %d"), es
);
1493 temp
= _("Unknown status");
1499 /* This is the way to print out information on a job if you
1500 know the index. FORMAT is:
1502 JLIST_NORMAL) [1]+ Running emacs
1503 JLIST_LONG ) [1]+ 2378 Running emacs
1504 -1 ) [1]+ 2378 emacs
1506 JLIST_NORMAL) [1]+ Stopped ls | more
1507 JLIST_LONG ) [1]+ 2369 Stopped ls
1510 Just list the pid of the process group leader (really
1513 Use format JLIST_NORMAL, but list only jobs about which
1514 the user has not been notified. */
1516 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1517 the JOBS array corresponding to this pipeline. FORMAT is as described
1518 above. Must be called with SIGCHLD blocked.
1520 If you're printing a pipeline that's not in the jobs array, like the
1521 current pipeline as it's being created, pass -1 for JOB_INDEX */
1523 print_pipeline (p
, job_index
, format
, stream
)
1525 int job_index
, format
;
1528 PROCESS
*first
, *last
, *show
;
1529 int es
, name_padding
;
1536 while (last
->next
!= first
)
1542 fprintf (stream
, format
? " " : " |");
1544 if (format
!= JLIST_STANDARD
)
1545 fprintf (stream
, "%5ld", (long)p
->pid
);
1547 fprintf (stream
, " ");
1549 if (format
> -1 && job_index
>= 0)
1551 show
= format
? p
: last
;
1552 temp
= printable_job_status (job_index
, show
, format
);
1558 if (show
->running
== first
->running
&&
1559 WSTATUS (show
->status
) == WSTATUS (first
->status
))
1563 temp
= (char *)NULL
;
1568 fprintf (stream
, "%s", temp
);
1572 es
= 2; /* strlen ("| ") */
1573 name_padding
= LONGEST_SIGNAL_DESC
- es
;
1575 fprintf (stream
, "%*s", name_padding
, "");
1577 if ((WIFSTOPPED (show
->status
) == 0) &&
1578 (WIFCONTINUED (show
->status
) == 0) &&
1579 WIFCORED (show
->status
))
1580 fprintf (stream
, _("(core dumped) "));
1584 if (p
!= first
&& format
)
1585 fprintf (stream
, "| ");
1588 fprintf (stream
, "%s", p
->command
);
1590 if (p
== last
&& job_index
>= 0)
1592 temp
= current_working_directory ();
1594 if (RUNNING (job_index
) && (IS_FOREGROUND (job_index
) == 0))
1595 fprintf (stream
, " &");
1597 if (strcmp (temp
, jobs
[job_index
]->wd
) != 0)
1599 _(" (wd: %s)"), polite_directory_format (jobs
[job_index
]->wd
));
1602 if (format
|| (p
== last
))
1604 /* We need to add a CR only if this is an interactive shell, and
1605 we're reporting the status of a completed job asynchronously.
1606 We can't really check whether this particular job is being
1607 reported asynchronously, so just add the CR if the shell is
1608 currently interactive and asynchronous notification is enabled. */
1609 if (asynchronous_notification
&& interactive
)
1610 fprintf (stream
, "\r\n");
1612 fprintf (stream
, "\n");
1622 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1623 Must be called with SIGCHLD blocked or queued with queue_sigchld */
1625 pretty_print_job (job_index
, format
, stream
)
1626 int job_index
, format
;
1629 register PROCESS
*p
;
1631 /* Format only pid information about the process group leader? */
1632 if (format
== JLIST_PID_ONLY
)
1634 fprintf (stream
, "%ld\n", (long)jobs
[job_index
]->pipe
->pid
);
1638 if (format
== JLIST_CHANGED_ONLY
)
1640 if (IS_NOTIFIED (job_index
))
1642 format
= JLIST_STANDARD
;
1645 if (format
!= JLIST_NONINTERACTIVE
)
1646 fprintf (stream
, "[%d]%c ", job_index
+ 1,
1647 (job_index
== js
.j_current
) ? '+':
1648 (job_index
== js
.j_previous
) ? '-' : ' ');
1650 if (format
== JLIST_NONINTERACTIVE
)
1651 format
= JLIST_LONG
;
1653 p
= jobs
[job_index
]->pipe
;
1655 print_pipeline (p
, job_index
, format
, stream
);
1657 /* We have printed information about this job. When the job's
1658 status changes, waitchld () sets the notification flag to 0. */
1659 jobs
[job_index
]->flags
|= J_NOTIFIED
;
1663 print_job (job
, format
, state
, job_index
)
1665 int format
, state
, job_index
;
1667 if (state
== -1 || (JOB_STATE
)state
== job
->state
)
1668 pretty_print_job (job_index
, format
, stdout
);
1673 list_one_job (job
, format
, ignore
, job_index
)
1675 int format
, ignore
, job_index
;
1677 pretty_print_job (job_index
, format
, stdout
);
1681 list_stopped_jobs (format
)
1684 cleanup_dead_jobs ();
1685 map_over_jobs (print_job
, format
, (int)JSTOPPED
);
1689 list_running_jobs (format
)
1692 cleanup_dead_jobs ();
1693 map_over_jobs (print_job
, format
, (int)JRUNNING
);
1696 /* List jobs. If FORMAT is non-zero, then the long form of the information
1697 is printed, else just a short version. */
1699 list_all_jobs (format
)
1702 cleanup_dead_jobs ();
1703 map_over_jobs (print_job
, format
, -1);
1706 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1707 COMMAND is just for remembering the name of the command; we don't do
1708 anything else with it. ASYNC_P says what to do with the tty. If
1709 non-zero, then don't give it away. */
1711 make_child (command
, async_p
)
1720 sigaddset (&set
, SIGCHLD
);
1721 sigaddset (&set
, SIGINT
);
1722 sigemptyset (&oset
);
1723 sigprocmask (SIG_BLOCK
, &set
, &oset
);
1729 #if defined (BUFFERED_INPUT)
1730 /* If default_buffered_input is active, we are reading a script. If
1731 the command is asynchronous, we have already duplicated /dev/null
1732 as fd 0, but have not changed the buffered stream corresponding to
1733 the old fd 0. We don't want to sync the stream in this case. */
1734 if (default_buffered_input
!= -1 &&
1735 (!async_p
|| default_buffered_input
> 0))
1736 sync_buffered_stream (default_buffered_input
);
1737 #endif /* BUFFERED_INPUT */
1739 /* Create the child, handle severe errors. Retry on EAGAIN. */
1740 while ((pid
= fork ()) < 0 && errno
== EAGAIN
&& forksleep
< FORKSLEEP_MAX
)
1743 /* If we can't create any children, try to reap some dead ones. */
1746 sys_error ("fork: retry");
1747 if (sleep (forksleep
) != 0)
1756 /* Kill all of the processes in the current pipeline. */
1757 terminate_current_pipeline ();
1759 /* Discard the current pipeline, if any. */
1761 kill_current_pipeline ();
1763 last_command_exit_value
= EX_NOEXEC
;
1764 throw_to_top_level (); /* Reset signals, etc. */
1769 /* In the child. Give this child the right process group, set the
1770 signals to the default state for a new process. */
1774 #if defined (BUFFERED_INPUT)
1775 /* Close default_buffered_input if it's > 0. We don't close it if it's
1776 0 because that's the file descriptor used when redirecting input,
1777 and it's wrong to close the file in that case. */
1778 unset_bash_input (0);
1779 #endif /* BUFFERED_INPUT */
1781 /* Restore top-level signal mask. */
1782 sigprocmask (SIG_SETMASK
, &top_level_mask
, (sigset_t
*)NULL
);
1786 /* All processes in this pipeline belong in the same
1789 if (pipeline_pgrp
== 0) /* This is the first child. */
1790 pipeline_pgrp
= mypid
;
1792 /* Check for running command in backquotes. */
1793 if (pipeline_pgrp
== shell_pgrp
)
1794 ignore_tty_job_signals ();
1796 default_tty_job_signals ();
1798 /* Set the process group before trying to mess with the terminal's
1799 process group. This is mandated by POSIX. */
1800 /* This is in accordance with the Posix 1003.1 standard,
1801 section B.7.2.4, which says that trying to set the terminal
1802 process group with tcsetpgrp() to an unused pgrp value (like
1803 this would have for the first child) is an error. Section
1804 B.4.3.3, p. 237 also covers this, in the context of job control
1806 if (setpgid (mypid
, pipeline_pgrp
) < 0)
1807 sys_error (_("child setpgid (%ld to %ld)"), (long)mypid
, (long)pipeline_pgrp
);
1809 /* By convention (and assumption above), if
1810 pipeline_pgrp == shell_pgrp, we are making a child for
1811 command substitution.
1812 In this case, we don't want to give the terminal to the
1813 shell's process group (we could be in the middle of a
1814 pipeline, for example). */
1815 if (async_p
== 0 && pipeline_pgrp
!= shell_pgrp
&& ((subshell_environment
&SUBSHELL_ASYNC
) == 0))
1816 give_terminal_to (pipeline_pgrp
, 0);
1818 #if defined (PGRP_PIPE)
1819 if (pipeline_pgrp
== mypid
)
1820 pipe_read (pgrp_pipe
);
1823 else /* Without job control... */
1825 if (pipeline_pgrp
== 0)
1826 pipeline_pgrp
= shell_pgrp
;
1828 /* If these signals are set to SIG_DFL, we encounter the curious
1829 situation of an interactive ^Z to a running process *working*
1830 and stopping the process, but being unable to do anything with
1831 that process to change its state. On the other hand, if they
1832 are set to SIG_IGN, jobs started from scripts do not stop when
1833 the shell running the script gets a SIGTSTP and stops. */
1835 default_tty_job_signals ();
1838 #if defined (PGRP_PIPE)
1839 /* Release the process group pipe, since our call to setpgid ()
1840 is done. The last call to sh_closepipe is done in stop_pipeline. */
1841 sh_closepipe (pgrp_pipe
);
1842 #endif /* PGRP_PIPE */
1845 /* Don't set last_asynchronous_pid in the child */
1847 last_asynchronous_pid
= mypid
; /* XXX */
1850 #if defined (RECYCLES_PIDS)
1851 if (last_asynchronous_pid
== mypid
)
1852 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
1853 last_asynchronous_pid
= 1;
1858 /* In the parent. Remember the pid of the child just created
1859 as the proper pgrp if this is the first child. */
1861 if (first_pid
== NO_PID
)
1863 else if (pid_wrap
== -1 && pid
< first_pid
)
1865 else if (pid_wrap
== 0 && pid
>= first_pid
)
1870 if (pipeline_pgrp
== 0)
1872 pipeline_pgrp
= pid
;
1873 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1874 not the good thing of twiddling them in the child! */
1875 /* give_terminal_to (pipeline_pgrp, 0); */
1877 /* This is done on the recommendation of the Rationale section of
1878 the POSIX 1003.1 standard, where it discusses job control and
1879 shells. It is done to avoid possible race conditions. (Ref.
1880 1003.1 Rationale, section B.4.3.3, page 236). */
1881 setpgid (pid
, pipeline_pgrp
);
1885 if (pipeline_pgrp
== 0)
1886 pipeline_pgrp
= shell_pgrp
;
1889 /* Place all processes into the jobs array regardless of the
1890 state of job_control. */
1891 add_process (command
, pid
);
1894 last_asynchronous_pid
= pid
;
1895 #if defined (RECYCLES_PIDS)
1896 else if (last_asynchronous_pid
== pid
)
1897 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
1898 last_asynchronous_pid
= 1;
1902 delete_old_job (pid
);
1904 #if !defined (RECYCLES_PIDS)
1905 /* Only check for saved status if we've saved more than CHILD_MAX
1906 statuses, unless the system recycles pids. */
1907 if ((js
.c_reaped
+ bgpids
.npid
) >= js
.c_childmax
)
1909 bgp_delete (pid
); /* new process, discard any saved status */
1911 last_made_pid
= pid
;
1917 /* Unblock SIGINT and SIGCHLD unless creating a pipeline, in which case
1918 SIGCHLD remains blocked until all commands in the pipeline have been
1920 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
1926 /* These two functions are called only in child processes. */
1928 ignore_tty_job_signals ()
1930 set_signal_handler (SIGTSTP
, SIG_IGN
);
1931 set_signal_handler (SIGTTIN
, SIG_IGN
);
1932 set_signal_handler (SIGTTOU
, SIG_IGN
);
1936 default_tty_job_signals ()
1938 set_signal_handler (SIGTSTP
, SIG_DFL
);
1939 set_signal_handler (SIGTTIN
, SIG_DFL
);
1940 set_signal_handler (SIGTTOU
, SIG_DFL
);
1943 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1944 state kept in here. When a job ends normally, we set the state in here
1945 to the state of the tty. */
1947 static TTYSTRUCT shell_tty_info
;
1949 #if defined (NEW_TTY_DRIVER)
1950 static struct tchars shell_tchars
;
1951 static struct ltchars shell_ltchars
;
1952 #endif /* NEW_TTY_DRIVER */
1954 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1955 /* Since the BSD tty driver does not allow us to change the tty modes
1956 while simultaneously waiting for output to drain and preserving
1957 typeahead, we have to drain the output ourselves before calling
1958 ioctl. We cheat by finding the length of the output queue, and
1959 using select to wait for an appropriate length of time. This is
1960 a hack, and should be labeled as such (it's a hastily-adapted
1961 mutation of a `usleep' implementation). It's only reason for
1962 existing is the flaw in the BSD tty driver. */
1964 static int ttspeeds
[] =
1966 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1967 1800, 2400, 4800, 9600, 19200, 38400
1974 register int delay
= ttspeeds
[ospeed
];
1980 while ((ioctl (fd
, TIOCOUTQ
, &n
) == 0) && n
)
1982 if (n
> (delay
/ 100))
1986 n
*= 10; /* 2 bits more for conservativeness. */
1987 tv
.tv_sec
= n
/ delay
;
1988 tv
.tv_usec
= ((n
% delay
) * 1000000) / delay
;
1989 select (fd
, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &tv
);
1995 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1997 /* Return the fd from which we are actually getting input. */
1998 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
2000 /* Fill the contents of shell_tty_info with the current tty info. */
2009 #if defined (NEW_TTY_DRIVER)
2010 ioctl (tty
, TIOCGETP
, &shell_tty_info
);
2011 ioctl (tty
, TIOCGETC
, &shell_tchars
);
2012 ioctl (tty
, TIOCGLTC
, &shell_ltchars
);
2013 #endif /* NEW_TTY_DRIVER */
2015 #if defined (TERMIO_TTY_DRIVER)
2016 ioctl (tty
, TCGETA
, &shell_tty_info
);
2017 #endif /* TERMIO_TTY_DRIVER */
2019 #if defined (TERMIOS_TTY_DRIVER)
2020 if (tcgetattr (tty
, &shell_tty_info
) < 0)
2023 /* Only print an error message if we're really interactive at
2026 sys_error ("[%ld: %d (%d)] tcgetattr", (long)getpid (), shell_level
, tty
);
2030 #endif /* TERMIOS_TTY_DRIVER */
2031 if (check_window_size
)
2032 get_new_window_size (0, (int *)0, (int *)0);
2037 /* Make the current tty use the state in shell_tty_info. */
2046 #if defined (NEW_TTY_DRIVER)
2047 # if defined (DRAIN_OUTPUT)
2048 draino (tty
, shell_tty_info
.sg_ospeed
);
2049 # endif /* DRAIN_OUTPUT */
2050 ioctl (tty
, TIOCSETN
, &shell_tty_info
);
2051 ioctl (tty
, TIOCSETC
, &shell_tchars
);
2052 ioctl (tty
, TIOCSLTC
, &shell_ltchars
);
2053 #endif /* NEW_TTY_DRIVER */
2055 #if defined (TERMIO_TTY_DRIVER)
2056 ioctl (tty
, TCSETAW
, &shell_tty_info
);
2057 #endif /* TERMIO_TTY_DRIVER */
2059 #if defined (TERMIOS_TTY_DRIVER)
2060 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
2062 /* Only print an error message if we're really interactive at
2065 sys_error ("[%ld: %d (%d)] tcsetattr", (long)getpid (), shell_level
, tty
);
2068 #endif /* TERMIOS_TTY_DRIVER */
2073 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2074 process in that job's pipeline. This is the one whose exit status
2075 counts. Must be called with SIGCHLD blocked or queued. */
2077 find_last_proc (job
, block
)
2081 register PROCESS
*p
;
2085 BLOCK_CHILD (set
, oset
);
2087 p
= jobs
[job
]->pipe
;
2088 while (p
&& p
->next
!= jobs
[job
]->pipe
)
2092 UNBLOCK_CHILD (oset
);
2098 find_last_pid (job
, block
)
2104 p
= find_last_proc (job
, block
);
2105 /* Possible race condition here. */
2109 /* Wait for a particular child of the shell to finish executing.
2110 This low-level function prints an error message if PID is not
2111 a child of this shell. It returns -1 if it fails, or whatever
2112 wait_for returns otherwise. If the child is not found in the
2113 jobs table, it returns 127. */
2115 wait_for_single_pid (pid
)
2118 register PROCESS
*child
;
2122 BLOCK_CHILD (set
, oset
);
2123 child
= find_pipeline (pid
, 0, (int *)NULL
);
2124 UNBLOCK_CHILD (oset
);
2128 r
= bgp_search (pid
);
2135 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid
);
2141 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2143 BLOCK_CHILD (set
, oset
);
2144 job
= find_job (pid
, 0, NULL
);
2145 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
2146 jobs
[job
]->flags
|= J_NOTIFIED
;
2147 UNBLOCK_CHILD (oset
);
2149 /* If running in posix mode, remove the job from the jobs table immediately */
2150 if (posixly_correct
)
2152 cleanup_dead_jobs ();
2159 /* Wait for all of the background processes started by this shell to finish. */
2161 wait_for_background_pids ()
2163 register int i
, r
, waited_for
;
2167 for (waited_for
= 0;;)
2169 BLOCK_CHILD (set
, oset
);
2171 /* find first running job; if none running in foreground, break */
2172 /* XXX could use js.j_firstj and js.j_lastj here */
2173 for (i
= 0; i
< js
.j_jobslots
; i
++)
2176 if (i
< js
.j_firstj
&& jobs
[i
])
2177 itrace("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
2178 if (i
> js
.j_lastj
&& jobs
[i
])
2179 itrace("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
2181 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
2184 if (i
== js
.j_jobslots
)
2186 UNBLOCK_CHILD (oset
);
2190 /* now wait for the last pid in that job. */
2191 pid
= find_last_pid (i
, 0);
2192 UNBLOCK_CHILD (oset
);
2194 errno
= 0; /* XXX */
2195 r
= wait_for_single_pid (pid
);
2198 /* If we're mistaken about job state, compensate. */
2199 if (errno
== ECHILD
)
2200 mark_all_jobs_as_dead ();
2206 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2207 `wait' is called with no arguments. */
2208 mark_dead_jobs_as_notified (1);
2209 cleanup_dead_jobs ();
2213 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2214 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2215 static SigHandler
*old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2217 static int wait_sigint_received
;
2218 static int child_caught_sigint
;
2219 static int waiting_for_child
;
2222 restore_sigint_handler ()
2224 if (old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
2226 set_signal_handler (SIGINT
, old_sigint_handler
);
2227 old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2228 waiting_for_child
= 0;
2232 /* Handle SIGINT while we are waiting for children in a script to exit.
2233 The `wait' builtin should be interruptible, but all others should be
2234 effectively ignored (i.e. not cause the shell to exit). */
2236 wait_sigint_handler (sig
)
2239 SigHandler
*sigint_handler
;
2241 if (interrupt_immediately
||
2242 (this_shell_builtin
&& this_shell_builtin
== wait_builtin
))
2244 last_command_exit_value
= EXECUTION_FAILURE
;
2245 restore_sigint_handler ();
2246 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2247 what POSIX.2 says (see builtins/wait.def for more info). */
2248 if (this_shell_builtin
&& this_shell_builtin
== wait_builtin
&&
2249 signal_is_trapped (SIGINT
) &&
2250 ((sigint_handler
= trap_to_sighandler (SIGINT
)) == trap_handler
))
2252 interrupt_immediately
= 0;
2253 trap_handler (SIGINT
); /* set pending_traps[SIGINT] */
2254 wait_signal_received
= SIGINT
;
2255 longjmp (wait_intr_buf
, 1);
2262 /* XXX - should this be interrupt_state? If it is, the shell will act
2263 as if it got the SIGINT interrupt. */
2264 if (waiting_for_child
)
2265 wait_sigint_received
= 1;
2268 last_command_exit_value
= 128+SIGINT
;
2269 restore_sigint_handler ();
2270 kill (getpid (), SIGINT
);
2273 /* Otherwise effectively ignore the SIGINT and allow the running job to
2279 process_exit_signal (status
)
2282 return (WIFSIGNALED (status
) ? WTERMSIG (status
) : 0);
2286 process_exit_status (status
)
2289 if (WIFSIGNALED (status
))
2290 return (128 + WTERMSIG (status
));
2291 else if (WIFSTOPPED (status
) == 0)
2292 return (WEXITSTATUS (status
));
2294 return (EXECUTION_SUCCESS
);
2298 job_signal_status (job
)
2301 register PROCESS
*p
;
2304 p
= jobs
[job
]->pipe
;
2308 if (WIFSIGNALED(s
) || WIFSTOPPED(s
))
2312 while (p
!= jobs
[job
]->pipe
);
2317 /* Return the exit status of the last process in the pipeline for job JOB.
2318 This is the exit status of the entire job. */
2320 raw_job_exit_status (job
)
2323 register PROCESS
*p
;
2330 p
= jobs
[job
]->pipe
;
2333 if (WSTATUS (p
->status
) != EXECUTION_SUCCESS
)
2334 fail
= WSTATUS(p
->status
);
2337 while (p
!= jobs
[job
]->pipe
);
2338 WSTATUS (ret
) = fail
;
2342 for (p
= jobs
[job
]->pipe
; p
->next
!= jobs
[job
]->pipe
; p
= p
->next
)
2347 /* Return the exit status of job JOB. This is the exit status of the last
2348 (rightmost) process in the job's pipeline, modified if the job was killed
2349 by a signal or stopped. */
2351 job_exit_status (job
)
2354 return (process_exit_status (raw_job_exit_status (job
)));
2358 job_exit_signal (job
)
2361 return (process_exit_signal (raw_job_exit_status (job
)));
2364 #define FIND_CHILD(pid, child) \
2367 child = find_pipeline (pid, 0, (int *)NULL); \
2370 give_terminal_to (shell_pgrp, 0); \
2371 UNBLOCK_CHILD (oset); \
2372 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2373 restore_sigint_handler (); \
2374 return (termination_state = 127); \
2379 /* Wait for pid (one of our children) to terminate, then
2380 return the termination state. Returns 127 if PID is not found in
2381 the jobs table. Returns -1 if waitchld() returns -1, indicating
2382 that there are no unwaited-for child processes. */
2387 int job
, termination_state
, r
;
2389 register PROCESS
*child
;
2392 /* In the case that this code is interrupted, and we longjmp () out of it,
2393 we are relying on the code in throw_to_top_level () to restore the
2394 top-level signal mask. */
2395 BLOCK_CHILD (set
, oset
);
2397 /* Ignore interrupts while waiting for a job run without job control
2398 to finish. We don't want the shell to exit if an interrupt is
2399 received, only if one of the jobs run is killed via SIGINT. If
2400 job control is not set, the job will be run in the same pgrp as
2401 the shell, and the shell will see any signals the job gets. In
2402 fact, we want this set every time the waiting shell and the waited-
2403 for process are in the same process group, including command
2406 /* This is possibly a race condition -- should it go in stop_pipeline? */
2407 wait_sigint_received
= child_caught_sigint
= 0;
2408 if (job_control
== 0 || (subshell_environment
&SUBSHELL_COMSUB
))
2410 old_sigint_handler
= set_signal_handler (SIGINT
, wait_sigint_handler
);
2411 waiting_for_child
= 0;
2412 if (old_sigint_handler
== SIG_IGN
)
2413 set_signal_handler (SIGINT
, old_sigint_handler
);
2416 termination_state
= last_command_exit_value
;
2418 if (interactive
&& job_control
== 0)
2420 /* Check for terminating signals and exit the shell if we receive one */
2423 /* If we say wait_for (), then we have a record of this child somewhere.
2424 If it and none of its peers are running, don't call waitchld(). */
2429 FIND_CHILD (pid
, child
);
2431 /* If this child is part of a job, then we are really waiting for the
2432 job to finish. Otherwise, we are waiting for the child to finish.
2433 We check for JDEAD in case the job state has been set by waitchld
2434 after receipt of a SIGCHLD. */
2436 job
= find_job (pid
, 0, NULL
);
2438 /* waitchld() takes care of setting the state of the job. If the job
2439 has already exited before this is called, sigchld_handler will have
2440 called waitchld and the state will be set to JDEAD. */
2442 if (PRUNNING(child
) || (job
!= NO_JOB
&& RUNNING (job
)))
2444 #if defined (WAITPID_BROKEN) /* SCOv4 */
2445 sigset_t suspend_set
;
2446 sigemptyset (&suspend_set
);
2447 sigsuspend (&suspend_set
);
2448 #else /* !WAITPID_BROKEN */
2449 # if defined (MUST_UNBLOCK_CHLD)
2450 struct sigaction act
, oact
;
2451 sigset_t nullset
, chldset
;
2453 sigemptyset (&nullset
);
2454 sigemptyset (&chldset
);
2455 sigprocmask (SIG_SETMASK
, &nullset
, &chldset
);
2456 act
.sa_handler
= SIG_DFL
;
2457 sigemptyset (&act
.sa_mask
);
2458 sigemptyset (&oact
.sa_mask
);
2460 sigaction (SIGCHLD
, &act
, &oact
);
2463 waiting_for_child
++;
2464 r
= waitchld (pid
, 1);
2465 waiting_for_child
--;
2466 # if defined (MUST_UNBLOCK_CHLD)
2467 sigaction (SIGCHLD
, &oact
, (struct sigaction
*)NULL
);
2468 sigprocmask (SIG_SETMASK
, &chldset
, (sigset_t
*)NULL
);
2471 if (r
== -1 && errno
== ECHILD
&& this_shell_builtin
== wait_builtin
)
2473 termination_state
= -1;
2474 goto wait_for_return
;
2477 /* If child is marked as running, but waitpid() returns -1/ECHILD,
2478 there is something wrong. Somewhere, wait should have returned
2479 that child's pid. Mark the child as not running and the job,
2480 if it exists, as JDEAD. */
2481 if (r
== -1 && errno
== ECHILD
)
2483 child
->running
= PS_DONE
;
2484 WSTATUS (child
->status
) = 0; /* XXX -- can't find true status */
2485 js
.c_living
= 0; /* no living child processes */
2488 jobs
[job
]->state
= JDEAD
;
2493 #endif /* WAITPID_BROKEN */
2496 /* If the shell is interactive, and job control is disabled, see
2497 if the foreground process has died due to SIGINT and jump out
2498 of the wait loop if it has. waitchld has already restored the
2499 old SIGINT signal handler. */
2500 if (interactive
&& job_control
== 0)
2502 /* Check for terminating signals and exit the shell if we receive one */
2505 while (PRUNNING (child
) || (job
!= NO_JOB
&& RUNNING (job
)));
2507 /* Restore the original SIGINT signal handler before we return. */
2508 restore_sigint_handler ();
2510 /* The exit state of the command is either the termination state of the
2511 child, or the termination state of the job. If a job, the status
2512 of the last child in the pipeline is the significant one. If the command
2513 or job was terminated by a signal, note that value also. */
2514 termination_state
= (job
!= NO_JOB
) ? job_exit_status (job
)
2515 : process_exit_status (child
->status
);
2516 last_command_exit_signal
= (job
!= NO_JOB
) ? job_exit_signal (job
)
2517 : process_exit_signal (child
->status
);
2520 if ((job
!= NO_JOB
&& JOBSTATE (job
) == JSTOPPED
) || WIFSTOPPED (child
->status
))
2521 termination_state
= 128 + WSTOPSIG (child
->status
);
2523 if (job
== NO_JOB
|| IS_JOBCONTROL (job
))
2525 /* XXX - under what circumstances is a job not present in the jobs
2526 table (job == NO_JOB)?
2527 1. command substitution
2529 In the case of command substitution, at least, it's probably not
2530 the right thing to give the terminal to the shell's process group,
2531 even though there is code in subst.c:command_substitute to work
2535 $PROMPT_COMMAND execution
2536 process substitution
2540 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp
);
2542 give_terminal_to (shell_pgrp
, 0);
2545 /* If the command did not exit cleanly, or the job is just
2546 being stopped, then reset the tty state back to what it
2547 was before this command. Reset the tty state and notify
2548 the user of the job termination only if the shell is
2549 interactive. Clean up any dead jobs in either case. */
2552 if (interactive_shell
&& subshell_environment
== 0)
2554 /* This used to use `child->status'. That's wrong, however, for
2555 pipelines. `child' is the first process in the pipeline. It's
2556 likely that the process we want to check for abnormal termination
2557 or stopping is the last process in the pipeline, especially if
2558 it's long-lived and the first process is short-lived. Since we
2559 know we have a job here, we can check all the processes in this
2560 job's pipeline and see if one of them stopped or terminated due
2561 to a signal. We might want to change this later to just check
2562 the last process in the pipeline. If no process exits due to a
2563 signal, S is left as the status of the last job in the pipeline. */
2564 s
= job_signal_status (job
);
2566 if (WIFSIGNALED (s
) || WIFSTOPPED (s
))
2570 /* If the current job was stopped or killed by a signal, and
2571 the user has requested it, get a possibly new window size */
2572 if (check_window_size
&& (job
== js
.j_current
|| IS_FOREGROUND (job
)))
2573 get_new_window_size (0, (int *)0, (int *)0);
2578 /* If job control is enabled, the job was started with job
2579 control, the job was the foreground job, and it was killed
2580 by SIGINT, then print a newline to compensate for the kernel
2581 printing the ^C without a trailing newline. */
2582 if (job_control
&& IS_JOBCONTROL (job
) && IS_FOREGROUND (job
) &&
2583 WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
)
2585 /* If SIGINT is not trapped and the shell is in a for, while,
2586 or until loop, act as if the shell received SIGINT as
2587 well, so the loop can be broken. This doesn't call the
2588 SIGINT signal handler; maybe it should. */
2589 if (signal_is_trapped (SIGINT
) == 0 && (loop_level
|| (shell_compatibility_level
> 32 && executing_list
)))
2598 else if ((subshell_environment
& (SUBSHELL_COMSUB
|SUBSHELL_PIPE
)) && wait_sigint_received
)
2600 /* If waiting for a job in a subshell started to do command
2601 substitution or to run a pipeline element that consists of
2602 something like a while loop or a for loop, simulate getting
2603 and being killed by the SIGINT to pass the status back to our
2605 s
= job_signal_status (job
);
2607 if (child_caught_sigint
== 0 && signal_is_trapped (SIGINT
) == 0)
2609 UNBLOCK_CHILD (oset
);
2610 old_sigint_handler
= set_signal_handler (SIGINT
, SIG_DFL
);
2611 if (old_sigint_handler
== SIG_IGN
)
2612 restore_sigint_handler ();
2614 kill (getpid (), SIGINT
);
2617 else if (interactive_shell
== 0 && IS_FOREGROUND (job
) && check_window_size
)
2618 get_new_window_size (0, (int *)0, (int *)0);
2620 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
2621 signal handler path */
2622 if (DEADJOB (job
) && IS_FOREGROUND (job
) /*&& subshell_environment == 0*/)
2625 /* If this job is dead, notify the user of the status. If the shell
2626 is interactive, this will display a message on the terminal. If
2627 the shell is not interactive, make sure we turn on the notify bit
2628 so we don't get an unwanted message about the job's termination,
2629 and so delete_job really clears the slot in the jobs table. */
2630 notify_and_cleanup ();
2635 UNBLOCK_CHILD (oset
);
2637 return (termination_state
);
2640 /* Wait for the last process in the pipeline for JOB. Returns whatever
2641 wait_for returns: the last process's termination state or -1 if there
2642 are no unwaited-for child processes or an error occurs. */
2651 BLOCK_CHILD(set
, oset
);
2652 if (JOBSTATE (job
) == JSTOPPED
)
2653 internal_warning (_("wait_for_job: job %d is stopped"), job
+1);
2655 pid
= find_last_pid (job
, 0);
2656 UNBLOCK_CHILD(oset
);
2659 /* POSIX.2: we can remove the job from the jobs table if we just waited
2661 BLOCK_CHILD (set
, oset
);
2662 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
2663 jobs
[job
]->flags
|= J_NOTIFIED
;
2664 UNBLOCK_CHILD (oset
);
2669 /* Print info about dead jobs, and then delete them from the list
2670 of known jobs. This does not actually delete jobs when the
2671 shell is not interactive, because the dead jobs are not marked
2674 notify_and_cleanup ()
2676 if (jobs_list_frozen
)
2679 if (interactive
|| interactive_shell
== 0 || sourcelevel
)
2680 notify_of_job_status ();
2682 cleanup_dead_jobs ();
2685 /* Make dead jobs disappear from the jobs array without notification.
2686 This is used when the shell is not interactive. */
2690 mark_dead_jobs_as_notified (0);
2691 cleanup_dead_jobs ();
2694 /* Return the next closest (chronologically) job to JOB which is in
2695 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
2696 there is no next recent job. */
2698 most_recent_job_in_state (job
, state
)
2702 register int i
, result
;
2705 BLOCK_CHILD (set
, oset
);
2707 for (result
= NO_JOB
, i
= job
- 1; i
>= 0; i
--)
2709 if (jobs
[i
] && (JOBSTATE (i
) == state
))
2716 UNBLOCK_CHILD (oset
);
2721 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
2724 job_last_stopped (job
)
2727 return (most_recent_job_in_state (job
, JSTOPPED
));
2730 /* Return the newest *running* job older than JOB, or NO_JOB if not
2733 job_last_running (job
)
2736 return (most_recent_job_in_state (job
, JRUNNING
));
2739 /* Make JOB be the current job, and make previous be useful. Must be
2740 called with SIGCHLD blocked. */
2742 set_current_job (job
)
2747 if (js
.j_current
!= job
)
2749 js
.j_previous
= js
.j_current
;
2753 /* First choice for previous job is the old current job. */
2754 if (js
.j_previous
!= js
.j_current
&&
2755 js
.j_previous
!= NO_JOB
&&
2756 jobs
[js
.j_previous
] &&
2757 STOPPED (js
.j_previous
))
2760 /* Second choice: Newest stopped job that is older than
2763 if (STOPPED (js
.j_current
))
2765 candidate
= job_last_stopped (js
.j_current
);
2767 if (candidate
!= NO_JOB
)
2769 js
.j_previous
= candidate
;
2774 /* If we get here, there is either only one stopped job, in which case it is
2775 the current job and the previous job should be set to the newest running
2776 job, or there are only running jobs and the previous job should be set to
2777 the newest running job older than the current job. We decide on which
2778 alternative to use based on whether or not JOBSTATE(js.j_current) is
2781 candidate
= RUNNING (js
.j_current
) ? job_last_running (js
.j_current
)
2782 : job_last_running (js
.j_jobslots
);
2784 if (candidate
!= NO_JOB
)
2786 js
.j_previous
= candidate
;
2790 /* There is only a single job, and it is both `+' and `-'. */
2791 js
.j_previous
= js
.j_current
;
2794 /* Make current_job be something useful, if it isn't already. */
2796 /* Here's the deal: The newest non-running job should be `+', and the
2797 next-newest non-running job should be `-'. If there is only a single
2798 stopped job, the js.j_previous is the newest non-running job. If there
2799 are only running jobs, the newest running job is `+' and the
2800 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
2807 if (js
.j_jobslots
&& js
.j_current
!= NO_JOB
&& jobs
[js
.j_current
] && STOPPED (js
.j_current
))
2808 candidate
= js
.j_current
;
2813 /* First choice: the previous job. */
2814 if (js
.j_previous
!= NO_JOB
&& jobs
[js
.j_previous
] && STOPPED (js
.j_previous
))
2815 candidate
= js
.j_previous
;
2817 /* Second choice: the most recently stopped job. */
2818 if (candidate
== NO_JOB
)
2819 candidate
= job_last_stopped (js
.j_jobslots
);
2821 /* Third choice: the newest running job. */
2822 if (candidate
== NO_JOB
)
2823 candidate
= job_last_running (js
.j_jobslots
);
2826 /* If we found a job to use, then use it. Otherwise, there
2827 are no jobs period. */
2828 if (candidate
!= NO_JOB
)
2829 set_current_job (candidate
);
2831 js
.j_current
= js
.j_previous
= NO_JOB
;
2834 /* Set up the job structures so we know the job and its processes are
2837 set_job_running (job
)
2840 register PROCESS
*p
;
2842 /* Each member of the pipeline is now running. */
2843 p
= jobs
[job
]->pipe
;
2847 if (WIFSTOPPED (p
->status
))
2848 p
->running
= PS_RUNNING
; /* XXX - could be PS_STOPPED */
2851 while (p
!= jobs
[job
]->pipe
);
2853 /* This means that the job is running. */
2854 JOBSTATE (job
) = JRUNNING
;
2857 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2858 start the job in the background. JOB is a zero-based index into
2859 JOBS. Returns -1 if it is unable to start a job, and the return
2860 status of the job otherwise. */
2862 start_job (job
, foreground
)
2863 int job
, foreground
;
2865 register PROCESS
*p
;
2866 int already_running
;
2869 static TTYSTRUCT save_stty
;
2871 BLOCK_CHILD (set
, oset
);
2875 internal_error (_("%s: job has terminated"), this_command_name
);
2876 UNBLOCK_CHILD (oset
);
2880 already_running
= RUNNING (job
);
2882 if (foreground
== 0 && already_running
)
2884 internal_error (_("%s: job %d already in background"), this_command_name
, job
+ 1);
2885 UNBLOCK_CHILD (oset
);
2886 return (0); /* XPG6/SUSv3 says this is not an error */
2889 wd
= current_working_directory ();
2891 /* You don't know about the state of this job. Do you? */
2892 jobs
[job
]->flags
&= ~J_NOTIFIED
;
2896 set_current_job (job
);
2897 jobs
[job
]->flags
|= J_FOREGROUND
;
2900 /* Tell the outside world what we're doing. */
2901 p
= jobs
[job
]->pipe
;
2903 if (foreground
== 0)
2905 /* POSIX.2 says `bg' doesn't give any indication about current or
2907 if (posixly_correct
== 0)
2908 s
= (job
== js
.j_current
) ? "+ ": ((job
== js
.j_previous
) ? "- " : " ");
2911 printf ("[%d]%s", job
+ 1, s
);
2917 p
->command
? p
->command
: "",
2918 p
->next
!= jobs
[job
]->pipe
? " | " : "");
2921 while (p
!= jobs
[job
]->pipe
);
2923 if (foreground
== 0)
2926 if (strcmp (wd
, jobs
[job
]->wd
) != 0)
2927 printf (" (wd: %s)", polite_directory_format (jobs
[job
]->wd
));
2932 if (already_running
== 0)
2933 set_job_running (job
);
2935 /* Save the tty settings before we start the job in the foreground. */
2939 save_stty
= shell_tty_info
;
2940 /* Give the terminal to this job. */
2941 if (IS_JOBCONTROL (job
))
2942 give_terminal_to (jobs
[job
]->pgrp
, 0);
2945 jobs
[job
]->flags
&= ~J_FOREGROUND
;
2947 /* If the job is already running, then don't bother jump-starting it. */
2948 if (already_running
== 0)
2950 jobs
[job
]->flags
|= J_NOTIFIED
;
2951 killpg (jobs
[job
]->pgrp
, SIGCONT
);
2959 pid
= find_last_pid (job
, 0);
2960 UNBLOCK_CHILD (oset
);
2961 st
= wait_for (pid
);
2962 shell_tty_info
= save_stty
;
2969 UNBLOCK_CHILD (oset
);
2974 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2975 If PID does belong to a job, and the job is stopped, then CONTinue the
2976 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2977 then kill the process group associated with PID. */
2979 kill_pid (pid
, sig
, group
)
2983 register PROCESS
*p
;
2984 int job
, result
, negative
;
2990 group
= negative
= 1;
2995 result
= EXECUTION_SUCCESS
;
2998 BLOCK_CHILD (set
, oset
);
2999 p
= find_pipeline (pid
, 0, &job
);
3003 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3005 /* Kill process in backquotes or one started without job control? */
3007 /* If we're passed a pid < -1, just call killpg and see what happens */
3008 if (negative
&& jobs
[job
]->pgrp
== shell_pgrp
)
3009 result
= killpg (pid
, sig
);
3010 /* If we're killing using job control notification, for example,
3011 without job control active, we have to do things ourselves. */
3012 else if (jobs
[job
]->pgrp
== shell_pgrp
)
3014 p
= jobs
[job
]->pipe
;
3017 if (PALIVE (p
) == 0)
3018 continue; /* avoid pid recycling problem */
3020 if (PEXITED (p
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3021 kill (p
->pid
, SIGCONT
);
3024 while (p
!= jobs
[job
]->pipe
);
3028 result
= killpg (jobs
[job
]->pgrp
, sig
);
3029 if (p
&& STOPPED (job
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
3030 killpg (jobs
[job
]->pgrp
, SIGCONT
);
3031 /* If we're continuing a stopped job via kill rather than bg or
3032 fg, emulate the `bg' behavior. */
3033 if (p
&& STOPPED (job
) && (sig
== SIGCONT
))
3035 set_job_running (job
);
3036 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3037 jobs
[job
]->flags
|= J_NOTIFIED
;
3042 result
= killpg (pid
, sig
);
3044 UNBLOCK_CHILD (oset
);
3047 result
= kill (pid
, sig
);
3052 /* sigchld_handler () flushes at least one of the children that we are
3053 waiting for. It gets run when we have gotten a SIGCHLD signal. */
3055 sigchld_handler (sig
)
3061 REINSTALL_SIGCHLD_HANDLER
;
3064 if (queue_sigchld
== 0)
3065 n
= waitchld (-1, 0);
3070 /* waitchld() reaps dead or stopped children. It's called by wait_for and
3071 sigchld_handler, and runs until there aren't any children terminating any
3073 If BLOCK is 1, this is to be a blocking wait for a single child, although
3074 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
3075 the number of children reaped, or -1 if there are no unwaited-for child
3078 waitchld (wpid
, block
)
3085 int call_set_current
, last_stopped_job
, job
, children_exited
, waitpid_flags
;
3086 static int wcontinued
= WCONTINUED
; /* run-time fix for glibc problem */
3088 call_set_current
= children_exited
= 0;
3089 last_stopped_job
= NO_JOB
;
3093 /* We don't want to be notified about jobs stopping if job control
3094 is not active. XXX - was interactive_shell instead of job_control */
3095 waitpid_flags
= (job_control
&& subshell_environment
== 0)
3096 ? (WUNTRACED
|wcontinued
)
3098 if (sigchld
|| block
== 0)
3099 waitpid_flags
|= WNOHANG
;
3100 /* Check for terminating signals and exit the shell if we receive one */
3103 if (block
== 1 && queue_sigchld
== 0 && (waitpid_flags
& WNOHANG
) == 0)
3105 internal_warning (_("waitchld: turning on WNOHANG to avoid indefinite block"));
3106 waitpid_flags
|= WNOHANG
;
3109 pid
= WAITPID (-1, &status
, waitpid_flags
);
3111 /* WCONTINUED may be rejected by waitpid as invalid even when defined */
3112 if (wcontinued
&& pid
< 0 && errno
== EINVAL
)
3115 continue; /* jump back to the test and retry without WCONTINUED */
3118 /* The check for WNOHANG is to make sure we decrement sigchld only
3119 if it was non-zero before we called waitpid. */
3120 if (sigchld
> 0 && (waitpid_flags
& WNOHANG
))
3123 /* If waitpid returns -1 with errno == ECHILD, there are no more
3124 unwaited-for child processes of this shell. */
3125 if (pid
< 0 && errno
== ECHILD
)
3127 if (children_exited
== 0)
3133 /* If waitpid returns 0, there are running children. If it returns -1,
3134 the only other error POSIX says it can return is EINTR. */
3137 /* If waitpid returns -1/EINTR and the shell saw a SIGINT, then we
3138 assume the child has blocked or handled SIGINT. In that case, we
3139 require the child to actually die due to SIGINT to act on the
3140 SIGINT we received; otherwise we assume the child handled it and
3142 if (pid
< 0 && errno
== EINTR
&& wait_sigint_received
)
3143 child_caught_sigint
= 1;
3146 continue; /* jumps right to the test */
3148 /* If the child process did die due to SIGINT, forget our assumption
3149 that it caught or otherwise handled it. */
3150 if (WIFSIGNALED (status
) && WTERMSIG (status
) == SIGINT
)
3151 child_caught_sigint
= 0;
3153 /* children_exited is used to run traps on SIGCHLD. We don't want to
3154 run the trap if a process is just being continued. */
3155 if (WIFCONTINUED(status
) == 0)
3161 /* Locate our PROCESS for this pid. */
3162 child
= find_process (pid
, 1, &job
); /* want living procs only */
3164 #if defined (COPROCESS_SUPPORT)
3165 coproc_pidchk (pid
, status
);
3168 /* It is not an error to have a child terminate that we did
3169 not have a record of. This child could have been part of
3170 a pipeline in backquote substitution. Even so, I'm not
3171 sure child is ever non-zero. */
3174 if (WIFEXITED (status
) || WIFSIGNALED (status
))
3179 /* Remember status, and whether or not the process is running. */
3180 child
->status
= status
;
3181 child
->running
= WIFCONTINUED(status
) ? PS_RUNNING
: PS_DONE
;
3183 if (PEXITED (child
))
3193 call_set_current
+= set_job_status_and_cleanup (job
);
3196 last_stopped_job
= job
;
3197 else if (DEADJOB (job
) && last_stopped_job
== job
)
3198 last_stopped_job
= NO_JOB
;
3200 while ((sigchld
|| block
== 0) && pid
> (pid_t
)0);
3202 /* If a job was running and became stopped, then set the current
3203 job. Otherwise, don't change a thing. */
3204 if (call_set_current
)
3206 if (last_stopped_job
!= NO_JOB
)
3207 set_current_job (last_stopped_job
);
3212 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3213 if (job_control
&& signal_is_trapped (SIGCHLD
) && children_exited
&&
3214 trap_list
[SIGCHLD
] != (char *)IGNORE_SIG
)
3216 if (posixly_correct
&& this_shell_builtin
&& this_shell_builtin
== wait_builtin
)
3218 interrupt_immediately
= 0;
3219 trap_handler (SIGCHLD
); /* set pending_traps[SIGCHLD] */
3220 wait_signal_received
= SIGCHLD
;
3221 longjmp (wait_intr_buf
, 1);
3224 run_sigchld_trap (children_exited
);
3227 /* We have successfully recorded the useful information about this process
3228 that has just changed state. If we notify asynchronously, and the job
3229 that this process belongs to is no longer running, then notify the user
3230 of that fact now. */
3231 if (asynchronous_notification
&& interactive
)
3232 notify_of_job_status ();
3234 return (children_exited
);
3237 /* Set the status of JOB and perform any necessary cleanup if the job is
3240 Currently, the cleanup activity is restricted to handling any SIGINT
3241 received while waiting for a foreground job to finish. */
3243 set_job_status_and_cleanup (job
)
3247 int tstatus
, job_state
, any_stopped
, any_tstped
, call_set_current
;
3248 SigHandler
*temp_handler
;
3250 child
= jobs
[job
]->pipe
;
3251 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3253 call_set_current
= 0;
3256 * COMPUTE JOB STATUS
3259 /* If all children are not running, but any of them is stopped, then
3260 the job is stopped, not dead. */
3261 job_state
= any_stopped
= any_tstped
= 0;
3264 job_state
|= PRUNNING (child
);
3266 if (PEXITED (child
) && (WIFSTOPPED (child
->status
)))
3268 /* Only checking for WIFSTOPPED now, not for PS_DONE */
3269 if (PSTOPPED (child
))
3273 any_tstped
|= interactive
&& job_control
&&
3274 (WSTOPSIG (child
->status
) == SIGTSTP
);
3276 child
= child
->next
;
3278 while (child
!= jobs
[job
]->pipe
);
3280 /* If job_state != 0, the job is still running, so don't bother with
3281 setting the process exit status and job state unless we're
3282 transitioning from stopped to running. */
3283 if (job_state
!= 0 && JOBSTATE(job
) != JSTOPPED
)
3290 /* The job is either stopped or dead. Set the state of the job accordingly. */
3293 jobs
[job
]->state
= JSTOPPED
;
3294 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3296 /* Suspending a job with SIGTSTP breaks all active loops. */
3297 if (any_tstped
&& loop_level
)
3298 breaking
= loop_level
;
3300 else if (job_state
!= 0) /* was stopped, now running */
3302 jobs
[job
]->state
= JRUNNING
;
3307 jobs
[job
]->state
= JDEAD
;
3311 if (IS_FOREGROUND (job
))
3315 /* If this job has a cleanup function associated with it, call it
3316 with `cleanarg' as the single argument, then set the function
3317 pointer to NULL so it is not inadvertently called twice. The
3318 cleanup function is responsible for deallocating cleanarg. */
3319 if (jobs
[job
]->j_cleanup
)
3321 (*jobs
[job
]->j_cleanup
) (jobs
[job
]->cleanarg
);
3322 jobs
[job
]->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
3329 * Currently, we just do special things if we got a SIGINT while waiting
3330 * for a foreground job to complete
3333 if (JOBSTATE (job
) == JDEAD
)
3335 /* If we're running a shell script and we get a SIGINT with a
3336 SIGINT trap handler, but the foreground job handles it and
3337 does not exit due to SIGINT, run the trap handler but do not
3338 otherwise act as if we got the interrupt. */
3339 if (wait_sigint_received
&& interactive_shell
== 0 &&
3340 child_caught_sigint
&& IS_FOREGROUND (job
) &&
3341 signal_is_trapped (SIGINT
))
3344 wait_sigint_received
= 0;
3345 last_command_exit_value
= process_exit_status (child
->status
);
3347 old_frozen
= jobs_list_frozen
;
3348 jobs_list_frozen
= 1;
3349 tstatus
= maybe_call_trap_handler (SIGINT
);
3350 jobs_list_frozen
= old_frozen
;
3353 /* If the foreground job is killed by SIGINT when job control is not
3354 active, we need to perform some special handling.
3356 The check of wait_sigint_received is a way to determine if the
3357 SIGINT came from the keyboard (in which case the shell has already
3358 seen it, and wait_sigint_received is non-zero, because keyboard
3359 signals are sent to process groups) or via kill(2) to the foreground
3360 process by another process (or itself). If the shell did receive the
3361 SIGINT, it needs to perform normal SIGINT processing. */
3362 else if (wait_sigint_received
&&
3363 child_caught_sigint
== 0 &&
3364 IS_FOREGROUND (job
) && IS_JOBCONTROL (job
) == 0)
3368 wait_sigint_received
= 0;
3370 /* If SIGINT is trapped, set the exit status so that the trap
3371 handler can see it. */
3372 if (signal_is_trapped (SIGINT
))
3373 last_command_exit_value
= process_exit_status (child
->status
);
3375 /* If the signal is trapped, let the trap handler get it no matter
3376 what and simply return if the trap handler returns.
3377 maybe_call_trap_handler() may cause dead jobs to be removed from
3378 the job table because of a call to execute_command. We work
3379 around this by setting JOBS_LIST_FROZEN. */
3380 old_frozen
= jobs_list_frozen
;
3381 jobs_list_frozen
= 1;
3382 tstatus
= maybe_call_trap_handler (SIGINT
);
3383 jobs_list_frozen
= old_frozen
;
3384 if (tstatus
== 0 && old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
3386 /* wait_sigint_handler () has already seen SIGINT and
3387 allowed the wait builtin to jump out. We need to
3388 call the original SIGINT handler, if necessary. If
3389 the original handler is SIG_DFL, we need to resend
3390 the signal to ourselves. */
3392 temp_handler
= old_sigint_handler
;
3394 /* Bogus. If we've reset the signal handler as the result
3395 of a trap caught on SIGINT, then old_sigint_handler
3396 will point to trap_handler, which now knows nothing about
3397 SIGINT (if we reset the sighandler to the default).
3398 In this case, we have to fix things up. What a crock. */
3399 if (temp_handler
== trap_handler
&& signal_is_trapped (SIGINT
) == 0)
3400 temp_handler
= trap_to_sighandler (SIGINT
);
3401 restore_sigint_handler ();
3402 if (temp_handler
== SIG_DFL
)
3403 termsig_handler (SIGINT
); /* XXX */
3404 else if (temp_handler
!= SIG_IGN
)
3405 (*temp_handler
) (SIGINT
);
3410 return call_set_current
;
3413 /* Build the array of values for the $PIPESTATUS variable from the set of
3414 exit statuses of all processes in the job J. */
3419 #if defined (ARRAY_VARS)
3421 register PROCESS
*p
;
3423 for (i
= 1, p
= jobs
[j
]->pipe
; p
->next
!= jobs
[j
]->pipe
; p
= p
->next
, i
++)
3428 pstatuses
= (int *)xrealloc (pstatuses
, i
* sizeof (int));
3435 pstatuses
[i
++] = process_exit_status (p
->status
);
3438 while (p
!= jobs
[j
]->pipe
);
3440 pstatuses
[i
] = -1; /* sentinel */
3441 set_pipestatus_array (pstatuses
, i
);
3446 run_sigchld_trap (nchild
)
3452 /* Turn off the trap list during the call to parse_and_execute ()
3453 to avoid potentially infinite recursive calls. Preserve the
3454 values of last_command_exit_value, last_made_pid, and the_pipeline
3455 around the execution of the trap commands. */
3456 trap_command
= savestring (trap_list
[SIGCHLD
]);
3458 begin_unwind_frame ("SIGCHLD trap");
3459 unwind_protect_int (last_command_exit_value
);
3460 unwind_protect_int (last_command_exit_signal
);
3461 unwind_protect_var (last_made_pid
);
3462 unwind_protect_int (interrupt_immediately
);
3463 unwind_protect_int (jobs_list_frozen
);
3464 unwind_protect_pointer (the_pipeline
);
3465 unwind_protect_pointer (subst_assign_varlist
);
3467 /* We have to add the commands this way because they will be run
3468 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
3469 to reference freed memory. */
3470 add_unwind_protect (xfree
, trap_command
);
3471 add_unwind_protect (maybe_set_sigchld_trap
, trap_command
);
3473 subst_assign_varlist
= (WORD_LIST
*)NULL
;
3474 the_pipeline
= (PROCESS
*)NULL
;
3476 set_impossible_sigchld_trap ();
3477 jobs_list_frozen
= 1;
3478 for (i
= 0; i
< nchild
; i
++)
3480 interrupt_immediately
= 1;
3481 parse_and_execute (savestring (trap_command
), "trap", SEVAL_NOHIST
|SEVAL_RESETLINE
);
3484 run_unwind_frame ("SIGCHLD trap");
3487 /* Function to call when you want to notify people of changes
3488 in job status. This prints out all jobs which are pending
3489 notification to stderr, and marks those printed as already
3490 notified, thus making them candidates for cleanup. */
3492 notify_of_job_status ()
3494 register int job
, termsig
;
3499 if (jobs
== 0 || js
.j_jobslots
== 0)
3505 sigaddset (&set
, SIGCHLD
);
3506 sigaddset (&set
, SIGTTOU
);
3507 sigemptyset (&oset
);
3508 sigprocmask (SIG_BLOCK
, &set
, &oset
);
3513 /* XXX could use js.j_firstj here */
3514 for (job
= 0, dir
= (char *)NULL
; job
< js
.j_jobslots
; job
++)
3516 if (jobs
[job
] && IS_NOTIFIED (job
) == 0)
3518 s
= raw_job_exit_status (job
);
3519 termsig
= WTERMSIG (s
);
3521 /* POSIX.2 says we have to hang onto the statuses of at most the
3522 last CHILD_MAX background processes if the shell is running a
3523 script. If the shell is running a script, either from a file
3524 or standard input, don't print anything unless the job was
3525 killed by a signal. */
3526 if (startup_state
== 0 && WIFSIGNALED (s
) == 0 &&
3527 ((DEADJOB (job
) && IS_FOREGROUND (job
) == 0) || STOPPED (job
)))
3531 /* If job control is disabled, don't print the status messages.
3532 Mark dead jobs as notified so that they get cleaned up. If
3533 startup_state == 2, we were started to run `-c command', so
3534 don't print anything. */
3535 if ((job_control
== 0 && interactive_shell
) || startup_state
== 2)
3537 /* If job control is disabled, don't print the status messages.
3538 Mark dead jobs as notified so that they get cleaned up. If
3539 startup_state == 2 and subshell_environment has the
3540 SUBSHELL_COMSUB bit turned on, we were started to run a command
3541 substitution, so don't print anything. */
3542 if ((job_control
== 0 && interactive_shell
) ||
3543 (startup_state
== 2 && (subshell_environment
& SUBSHELL_COMSUB
)))
3546 /* POSIX.2 compatibility: if the shell is not interactive,
3547 hang onto the job corresponding to the last asynchronous
3548 pid until the user has been notified of its status or does
3550 if (DEADJOB (job
) && (interactive_shell
|| (find_last_pid (job
, 0) != last_asynchronous_pid
)))
3551 jobs
[job
]->flags
|= J_NOTIFIED
;
3555 /* Print info on jobs that are running in the background,
3556 and on foreground jobs that were killed by anything
3557 except SIGINT (and possibly SIGPIPE). */
3558 switch (JOBSTATE (job
))
3561 if (interactive_shell
== 0 && termsig
&& WIFSIGNALED (s
) &&
3562 termsig
!= SIGINT
&&
3563 #if defined (DONT_REPORT_SIGTERM)
3564 termsig
!= SIGTERM
&&
3566 #if defined (DONT_REPORT_SIGPIPE)
3567 termsig
!= SIGPIPE
&&
3569 signal_is_trapped (termsig
) == 0)
3571 /* Don't print `0' for a line number. */
3572 fprintf (stderr
, _("%s: line %d: "), get_name_for_error (), (line_number
== 0) ? 1 : line_number
);
3573 pretty_print_job (job
, JLIST_NONINTERACTIVE
, stderr
);
3575 else if (IS_FOREGROUND (job
))
3577 #if !defined (DONT_REPORT_SIGPIPE)
3578 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
)
3580 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
&& termsig
!= SIGPIPE
)
3583 fprintf (stderr
, "%s", j_strsignal (termsig
));
3586 fprintf (stderr
, _(" (core dumped)"));
3588 fprintf (stderr
, "\n");
3591 else if (job_control
) /* XXX job control test added */
3594 dir
= current_working_directory ();
3595 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
3596 if (dir
&& strcmp (dir
, jobs
[job
]->wd
) != 0)
3598 _("(wd now: %s)\n"), polite_directory_format (dir
));
3601 jobs
[job
]->flags
|= J_NOTIFIED
;
3605 fprintf (stderr
, "\n");
3607 dir
= current_working_directory ();
3608 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
3609 if (dir
&& (strcmp (dir
, jobs
[job
]->wd
) != 0))
3611 _("(wd now: %s)\n"), polite_directory_format (dir
));
3612 jobs
[job
]->flags
|= J_NOTIFIED
;
3620 programming_error ("notify_of_job_status");
3625 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
3630 /* Initialize the job control mechanism, and set up the tty stuff. */
3632 initialize_job_control (force
)
3639 shell_pgrp
= getpgid (0);
3641 if (shell_pgrp
== -1)
3643 sys_error (_("initialize_job_control: getpgrp failed"));
3647 /* We can only have job control if we are interactive. */
3648 if (interactive
== 0)
3651 original_pgrp
= NO_PID
;
3652 shell_tty
= fileno (stderr
);
3658 /* If forced_interactive is set, we skip the normal check that stderr
3659 is attached to a tty, so we need to check here. If it's not, we
3660 need to see whether we have a controlling tty by opening /dev/tty,
3661 since trying to use job control tty pgrp manipulations on a non-tty
3662 is going to fail. */
3663 if (forced_interactive
&& isatty (fileno (stderr
)) == 0)
3664 shell_tty
= open ("/dev/tty", O_RDWR
|O_NONBLOCK
);
3666 /* Get our controlling terminal. If job_control is set, or
3667 interactive is set, then this is an interactive shell no
3668 matter where fd 2 is directed. */
3669 if (shell_tty
== -1)
3670 shell_tty
= dup (fileno (stderr
)); /* fd 2 */
3672 if (shell_tty
!= -1)
3673 shell_tty
= move_to_high_fd (shell_tty
, 1, -1);
3675 /* Compensate for a bug in systems that compiled the BSD
3676 rlogind with DEBUG defined, like NeXT and Alliant. */
3677 if (shell_pgrp
== 0)
3679 shell_pgrp
= getpid ();
3680 setpgid (0, shell_pgrp
);
3681 tcsetpgrp (shell_tty
, shell_pgrp
);
3684 while ((terminal_pgrp
= tcgetpgrp (shell_tty
)) != -1)
3686 if (shell_pgrp
!= terminal_pgrp
)
3690 ottin
= set_signal_handler(SIGTTIN
, SIG_DFL
);
3692 set_signal_handler (SIGTTIN
, ottin
);
3698 if (terminal_pgrp
== -1)
3701 /* Make sure that we are using the new line discipline. */
3702 if (set_new_line_discipline (shell_tty
) < 0)
3704 sys_error (_("initialize_job_control: line discipline"));
3709 original_pgrp
= shell_pgrp
;
3710 shell_pgrp
= getpid ();
3712 if ((original_pgrp
!= shell_pgrp
) && (setpgid (0, shell_pgrp
) < 0))
3714 sys_error (_("initialize_job_control: setpgid"));
3715 shell_pgrp
= original_pgrp
;
3720 /* If (and only if) we just set our process group to our pid,
3721 thereby becoming a process group leader, and the terminal
3722 is not in the same process group as our (new) process group,
3723 then set the terminal's process group to our (new) process
3724 group. If that fails, set our process group back to what it
3725 was originally (so we can still read from the terminal) and
3726 turn off job control. */
3727 if (shell_pgrp
!= original_pgrp
&& shell_pgrp
!= terminal_pgrp
)
3729 if (give_terminal_to (shell_pgrp
, 0) < 0)
3732 setpgid (0, original_pgrp
);
3733 shell_pgrp
= original_pgrp
;
3738 if (job_control
&& ((t
= tcgetpgrp (shell_tty
)) == -1 || t
!= shell_pgrp
))
3742 sys_error (_("cannot set terminal process group (%d)"), t
);
3746 if (job_control
== 0)
3747 internal_error (_("no job control in this shell"));
3750 if (shell_tty
!= fileno (stderr
))
3751 SET_CLOSE_ON_EXEC (shell_tty
);
3753 set_signal_handler (SIGCHLD
, sigchld_handler
);
3755 change_flag ('m', job_control
? '-' : '+');
3760 if (js
.c_childmax
< 0)
3761 js
.c_childmax
= getmaxchild ();
3762 if (js
.c_childmax
< 0)
3763 js
.c_childmax
= DEFAULT_CHILD_MAX
;
3770 debug_print_pgrps ()
3772 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
3773 (long)original_pgrp
, (long)shell_pgrp
, (long)terminal_pgrp
);
3774 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
3775 shell_tty
, (long)tcgetpgrp (shell_tty
), (long)getpgid(0));
3779 /* Set the line discipline to the best this system has to offer.
3780 Return -1 if this is not possible. */
3782 set_new_line_discipline (tty
)
3785 #if defined (NEW_TTY_DRIVER)
3788 if (ioctl (tty
, TIOCGETD
, &ldisc
) < 0)
3791 if (ldisc
!= NTTYDISC
)
3795 if (ioctl (tty
, TIOCSETD
, &ldisc
) < 0)
3799 #endif /* NEW_TTY_DRIVER */
3801 #if defined (TERMIO_TTY_DRIVER)
3802 # if defined (TERMIO_LDISC) && (NTTYDISC)
3803 if (ioctl (tty
, TCGETA
, &shell_tty_info
) < 0)
3806 if (shell_tty_info
.c_line
!= NTTYDISC
)
3808 shell_tty_info
.c_line
= NTTYDISC
;
3809 if (ioctl (tty
, TCSETAW
, &shell_tty_info
) < 0)
3812 # endif /* TERMIO_LDISC && NTTYDISC */
3814 #endif /* TERMIO_TTY_DRIVER */
3816 #if defined (TERMIOS_TTY_DRIVER)
3817 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
3818 if (tcgetattr (tty
, &shell_tty_info
) < 0)
3821 if (shell_tty_info
.c_line
!= NTTYDISC
)
3823 shell_tty_info
.c_line
= NTTYDISC
;
3824 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
3827 # endif /* TERMIOS_LDISC && NTTYDISC */
3829 #endif /* TERMIOS_TTY_DRIVER */
3831 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
3836 /* Setup this shell to handle C-C, etc. */
3838 initialize_job_signals ()
3842 set_signal_handler (SIGINT
, sigint_sighandler
);
3843 set_signal_handler (SIGTSTP
, SIG_IGN
);
3844 set_signal_handler (SIGTTOU
, SIG_IGN
);
3845 set_signal_handler (SIGTTIN
, SIG_IGN
);
3847 else if (job_control
)
3849 old_tstp
= set_signal_handler (SIGTSTP
, sigstop_sighandler
);
3850 old_ttin
= set_signal_handler (SIGTTIN
, sigstop_sighandler
);
3851 old_ttou
= set_signal_handler (SIGTTOU
, sigstop_sighandler
);
3853 /* Leave these things alone for non-interactive shells without job
3857 /* Here we handle CONT signals. */
3859 sigcont_sighandler (sig
)
3862 initialize_job_signals ();
3863 set_signal_handler (SIGCONT
, old_cont
);
3864 kill (getpid (), SIGCONT
);
3869 /* Here we handle stop signals while we are running not as a login shell. */
3871 sigstop_sighandler (sig
)
3874 set_signal_handler (SIGTSTP
, old_tstp
);
3875 set_signal_handler (SIGTTOU
, old_ttou
);
3876 set_signal_handler (SIGTTIN
, old_ttin
);
3878 old_cont
= set_signal_handler (SIGCONT
, sigcont_sighandler
);
3880 give_terminal_to (shell_pgrp
, 0);
3882 kill (getpid (), sig
);
3887 /* Give the terminal to PGRP. */
3889 give_terminal_to (pgrp
, force
)
3897 if (job_control
|| force
)
3900 sigaddset (&set
, SIGTTOU
);
3901 sigaddset (&set
, SIGTTIN
);
3902 sigaddset (&set
, SIGTSTP
);
3903 sigaddset (&set
, SIGCHLD
);
3904 sigemptyset (&oset
);
3905 sigprocmask (SIG_BLOCK
, &set
, &oset
);
3907 if (tcsetpgrp (shell_tty
, pgrp
) < 0)
3909 /* Maybe we should print an error message? */
3911 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
3912 shell_tty
, (long)getpid(), (long)pgrp
);
3918 terminal_pgrp
= pgrp
;
3919 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
3928 /* Give terminal to NPGRP iff it's currently owned by OPGRP. FLAGS are the
3929 flags to pass to give_terminal_to(). */
3931 maybe_give_terminal_to (opgrp
, npgrp
, flags
)
3937 tpgrp
= tcgetpgrp (shell_tty
);
3938 if (tpgrp
< 0 && errno
== ENOTTY
)
3942 terminal_pgrp
= npgrp
;
3945 else if (tpgrp
!= opgrp
)
3948 internal_warning ("maybe_give_terminal_to: terminal pgrp == %d shell pgrp = %d new pgrp = %d", tpgrp
, opgrp
, npgrp
);
3953 return (give_terminal_to (npgrp
, flags
));
3956 /* Clear out any jobs in the job array. This is intended to be used by
3957 children of the shell, who should not have any job structures as baggage
3958 when they start executing (forking subshells for parenthesized execution
3959 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
3960 is nonzero, only running jobs are removed from the table. */
3962 delete_all_jobs (running_only
)
3968 BLOCK_CHILD (set
, oset
);
3970 /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
3973 js
.j_current
= js
.j_previous
= NO_JOB
;
3975 /* XXX could use js.j_firstj here */
3976 for (i
= 0; i
< js
.j_jobslots
; i
++)
3979 if (i
< js
.j_firstj
&& jobs
[i
])
3980 itrace("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
3981 if (i
> js
.j_lastj
&& jobs
[i
])
3982 itrace("delete_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
3984 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
3985 delete_job (i
, DEL_WARNSTOPPED
);
3987 if (running_only
== 0)
3989 free ((char *)jobs
);
3991 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
3995 if (running_only
== 0)
3998 UNBLOCK_CHILD (oset
);
4001 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
4002 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
4004 nohup_all_jobs (running_only
)
4010 BLOCK_CHILD (set
, oset
);
4014 /* XXX could use js.j_firstj here */
4015 for (i
= 0; i
< js
.j_jobslots
; i
++)
4016 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
4020 UNBLOCK_CHILD (oset
);
4029 /* This really counts all non-dead jobs. */
4030 BLOCK_CHILD (set
, oset
);
4031 /* XXX could use js.j_firstj here */
4032 for (i
= n
= 0; i
< js
.j_jobslots
; i
++)
4035 if (i
< js
.j_firstj
&& jobs
[i
])
4036 itrace("count_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4037 if (i
> js
.j_lastj
&& jobs
[i
])
4038 itrace("count_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4040 if (jobs
[i
] && DEADJOB(i
) == 0)
4043 UNBLOCK_CHILD (oset
);
4048 mark_all_jobs_as_dead ()
4053 if (js
.j_jobslots
== 0)
4056 BLOCK_CHILD (set
, oset
);
4058 /* XXX could use js.j_firstj here */
4059 for (i
= 0; i
< js
.j_jobslots
; i
++)
4062 jobs
[i
]->state
= JDEAD
;
4066 UNBLOCK_CHILD (oset
);
4069 /* Mark all dead jobs as notified, so delete_job () cleans them out
4070 of the job table properly. POSIX.2 says we need to save the
4071 status of the last CHILD_MAX jobs, so we count the number of dead
4072 jobs and mark only enough as notified to save CHILD_MAX statuses. */
4074 mark_dead_jobs_as_notified (force
)
4077 register int i
, ndead
, ndeadproc
;
4080 if (js
.j_jobslots
== 0)
4083 BLOCK_CHILD (set
, oset
);
4085 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
4086 around; just run through the array. */
4089 /* XXX could use js.j_firstj here */
4090 for (i
= 0; i
< js
.j_jobslots
; i
++)
4092 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4093 jobs
[i
]->flags
|= J_NOTIFIED
;
4095 UNBLOCK_CHILD (oset
);
4099 /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
4100 array with the corresponding not marked as notified. This is a better
4101 way to avoid pid aliasing and reuse problems than keeping the POSIX-
4102 mandated CHILD_MAX jobs around. delete_job() takes care of keeping the
4103 bgpids list regulated. */
4105 /* Count the number of dead jobs */
4106 /* XXX could use js.j_firstj here */
4107 for (i
= ndead
= ndeadproc
= 0; i
< js
.j_jobslots
; i
++)
4110 if (i
< js
.j_firstj
&& jobs
[i
])
4111 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4112 if (i
> js
.j_lastj
&& jobs
[i
])
4113 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4115 if (jobs
[i
] && DEADJOB (i
))
4118 ndeadproc
+= processes_in_job (i
);
4123 if (ndeadproc
!= js
.c_reaped
)
4124 itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc
, js
.c_reaped
);
4125 if (ndead
!= js
.j_ndead
)
4126 itrace("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead
, js
.j_ndead
);
4129 if (js
.c_childmax
< 0)
4130 js
.c_childmax
= getmaxchild ();
4131 if (js
.c_childmax
< 0)
4132 js
.c_childmax
= DEFAULT_CHILD_MAX
;
4134 /* Don't do anything if the number of dead processes is less than CHILD_MAX
4135 and we're not forcing a cleanup. */
4136 if (ndeadproc
<= js
.c_childmax
)
4138 UNBLOCK_CHILD (oset
);
4143 itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js
.c_childmax
, ndead
, ndeadproc
);
4146 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
4147 the list. This isn't exactly right yet; changes need to be made
4148 to stop_pipeline so we don't mark the newer jobs after we've
4149 created CHILD_MAX slots in the jobs array. This needs to be
4150 integrated with a way to keep the jobs array from growing without
4151 bound. Maybe we wrap back around to 0 after we reach some max
4152 limit, and there are sufficient job slots free (keep track of total
4153 size of jobs array (js.j_jobslots) and running count of number of jobs
4154 in jobs array. Then keep a job index corresponding to the `oldest job'
4155 and start this loop there, wrapping around as necessary. In effect,
4156 we turn the list into a circular buffer. */
4157 /* XXX could use js.j_firstj here */
4158 for (i
= 0; i
< js
.j_jobslots
; i
++)
4160 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
4163 if (i
< js
.j_firstj
&& jobs
[i
])
4164 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
4165 if (i
> js
.j_lastj
&& jobs
[i
])
4166 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
4168 /* If marking this job as notified would drop us down below
4169 child_max, don't mark it so we can keep at least child_max
4170 statuses. XXX -- need to check what Posix actually says
4171 about keeping statuses. */
4172 if ((ndeadproc
-= processes_in_job (i
)) <= js
.c_childmax
)
4174 jobs
[i
]->flags
|= J_NOTIFIED
;
4178 UNBLOCK_CHILD (oset
);
4181 /* Here to allow other parts of the shell (like the trap stuff) to
4182 freeze and unfreeze the jobs list. */
4186 jobs_list_frozen
= 1;
4190 unfreeze_jobs_list ()
4192 jobs_list_frozen
= 0;
4195 /* Allow or disallow job control to take place. Returns the old value
4198 set_job_control (arg
)
4206 /* If we're turning on job control, reset pipeline_pgrp so make_child will
4207 put new child processes into the right pgrp */
4208 if (job_control
!= old
&& job_control
)
4214 /* Turn off all traces of job control. This is run by children of the shell
4215 which are going to do shellsy things, like wait (), etc. */
4217 without_job_control ()
4219 stop_making_children ();
4221 #if defined (PGRP_PIPE)
4222 sh_closepipe (pgrp_pipe
);
4224 delete_all_jobs (0);
4225 set_job_control (0);
4228 /* If this shell is interactive, terminate all stopped jobs and
4229 restore the original terminal process group. This is done
4230 before the `exec' builtin calls shell_execve. */
4234 if (interactive_shell
) /* XXX - should it be interactive? */
4236 terminate_stopped_jobs ();
4238 if (original_pgrp
>= 0)
4239 give_terminal_to (original_pgrp
, 1);
4242 if (original_pgrp
>= 0)
4243 setpgid (0, original_pgrp
);
4246 /* Restart job control by closing shell tty and reinitializing. This is
4247 called after an exec fails in an interactive shell and we do not exit. */
4249 restart_job_control ()
4251 if (shell_tty
!= -1)
4253 initialize_job_control (0);
4256 /* Set the handler to run when the shell receives a SIGCHLD signal. */
4258 set_sigchld_handler ()
4260 set_signal_handler (SIGCHLD
, sigchld_handler
);
4263 #if defined (PGRP_PIPE)
4264 /* Read from the read end of a pipe. This is how the process group leader
4265 blocks until all of the processes in a pipeline have been made. */
4280 while (read (pp
[0], &ch
, 1) == -1 && errno
== EINTR
)
4285 /* Functional interface closes our local-to-job-control pipes. */
4289 sh_closepipe (pgrp_pipe
);
4293 save_pgrp_pipe (p
, clear
)
4297 p
[0] = pgrp_pipe
[0];
4298 p
[1] = pgrp_pipe
[1];
4300 pgrp_pipe
[0] = pgrp_pipe
[1] = -1;
4304 restore_pgrp_pipe (p
)
4307 pgrp_pipe
[0] = p
[0];
4308 pgrp_pipe
[1] = p
[1];
4311 #endif /* PGRP_PIPE */