1 /* The thing that makes children, remembers them, and contains wait loops. */
3 /* This file works with both POSIX and BSD systems. It implements job
6 /* Copyright (C) 1989-2006 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 it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 2, or (at your option) any later
15 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 You should have received a copy of the GNU General Public License along
21 with Bash; see the file COPYING. If not, write to the Free Software
22 Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
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 #include <sys/param.h>
50 #if defined (BUFFERED_INPUT)
54 /* Need to include this up here for *_TTY_DRIVER definitions. */
57 /* Define this if your output is getting swallowed. It's a no-op on
58 machines with the termio or termios tty drivers. */
59 /* #define DRAIN_OUTPUT */
61 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
62 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
64 #endif /* hpux && !TERMIOS_TTY_DRIVER */
72 #include "builtins/builtext.h"
73 #include "builtins/common.h"
79 #define DEFAULT_CHILD_MAX 32
81 #define MAX_JOBS_IN_ARRAY 4096 /* production */
83 #define MAX_JOBS_IN_ARRAY 128 /* testing */
86 /* Flag values for second argument to delete_job */
87 #define DEL_WARNSTOPPED 1 /* warn about deleting stopped jobs */
88 #define DEL_NOBGPID 2 /* don't add pgrp leader to bgpids */
90 /* Take care of system dependencies that must be handled when waiting for
91 children. The arguments to the WAITPID macro match those to the Posix.1
92 waitpid() function. */
94 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
95 # define WAITPID(pid, statusp, options) \
96 wait3 ((union wait *)statusp, options, (struct rusage *)0)
98 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
99 # define WAITPID(pid, statusp, options) \
100 waitpid ((pid_t)pid, statusp, options)
102 # if defined (HAVE_WAIT3)
103 # define WAITPID(pid, statusp, options) \
104 wait3 (statusp, options, (struct rusage *)0)
106 # define WAITPID(pid, statusp, options) \
107 wait3 (statusp, options, (int *)0)
108 # endif /* HAVE_WAIT3 */
109 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
110 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
112 /* getpgrp () varies between systems. Even systems that claim to be
113 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
114 #if defined (GETPGRP_VOID)
115 # define getpgid(p) getpgrp ()
117 # define getpgid(p) getpgrp (p)
118 #endif /* !GETPGRP_VOID */
120 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
121 handler for SIGCHLD. */
122 #if defined (MUST_REINSTALL_SIGHANDLERS)
123 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
125 # define REINSTALL_SIGCHLD_HANDLER
126 #endif /* !MUST_REINSTALL_SIGHANDLERS */
128 /* Some systems let waitpid(2) tell callers about stopped children. */
129 #if !defined (WCONTINUED) || defined (WCONTINUED_BROKEN)
131 # define WCONTINUED 0
133 #if !defined (WIFCONTINUED)
134 # define WIFCONTINUED(s) (0)
137 /* The number of additional slots to allocate when we run out. */
140 typedef int sh_job_map_func_t
__P((JOB
*, int, int, int));
142 /* Variables used here but defined in other files. */
143 extern int subshell_environment
, line_number
;
144 extern int posixly_correct
, shell_level
;
145 extern int last_command_exit_value
, last_command_exit_signal
;
146 extern int loop_level
, breaking
;
147 extern int sourcelevel
;
148 extern int running_trap
;
149 extern sh_builtin_func_t
*this_shell_builtin
;
150 extern char *shell_name
, *this_command_name
;
151 extern sigset_t top_level_mask
;
152 extern procenv_t wait_intr_buf
;
153 extern int wait_signal_received
;
154 extern WORD_LIST
*subst_assign_varlist
;
156 static struct jobstats zerojs
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
157 struct jobstats js
= { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB
, NO_JOB
, 0, 0 };
159 struct bgpids bgpids
= { 0, 0, 0 };
161 /* The array of known jobs. */
162 JOB
**jobs
= (JOB
**)NULL
;
165 /* The number of slots currently allocated to JOBS. */
169 /* The controlling tty for this shell. */
172 /* The shell's process group. */
173 pid_t shell_pgrp
= NO_PID
;
175 /* The terminal's process group. */
176 pid_t terminal_pgrp
= NO_PID
;
178 /* The process group of the shell's parent. */
179 pid_t original_pgrp
= NO_PID
;
181 /* The process group of the pipeline currently being made. */
182 pid_t pipeline_pgrp
= (pid_t
)0;
184 #if defined (PGRP_PIPE)
185 /* Pipes which each shell uses to communicate with the process group leader
186 until all of the processes in a pipeline have been started. Then the
187 process leader is allowed to continue. */
188 int pgrp_pipe
[2] = { -1, -1 };
192 /* The job which is current; i.e. the one that `%+' stands for. */
193 int current_job
= NO_JOB
;
195 /* The previous job; i.e. the one that `%-' stands for. */
196 int previous_job
= NO_JOB
;
199 /* Last child made by the shell. */
200 pid_t last_made_pid
= NO_PID
;
202 /* Pid of the last asynchronous child. */
203 pid_t last_asynchronous_pid
= NO_PID
;
205 /* The pipeline currently being built. */
206 PROCESS
*the_pipeline
= (PROCESS
*)NULL
;
208 /* If this is non-zero, do job control. */
211 /* Call this when you start making children. */
212 int already_making_children
= 0;
214 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
215 exits from get_tty_state(). */
216 int check_window_size
;
218 /* Functions local to this file. */
220 static void run_sigchld_trap
__P((int));
222 static sighandler wait_sigint_handler
__P((int));
223 static sighandler sigchld_handler
__P((int));
224 static sighandler sigcont_sighandler
__P((int));
225 static sighandler sigstop_sighandler
__P((int));
227 static int waitchld
__P((pid_t
, int));
229 static PROCESS
*find_pipeline
__P((pid_t
, int, int *));
230 static PROCESS
*find_process
__P((pid_t
, int, int *));
232 static char *current_working_directory
__P((void));
233 static char *job_working_directory
__P((void));
234 static char *j_strsignal
__P((int));
235 static char *printable_job_status
__P((int, PROCESS
*, int));
237 static PROCESS
*find_last_proc
__P((int, int));
238 static pid_t find_last_pid
__P((int, int));
240 static int set_new_line_discipline
__P((int));
241 static int map_over_jobs
__P((sh_job_map_func_t
*, int, int));
242 static int job_last_stopped
__P((int));
243 static int job_last_running
__P((int));
244 static int most_recent_job_in_state
__P((int, JOB_STATE
));
245 static int find_job
__P((pid_t
, int, PROCESS
**));
246 static int print_job
__P((JOB
*, int, int, int));
247 static int process_exit_status
__P((WAIT
));
248 static int process_exit_signal
__P((WAIT
));
249 static int job_exit_status
__P((int));
250 static int job_exit_signal
__P((int));
251 static int set_job_status_and_cleanup
__P((int));
253 static WAIT job_signal_status
__P((int));
254 static WAIT raw_job_exit_status
__P((int));
256 static void notify_of_job_status
__P((void));
257 static void reset_job_indices
__P((void));
258 static void cleanup_dead_jobs
__P((void));
259 static int processes_in_job
__P((int));
260 static void realloc_jobs_list
__P((void));
261 static int compact_jobs_list
__P((int));
262 static int discard_pipeline
__P((PROCESS
*));
263 static void add_process
__P((char *, pid_t
));
264 static void print_pipeline
__P((PROCESS
*, int, int, FILE *));
265 static void pretty_print_job
__P((int, int, FILE *));
266 static void set_current_job
__P((int));
267 static void reset_current
__P((void));
268 static void set_job_running
__P((int));
269 static void setjstatus
__P((int));
270 static void mark_all_jobs_as_dead
__P((void));
271 static void mark_dead_jobs_as_notified
__P((int));
272 static void restore_sigint_handler
__P((void));
273 #if defined (PGRP_PIPE)
274 static void pipe_read
__P((int *));
275 static void pipe_close
__P((int *));
278 static struct pidstat
*bgp_alloc
__P((pid_t
, int));
279 static struct pidstat
*bgp_add
__P((pid_t
, int));
280 static int bgp_delete
__P((pid_t
));
281 static void bgp_clear
__P((void));
282 static int bgp_search
__P((pid_t
));
283 static void bgp_prune
__P((void));
285 #if defined (ARRAY_VARS)
286 static int *pstatuses
; /* list of pipeline statuses */
290 /* Used to synchronize between wait_for and other functions and the SIGCHLD
293 static int queue_sigchld
;
295 #define QUEUE_SIGCHLD(os) (os) = sigchld, queue_sigchld++
297 #define UNQUEUE_SIGCHLD(os) \
300 if (queue_sigchld == 0 && os != sigchld) \
304 static SigHandler
*old_tstp
, *old_ttou
, *old_ttin
;
305 static SigHandler
*old_cont
= (SigHandler
*)SIG_DFL
;
307 /* A place to temporarily save the current pipeline. */
308 static PROCESS
*saved_pipeline
;
309 static int saved_already_making_children
;
311 /* Set this to non-zero whenever you don't want the jobs list to change at
312 all: no jobs deleted and no status change notifications. This is used,
313 for example, when executing SIGCHLD traps, which may run arbitrary
315 static int jobs_list_frozen
;
317 static char retcode_name_buffer
[64];
319 /* flags to detect pid wraparound */
320 static pid_t first_pid
= NO_PID
;
321 static int pid_wrap
= -1;
323 #if !defined (_POSIX_VERSION)
325 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
326 library functions and system calls. */
327 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
328 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
336 /* ioctl will handle setting errno correctly. */
337 if (ioctl (fd
, TIOCGPGRP
, &pgrp
) < 0)
342 #endif /* !_POSIX_VERSION */
344 /* Initialize the global job stats structure and other bookkeeping variables */
353 /* Return the working directory for the current process. Unlike
354 job_working_directory, this does not call malloc (), nor do any
355 of the functions it calls. This is so that it can safely be called
356 from a signal handler. */
358 current_working_directory ()
361 static char d
[PATH_MAX
];
363 dir
= get_string_value ("PWD");
365 if (dir
== 0 && the_current_working_directory
&& no_symbolic_links
)
366 dir
= the_current_working_directory
;
370 dir
= getcwd (d
, sizeof(d
));
375 return (dir
== 0) ? "<unknown>" : dir
;
378 /* Return the working directory for the current process. */
380 job_working_directory ()
384 dir
= get_string_value ("PWD");
386 return (savestring (dir
));
388 dir
= get_working_directory ("job-working-directory");
392 return (savestring ("<unknown>"));
398 if (already_making_children
)
401 already_making_children
= 1;
406 stop_making_children ()
408 already_making_children
= 0;
412 cleanup_the_pipeline ()
417 BLOCK_CHILD (set
, oset
);
418 disposer
= the_pipeline
;
419 the_pipeline
= (PROCESS
*)NULL
;
420 UNBLOCK_CHILD (oset
);
423 discard_pipeline (disposer
);
427 save_pipeline (clear
)
430 saved_pipeline
= the_pipeline
;
432 the_pipeline
= (PROCESS
*)NULL
;
433 saved_already_making_children
= already_making_children
;
437 restore_pipeline (discard
)
440 PROCESS
*old_pipeline
;
442 old_pipeline
= the_pipeline
;
443 the_pipeline
= saved_pipeline
;
444 already_making_children
= saved_already_making_children
;
446 discard_pipeline (old_pipeline
);
449 /* Start building a pipeline. */
455 cleanup_the_pipeline ();
457 #if defined (PGRP_PIPE)
458 pipe_close (pgrp_pipe
);
462 #if defined (PGRP_PIPE)
465 if (pipe (pgrp_pipe
) == -1)
466 sys_error ("start_pipeline: pgrp pipe");
471 /* Stop building a pipeline. Install the process list in the job array.
472 This returns the index of the newly installed job.
473 DEFERRED is a command structure to be executed upon satisfactory
474 execution exit of this pipeline. */
476 stop_pipeline (async
, deferred
)
484 BLOCK_CHILD (set
, oset
);
486 #if defined (PGRP_PIPE)
487 /* The parent closes the process group synchronization pipe. */
488 pipe_close (pgrp_pipe
);
491 cleanup_dead_jobs ();
493 if (js
.j_jobslots
== 0)
495 js
.j_jobslots
= JOB_SLOTS
;
496 jobs
= (JOB
**)xmalloc (js
.j_jobslots
* sizeof (JOB
*));
498 /* Now blank out these new entries. */
499 for (i
= 0; i
< js
.j_jobslots
; i
++)
500 jobs
[i
] = (JOB
*)NULL
;
502 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
505 /* Scan from the last slot backward, looking for the next free one. */
506 /* XXX - revisit this interactive assumption */
507 /* XXX - this way for now */
510 for (i
= js
.j_jobslots
; i
; i
--)
517 /* This wraps around, but makes it inconvenient to extend the array */
518 for (i
= js
.j_lastj
+1; i
!= js
.j_lastj
; i
++)
520 if (i
>= js
.j_jobslots
)
528 /* This doesn't wrap around yet. */
529 for (i
= js
.j_lastj
? js
.j_lastj
+ 1 : js
.j_lastj
; i
< js
.j_jobslots
; i
++)
535 /* Do we need more room? */
537 /* First try compaction */
538 if ((interactive_shell
== 0 || subshell_environment
) && i
== js
.j_jobslots
&& js
.j_jobslots
>= MAX_JOBS_IN_ARRAY
)
539 i
= compact_jobs_list (0);
541 /* If we can't compact, reallocate */
542 if (i
== js
.j_jobslots
)
544 js
.j_jobslots
+= JOB_SLOTS
;
545 jobs
= (JOB
**)xrealloc (jobs
, (js
.j_jobslots
* sizeof (JOB
*)));
547 for (j
= i
; j
< js
.j_jobslots
; j
++)
548 jobs
[j
] = (JOB
*)NULL
;
551 /* Add the current pipeline to the job list. */
555 int any_running
, any_stopped
, n
;
557 newjob
= (JOB
*)xmalloc (sizeof (JOB
));
559 for (n
= 1, p
= the_pipeline
; p
->next
!= the_pipeline
; n
++, p
= p
->next
)
561 p
->next
= (PROCESS
*)NULL
;
562 newjob
->pipe
= REVERSE_LIST (the_pipeline
, PROCESS
*);
563 for (p
= newjob
->pipe
; p
->next
; p
= p
->next
)
565 p
->next
= newjob
->pipe
;
567 the_pipeline
= (PROCESS
*)NULL
;
568 newjob
->pgrp
= pipeline_pgrp
;
573 /* Flag to see if in another pgrp. */
575 newjob
->flags
|= J_JOBCONTROL
;
577 /* Set the state of this pipeline. */
579 any_running
= any_stopped
= 0;
582 any_running
|= PRUNNING (p
);
583 any_stopped
|= PSTOPPED (p
);
586 while (p
!= newjob
->pipe
);
588 newjob
->state
= any_running
? JRUNNING
: (any_stopped
? JSTOPPED
: JDEAD
);
589 newjob
->wd
= job_working_directory ();
590 newjob
->deferred
= deferred
;
592 newjob
->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
593 newjob
->cleanarg
= (PTR_T
) NULL
;
596 if (newjob
->state
== JDEAD
&& (newjob
->flags
& J_FOREGROUND
))
598 if (newjob
->state
== JDEAD
)
600 js
.c_reaped
+= n
; /* wouldn't have been done since this was not part of a job */
609 newjob
= (JOB
*)NULL
;
612 js
.j_lastmade
= newjob
;
618 newjob
->flags
&= ~J_FOREGROUND
;
619 newjob
->flags
|= J_ASYNC
;
620 js
.j_lastasync
= newjob
;
628 newjob
->flags
|= J_FOREGROUND
;
630 * !!!!! NOTE !!!!! (chet@ins.cwru.edu)
632 * The currently-accepted job control wisdom says to set the
633 * terminal's process group n+1 times in an n-step pipeline:
634 * once in the parent and once in each child. This is where
635 * the parent gives it away.
637 * Don't give the terminal away if this shell is an asynchronous
641 if (job_control
&& newjob
->pgrp
&& (subshell_environment
&SUBSHELL_ASYNC
) == 0)
642 give_terminal_to (newjob
->pgrp
, 0);
646 stop_making_children ();
647 UNBLOCK_CHILD (oset
);
648 return (js
.j_current
);
651 /* Functions to manage the list of exited background pids whose status has
654 static struct pidstat
*
655 bgp_alloc (pid
, status
)
661 ps
= (struct pidstat
*)xmalloc (sizeof (struct pidstat
));
664 ps
->next
= (struct pidstat
*)0;
668 static struct pidstat
*
669 bgp_add (pid
, status
)
675 ps
= bgp_alloc (pid
, status
);
677 if (bgpids
.list
== 0)
679 bgpids
.list
= bgpids
.end
= ps
;
680 bgpids
.npid
= 0; /* just to make sure */
684 bgpids
.end
->next
= ps
;
689 if (bgpids
.npid
> js
.c_childmax
)
699 struct pidstat
*prev
, *p
;
701 for (prev
= p
= bgpids
.list
; p
; prev
= p
, p
= p
->next
)
704 prev
->next
= p
->next
; /* remove from list */
709 return 0; /* not found */
712 itrace("bgp_delete: deleting %d", pid
);
715 /* Housekeeping in the border cases. */
716 if (p
== bgpids
.list
)
717 bgpids
.list
= bgpids
.list
->next
;
718 else if (p
== bgpids
.end
)
722 if (bgpids
.npid
== 0)
723 bgpids
.list
= bgpids
.end
= 0;
724 else if (bgpids
.npid
== 1)
725 bgpids
.end
= bgpids
.list
; /* just to make sure */
731 /* Clear out the list of saved statuses */
735 struct pidstat
*ps
, *p
;
737 for (ps
= bgpids
.list
; ps
; )
743 bgpids
.list
= bgpids
.end
= 0;
747 /* Search for PID in the list of saved background pids; return its status if
748 found. If not found, return -1. */
755 for (ps
= bgpids
.list
; ps
; ps
= ps
->next
)
766 while (bgpids
.npid
> js
.c_childmax
)
769 bgpids
.list
= bgpids
.list
->next
;
775 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
776 been deleted. The caller should check whether js.j_njobs is 0 before
777 calling this. This wraps around, but the rest of the code does not. At
778 this point, it should not matter. */
784 if (jobs
[js
.j_firstj
] == 0)
787 if (old
>= js
.j_jobslots
)
788 old
= js
.j_jobslots
- 1;
789 while (js
.j_firstj
!= old
)
791 if (js
.j_firstj
>= js
.j_jobslots
)
793 if (jobs
[js
.j_firstj
] || js
.j_firstj
== old
) /* needed if old == 0 */
797 if (js
.j_firstj
== old
)
798 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
800 if (jobs
[js
.j_lastj
] == 0)
805 while (js
.j_lastj
!= old
)
808 js
.j_lastj
= js
.j_jobslots
- 1;
809 if (jobs
[js
.j_lastj
] || js
.j_lastj
== old
) /* needed if old == js.j_jobslots */
813 if (js
.j_lastj
== old
)
814 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
818 /* Delete all DEAD jobs that the user had received notification about. */
825 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
830 /* XXX could use js.j_firstj and js.j_lastj here */
831 for (i
= 0; i
< js
.j_jobslots
; i
++)
834 if (i
< js
.j_firstj
&& jobs
[i
])
835 itrace("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
836 if (i
> js
.j_lastj
&& jobs
[i
])
837 itrace("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
840 if (jobs
[i
] && DEADJOB (i
) && IS_NOTIFIED (i
))
847 processes_in_job (job
)
859 while (p
!= jobs
[job
]->pipe
);
871 job
= find_job (pid
, 0, &p
);
875 itrace ("delete_old_job: found pid %d in job %d with state %d", pid
, job
, jobs
[job
]->state
);
877 if (JOBSTATE (job
) == JDEAD
)
878 delete_job (job
, DEL_NOBGPID
);
881 internal_warning (_("forked pid %d appears in running job %d"), pid
, job
);
888 /* Reallocate and compress the jobs list. This returns with a jobs array
889 whose size is a multiple of JOB_SLOTS and can hold the current number of
890 jobs. Heuristics are used to minimize the number of new reallocs. */
895 int nsize
, i
, j
, ncur
, nprev
;
898 ncur
= nprev
= NO_JOB
;
899 nsize
= ((js
.j_njobs
+ JOB_SLOTS
- 1) / JOB_SLOTS
);
901 i
= js
.j_njobs
% JOB_SLOTS
;
902 if (i
== 0 || i
> (JOB_SLOTS
>> 1))
905 BLOCK_CHILD (set
, oset
);
906 nlist
= (js
.j_jobslots
== nsize
) ? jobs
: (JOB
**) xmalloc (nsize
* sizeof (JOB
*));
908 for (i
= j
= 0; i
< js
.j_jobslots
; i
++)
911 if (i
== js
.j_current
)
913 if (i
== js
.j_previous
)
915 nlist
[j
++] = jobs
[i
];
919 itrace ("realloc_jobs_list: resize jobs list from %d to %d", js
.j_jobslots
, nsize
);
920 itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js
.j_lastj
, (j
> 0) ? j
- 1 : 0);
921 itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js
.j_njobs
, (j
> 0) ? j
- 1 : 0);
925 js
.j_lastj
= (j
> 0) ? j
- 1 : 0;
927 js
.j_jobslots
= nsize
;
929 /* Zero out remaining slots in new jobs list */
930 for ( ; j
< nsize
; j
++)
931 nlist
[j
] = (JOB
*)NULL
;
942 js
.j_previous
= nprev
;
944 /* Need to reset these */
945 if (js
.j_current
== NO_JOB
|| js
.j_previous
== NO_JOB
|| js
.j_current
> js
.j_lastj
|| js
.j_previous
> js
.j_lastj
)
949 itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js
.j_current
, js
.j_previous
);
952 UNBLOCK_CHILD (oset
);
955 /* Compact the jobs list by removing dead jobs. Assumed that we have filled
956 the jobs array to some predefined maximum. Called when the shell is not
957 the foreground process (subshell_environment != 0). Returns the first
958 available slot in the compacted list. If that value is js.j_jobslots, then
959 the list needs to be reallocated. The jobs array may be in new memory if
960 this returns > 0 and < js.j_jobslots. FLAGS is reserved for future use. */
962 compact_jobs_list (flags
)
965 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
966 return js
.j_jobslots
;
969 realloc_jobs_list ();
972 itrace("compact_jobs_list: returning %d", (js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
975 return ((js
.j_lastj
|| jobs
[js
.j_lastj
]) ? js
.j_lastj
+ 1 : 0);
978 /* Delete the job at INDEX from the job list. Must be called
979 with SIGCHLD blocked. */
981 delete_job (job_index
, dflags
)
982 int job_index
, dflags
;
988 if (js
.j_jobslots
== 0 || jobs_list_frozen
)
991 if ((dflags
& DEL_WARNSTOPPED
) && subshell_environment
== 0 && STOPPED (job_index
))
992 internal_warning (_("deleting stopped job %d with process group %ld"), job_index
+1, (long)jobs
[job_index
]->pgrp
);
993 temp
= jobs
[job_index
];
997 if ((dflags
& DEL_NOBGPID
) == 0)
999 proc
= find_last_proc (job_index
, 0);
1000 /* Could do this just for J_ASYNC jobs, but we save all. */
1002 bgp_add (proc
->pid
, process_exit_status (proc
->status
));
1005 jobs
[job_index
] = (JOB
*)NULL
;
1006 if (temp
== js
.j_lastmade
)
1008 else if (temp
== js
.j_lastasync
)
1012 ndel
= discard_pipeline (temp
->pipe
);
1014 js
.c_injobs
-= ndel
;
1015 if (temp
->state
== JDEAD
)
1017 js
.c_reaped
-= ndel
;
1019 if (js
.c_reaped
< 0)
1022 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
);
1029 dispose_command (temp
->deferred
);
1034 if (js
.j_njobs
== 0)
1035 js
.j_firstj
= js
.j_lastj
= 0;
1036 else if (jobs
[js
.j_firstj
] == 0 || jobs
[js
.j_lastj
] == 0)
1037 reset_job_indices ();
1039 if (job_index
== js
.j_current
|| job_index
== js
.j_previous
)
1043 /* Must be called with SIGCHLD blocked. */
1045 nohup_job (job_index
)
1050 if (js
.j_jobslots
== 0)
1053 if (temp
= jobs
[job_index
])
1054 temp
->flags
|= J_NOHUP
;
1057 /* Get rid of the data structure associated with a process chain. */
1059 discard_pipeline (chain
)
1060 register PROCESS
*chain
;
1062 register PROCESS
*this, *next
;
1070 FREE (this->command
);
1075 while (this != chain
);
1080 /* Add this process to the chain being built in the_pipeline.
1081 NAME is the command string that will be exec'ed later.
1082 PID is the process id of the child. */
1084 add_process (name
, pid
)
1090 #if defined (RECYCLES_PIDS)
1092 p
= find_process (pid
, 0, &j
);
1097 internal_warning ("add_process: process %5ld (%s) in the_pipeline", (long)p
->pid
, p
->command
);
1100 internal_warning ("add_process: pid %5ld (%s) marked as still alive", (long)p
->pid
, p
->command
);
1101 p
->running
= PS_RECYCLED
; /* mark as recycled */
1105 t
= (PROCESS
*)xmalloc (sizeof (PROCESS
));
1106 t
->next
= the_pipeline
;
1108 WSTATUS (t
->status
) = 0;
1109 t
->running
= PS_RUNNING
;
1118 while (p
->next
!= t
->next
)
1125 /* Take the last job and make it the first job. Must be called with
1128 rotate_the_pipeline ()
1132 if (the_pipeline
->next
== the_pipeline
)
1134 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1139 /* Reverse the order of the processes in the_pipeline. Must be called with
1142 reverse_the_pipeline ()
1146 if (the_pipeline
->next
== the_pipeline
)
1149 for (p
= the_pipeline
; p
->next
!= the_pipeline
; p
= p
->next
)
1151 p
->next
= (PROCESS
*)NULL
;
1153 n
= REVERSE_LIST (the_pipeline
, PROCESS
*);
1156 for (p
= the_pipeline
; p
->next
; p
= p
->next
)
1158 p
->next
= the_pipeline
;
1162 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
1163 then it is time to stop mapping, and that is the return value
1164 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
1167 map_over_jobs (func
, arg1
, arg2
)
1168 sh_job_map_func_t
*func
;
1175 if (js
.j_jobslots
== 0)
1178 BLOCK_CHILD (set
, oset
);
1180 /* XXX could use js.j_firstj here */
1181 for (i
= result
= 0; i
< js
.j_jobslots
; i
++)
1184 if (i
< js
.j_firstj
&& jobs
[i
])
1185 itrace("map_over_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1186 if (i
> js
.j_lastj
&& jobs
[i
])
1187 itrace("map_over_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1191 result
= (*func
)(jobs
[i
], arg1
, arg2
, i
);
1197 UNBLOCK_CHILD (oset
);
1202 /* Cause all the jobs in the current pipeline to exit. */
1204 terminate_current_pipeline ()
1206 if (pipeline_pgrp
&& pipeline_pgrp
!= shell_pgrp
)
1208 killpg (pipeline_pgrp
, SIGTERM
);
1209 killpg (pipeline_pgrp
, SIGCONT
);
1213 /* Cause all stopped jobs to exit. */
1215 terminate_stopped_jobs ()
1219 /* XXX could use js.j_firstj here */
1220 for (i
= 0; i
< js
.j_jobslots
; i
++)
1222 if (jobs
[i
] && STOPPED (i
))
1224 killpg (jobs
[i
]->pgrp
, SIGTERM
);
1225 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1230 /* Cause all jobs, running or stopped, to receive a hangup signal. If
1231 a job is marked J_NOHUP, don't send the SIGHUP. */
1237 /* XXX could use js.j_firstj here */
1238 for (i
= 0; i
< js
.j_jobslots
; i
++)
1242 if (jobs
[i
]->flags
& J_NOHUP
)
1244 killpg (jobs
[i
]->pgrp
, SIGHUP
);
1246 killpg (jobs
[i
]->pgrp
, SIGCONT
);
1252 kill_current_pipeline ()
1254 stop_making_children ();
1258 /* Return the pipeline that PID belongs to. Note that the pipeline
1259 doesn't have to belong to a job. Must be called with SIGCHLD blocked.
1260 If JOBP is non-null, return the index of the job containing PID. */
1262 find_pipeline (pid
, alive_only
, jobp
)
1265 int *jobp
; /* index into jobs list or NO_JOB */
1270 /* See if this process is in the pipeline that we are building. */
1278 /* Return it if we found it. Don't ever return a recycled pid. */
1279 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1284 while (p
!= the_pipeline
);
1287 job
= find_job (pid
, alive_only
, &p
);
1290 return (job
== NO_JOB
) ? (PROCESS
*)NULL
: jobs
[job
]->pipe
;
1293 /* Return the PROCESS * describing PID. If JOBP is non-null return the index
1294 into the jobs array of the job containing PID. Must be called with
1297 find_process (pid
, alive_only
, jobp
)
1300 int *jobp
; /* index into jobs list or NO_JOB */
1304 p
= find_pipeline (pid
, alive_only
, jobp
);
1305 while (p
&& p
->pid
!= pid
)
1310 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1311 belong to any job. Must be called with SIGCHLD blocked. */
1313 find_job (pid
, alive_only
, procp
)
1321 /* XXX could use js.j_firstj here, and should check js.j_lastj */
1322 for (i
= 0; i
< js
.j_jobslots
; i
++)
1325 if (i
< js
.j_firstj
&& jobs
[i
])
1326 itrace("find_job: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
1327 if (i
> js
.j_lastj
&& jobs
[i
])
1328 itrace("find_job: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
1336 if (p
->pid
== pid
&& ((alive_only
== 0 && PRECYCLED(p
) == 0) || PALIVE(p
)))
1345 while (p
!= jobs
[i
]->pipe
);
1352 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
1353 required by find_job. */
1355 get_job_by_pid (pid
, block
)
1363 BLOCK_CHILD (set
, oset
);
1365 job
= find_job (pid
, 0, NULL
);
1368 UNBLOCK_CHILD (oset
);
1373 /* Print descriptive information about the job with leader pid PID. */
1381 BLOCK_CHILD (set
, oset
);
1383 job
= find_job (pid
, 0, NULL
);
1386 fprintf (stderr
, "[%d] %ld\n", job
+ 1, (long)pid
);
1388 programming_error (_("describe_pid: %ld: no such pid"), (long)pid
);
1390 UNBLOCK_CHILD (oset
);
1402 x
= retcode_name_buffer
;
1403 sprintf (x
, "Signal %d", s
);
1409 printable_job_status (j
, p
, format
)
1419 if (STOPPED (j
) && format
== 0)
1421 if (posixly_correct
== 0 || p
== 0 || (WIFSTOPPED (p
->status
) == 0))
1425 temp
= retcode_name_buffer
;
1426 sprintf (temp
, "Stopped(%s)", signal_name (WSTOPSIG (p
->status
)));
1429 else if (RUNNING (j
))
1433 if (WIFSTOPPED (p
->status
))
1434 temp
= j_strsignal (WSTOPSIG (p
->status
));
1435 else if (WIFSIGNALED (p
->status
))
1436 temp
= j_strsignal (WTERMSIG (p
->status
));
1437 else if (WIFEXITED (p
->status
))
1439 temp
= retcode_name_buffer
;
1440 es
= WEXITSTATUS (p
->status
);
1442 strcpy (temp
, "Done");
1443 else if (posixly_correct
)
1444 sprintf (temp
, "Done(%d)", es
);
1446 sprintf (temp
, "Exit %d", es
);
1449 temp
= "Unknown status";
1455 /* This is the way to print out information on a job if you
1456 know the index. FORMAT is:
1458 JLIST_NORMAL) [1]+ Running emacs
1459 JLIST_LONG ) [1]+ 2378 Running emacs
1460 -1 ) [1]+ 2378 emacs
1462 JLIST_NORMAL) [1]+ Stopped ls | more
1463 JLIST_LONG ) [1]+ 2369 Stopped ls
1466 Just list the pid of the process group leader (really
1469 Use format JLIST_NORMAL, but list only jobs about which
1470 the user has not been notified. */
1472 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1473 the JOBS array corresponding to this pipeline. FORMAT is as described
1474 above. Must be called with SIGCHLD blocked.
1476 If you're printing a pipeline that's not in the jobs array, like the
1477 current pipeline as it's being created, pass -1 for JOB_INDEX */
1479 print_pipeline (p
, job_index
, format
, stream
)
1481 int job_index
, format
;
1484 PROCESS
*first
, *last
, *show
;
1485 int es
, name_padding
;
1492 while (last
->next
!= first
)
1498 fprintf (stream
, format
? " " : " |");
1500 if (format
!= JLIST_STANDARD
)
1501 fprintf (stream
, "%5ld", (long)p
->pid
);
1503 fprintf (stream
, " ");
1505 if (format
> -1 && job_index
>= 0)
1507 show
= format
? p
: last
;
1508 temp
= printable_job_status (job_index
, show
, format
);
1514 if (show
->running
== first
->running
&&
1515 WSTATUS (show
->status
) == WSTATUS (first
->status
))
1519 temp
= (char *)NULL
;
1524 fprintf (stream
, "%s", temp
);
1528 es
= 2; /* strlen ("| ") */
1529 name_padding
= LONGEST_SIGNAL_DESC
- es
;
1531 fprintf (stream
, "%*s", name_padding
, "");
1533 if ((WIFSTOPPED (show
->status
) == 0) &&
1534 (WIFCONTINUED (show
->status
) == 0) &&
1535 WIFCORED (show
->status
))
1536 fprintf (stream
, "(core dumped) ");
1540 if (p
!= first
&& format
)
1541 fprintf (stream
, "| ");
1544 fprintf (stream
, "%s", p
->command
);
1546 if (p
== last
&& job_index
>= 0)
1548 temp
= current_working_directory ();
1550 if (RUNNING (job_index
) && (IS_FOREGROUND (job_index
) == 0))
1551 fprintf (stream
, " &");
1553 if (strcmp (temp
, jobs
[job_index
]->wd
) != 0)
1555 " (wd: %s)", polite_directory_format (jobs
[job_index
]->wd
));
1558 if (format
|| (p
== last
))
1560 /* We need to add a CR only if this is an interactive shell, and
1561 we're reporting the status of a completed job asynchronously.
1562 We can't really check whether this particular job is being
1563 reported asynchronously, so just add the CR if the shell is
1564 currently interactive and asynchronous notification is enabled. */
1565 if (asynchronous_notification
&& interactive
)
1566 fprintf (stream
, "\r\n");
1568 fprintf (stream
, "\n");
1578 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
1579 Must be called with SIGCHLD blocked or queued with queue_sigchld */
1581 pretty_print_job (job_index
, format
, stream
)
1582 int job_index
, format
;
1585 register PROCESS
*p
;
1587 /* Format only pid information about the process group leader? */
1588 if (format
== JLIST_PID_ONLY
)
1590 fprintf (stream
, "%ld\n", (long)jobs
[job_index
]->pipe
->pid
);
1594 if (format
== JLIST_CHANGED_ONLY
)
1596 if (IS_NOTIFIED (job_index
))
1598 format
= JLIST_STANDARD
;
1601 if (format
!= JLIST_NONINTERACTIVE
)
1602 fprintf (stream
, "[%d]%c ", job_index
+ 1,
1603 (job_index
== js
.j_current
) ? '+':
1604 (job_index
== js
.j_previous
) ? '-' : ' ');
1606 if (format
== JLIST_NONINTERACTIVE
)
1607 format
= JLIST_LONG
;
1609 p
= jobs
[job_index
]->pipe
;
1611 print_pipeline (p
, job_index
, format
, stream
);
1613 /* We have printed information about this job. When the job's
1614 status changes, waitchld () sets the notification flag to 0. */
1615 jobs
[job_index
]->flags
|= J_NOTIFIED
;
1619 print_job (job
, format
, state
, job_index
)
1621 int format
, state
, job_index
;
1623 if (state
== -1 || (JOB_STATE
)state
== job
->state
)
1624 pretty_print_job (job_index
, format
, stdout
);
1629 list_one_job (job
, format
, ignore
, job_index
)
1631 int format
, ignore
, job_index
;
1633 pretty_print_job (job_index
, format
, stdout
);
1637 list_stopped_jobs (format
)
1640 cleanup_dead_jobs ();
1641 map_over_jobs (print_job
, format
, (int)JSTOPPED
);
1645 list_running_jobs (format
)
1648 cleanup_dead_jobs ();
1649 map_over_jobs (print_job
, format
, (int)JRUNNING
);
1652 /* List jobs. If FORMAT is non-zero, then the long form of the information
1653 is printed, else just a short version. */
1655 list_all_jobs (format
)
1658 cleanup_dead_jobs ();
1659 map_over_jobs (print_job
, format
, -1);
1662 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
1663 COMMAND is just for remembering the name of the command; we don't do
1664 anything else with it. ASYNC_P says what to do with the tty. If
1665 non-zero, then don't give it away. */
1667 make_child (command
, async_p
)
1675 sigaddset (&set
, SIGCHLD
);
1676 sigaddset (&set
, SIGINT
);
1677 sigemptyset (&oset
);
1678 sigprocmask (SIG_BLOCK
, &set
, &oset
);
1682 #if defined (BUFFERED_INPUT)
1683 /* If default_buffered_input is active, we are reading a script. If
1684 the command is asynchronous, we have already duplicated /dev/null
1685 as fd 0, but have not changed the buffered stream corresponding to
1686 the old fd 0. We don't want to sync the stream in this case. */
1687 if (default_buffered_input
!= -1 &&
1688 (!async_p
|| default_buffered_input
> 0))
1689 sync_buffered_stream (default_buffered_input
);
1690 #endif /* BUFFERED_INPUT */
1692 /* Create the child, handle severe errors. */
1693 if ((pid
= fork ()) < 0)
1697 /* Kill all of the processes in the current pipeline. */
1698 terminate_current_pipeline ();
1700 /* Discard the current pipeline, if any. */
1702 kill_current_pipeline ();
1704 throw_to_top_level (); /* Reset signals, etc. */
1709 /* In the child. Give this child the right process group, set the
1710 signals to the default state for a new process. */
1714 #if defined (BUFFERED_INPUT)
1715 /* Close default_buffered_input if it's > 0. We don't close it if it's
1716 0 because that's the file descriptor used when redirecting input,
1717 and it's wrong to close the file in that case. */
1718 unset_bash_input (0);
1719 #endif /* BUFFERED_INPUT */
1721 /* Restore top-level signal mask. */
1722 sigprocmask (SIG_SETMASK
, &top_level_mask
, (sigset_t
*)NULL
);
1726 /* All processes in this pipeline belong in the same
1729 if (pipeline_pgrp
== 0) /* This is the first child. */
1730 pipeline_pgrp
= mypid
;
1732 /* Check for running command in backquotes. */
1733 if (pipeline_pgrp
== shell_pgrp
)
1734 ignore_tty_job_signals ();
1736 default_tty_job_signals ();
1738 /* Set the process group before trying to mess with the terminal's
1739 process group. This is mandated by POSIX. */
1740 /* This is in accordance with the Posix 1003.1 standard,
1741 section B.7.2.4, which says that trying to set the terminal
1742 process group with tcsetpgrp() to an unused pgrp value (like
1743 this would have for the first child) is an error. Section
1744 B.4.3.3, p. 237 also covers this, in the context of job control
1746 if (setpgid (mypid
, pipeline_pgrp
) < 0)
1747 sys_error ("child setpgid (%ld to %ld)", (long)mypid
, (long)pipeline_pgrp
);
1749 /* By convention (and assumption above), if
1750 pipeline_pgrp == shell_pgrp, we are making a child for
1751 command substitution.
1752 In this case, we don't want to give the terminal to the
1753 shell's process group (we could be in the middle of a
1754 pipeline, for example). */
1755 if (async_p
== 0 && pipeline_pgrp
!= shell_pgrp
&& ((subshell_environment
&SUBSHELL_ASYNC
) == 0))
1756 give_terminal_to (pipeline_pgrp
, 0);
1758 #if defined (PGRP_PIPE)
1759 if (pipeline_pgrp
== mypid
)
1760 pipe_read (pgrp_pipe
);
1763 else /* Without job control... */
1765 if (pipeline_pgrp
== 0)
1766 pipeline_pgrp
= shell_pgrp
;
1768 /* If these signals are set to SIG_DFL, we encounter the curious
1769 situation of an interactive ^Z to a running process *working*
1770 and stopping the process, but being unable to do anything with
1771 that process to change its state. On the other hand, if they
1772 are set to SIG_IGN, jobs started from scripts do not stop when
1773 the shell running the script gets a SIGTSTP and stops. */
1775 default_tty_job_signals ();
1778 #if defined (PGRP_PIPE)
1779 /* Release the process group pipe, since our call to setpgid ()
1780 is done. The last call to pipe_close is done in stop_pipeline. */
1781 pipe_close (pgrp_pipe
);
1782 #endif /* PGRP_PIPE */
1785 last_asynchronous_pid
= mypid
;
1786 #if defined (RECYCLES_PIDS)
1787 else if (last_asynchronous_pid
== mypid
)
1788 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
1789 last_asynchronous_pid
= 1;
1794 /* In the parent. Remember the pid of the child just created
1795 as the proper pgrp if this is the first child. */
1797 if (first_pid
== NO_PID
)
1799 else if (pid_wrap
== -1 && pid
< first_pid
)
1801 else if (pid_wrap
== 0 && pid
>= first_pid
)
1806 if (pipeline_pgrp
== 0)
1808 pipeline_pgrp
= pid
;
1809 /* Don't twiddle terminal pgrps in the parent! This is the bug,
1810 not the good thing of twiddling them in the child! */
1811 /* give_terminal_to (pipeline_pgrp, 0); */
1813 /* This is done on the recommendation of the Rationale section of
1814 the POSIX 1003.1 standard, where it discusses job control and
1815 shells. It is done to avoid possible race conditions. (Ref.
1816 1003.1 Rationale, section B.4.3.3, page 236). */
1817 setpgid (pid
, pipeline_pgrp
);
1821 if (pipeline_pgrp
== 0)
1822 pipeline_pgrp
= shell_pgrp
;
1825 /* Place all processes into the jobs array regardless of the
1826 state of job_control. */
1827 add_process (command
, pid
);
1830 last_asynchronous_pid
= pid
;
1831 #if defined (RECYCLES_PIDS)
1832 else if (last_asynchronous_pid
== pid
)
1833 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
1834 last_asynchronous_pid
= 1;
1838 delete_old_job (pid
);
1840 #if !defined (RECYCLES_PIDS)
1841 /* Only check for saved status if we've saved more than CHILD_MAX
1842 statuses, unless the system recycles pids. */
1843 if ((js
.c_reaped
+ bgpids
.npid
) >= js
.c_childmax
)
1845 bgp_delete (pid
); /* new process, discard any saved status */
1847 last_made_pid
= pid
;
1853 /* Unblock SIGINT and SIGCHLD unless creating a pipeline, in which case
1854 SIGCHLD remains blocked until all commands in the pipeline have been
1856 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
1862 /* These two functions are called only in child processes. */
1864 ignore_tty_job_signals ()
1866 set_signal_handler (SIGTSTP
, SIG_IGN
);
1867 set_signal_handler (SIGTTIN
, SIG_IGN
);
1868 set_signal_handler (SIGTTOU
, SIG_IGN
);
1872 default_tty_job_signals ()
1874 set_signal_handler (SIGTSTP
, SIG_DFL
);
1875 set_signal_handler (SIGTTIN
, SIG_DFL
);
1876 set_signal_handler (SIGTTOU
, SIG_DFL
);
1879 /* When we end a job abnormally, or if we stop a job, we set the tty to the
1880 state kept in here. When a job ends normally, we set the state in here
1881 to the state of the tty. */
1883 static TTYSTRUCT shell_tty_info
;
1885 #if defined (NEW_TTY_DRIVER)
1886 static struct tchars shell_tchars
;
1887 static struct ltchars shell_ltchars
;
1888 #endif /* NEW_TTY_DRIVER */
1890 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
1891 /* Since the BSD tty driver does not allow us to change the tty modes
1892 while simultaneously waiting for output to drain and preserving
1893 typeahead, we have to drain the output ourselves before calling
1894 ioctl. We cheat by finding the length of the output queue, and
1895 using select to wait for an appropriate length of time. This is
1896 a hack, and should be labeled as such (it's a hastily-adapted
1897 mutation of a `usleep' implementation). It's only reason for
1898 existing is the flaw in the BSD tty driver. */
1900 static int ttspeeds
[] =
1902 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
1903 1800, 2400, 4800, 9600, 19200, 38400
1910 register int delay
= ttspeeds
[ospeed
];
1916 while ((ioctl (fd
, TIOCOUTQ
, &n
) == 0) && n
)
1918 if (n
> (delay
/ 100))
1922 n
*= 10; /* 2 bits more for conservativeness. */
1923 tv
.tv_sec
= n
/ delay
;
1924 tv
.tv_usec
= ((n
% delay
) * 1000000) / delay
;
1925 select (fd
, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &tv
);
1931 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
1933 /* Return the fd from which we are actually getting input. */
1934 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
1936 /* Fill the contents of shell_tty_info with the current tty info. */
1945 #if defined (NEW_TTY_DRIVER)
1946 ioctl (tty
, TIOCGETP
, &shell_tty_info
);
1947 ioctl (tty
, TIOCGETC
, &shell_tchars
);
1948 ioctl (tty
, TIOCGLTC
, &shell_ltchars
);
1949 #endif /* NEW_TTY_DRIVER */
1951 #if defined (TERMIO_TTY_DRIVER)
1952 ioctl (tty
, TCGETA
, &shell_tty_info
);
1953 #endif /* TERMIO_TTY_DRIVER */
1955 #if defined (TERMIOS_TTY_DRIVER)
1956 if (tcgetattr (tty
, &shell_tty_info
) < 0)
1959 /* Only print an error message if we're really interactive at
1962 sys_error ("[%ld: %d] tcgetattr", (long)getpid (), shell_level
);
1966 #endif /* TERMIOS_TTY_DRIVER */
1967 if (check_window_size
)
1968 get_new_window_size (0, (int *)0, (int *)0);
1973 /* Make the current tty use the state in shell_tty_info. */
1982 #if defined (NEW_TTY_DRIVER)
1983 # if defined (DRAIN_OUTPUT)
1984 draino (tty
, shell_tty_info
.sg_ospeed
);
1985 # endif /* DRAIN_OUTPUT */
1986 ioctl (tty
, TIOCSETN
, &shell_tty_info
);
1987 ioctl (tty
, TIOCSETC
, &shell_tchars
);
1988 ioctl (tty
, TIOCSLTC
, &shell_ltchars
);
1989 #endif /* NEW_TTY_DRIVER */
1991 #if defined (TERMIO_TTY_DRIVER)
1992 ioctl (tty
, TCSETAW
, &shell_tty_info
);
1993 #endif /* TERMIO_TTY_DRIVER */
1995 #if defined (TERMIOS_TTY_DRIVER)
1996 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
1998 /* Only print an error message if we're really interactive at
2001 sys_error ("[%ld: %d] tcsetattr", (long)getpid (), shell_level
);
2004 #endif /* TERMIOS_TTY_DRIVER */
2009 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2010 process in that job's pipeline. This is the one whose exit status
2011 counts. Must be called with SIGCHLD blocked or queued. */
2013 find_last_proc (job
, block
)
2017 register PROCESS
*p
;
2021 BLOCK_CHILD (set
, oset
);
2023 p
= jobs
[job
]->pipe
;
2024 while (p
&& p
->next
!= jobs
[job
]->pipe
)
2028 UNBLOCK_CHILD (oset
);
2034 find_last_pid (job
, block
)
2040 p
= find_last_proc (job
, block
);
2041 /* Possible race condition here. */
2045 /* Wait for a particular child of the shell to finish executing.
2046 This low-level function prints an error message if PID is not
2047 a child of this shell. It returns -1 if it fails, or whatever
2048 wait_for returns otherwise. If the child is not found in the
2049 jobs table, it returns 127. */
2051 wait_for_single_pid (pid
)
2054 register PROCESS
*child
;
2058 BLOCK_CHILD (set
, oset
);
2059 child
= find_pipeline (pid
, 0, (int *)NULL
);
2060 UNBLOCK_CHILD (oset
);
2064 r
= bgp_search (pid
);
2071 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid
);
2077 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2079 BLOCK_CHILD (set
, oset
);
2080 job
= find_job (pid
, 0, NULL
);
2081 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
2082 jobs
[job
]->flags
|= J_NOTIFIED
;
2083 UNBLOCK_CHILD (oset
);
2085 /* If running in posix mode, remove the job from the jobs table immediately */
2086 if (posixly_correct
)
2088 cleanup_dead_jobs ();
2095 /* Wait for all of the backgrounds of this shell to finish. */
2097 wait_for_background_pids ()
2099 register int i
, r
, waited_for
;
2103 for (waited_for
= 0;;)
2105 BLOCK_CHILD (set
, oset
);
2107 /* find first running job; if none running in foreground, break */
2108 /* XXX could use js.j_firstj and js.j_lastj here */
2109 for (i
= 0; i
< js
.j_jobslots
; i
++)
2112 if (i
< js
.j_firstj
&& jobs
[i
])
2113 itrace("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
2114 if (i
> js
.j_lastj
&& jobs
[i
])
2115 itrace("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
2117 if (jobs
[i
] && RUNNING (i
) && IS_FOREGROUND (i
) == 0)
2120 if (i
== js
.j_jobslots
)
2122 UNBLOCK_CHILD (oset
);
2126 /* now wait for the last pid in that job. */
2127 pid
= find_last_pid (i
, 0);
2128 UNBLOCK_CHILD (oset
);
2130 errno
= 0; /* XXX */
2131 r
= wait_for_single_pid (pid
);
2134 /* If we're mistaken about job state, compensate. */
2135 if (errno
== ECHILD
)
2136 mark_all_jobs_as_dead ();
2142 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2143 `wait' is called with no arguments. */
2144 mark_dead_jobs_as_notified (1);
2145 cleanup_dead_jobs ();
2149 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2150 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2151 static SigHandler
*old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2154 restore_sigint_handler ()
2156 if (old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
2158 set_signal_handler (SIGINT
, old_sigint_handler
);
2159 old_sigint_handler
= INVALID_SIGNAL_HANDLER
;
2163 static int wait_sigint_received
;
2165 /* Handle SIGINT while we are waiting for children in a script to exit.
2166 The `wait' builtin should be interruptible, but all others should be
2167 effectively ignored (i.e. not cause the shell to exit). */
2169 wait_sigint_handler (sig
)
2172 SigHandler
*sigint_handler
;
2174 if (interrupt_immediately
||
2175 (this_shell_builtin
&& this_shell_builtin
== wait_builtin
))
2177 last_command_exit_value
= EXECUTION_FAILURE
;
2178 restore_sigint_handler ();
2179 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2180 what POSIX.2 says (see builtins/wait.def for more info). */
2181 if (this_shell_builtin
&& this_shell_builtin
== wait_builtin
&&
2182 signal_is_trapped (SIGINT
) &&
2183 ((sigint_handler
= trap_to_sighandler (SIGINT
)) == trap_handler
))
2185 interrupt_immediately
= 0;
2186 trap_handler (SIGINT
); /* set pending_traps[SIGINT] */
2187 wait_signal_received
= SIGINT
;
2188 longjmp (wait_intr_buf
, 1);
2195 /* XXX - should this be interrupt_state? If it is, the shell will act
2196 as if it got the SIGINT interrupt. */
2197 wait_sigint_received
= 1;
2199 /* Otherwise effectively ignore the SIGINT and allow the running job to
2205 process_exit_signal (status
)
2208 return (WIFSIGNALED (status
) ? WTERMSIG (status
) : 0);
2212 process_exit_status (status
)
2215 if (WIFSIGNALED (status
))
2216 return (128 + WTERMSIG (status
));
2217 else if (WIFSTOPPED (status
) == 0)
2218 return (WEXITSTATUS (status
));
2220 return (EXECUTION_SUCCESS
);
2224 job_signal_status (job
)
2227 register PROCESS
*p
;
2230 p
= jobs
[job
]->pipe
;
2234 if (WIFSIGNALED(s
) || WIFSTOPPED(s
))
2238 while (p
!= jobs
[job
]->pipe
);
2243 /* Return the exit status of the last process in the pipeline for job JOB.
2244 This is the exit status of the entire job. */
2246 raw_job_exit_status (job
)
2249 register PROCESS
*p
;
2255 p
= jobs
[job
]->pipe
;
2258 if (p
->status
!= EXECUTION_SUCCESS
) fail
= p
->status
;
2261 while (p
!= jobs
[job
]->pipe
);
2265 for (p
= jobs
[job
]->pipe
; p
->next
!= jobs
[job
]->pipe
; p
= p
->next
)
2270 /* Return the exit status of job JOB. This is the exit status of the last
2271 (rightmost) process in the job's pipeline, modified if the job was killed
2272 by a signal or stopped. */
2274 job_exit_status (job
)
2277 return (process_exit_status (raw_job_exit_status (job
)));
2281 job_exit_signal (job
)
2284 return (process_exit_signal (raw_job_exit_status (job
)));
2287 #define FIND_CHILD(pid, child) \
2290 child = find_pipeline (pid, 0, (int *)NULL); \
2293 give_terminal_to (shell_pgrp, 0); \
2294 UNBLOCK_CHILD (oset); \
2295 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2296 restore_sigint_handler (); \
2297 return (termination_state = 127); \
2302 /* Wait for pid (one of our children) to terminate, then
2303 return the termination state. Returns 127 if PID is not found in
2304 the jobs table. Returns -1 if waitchld() returns -1, indicating
2305 that there are no unwaited-for child processes. */
2310 int job
, termination_state
, r
;
2312 register PROCESS
*child
;
2314 register PROCESS
*p
;
2316 /* In the case that this code is interrupted, and we longjmp () out of it,
2317 we are relying on the code in throw_to_top_level () to restore the
2318 top-level signal mask. */
2319 BLOCK_CHILD (set
, oset
);
2321 /* Ignore interrupts while waiting for a job run without job control
2322 to finish. We don't want the shell to exit if an interrupt is
2323 received, only if one of the jobs run is killed via SIGINT. If
2324 job control is not set, the job will be run in the same pgrp as
2325 the shell, and the shell will see any signals the job gets. In
2326 fact, we want this set every time the waiting shell and the waited-
2327 for process are in the same process group, including command
2330 /* This is possibly a race condition -- should it go in stop_pipeline? */
2331 wait_sigint_received
= 0;
2332 if (job_control
== 0 || (subshell_environment
&SUBSHELL_COMSUB
))
2334 old_sigint_handler
= set_signal_handler (SIGINT
, wait_sigint_handler
);
2335 if (old_sigint_handler
== SIG_IGN
)
2336 set_signal_handler (SIGINT
, old_sigint_handler
);
2339 termination_state
= last_command_exit_value
;
2341 if (interactive
&& job_control
== 0)
2344 /* If we say wait_for (), then we have a record of this child somewhere.
2345 If it and none of its peers are running, don't call waitchld(). */
2350 FIND_CHILD (pid
, child
);
2352 /* If this child is part of a job, then we are really waiting for the
2353 job to finish. Otherwise, we are waiting for the child to finish.
2354 We check for JDEAD in case the job state has been set by waitchld
2355 after receipt of a SIGCHLD. */
2357 job
= find_job (pid
, 0, NULL
);
2359 /* waitchld() takes care of setting the state of the job. If the job
2360 has already exited before this is called, sigchld_handler will have
2361 called waitchld and the state will be set to JDEAD. */
2363 if (PRUNNING(child
) || (job
!= NO_JOB
&& RUNNING (job
)))
2365 #if defined (WAITPID_BROKEN) /* SCOv4 */
2366 sigset_t suspend_set
;
2367 sigemptyset (&suspend_set
);
2368 sigsuspend (&suspend_set
);
2369 #else /* !WAITPID_BROKEN */
2370 # if defined (MUST_UNBLOCK_CHLD)
2371 struct sigaction act
, oact
;
2372 sigset_t nullset
, chldset
;
2374 sigemptyset (&nullset
);
2375 sigemptyset (&chldset
);
2376 sigprocmask (SIG_SETMASK
, &nullset
, &chldset
);
2377 act
.sa_handler
= SIG_DFL
;
2378 sigemptyset (&act
.sa_mask
);
2379 sigemptyset (&oact
.sa_mask
);
2381 sigaction (SIGCHLD
, &act
, &oact
);
2384 r
= waitchld (pid
, 1);
2385 # if defined (MUST_UNBLOCK_CHLD)
2386 sigaction (SIGCHLD
, &oact
, (struct sigaction
*)NULL
);
2387 sigprocmask (SIG_SETMASK
, &chldset
, (sigset_t
*)NULL
);
2390 if (r
== -1 && errno
== ECHILD
&& this_shell_builtin
== wait_builtin
)
2392 termination_state
= -1;
2393 goto wait_for_return
;
2396 /* If child is marked as running, but waitpid() returns -1/ECHILD,
2397 there is something wrong. Somewhere, wait should have returned
2398 that child's pid. Mark the child as not running and the job,
2399 if it exists, as JDEAD. */
2400 if (r
== -1 && errno
== ECHILD
)
2402 child
->running
= PS_DONE
;
2403 child
->status
= 0; /* XXX -- can't find true status */
2404 js
.c_living
= 0; /* no living child processes */
2407 jobs
[job
]->state
= JDEAD
;
2412 #endif /* WAITPID_BROKEN */
2415 /* If the shell is interactive, and job control is disabled, see
2416 if the foreground process has died due to SIGINT and jump out
2417 of the wait loop if it has. waitchld has already restored the
2418 old SIGINT signal handler. */
2419 if (interactive
&& job_control
== 0)
2422 while (PRUNNING (child
) || (job
!= NO_JOB
&& RUNNING (job
)));
2424 /* The exit state of the command is either the termination state of the
2425 child, or the termination state of the job. If a job, the status
2426 of the last child in the pipeline is the significant one. If the command
2427 or job was terminated by a signal, note that value also. */
2428 termination_state
= (job
!= NO_JOB
) ? job_exit_status (job
)
2429 : process_exit_status (child
->status
);
2430 last_command_exit_signal
= (job
!= NO_JOB
) ? job_exit_signal (job
)
2431 : process_exit_signal (child
->status
);
2434 if ((job
!= NO_JOB
&& JOBSTATE (job
) == JSTOPPED
) || WIFSTOPPED (child
->status
))
2435 termination_state
= 128 + WSTOPSIG (child
->status
);
2437 if (job
== NO_JOB
|| IS_JOBCONTROL (job
))
2439 /* XXX - under what circumstances is a job not present in the jobs
2440 table (job == NO_JOB)?
2441 1. command substitution
2443 In the case of command substitution, at least, it's probably not
2444 the right thing to give the terminal to the shell's process group,
2445 even though there is code in subst.c:command_substitute to work
2449 $PROMPT_COMMAND execution
2450 process substitution
2454 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp
);
2456 give_terminal_to (shell_pgrp
, 0);
2459 /* If the command did not exit cleanly, or the job is just
2460 being stopped, then reset the tty state back to what it
2461 was before this command. Reset the tty state and notify
2462 the user of the job termination only if the shell is
2463 interactive. Clean up any dead jobs in either case. */
2466 if (interactive_shell
&& subshell_environment
== 0)
2468 /* This used to use `child->status'. That's wrong, however, for
2469 pipelines. `child' is the first process in the pipeline. It's
2470 likely that the process we want to check for abnormal termination
2471 or stopping is the last process in the pipeline, especially if
2472 it's long-lived and the first process is short-lived. Since we
2473 know we have a job here, we can check all the processes in this
2474 job's pipeline and see if one of them stopped or terminated due
2475 to a signal. We might want to change this later to just check
2476 the last process in the pipeline. If no process exits due to a
2477 signal, S is left as the status of the last job in the pipeline. */
2478 s
= job_signal_status (job
);
2480 if (WIFSIGNALED (s
) || WIFSTOPPED (s
))
2484 /* If the current job was stopped or killed by a signal, and
2485 the user has requested it, get a possibly new window size */
2486 if (check_window_size
&& (job
== js
.j_current
|| IS_FOREGROUND (job
)))
2487 get_new_window_size (0, (int *)0, (int *)0);
2492 /* If job control is enabled, the job was started with job
2493 control, the job was the foreground job, and it was killed
2494 by SIGINT, then print a newline to compensate for the kernel
2495 printing the ^C without a trailing newline. */
2496 if (job_control
&& IS_JOBCONTROL (job
) && IS_FOREGROUND (job
) &&
2497 WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
)
2499 /* If SIGINT is not trapped and the shell is in a for, while,
2500 or until loop, act as if the shell received SIGINT as
2501 well, so the loop can be broken. This doesn't call the
2502 SIGINT signal handler; maybe it should. */
2503 if (signal_is_trapped (SIGINT
) == 0 && loop_level
)
2512 else if ((subshell_environment
& SUBSHELL_COMSUB
) && wait_sigint_received
)
2514 /* If waiting for a job in a subshell started to do command
2515 substitution, simulate getting and being killed by the SIGINT to
2516 pass the status back to our parent. */
2517 s
= job_signal_status (job
);
2519 if (WIFSIGNALED (s
) && WTERMSIG (s
) == SIGINT
&& signal_is_trapped (SIGINT
) == 0)
2521 UNBLOCK_CHILD (oset
);
2522 restore_sigint_handler ();
2523 old_sigint_handler
= set_signal_handler (SIGINT
, SIG_DFL
);
2524 if (old_sigint_handler
== SIG_IGN
)
2525 restore_sigint_handler ();
2527 kill (getpid (), SIGINT
);
2531 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
2532 signal handler path */
2533 if (DEADJOB (job
) && IS_FOREGROUND (job
) /*&& subshell_environment == 0*/)
2536 /* If this job is dead, notify the user of the status. If the shell
2537 is interactive, this will display a message on the terminal. If
2538 the shell is not interactive, make sure we turn on the notify bit
2539 so we don't get an unwanted message about the job's termination,
2540 and so delete_job really clears the slot in the jobs table. */
2541 notify_and_cleanup ();
2546 UNBLOCK_CHILD (oset
);
2548 /* Restore the original SIGINT signal handler before we return. */
2549 restore_sigint_handler ();
2551 return (termination_state
);
2554 /* Wait for the last process in the pipeline for JOB. Returns whatever
2555 wait_for returns: the last process's termination state or -1 if there
2556 are no unwaited-for child processes or an error occurs. */
2565 BLOCK_CHILD(set
, oset
);
2566 if (JOBSTATE (job
) == JSTOPPED
)
2567 internal_warning (_("wait_for_job: job %d is stopped"), job
+1);
2569 pid
= find_last_pid (job
, 0);
2570 UNBLOCK_CHILD(oset
);
2573 /* POSIX.2: we can remove the job from the jobs table if we just waited
2575 BLOCK_CHILD (set
, oset
);
2576 if (job
!= NO_JOB
&& jobs
[job
] && DEADJOB (job
))
2577 jobs
[job
]->flags
|= J_NOTIFIED
;
2578 UNBLOCK_CHILD (oset
);
2583 /* Print info about dead jobs, and then delete them from the list
2584 of known jobs. This does not actually delete jobs when the
2585 shell is not interactive, because the dead jobs are not marked
2588 notify_and_cleanup ()
2590 if (jobs_list_frozen
)
2593 if (interactive
|| interactive_shell
== 0 || sourcelevel
)
2594 notify_of_job_status ();
2596 cleanup_dead_jobs ();
2599 /* Make dead jobs disappear from the jobs array without notification.
2600 This is used when the shell is not interactive. */
2604 mark_dead_jobs_as_notified (0);
2605 cleanup_dead_jobs ();
2608 /* Return the next closest (chronologically) job to JOB which is in
2609 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
2610 there is no next recent job. */
2612 most_recent_job_in_state (job
, state
)
2616 register int i
, result
;
2619 BLOCK_CHILD (set
, oset
);
2621 for (result
= NO_JOB
, i
= job
- 1; i
>= 0; i
--)
2623 if (jobs
[i
] && (JOBSTATE (i
) == state
))
2630 UNBLOCK_CHILD (oset
);
2635 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
2638 job_last_stopped (job
)
2641 return (most_recent_job_in_state (job
, JSTOPPED
));
2644 /* Return the newest *running* job older than JOB, or NO_JOB if not
2647 job_last_running (job
)
2650 return (most_recent_job_in_state (job
, JRUNNING
));
2653 /* Make JOB be the current job, and make previous be useful. Must be
2654 called with SIGCHLD blocked. */
2656 set_current_job (job
)
2661 if (js
.j_current
!= job
)
2663 js
.j_previous
= js
.j_current
;
2667 /* First choice for previous job is the old current job. */
2668 if (js
.j_previous
!= js
.j_current
&&
2669 js
.j_previous
!= NO_JOB
&&
2670 jobs
[js
.j_previous
] &&
2671 STOPPED (js
.j_previous
))
2674 /* Second choice: Newest stopped job that is older than
2677 if (STOPPED (js
.j_current
))
2679 candidate
= job_last_stopped (js
.j_current
);
2681 if (candidate
!= NO_JOB
)
2683 js
.j_previous
= candidate
;
2688 /* If we get here, there is either only one stopped job, in which case it is
2689 the current job and the previous job should be set to the newest running
2690 job, or there are only running jobs and the previous job should be set to
2691 the newest running job older than the current job. We decide on which
2692 alternative to use based on whether or not JOBSTATE(js.j_current) is
2695 candidate
= RUNNING (js
.j_current
) ? job_last_running (js
.j_current
)
2696 : job_last_running (js
.j_jobslots
);
2698 if (candidate
!= NO_JOB
)
2700 js
.j_previous
= candidate
;
2704 /* There is only a single job, and it is both `+' and `-'. */
2705 js
.j_previous
= js
.j_current
;
2708 /* Make current_job be something useful, if it isn't already. */
2710 /* Here's the deal: The newest non-running job should be `+', and the
2711 next-newest non-running job should be `-'. If there is only a single
2712 stopped job, the js.j_previous is the newest non-running job. If there
2713 are only running jobs, the newest running job is `+' and the
2714 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
2721 if (js
.j_jobslots
&& js
.j_current
!= NO_JOB
&& jobs
[js
.j_current
] && STOPPED (js
.j_current
))
2722 candidate
= js
.j_current
;
2727 /* First choice: the previous job. */
2728 if (js
.j_previous
!= NO_JOB
&& jobs
[js
.j_previous
] && STOPPED (js
.j_previous
))
2729 candidate
= js
.j_previous
;
2731 /* Second choice: the most recently stopped job. */
2732 if (candidate
== NO_JOB
)
2733 candidate
= job_last_stopped (js
.j_jobslots
);
2735 /* Third choice: the newest running job. */
2736 if (candidate
== NO_JOB
)
2737 candidate
= job_last_running (js
.j_jobslots
);
2740 /* If we found a job to use, then use it. Otherwise, there
2741 are no jobs period. */
2742 if (candidate
!= NO_JOB
)
2743 set_current_job (candidate
);
2745 js
.j_current
= js
.j_previous
= NO_JOB
;
2748 /* Set up the job structures so we know the job and its processes are
2751 set_job_running (job
)
2754 register PROCESS
*p
;
2756 /* Each member of the pipeline is now running. */
2757 p
= jobs
[job
]->pipe
;
2761 if (WIFSTOPPED (p
->status
))
2762 p
->running
= PS_RUNNING
; /* XXX - could be PS_STOPPED */
2765 while (p
!= jobs
[job
]->pipe
);
2767 /* This means that the job is running. */
2768 JOBSTATE (job
) = JRUNNING
;
2771 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2772 start the job in the background. JOB is a zero-based index into
2773 JOBS. Returns -1 if it is unable to start a job, and the return
2774 status of the job otherwise. */
2776 start_job (job
, foreground
)
2777 int job
, foreground
;
2779 register PROCESS
*p
;
2780 int already_running
;
2783 static TTYSTRUCT save_stty
;
2785 BLOCK_CHILD (set
, oset
);
2789 internal_error (_("%s: job has terminated"), this_command_name
);
2790 UNBLOCK_CHILD (oset
);
2794 already_running
= RUNNING (job
);
2796 if (foreground
== 0 && already_running
)
2798 internal_error (_("%s: job %d already in background"), this_command_name
, job
+ 1);
2799 UNBLOCK_CHILD (oset
);
2800 return (0); /* XPG6/SUSv3 says this is not an error */
2803 wd
= current_working_directory ();
2805 /* You don't know about the state of this job. Do you? */
2806 jobs
[job
]->flags
&= ~J_NOTIFIED
;
2810 set_current_job (job
);
2811 jobs
[job
]->flags
|= J_FOREGROUND
;
2814 /* Tell the outside world what we're doing. */
2815 p
= jobs
[job
]->pipe
;
2817 if (foreground
== 0)
2819 /* POSIX.2 says `bg' doesn't give any indication about current or
2821 if (posixly_correct
== 0)
2822 s
= (job
== js
.j_current
) ? "+ ": ((job
== js
.j_previous
) ? "- " : " ");
2825 printf ("[%d]%s", job
+ 1, s
);
2831 p
->command
? p
->command
: "",
2832 p
->next
!= jobs
[job
]->pipe
? " | " : "");
2835 while (p
!= jobs
[job
]->pipe
);
2837 if (foreground
== 0)
2840 if (strcmp (wd
, jobs
[job
]->wd
) != 0)
2841 printf (" (wd: %s)", polite_directory_format (jobs
[job
]->wd
));
2846 if (already_running
== 0)
2847 set_job_running (job
);
2849 /* Save the tty settings before we start the job in the foreground. */
2853 save_stty
= shell_tty_info
;
2854 /* Give the terminal to this job. */
2855 if (IS_JOBCONTROL (job
))
2856 give_terminal_to (jobs
[job
]->pgrp
, 0);
2859 jobs
[job
]->flags
&= ~J_FOREGROUND
;
2861 /* If the job is already running, then don't bother jump-starting it. */
2862 if (already_running
== 0)
2864 jobs
[job
]->flags
|= J_NOTIFIED
;
2865 killpg (jobs
[job
]->pgrp
, SIGCONT
);
2873 pid
= find_last_pid (job
, 0);
2874 UNBLOCK_CHILD (oset
);
2875 st
= wait_for (pid
);
2876 shell_tty_info
= save_stty
;
2883 UNBLOCK_CHILD (oset
);
2888 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2889 If PID does belong to a job, and the job is stopped, then CONTinue the
2890 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2891 then kill the process group associated with PID. */
2893 kill_pid (pid
, sig
, group
)
2897 register PROCESS
*p
;
2898 int job
, result
, negative
;
2904 group
= negative
= 1;
2909 result
= EXECUTION_SUCCESS
;
2912 BLOCK_CHILD (set
, oset
);
2913 p
= find_pipeline (pid
, 0, &job
);
2917 jobs
[job
]->flags
&= ~J_NOTIFIED
;
2919 /* Kill process in backquotes or one started without job control? */
2921 /* If we're passed a pid < -1, just call killpg and see what happens */
2922 if (negative
&& jobs
[job
]->pgrp
== shell_pgrp
)
2923 result
= killpg (pid
, sig
);
2924 /* If we're killing using job control notification, for example,
2925 without job control active, we have to do things ourselves. */
2926 else if (jobs
[job
]->pgrp
== shell_pgrp
)
2928 p
= jobs
[job
]->pipe
;
2931 if (PALIVE (p
) == 0)
2932 continue; /* avoid pid recycling problem */
2934 if (PEXITED (p
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
2935 kill (p
->pid
, SIGCONT
);
2938 while (p
!= jobs
[job
]->pipe
);
2942 result
= killpg (jobs
[job
]->pgrp
, sig
);
2943 if (p
&& STOPPED (job
) && (sig
== SIGTERM
|| sig
== SIGHUP
))
2944 killpg (jobs
[job
]->pgrp
, SIGCONT
);
2945 /* If we're continuing a stopped job via kill rather than bg or
2946 fg, emulate the `bg' behavior. */
2947 if (p
&& STOPPED (job
) && (sig
== SIGCONT
))
2949 set_job_running (job
);
2950 jobs
[job
]->flags
&= ~J_FOREGROUND
;
2951 jobs
[job
]->flags
|= J_NOTIFIED
;
2956 result
= killpg (pid
, sig
);
2958 UNBLOCK_CHILD (oset
);
2961 result
= kill (pid
, sig
);
2966 /* sigchld_handler () flushes at least one of the children that we are
2967 waiting for. It gets run when we have gotten a SIGCHLD signal. */
2969 sigchld_handler (sig
)
2975 REINSTALL_SIGCHLD_HANDLER
;
2978 if (queue_sigchld
== 0)
2979 n
= waitchld (-1, 0);
2984 /* waitchld() reaps dead or stopped children. It's called by wait_for and
2985 sigchld_handler, and runs until there aren't any children terminating any
2987 If BLOCK is 1, this is to be a blocking wait for a single child, although
2988 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
2989 the number of children reaped, or -1 if there are no unwaited-for child
2992 waitchld (wpid
, block
)
2999 int call_set_current
, last_stopped_job
, job
, children_exited
, waitpid_flags
;
3000 static int wcontinued
= WCONTINUED
; /* run-time fix for glibc problem */
3002 call_set_current
= children_exited
= 0;
3003 last_stopped_job
= NO_JOB
;
3007 /* We don't want to be notified about jobs stopping if job control
3008 is not active. XXX - was interactive_shell instead of job_control */
3009 waitpid_flags
= (job_control
&& subshell_environment
== 0)
3010 ? (WUNTRACED
|wcontinued
)
3012 if (sigchld
|| block
== 0)
3013 waitpid_flags
|= WNOHANG
;
3015 pid
= WAITPID (-1, &status
, waitpid_flags
);
3017 /* WCONTINUED may be rejected by waitpid as invalid even when defined */
3018 if (wcontinued
&& pid
< 0 && errno
== EINVAL
)
3021 continue; /* jump back to the test and retry without WCONTINUED */
3024 /* The check for WNOHANG is to make sure we decrement sigchld only
3025 if it was non-zero before we called waitpid. */
3026 if (sigchld
> 0 && (waitpid_flags
& WNOHANG
))
3029 /* If waitpid returns -1 with errno == ECHILD, there are no more
3030 unwaited-for child processes of this shell. */
3031 if (pid
< 0 && errno
== ECHILD
)
3033 if (children_exited
== 0)
3039 /* If waitpid returns 0, there are running children. If it returns -1,
3040 the only other error POSIX says it can return is EINTR. */
3043 continue; /* jumps right to the test */
3045 /* children_exited is used to run traps on SIGCHLD. We don't want to
3046 run the trap if a process is just being continued. */
3047 if (WIFCONTINUED(status
) == 0)
3053 /* Locate our PROCESS for this pid. */
3054 child
= find_process (pid
, 1, &job
); /* want living procs only */
3056 /* It is not an error to have a child terminate that we did
3057 not have a record of. This child could have been part of
3058 a pipeline in backquote substitution. Even so, I'm not
3059 sure child is ever non-zero. */
3063 /* Remember status, and whether or not the process is running. */
3064 child
->status
= status
;
3065 child
->running
= WIFCONTINUED(status
) ? PS_RUNNING
: PS_DONE
;
3067 if (PEXITED (child
))
3077 call_set_current
+= set_job_status_and_cleanup (job
);
3080 last_stopped_job
= job
;
3081 else if (DEADJOB (job
) && last_stopped_job
== job
)
3082 last_stopped_job
= NO_JOB
;
3084 while ((sigchld
|| block
== 0) && pid
> (pid_t
)0);
3086 /* If a job was running and became stopped, then set the current
3087 job. Otherwise, don't change a thing. */
3088 if (call_set_current
)
3090 if (last_stopped_job
!= NO_JOB
)
3091 set_current_job (last_stopped_job
);
3096 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3097 if (job_control
&& signal_is_trapped (SIGCHLD
) && children_exited
&&
3098 trap_list
[SIGCHLD
] != (char *)IGNORE_SIG
)
3099 run_sigchld_trap (children_exited
);
3101 /* We have successfully recorded the useful information about this process
3102 that has just changed state. If we notify asynchronously, and the job
3103 that this process belongs to is no longer running, then notify the user
3104 of that fact now. */
3105 if (asynchronous_notification
&& interactive
)
3106 notify_of_job_status ();
3108 return (children_exited
);
3111 /* Set the status of JOB and perform any necessary cleanup if the job is
3114 Currently, the cleanup activity is restricted to handling any SIGINT
3115 received while waiting for a foreground job to finish. */
3117 set_job_status_and_cleanup (job
)
3121 int tstatus
, job_state
, any_stopped
, any_tstped
, call_set_current
;
3122 SigHandler
*temp_handler
;
3124 child
= jobs
[job
]->pipe
;
3125 jobs
[job
]->flags
&= ~J_NOTIFIED
;
3127 call_set_current
= 0;
3130 * COMPUTE JOB STATUS
3133 /* If all children are not running, but any of them is stopped, then
3134 the job is stopped, not dead. */
3135 job_state
= any_stopped
= any_tstped
= 0;
3138 job_state
|= PRUNNING (child
);
3140 if (PEXITED (child
) && (WIFSTOPPED (child
->status
)))
3142 /* Only checking for WIFSTOPPED now, not for PS_DONE */
3143 if (PSTOPPED (child
))
3147 any_tstped
|= interactive
&& job_control
&&
3148 (WSTOPSIG (child
->status
) == SIGTSTP
);
3150 child
= child
->next
;
3152 while (child
!= jobs
[job
]->pipe
);
3154 /* If job_state != 0, the job is still running, so don't bother with
3155 setting the process exit status and job state unless we're
3156 transitioning from stopped to running. */
3157 if (job_state
!= 0 && JOBSTATE(job
) != JSTOPPED
)
3164 /* The job is either stopped or dead. Set the state of the job accordingly. */
3167 jobs
[job
]->state
= JSTOPPED
;
3168 jobs
[job
]->flags
&= ~J_FOREGROUND
;
3170 /* Suspending a job with SIGTSTP breaks all active loops. */
3171 if (any_tstped
&& loop_level
)
3172 breaking
= loop_level
;
3174 else if (job_state
!= 0) /* was stopped, now running */
3176 jobs
[job
]->state
= JRUNNING
;
3181 jobs
[job
]->state
= JDEAD
;
3185 if (IS_FOREGROUND (job
))
3189 /* If this job has a cleanup function associated with it, call it
3190 with `cleanarg' as the single argument, then set the function
3191 pointer to NULL so it is not inadvertently called twice. The
3192 cleanup function is responsible for deallocating cleanarg. */
3193 if (jobs
[job
]->j_cleanup
)
3195 (*jobs
[job
]->j_cleanup
) (jobs
[job
]->cleanarg
);
3196 jobs
[job
]->j_cleanup
= (sh_vptrfunc_t
*)NULL
;
3203 * Currently, we just do special things if we got a SIGINT while waiting
3204 * for a foreground job to complete
3207 if (JOBSTATE (job
) == JDEAD
)
3209 /* If we're running a shell script and we get a SIGINT with a
3210 SIGINT trap handler, but the foreground job handles it and
3211 does not exit due to SIGINT, run the trap handler but do not
3212 otherwise act as if we got the interrupt. */
3213 if (wait_sigint_received
&& interactive_shell
== 0 &&
3214 WIFSIGNALED (child
->status
) == 0 && IS_FOREGROUND (job
) &&
3215 signal_is_trapped (SIGINT
))
3218 wait_sigint_received
= 0;
3219 last_command_exit_value
= process_exit_status (child
->status
);
3221 old_frozen
= jobs_list_frozen
;
3222 jobs_list_frozen
= 1;
3223 tstatus
= maybe_call_trap_handler (SIGINT
);
3224 jobs_list_frozen
= old_frozen
;
3227 /* If the foreground job is killed by SIGINT when job control is not
3228 active, we need to perform some special handling.
3230 The check of wait_sigint_received is a way to determine if the
3231 SIGINT came from the keyboard (in which case the shell has already
3232 seen it, and wait_sigint_received is non-zero, because keyboard
3233 signals are sent to process groups) or via kill(2) to the foreground
3234 process by another process (or itself). If the shell did receive the
3235 SIGINT, it needs to perform normal SIGINT processing. */
3236 else if (wait_sigint_received
&& (WTERMSIG (child
->status
) == SIGINT
) &&
3237 IS_FOREGROUND (job
) && IS_JOBCONTROL (job
) == 0)
3241 wait_sigint_received
= 0;
3243 /* If SIGINT is trapped, set the exit status so that the trap
3244 handler can see it. */
3245 if (signal_is_trapped (SIGINT
))
3246 last_command_exit_value
= process_exit_status (child
->status
);
3248 /* If the signal is trapped, let the trap handler get it no matter
3249 what and simply return if the trap handler returns.
3250 maybe_call_trap_handler() may cause dead jobs to be removed from
3251 the job table because of a call to execute_command. We work
3252 around this by setting JOBS_LIST_FROZEN. */
3253 old_frozen
= jobs_list_frozen
;
3254 jobs_list_frozen
= 1;
3255 tstatus
= maybe_call_trap_handler (SIGINT
);
3256 jobs_list_frozen
= old_frozen
;
3257 if (tstatus
== 0 && old_sigint_handler
!= INVALID_SIGNAL_HANDLER
)
3259 /* wait_sigint_handler () has already seen SIGINT and
3260 allowed the wait builtin to jump out. We need to
3261 call the original SIGINT handler, if necessary. If
3262 the original handler is SIG_DFL, we need to resend
3263 the signal to ourselves. */
3265 temp_handler
= old_sigint_handler
;
3267 /* Bogus. If we've reset the signal handler as the result
3268 of a trap caught on SIGINT, then old_sigint_handler
3269 will point to trap_handler, which now knows nothing about
3270 SIGINT (if we reset the sighandler to the default).
3271 In this case, we have to fix things up. What a crock. */
3272 if (temp_handler
== trap_handler
&& signal_is_trapped (SIGINT
) == 0)
3273 temp_handler
= trap_to_sighandler (SIGINT
);
3274 restore_sigint_handler ();
3275 if (temp_handler
== SIG_DFL
)
3276 termsig_handler (SIGINT
);
3277 else if (temp_handler
!= SIG_IGN
)
3278 (*temp_handler
) (SIGINT
);
3283 return call_set_current
;
3286 /* Build the array of values for the $PIPESTATUS variable from the set of
3287 exit statuses of all processes in the job J. */
3292 #if defined (ARRAY_VARS)
3294 register PROCESS
*p
;
3296 for (i
= 1, p
= jobs
[j
]->pipe
; p
->next
!= jobs
[j
]->pipe
; p
= p
->next
, i
++)
3301 pstatuses
= (int *)xrealloc (pstatuses
, i
* sizeof (int));
3308 pstatuses
[i
++] = process_exit_status (p
->status
);
3311 while (p
!= jobs
[j
]->pipe
);
3313 pstatuses
[i
] = -1; /* sentinel */
3314 set_pipestatus_array (pstatuses
, i
);
3319 run_sigchld_trap (nchild
)
3325 /* Turn off the trap list during the call to parse_and_execute ()
3326 to avoid potentially infinite recursive calls. Preserve the
3327 values of last_command_exit_value, last_made_pid, and the_pipeline
3328 around the execution of the trap commands. */
3329 trap_command
= savestring (trap_list
[SIGCHLD
]);
3331 begin_unwind_frame ("SIGCHLD trap");
3332 unwind_protect_int (last_command_exit_value
);
3333 unwind_protect_int (last_command_exit_signal
);
3334 unwind_protect_var (last_made_pid
);
3335 unwind_protect_int (interrupt_immediately
);
3336 unwind_protect_int (jobs_list_frozen
);
3337 unwind_protect_pointer (the_pipeline
);
3338 unwind_protect_pointer (subst_assign_varlist
);
3340 /* We have to add the commands this way because they will be run
3341 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
3342 to reference freed memory. */
3343 add_unwind_protect (xfree
, trap_command
);
3344 add_unwind_protect (maybe_set_sigchld_trap
, trap_command
);
3346 subst_assign_varlist
= (WORD_LIST
*)NULL
;
3347 the_pipeline
= (PROCESS
*)NULL
;
3349 restore_default_signal (SIGCHLD
);
3350 jobs_list_frozen
= 1;
3351 for (i
= 0; i
< nchild
; i
++)
3353 interrupt_immediately
= 1;
3354 parse_and_execute (savestring (trap_command
), "trap", SEVAL_NOHIST
|SEVAL_RESETLINE
);
3357 run_unwind_frame ("SIGCHLD trap");
3360 /* Function to call when you want to notify people of changes
3361 in job status. This prints out all jobs which are pending
3362 notification to stderr, and marks those printed as already
3363 notified, thus making them candidates for cleanup. */
3365 notify_of_job_status ()
3367 register int job
, termsig
;
3372 if (jobs
== 0 || js
.j_jobslots
== 0)
3378 sigaddset (&set
, SIGCHLD
);
3379 sigaddset (&set
, SIGTTOU
);
3380 sigemptyset (&oset
);
3381 sigprocmask (SIG_BLOCK
, &set
, &oset
);
3386 /* XXX could use js.j_firstj here */
3387 for (job
= 0, dir
= (char *)NULL
; job
< js
.j_jobslots
; job
++)
3389 if (jobs
[job
] && IS_NOTIFIED (job
) == 0)
3391 s
= raw_job_exit_status (job
);
3392 termsig
= WTERMSIG (s
);
3394 /* POSIX.2 says we have to hang onto the statuses of at most the
3395 last CHILD_MAX background processes if the shell is running a
3396 script. If the shell is running a script, either from a file
3397 or standard input, don't print anything unless the job was
3398 killed by a signal. */
3399 if (startup_state
== 0 && WIFSIGNALED (s
) == 0 &&
3400 ((DEADJOB (job
) && IS_FOREGROUND (job
) == 0) || STOPPED (job
)))
3404 /* If job control is disabled, don't print the status messages.
3405 Mark dead jobs as notified so that they get cleaned up. If
3406 startup_state == 2, we were started to run `-c command', so
3407 don't print anything. */
3408 if ((job_control
== 0 && interactive_shell
) || startup_state
== 2)
3410 /* If job control is disabled, don't print the status messages.
3411 Mark dead jobs as notified so that they get cleaned up. If
3412 startup_state == 2 and subshell_environment has the
3413 SUBSHELL_COMSUB bit turned on, we were started to run a command
3414 substitution, so don't print anything. */
3415 if ((job_control
== 0 && interactive_shell
) ||
3416 (startup_state
== 2 && (subshell_environment
& SUBSHELL_COMSUB
)))
3419 /* POSIX.2 compatibility: if the shell is not interactive,
3420 hang onto the job corresponding to the last asynchronous
3421 pid until the user has been notified of its status or does
3423 if (DEADJOB (job
) && (interactive_shell
|| (find_last_pid (job
, 0) != last_asynchronous_pid
)))
3424 jobs
[job
]->flags
|= J_NOTIFIED
;
3428 /* Print info on jobs that are running in the background,
3429 and on foreground jobs that were killed by anything
3430 except SIGINT (and possibly SIGPIPE). */
3431 switch (JOBSTATE (job
))
3434 if (interactive_shell
== 0 && termsig
&& WIFSIGNALED (s
) &&
3435 termsig
!= SIGINT
&&
3436 #if defined (DONT_REPORT_SIGPIPE)
3437 termsig
!= SIGPIPE
&&
3439 signal_is_trapped (termsig
) == 0)
3441 /* Don't print `0' for a line number. */
3442 fprintf (stderr
, "%s: line %d: ", get_name_for_error (), (line_number
== 0) ? 1 : line_number
);
3443 pretty_print_job (job
, JLIST_NONINTERACTIVE
, stderr
);
3445 else if (IS_FOREGROUND (job
))
3447 #if !defined (DONT_REPORT_SIGPIPE)
3448 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
)
3450 if (termsig
&& WIFSIGNALED (s
) && termsig
!= SIGINT
&& termsig
!= SIGPIPE
)
3453 fprintf (stderr
, "%s", j_strsignal (termsig
));
3456 fprintf (stderr
, " (core dumped)");
3458 fprintf (stderr
, "\n");
3461 else if (job_control
) /* XXX job control test added */
3464 dir
= current_working_directory ();
3465 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
3466 if (dir
&& strcmp (dir
, jobs
[job
]->wd
) != 0)
3468 "(wd now: %s)\n", polite_directory_format (dir
));
3471 jobs
[job
]->flags
|= J_NOTIFIED
;
3475 fprintf (stderr
, "\n");
3477 dir
= current_working_directory ();
3478 pretty_print_job (job
, JLIST_STANDARD
, stderr
);
3479 if (dir
&& (strcmp (dir
, jobs
[job
]->wd
) != 0))
3481 "(wd now: %s)\n", polite_directory_format (dir
));
3482 jobs
[job
]->flags
|= J_NOTIFIED
;
3490 programming_error ("notify_of_job_status");
3495 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
3500 /* Initialize the job control mechanism, and set up the tty stuff. */
3502 initialize_job_control (force
)
3505 shell_pgrp
= getpgid (0);
3507 if (shell_pgrp
== -1)
3509 sys_error ("initialize_job_control: getpgrp failed");
3513 /* We can only have job control if we are interactive. */
3514 if (interactive
== 0)
3517 original_pgrp
= NO_PID
;
3518 shell_tty
= fileno (stderr
);
3522 /* Get our controlling terminal. If job_control is set, or
3523 interactive is set, then this is an interactive shell no
3524 matter where fd 2 is directed. */
3525 shell_tty
= dup (fileno (stderr
)); /* fd 2 */
3527 shell_tty
= move_to_high_fd (shell_tty
, 1, -1);
3529 /* Compensate for a bug in systems that compiled the BSD
3530 rlogind with DEBUG defined, like NeXT and Alliant. */
3531 if (shell_pgrp
== 0)
3533 shell_pgrp
= getpid ();
3534 setpgid (0, shell_pgrp
);
3535 tcsetpgrp (shell_tty
, shell_pgrp
);
3538 while ((terminal_pgrp
= tcgetpgrp (shell_tty
)) != -1)
3540 if (shell_pgrp
!= terminal_pgrp
)
3544 ottin
= set_signal_handler(SIGTTIN
, SIG_DFL
);
3546 set_signal_handler (SIGTTIN
, ottin
);
3552 /* Make sure that we are using the new line discipline. */
3553 if (set_new_line_discipline (shell_tty
) < 0)
3555 sys_error ("initialize_job_control: line discipline");
3560 original_pgrp
= shell_pgrp
;
3561 shell_pgrp
= getpid ();
3563 if ((original_pgrp
!= shell_pgrp
) && (setpgid (0, shell_pgrp
) < 0))
3565 sys_error ("initialize_job_control: setpgid");
3566 shell_pgrp
= original_pgrp
;
3571 /* If (and only if) we just set our process group to our pid,
3572 thereby becoming a process group leader, and the terminal
3573 is not in the same process group as our (new) process group,
3574 then set the terminal's process group to our (new) process
3575 group. If that fails, set our process group back to what it
3576 was originally (so we can still read from the terminal) and
3577 turn off job control. */
3578 if (shell_pgrp
!= original_pgrp
&& shell_pgrp
!= terminal_pgrp
)
3580 if (give_terminal_to (shell_pgrp
, 0) < 0)
3582 setpgid (0, original_pgrp
);
3583 shell_pgrp
= original_pgrp
;
3588 if (job_control
== 0)
3589 internal_error (_("no job control in this shell"));
3592 if (shell_tty
!= fileno (stderr
))
3593 SET_CLOSE_ON_EXEC (shell_tty
);
3595 set_signal_handler (SIGCHLD
, sigchld_handler
);
3597 change_flag ('m', job_control
? '-' : '+');
3602 if (js
.c_childmax
< 0)
3603 js
.c_childmax
= getmaxchild ();
3604 if (js
.c_childmax
< 0)
3605 js
.c_childmax
= DEFAULT_CHILD_MAX
;
3612 debug_print_pgrps ()
3614 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
3615 (long)original_pgrp
, (long)shell_pgrp
, (long)terminal_pgrp
);
3616 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
3617 shell_tty
, (long)tcgetpgrp (shell_tty
), (long)getpgid(0));
3621 /* Set the line discipline to the best this system has to offer.
3622 Return -1 if this is not possible. */
3624 set_new_line_discipline (tty
)
3627 #if defined (NEW_TTY_DRIVER)
3630 if (ioctl (tty
, TIOCGETD
, &ldisc
) < 0)
3633 if (ldisc
!= NTTYDISC
)
3637 if (ioctl (tty
, TIOCSETD
, &ldisc
) < 0)
3641 #endif /* NEW_TTY_DRIVER */
3643 #if defined (TERMIO_TTY_DRIVER)
3644 # if defined (TERMIO_LDISC) && (NTTYDISC)
3645 if (ioctl (tty
, TCGETA
, &shell_tty_info
) < 0)
3648 if (shell_tty_info
.c_line
!= NTTYDISC
)
3650 shell_tty_info
.c_line
= NTTYDISC
;
3651 if (ioctl (tty
, TCSETAW
, &shell_tty_info
) < 0)
3654 # endif /* TERMIO_LDISC && NTTYDISC */
3656 #endif /* TERMIO_TTY_DRIVER */
3658 #if defined (TERMIOS_TTY_DRIVER)
3659 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
3660 if (tcgetattr (tty
, &shell_tty_info
) < 0)
3663 if (shell_tty_info
.c_line
!= NTTYDISC
)
3665 shell_tty_info
.c_line
= NTTYDISC
;
3666 if (tcsetattr (tty
, TCSADRAIN
, &shell_tty_info
) < 0)
3669 # endif /* TERMIOS_LDISC && NTTYDISC */
3671 #endif /* TERMIOS_TTY_DRIVER */
3673 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
3678 /* Setup this shell to handle C-C, etc. */
3680 initialize_job_signals ()
3684 set_signal_handler (SIGINT
, sigint_sighandler
);
3685 set_signal_handler (SIGTSTP
, SIG_IGN
);
3686 set_signal_handler (SIGTTOU
, SIG_IGN
);
3687 set_signal_handler (SIGTTIN
, SIG_IGN
);
3689 else if (job_control
)
3691 old_tstp
= set_signal_handler (SIGTSTP
, sigstop_sighandler
);
3692 old_ttin
= set_signal_handler (SIGTTIN
, sigstop_sighandler
);
3693 old_ttou
= set_signal_handler (SIGTTOU
, sigstop_sighandler
);
3695 /* Leave these things alone for non-interactive shells without job
3699 /* Here we handle CONT signals. */
3701 sigcont_sighandler (sig
)
3704 initialize_job_signals ();
3705 set_signal_handler (SIGCONT
, old_cont
);
3706 kill (getpid (), SIGCONT
);
3711 /* Here we handle stop signals while we are running not as a login shell. */
3713 sigstop_sighandler (sig
)
3716 set_signal_handler (SIGTSTP
, old_tstp
);
3717 set_signal_handler (SIGTTOU
, old_ttou
);
3718 set_signal_handler (SIGTTIN
, old_ttin
);
3720 old_cont
= set_signal_handler (SIGCONT
, sigcont_sighandler
);
3722 give_terminal_to (shell_pgrp
, 0);
3724 kill (getpid (), sig
);
3729 /* Give the terminal to PGRP. */
3731 give_terminal_to (pgrp
, force
)
3739 if (job_control
|| force
)
3742 sigaddset (&set
, SIGTTOU
);
3743 sigaddset (&set
, SIGTTIN
);
3744 sigaddset (&set
, SIGTSTP
);
3745 sigaddset (&set
, SIGCHLD
);
3746 sigemptyset (&oset
);
3747 sigprocmask (SIG_BLOCK
, &set
, &oset
);
3749 if (tcsetpgrp (shell_tty
, pgrp
) < 0)
3751 /* Maybe we should print an error message? */
3753 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
3754 shell_tty
, (long)getpid(), (long)pgrp
);
3759 terminal_pgrp
= pgrp
;
3760 sigprocmask (SIG_SETMASK
, &oset
, (sigset_t
*)NULL
);
3766 /* Clear out any jobs in the job array. This is intended to be used by
3767 children of the shell, who should not have any job structures as baggage
3768 when they start executing (forking subshells for parenthesized execution
3769 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
3770 is nonzero, only running jobs are removed from the table. */
3772 delete_all_jobs (running_only
)
3778 BLOCK_CHILD (set
, oset
);
3780 /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
3783 js
.j_current
= js
.j_previous
= NO_JOB
;
3785 /* XXX could use js.j_firstj here */
3786 for (i
= 0; i
< js
.j_jobslots
; i
++)
3789 if (i
< js
.j_firstj
&& jobs
[i
])
3790 itrace("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
3791 if (i
> js
.j_lastj
&& jobs
[i
])
3792 itrace("delete_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
3794 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
3795 delete_job (i
, DEL_WARNSTOPPED
);
3797 if (running_only
== 0)
3799 free ((char *)jobs
);
3801 js
.j_firstj
= js
.j_lastj
= js
.j_njobs
= 0;
3805 if (running_only
== 0)
3808 UNBLOCK_CHILD (oset
);
3811 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
3812 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
3814 nohup_all_jobs (running_only
)
3820 BLOCK_CHILD (set
, oset
);
3824 /* XXX could use js.j_firstj here */
3825 for (i
= 0; i
< js
.j_jobslots
; i
++)
3826 if (jobs
[i
] && (running_only
== 0 || (running_only
&& RUNNING(i
))))
3830 UNBLOCK_CHILD (oset
);
3839 /* This really counts all non-dead jobs. */
3840 BLOCK_CHILD (set
, oset
);
3841 /* XXX could use js.j_firstj here */
3842 for (i
= n
= 0; i
< js
.j_jobslots
; i
++)
3845 if (i
< js
.j_firstj
&& jobs
[i
])
3846 itrace("count_all_jobs: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
3847 if (i
> js
.j_lastj
&& jobs
[i
])
3848 itrace("count_all_jobs: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
3850 if (jobs
[i
] && DEADJOB(i
) == 0)
3853 UNBLOCK_CHILD (oset
);
3858 mark_all_jobs_as_dead ()
3863 if (js
.j_jobslots
== 0)
3866 BLOCK_CHILD (set
, oset
);
3868 /* XXX could use js.j_firstj here */
3869 for (i
= 0; i
< js
.j_jobslots
; i
++)
3872 jobs
[i
]->state
= JDEAD
;
3876 UNBLOCK_CHILD (oset
);
3879 /* Mark all dead jobs as notified, so delete_job () cleans them out
3880 of the job table properly. POSIX.2 says we need to save the
3881 status of the last CHILD_MAX jobs, so we count the number of dead
3882 jobs and mark only enough as notified to save CHILD_MAX statuses. */
3884 mark_dead_jobs_as_notified (force
)
3887 register int i
, ndead
, ndeadproc
;
3890 if (js
.j_jobslots
== 0)
3893 BLOCK_CHILD (set
, oset
);
3895 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
3896 around; just run through the array. */
3899 /* XXX could use js.j_firstj here */
3900 for (i
= 0; i
< js
.j_jobslots
; i
++)
3902 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
3903 jobs
[i
]->flags
|= J_NOTIFIED
;
3905 UNBLOCK_CHILD (oset
);
3909 /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
3910 array with the corresponding not marked as notified. This is a better
3911 way to avoid pid aliasing and reuse problems than keeping the POSIX-
3912 mandated CHILD_MAX jobs around. delete_job() takes care of keeping the
3913 bgpids list regulated. */
3915 /* Count the number of dead jobs */
3916 /* XXX could use js.j_firstj here */
3917 for (i
= ndead
= ndeadproc
= 0; i
< js
.j_jobslots
; i
++)
3920 if (i
< js
.j_firstj
&& jobs
[i
])
3921 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
3922 if (i
> js
.j_lastj
&& jobs
[i
])
3923 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
3925 if (jobs
[i
] && DEADJOB (i
))
3928 ndeadproc
+= processes_in_job (i
);
3933 if (ndeadproc
!= js
.c_reaped
)
3934 itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc
, js
.c_reaped
);
3935 if (ndead
!= js
.j_ndead
)
3936 itrace("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead
, js
.j_ndead
);
3939 if (js
.c_childmax
< 0)
3940 js
.c_childmax
= getmaxchild ();
3941 if (js
.c_childmax
< 0)
3942 js
.c_childmax
= DEFAULT_CHILD_MAX
;
3944 /* Don't do anything if the number of dead processes is less than CHILD_MAX
3945 and we're not forcing a cleanup. */
3946 if (ndeadproc
<= js
.c_childmax
)
3948 UNBLOCK_CHILD (oset
);
3953 itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js
.c_childmax
, ndead
, ndeadproc
);
3956 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
3957 the list. This isn't exactly right yet; changes need to be made
3958 to stop_pipeline so we don't mark the newer jobs after we've
3959 created CHILD_MAX slots in the jobs array. This needs to be
3960 integrated with a way to keep the jobs array from growing without
3961 bound. Maybe we wrap back around to 0 after we reach some max
3962 limit, and there are sufficient job slots free (keep track of total
3963 size of jobs array (js.j_jobslots) and running count of number of jobs
3964 in jobs array. Then keep a job index corresponding to the `oldest job'
3965 and start this loop there, wrapping around as necessary. In effect,
3966 we turn the list into a circular buffer. */
3967 /* XXX could use js.j_firstj here */
3968 for (i
= 0; i
< js
.j_jobslots
; i
++)
3970 if (jobs
[i
] && DEADJOB (i
) && (interactive_shell
|| (find_last_pid (i
, 0) != last_asynchronous_pid
)))
3973 if (i
< js
.j_firstj
&& jobs
[i
])
3974 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i
, js
.j_firstj
);
3975 if (i
> js
.j_lastj
&& jobs
[i
])
3976 itrace("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i
, js
.j_lastj
);
3978 /* If marking this job as notified would drop us down below
3979 child_max, don't mark it so we can keep at least child_max
3980 statuses. XXX -- need to check what Posix actually says
3981 about keeping statuses. */
3982 if ((ndeadproc
-= processes_in_job (i
)) <= js
.c_childmax
)
3984 jobs
[i
]->flags
|= J_NOTIFIED
;
3988 UNBLOCK_CHILD (oset
);
3991 /* Here to allow other parts of the shell (like the trap stuff) to
3992 unfreeze the jobs list. */
3994 unfreeze_jobs_list ()
3996 jobs_list_frozen
= 0;
3999 /* Allow or disallow job control to take place. Returns the old value
4002 set_job_control (arg
)
4010 /* If we're turning on job control, reset pipeline_pgrp so make_child will
4011 put new child processes into the right pgrp */
4012 if (job_control
!= old
&& job_control
)
4018 /* Turn off all traces of job control. This is run by children of the shell
4019 which are going to do shellsy things, like wait (), etc. */
4021 without_job_control ()
4023 stop_making_children ();
4025 #if defined (PGRP_PIPE)
4026 pipe_close (pgrp_pipe
);
4028 delete_all_jobs (0);
4029 set_job_control (0);
4032 /* If this shell is interactive, terminate all stopped jobs and
4033 restore the original terminal process group. This is done
4034 before the `exec' builtin calls shell_execve. */
4038 if (interactive_shell
) /* XXX - should it be interactive? */
4040 terminate_stopped_jobs ();
4042 if (original_pgrp
>= 0)
4043 give_terminal_to (original_pgrp
, 1);
4046 if (original_pgrp
>= 0)
4047 setpgid (0, original_pgrp
);
4050 /* Restart job control by closing shell tty and reinitializing. This is
4051 called after an exec fails in an interactive shell and we do not exit. */
4053 restart_job_control ()
4055 if (shell_tty
!= -1)
4057 initialize_job_control (0);
4060 /* Set the handler to run when the shell receives a SIGCHLD signal. */
4062 set_sigchld_handler ()
4064 set_signal_handler (SIGCHLD
, sigchld_handler
);
4067 #if defined (PGRP_PIPE)
4068 /* Read from the read end of a pipe. This is how the process group leader
4069 blocks until all of the processes in a pipeline have been made. */
4084 while (read (pp
[0], &ch
, 1) == -1 && errno
== EINTR
)
4089 /* Close the read and write ends of PP, an array of file descriptors. */
4103 /* Functional interface closes our local-to-job-control pipes. */
4107 pipe_close (pgrp_pipe
);
4110 #endif /* PGRP_PIPE */