]> git.ipfire.org Git - thirdparty/bash.git/blob - jobs.c
fix nofork comsub overwriting currently executing command; free readline undo list...
[thirdparty/bash.git] / jobs.c
1 /* jobs.c - functions that make children, remember them, and handle their termination. */
2
3 /* This file works with both POSIX and BSD systems. It implements job
4 control. */
5
6 /* Copyright (C) 1989-2024 Free Software Foundation, Inc.
7
8 This file is part of GNU Bash, the Bourne Again SHell.
9
10 Bash is free software: you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
14
15 Bash is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with Bash. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "config.h"
25
26 #include "bashtypes.h"
27 #include "trap.h"
28 #include <stdio.h>
29 #include <signal.h>
30 #include <errno.h>
31
32 #if defined (HAVE_UNISTD_H)
33 # include <unistd.h>
34 #endif
35
36 #include "posixtime.h"
37
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 */
41
42 #if defined (HAVE_SYS_FILE_H)
43 # include <sys/file.h>
44 #endif
45
46 #include "filecntl.h"
47 #include <sys/ioctl.h>
48 #if defined (HAVE_SYS_PARAM_H)
49 #include <sys/param.h>
50 #endif
51
52 #include "input.h"
53
54 /* Need to include this up here for *_TTY_DRIVER definitions. */
55 #include "shtty.h"
56
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 */
60
61 /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
62 #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
63 # include <bsdtty.h>
64 #endif /* hpux && !TERMIOS_TTY_DRIVER */
65
66 #include "bashansi.h"
67 #include "bashintl.h"
68 #include "shell.h"
69 #include "parser.h"
70 #include "jobs.h"
71 #include "execute_cmd.h"
72 #include "flags.h"
73
74 #include "typemax.h"
75
76 #include "builtins/builtext.h"
77 #include "builtins/common.h"
78
79 #if defined (READLINE)
80 # include <readline/readline.h>
81 #endif
82
83 #if !defined (errno)
84 extern int errno;
85 #endif /* !errno */
86
87 #if !defined (HAVE_KILLPG)
88 extern int killpg (pid_t, int);
89 #endif
90
91 #if !DEFAULT_CHILD_MAX
92 # define DEFAULT_CHILD_MAX 4096
93 #endif
94
95 #if !MAX_CHILD_MAX
96 # define MAX_CHILD_MAX 32768
97 #endif
98
99 #if !defined (DEBUG)
100 #define MAX_JOBS_IN_ARRAY 4096 /* production */
101 #else
102 #define MAX_JOBS_IN_ARRAY 128 /* testing */
103 #endif
104
105 /* XXX for now */
106 #define PIDSTAT_TABLE_SZ 4096
107 #define BGPIDS_TABLE_SZ 512
108
109 /* Flag values for second argument to delete_job */
110 #define DEL_WARNSTOPPED 1 /* warn about deleting stopped jobs */
111 #define DEL_NOBGPID 2 /* don't add pgrp leader to bgpids */
112
113 /* Take care of system dependencies that must be handled when waiting for
114 children. The arguments to the WAITPID macro match those to the Posix.1
115 waitpid() function. */
116
117 #if defined (ultrix) && defined (mips) && defined (_POSIX_VERSION)
118 # define WAITPID(pid, statusp, options) \
119 wait3 ((union wait *)statusp, options, (struct rusage *)0)
120 #else
121 # if defined (_POSIX_VERSION) || defined (HAVE_WAITPID)
122 # define WAITPID(pid, statusp, options) \
123 waitpid ((pid_t)pid, statusp, options)
124 # else
125 # if defined (HAVE_WAIT3)
126 # define WAITPID(pid, statusp, options) \
127 wait3 (statusp, options, (struct rusage *)0)
128 # else
129 # define WAITPID(pid, statusp, options) \
130 wait3 (statusp, options, (int *)0)
131 # endif /* HAVE_WAIT3 */
132 # endif /* !_POSIX_VERSION && !HAVE_WAITPID*/
133 #endif /* !(Ultrix && mips && _POSIX_VERSION) */
134
135 /* getpgrp () varies between systems. Even systems that claim to be
136 Posix.1 compatible lie sometimes (Ultrix, SunOS4, apollo). */
137 #if defined (GETPGRP_VOID)
138 # define getpgid(p) getpgrp ()
139 #else
140 # define getpgid(p) getpgrp (p)
141 #endif /* !GETPGRP_VOID */
142
143 /* If the system needs it, REINSTALL_SIGCHLD_HANDLER will reinstall the
144 handler for SIGCHLD. */
145 #if defined (MUST_REINSTALL_SIGHANDLERS)
146 # define REINSTALL_SIGCHLD_HANDLER signal (SIGCHLD, sigchld_handler)
147 #else
148 # define REINSTALL_SIGCHLD_HANDLER
149 #endif /* !MUST_REINSTALL_SIGHANDLERS */
150
151 /* Some systems let waitpid(2) tell callers about stopped children. */
152 #if !defined (WCONTINUED) || defined (WCONTINUED_BROKEN)
153 # undef WCONTINUED
154 # define WCONTINUED 0
155 #endif
156 #if !defined (WIFCONTINUED)
157 # define WIFCONTINUED(s) (0)
158 #endif
159
160 /* The number of additional slots to allocate when we run out. */
161 #define JOB_SLOTS 8
162
163 typedef int sh_job_map_func_t (JOB *, int, int, int);
164
165 /* Variables used here but defined in other files. */
166 extern WORD_LIST *subst_assign_varlist;
167
168 extern SigHandler **original_signals;
169
170 extern void set_original_signal (int, SigHandler *);
171
172 static struct jobstats zerojs = { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB, NO_JOB, 0, 0 };
173 struct jobstats js = { -1L, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NO_JOB, NO_JOB, 0, 0 };
174
175 ps_index_t pidstat_table[PIDSTAT_TABLE_SZ];
176 struct bgpids bgpids = { 0, 0, 0, 0 };
177
178 struct procchain procsubs = { 0, 0, 0 };
179
180 /* The array of known jobs. */
181 JOB **jobs = (JOB **)NULL;
182
183 #if 0
184 /* The number of slots currently allocated to JOBS. */
185 int job_slots = 0;
186 #endif
187
188 /* The controlling tty for this shell. */
189 int shell_tty = -1;
190
191 /* The shell's process group. */
192 pid_t shell_pgrp = NO_PID;
193
194 /* The terminal's process group. */
195 pid_t terminal_pgrp = NO_PID;
196
197 /* The process group of the shell's parent. */
198 pid_t original_pgrp = NO_PID;
199
200 /* The process group of the pipeline currently being made. */
201 pid_t pipeline_pgrp = (pid_t)0;
202
203 #if defined (PGRP_PIPE)
204 /* Pipes which each shell uses to communicate with the process group leader
205 until all of the processes in a pipeline have been started. Then the
206 process leader is allowed to continue. */
207 int pgrp_pipe[2] = { -1, -1 };
208 #endif
209
210 /* Last child made by the shell. */
211 volatile pid_t last_made_pid = NO_PID;
212
213 /* Pid of the last asynchronous child. */
214 volatile pid_t last_asynchronous_pid = NO_PID;
215
216 /* The pipeline currently being built. */
217 PROCESS *the_pipeline = (PROCESS *)NULL;
218
219 /* If this is non-zero, do job control. */
220 int job_control = 1;
221
222 /* Are we running in background? (terminal_pgrp != shell_pgrp) */
223 int running_in_background = 0;
224
225 /* Call this when you start making children. */
226 int already_making_children = 0;
227
228 /* If this is non-zero, $LINES and $COLUMNS are reset after every process
229 exits from get_tty_state(). */
230 int check_window_size = CHECKWINSIZE_DEFAULT;
231
232 PROCESS *last_procsub_child = (PROCESS *)NULL;
233
234 /* Functions local to this file. */
235
236 void debug_print_pgrps (void);
237
238 static sighandler wait_sigint_handler (int);
239 static sighandler sigchld_handler (int);
240 static sighandler sigcont_sighandler (int);
241 static sighandler sigstop_sighandler (int);
242
243 static int waitchld (pid_t, int);
244
245 static PROCESS *find_pid_in_pipeline (pid_t, PROCESS *, int);
246 static PROCESS *find_pipeline (pid_t, int, int *);
247 static PROCESS *find_process (pid_t, int, int *);
248
249 static char *current_working_directory (void);
250 static char *job_working_directory (void);
251 static char *j_strsignal (int);
252 static char *printable_job_status (int, PROCESS *, int);
253
254 static PROCESS *find_last_proc (int, int);
255 static pid_t find_last_pid (int, int);
256
257 static int set_new_line_discipline (int);
258 static int map_over_jobs (sh_job_map_func_t *, int, int);
259 static int job_last_stopped (int);
260 static int job_last_running (int);
261 static int most_recent_job_in_state (int, JOB_STATE);
262 static int find_job (pid_t, int, PROCESS **);
263 static int print_job (JOB *, int, int, int);
264 static int process_exit_status (WAIT);
265 static int process_exit_signal (WAIT);
266 static int set_job_status_and_cleanup (int);
267
268 static WAIT job_signal_status (int);
269 static WAIT raw_job_exit_status (int);
270
271 static int job_killed_by_signal (int);
272
273 static void notify_of_job_status (void);
274 static void reset_job_indices (void);
275 static void cleanup_dead_jobs (void);
276 static int processes_in_job (int);
277 static void realloc_jobs_list (void);
278 static int compact_jobs_list (int);
279 static void add_process (char *, pid_t);
280 static void print_pipeline (PROCESS *, int, int, FILE *);
281 static void pretty_print_job (int, int, FILE *);
282 static void set_current_job (int);
283 static void reset_current (void);
284 static void set_job_running (int);
285 static void setjstatus (int);
286 static int maybe_give_terminal_to (pid_t, pid_t, int);
287 static void mark_all_jobs_as_dead (void);
288 static void mark_dead_jobs_as_notified (int);
289 static void restore_sigint_handler (void);
290 #if defined (PGRP_PIPE)
291 static void pipe_read (int *);
292 #endif
293
294 /* Hash table manipulation */
295
296 static ps_index_t *pshash_getbucket (pid_t);
297 static void pshash_delindex (ps_index_t);
298
299 /* Saved background process status management */
300 static struct pidstat *bgp_add (pid_t, int);
301 static int bgp_delete (pid_t);
302 static void bgp_clear (void);
303 static int bgp_search (pid_t);
304
305 static struct pipeline_saver *alloc_pipeline_saver (void);
306
307 static ps_index_t bgp_getindex (void);
308 static void bgp_resize (void); /* XXX */
309
310 #if defined (ARRAY_VARS)
311 static int *pstatuses; /* list of pipeline statuses */
312 static int statsize;
313 #endif
314
315 /* Used to synchronize between wait_for and other functions and the SIGCHLD
316 signal handler. */
317 static int sigchld;
318 static int queue_sigchld;
319
320 #define QUEUE_SIGCHLD(os) (os) = sigchld, queue_sigchld++
321
322 /* We set queue_sigchld around the call to waitchld to protect data structures
323 from a SIGCHLD arriving while waitchld is executing. */
324 #define UNQUEUE_SIGCHLD(os) \
325 do { \
326 queue_sigchld--; \
327 if (queue_sigchld == 0 && os != sigchld) \
328 { \
329 queue_sigchld = 1; \
330 waitchld (-1, 0); \
331 queue_sigchld = 0; \
332 } \
333 } while (0)
334
335 static SigHandler *old_tstp, *old_ttou, *old_ttin;
336 static SigHandler *old_cont = (SigHandler *)SIG_DFL;
337
338 /* A place to temporarily save the current pipeline. */
339 static struct pipeline_saver *saved_pipeline;
340
341 /* Set this to non-zero whenever you don't want the jobs list to change at
342 all: no jobs deleted and no status change notifications. This is used,
343 for example, when executing SIGCHLD traps, which may run arbitrary
344 commands. */
345 static int jobs_list_frozen;
346
347 static char retcode_name_buffer[64];
348
349 #if !defined (_POSIX_VERSION)
350
351 /* These are definitions to map POSIX 1003.1 functions onto existing BSD
352 library functions and system calls. */
353 #define setpgid(pid, pgrp) setpgrp (pid, pgrp)
354 #define tcsetpgrp(fd, pgrp) ioctl ((fd), TIOCSPGRP, &(pgrp))
355
356 pid_t
357 tcgetpgrp (int fd)
358 {
359 pid_t pgrp;
360
361 /* ioctl will handle setting errno correctly. */
362 if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
363 return (-1);
364 return (pgrp);
365 }
366
367 #endif /* !_POSIX_VERSION */
368
369 /* Initialize the global job stats structure and other bookkeeping variables */
370 void
371 init_job_stats (void)
372 {
373 js = zerojs;
374 }
375
376 /* Return the working directory for the current process. Unlike
377 job_working_directory, this does not call malloc (), nor do any
378 of the functions it calls. This is so that it can safely be called
379 from a signal handler. */
380 static char *
381 current_working_directory (void)
382 {
383 char *dir;
384 static char d[PATH_MAX];
385
386 dir = get_string_value ("PWD");
387
388 if (dir == 0 && the_current_working_directory && no_symbolic_links)
389 dir = the_current_working_directory;
390
391 if (dir == 0)
392 {
393 dir = getcwd (d, sizeof(d));
394 if (dir)
395 dir = d;
396 }
397
398 return (dir == 0) ? "<unknown>" : dir;
399 }
400
401 /* Return the working directory for the current process. */
402 static char *
403 job_working_directory (void)
404 {
405 char *dir;
406
407 dir = get_string_value ("PWD");
408 if (dir)
409 return (savestring (dir));
410
411 dir = get_working_directory ("job-working-directory");
412 if (dir)
413 return (dir);
414
415 return (savestring ("<unknown>"));
416 }
417
418 void
419 making_children (void)
420 {
421 if (already_making_children)
422 return;
423
424 already_making_children = 1;
425 start_pipeline ();
426 }
427
428 void
429 stop_making_children (void)
430 {
431 already_making_children = 0;
432 }
433
434 void
435 cleanup_the_pipeline (void)
436 {
437 PROCESS *disposer;
438 sigset_t set, oset;
439
440 BLOCK_CHILD (set, oset);
441 disposer = the_pipeline;
442 the_pipeline = (PROCESS *)NULL;
443 UNBLOCK_CHILD (oset);
444
445 if (disposer)
446 discard_pipeline (disposer);
447 }
448
449 /* Not used right now */
450 void
451 discard_last_procsub_child (void)
452 {
453 PROCESS *disposer;
454 sigset_t set, oset;
455
456 BLOCK_CHILD (set, oset);
457 disposer = last_procsub_child;
458 last_procsub_child = (PROCESS *)NULL;
459 UNBLOCK_CHILD (oset);
460
461 if (disposer)
462 discard_pipeline (disposer);
463 }
464
465 static struct pipeline_saver *
466 alloc_pipeline_saver (void)
467 {
468 struct pipeline_saver *ret;
469
470 ret = (struct pipeline_saver *)xmalloc (sizeof (struct pipeline_saver));
471 ret->pipeline = 0;
472 ret->already_making_children = 0;
473 ret->next = 0;
474 return ret;
475 }
476
477 void
478 save_pipeline (int clear)
479 {
480 sigset_t set, oset;
481 struct pipeline_saver *saver;
482
483 BLOCK_CHILD (set, oset);
484 saver = alloc_pipeline_saver ();
485 saver->pipeline = the_pipeline;
486 saver->already_making_children = already_making_children;
487 saver->next = saved_pipeline;
488 saved_pipeline = saver;
489 if (clear)
490 the_pipeline = (PROCESS *)NULL;
491 UNBLOCK_CHILD (oset);
492 }
493
494 PROCESS *
495 restore_pipeline (int discard)
496 {
497 PROCESS *old_pipeline;
498 sigset_t set, oset;
499 struct pipeline_saver *saver;
500
501 BLOCK_CHILD (set, oset);
502 old_pipeline = the_pipeline;
503 the_pipeline = saved_pipeline->pipeline;
504 already_making_children = saved_pipeline->already_making_children;
505 saver = saved_pipeline;
506 saved_pipeline = saved_pipeline->next;
507 free (saver);
508 UNBLOCK_CHILD (oset);
509
510 if (discard && old_pipeline)
511 {
512 discard_pipeline (old_pipeline);
513 return ((PROCESS *)NULL);
514 }
515 return old_pipeline;
516 }
517
518 /* Start building a pipeline. */
519 void
520 start_pipeline (void)
521 {
522 if (the_pipeline)
523 {
524 cleanup_the_pipeline ();
525 /* If job_control == 0, pipeline_pgrp will always be equal to shell_pgrp;
526 if job_control != 0, pipeline_pgrp == shell_pgrp for command and
527 process substitution, in which case we want it to be the same as
528 shell_pgrp for the lifetime of this shell instance. */
529 if (pipeline_pgrp != shell_pgrp)
530 pipeline_pgrp = 0;
531 #if defined (PGRP_PIPE)
532 sh_closepipe (pgrp_pipe);
533 #endif
534 }
535
536 #if defined (PGRP_PIPE)
537 if (job_control)
538 {
539 if (pipe (pgrp_pipe) == -1)
540 sys_error (_("start_pipeline: pgrp pipe"));
541 }
542 #endif
543 }
544
545 /* Stop building a pipeline. Install the process list in the job array.
546 This returns the index of the newly installed job.
547 DEFERRED is a command structure to be executed upon satisfactory
548 execution exit of this pipeline. */
549 int
550 stop_pipeline (int async, COMMAND *deferred)
551 {
552 register int i, j;
553 JOB *newjob;
554 sigset_t set, oset;
555
556 BLOCK_CHILD (set, oset);
557
558 #if defined (PGRP_PIPE)
559 /* The parent closes the process group synchronization pipe. */
560 sh_closepipe (pgrp_pipe);
561 #endif
562
563 cleanup_dead_jobs ();
564
565 if (js.j_jobslots == 0)
566 {
567 js.j_jobslots = JOB_SLOTS;
568 jobs = (JOB **)xmalloc (js.j_jobslots * sizeof (JOB *));
569
570 /* Now blank out these new entries. */
571 for (i = 0; i < js.j_jobslots; i++)
572 jobs[i] = (JOB *)NULL;
573
574 js.j_firstj = js.j_lastj = js.j_njobs = 0;
575 }
576
577 /* Scan from the last slot backward, looking for the next free one. */
578 /* XXX - revisit this interactive assumption */
579 /* XXX - this way for now */
580 if (interactive)
581 {
582 for (i = js.j_jobslots; i; i--)
583 if (jobs[i - 1])
584 break;
585 }
586 else
587 {
588 #if 0
589 /* This wraps around, but makes it inconvenient to extend the array */
590 for (i = js.j_lastj+1; i != js.j_lastj; i++)
591 {
592 if (i >= js.j_jobslots)
593 i = 0;
594 if (jobs[i] == 0)
595 break;
596 }
597 if (i == js.j_lastj)
598 i = js.j_jobslots;
599 #else
600 /* This doesn't wrap around yet. */
601 for (i = js.j_lastj ? js.j_lastj + 1 : js.j_lastj; i < js.j_jobslots; i++)
602 if (jobs[i] == 0)
603 break;
604 #endif
605 }
606
607 /* Do we need more room? */
608
609 /* First try compaction */
610 if ((interactive_shell == 0 || subshell_environment) && i == js.j_jobslots && js.j_jobslots >= MAX_JOBS_IN_ARRAY)
611 i = compact_jobs_list (0);
612
613 /* If we can't compact, reallocate */
614 if (i == js.j_jobslots)
615 {
616 js.j_jobslots += JOB_SLOTS;
617 jobs = (JOB **)xrealloc (jobs, (js.j_jobslots * sizeof (JOB *)));
618
619 for (j = i; j < js.j_jobslots; j++)
620 jobs[j] = (JOB *)NULL;
621 }
622
623 /* Add the current pipeline to the job list. */
624 if (the_pipeline)
625 {
626 register PROCESS *p;
627 int any_running, any_stopped, n;
628
629 newjob = (JOB *)xmalloc (sizeof (JOB));
630
631 for (n = 1, p = the_pipeline; p->next != the_pipeline; n++, p = p->next)
632 ;
633 p->next = (PROCESS *)NULL;
634 newjob->pipe = REVERSE_LIST (the_pipeline, PROCESS *);
635 for (p = newjob->pipe; p->next; p = p->next)
636 ;
637 p->next = newjob->pipe;
638
639 the_pipeline = (PROCESS *)NULL;
640 newjob->pgrp = pipeline_pgrp;
641
642 /* Invariant: if the shell is executing a command substitution,
643 pipeline_pgrp == shell_pgrp. Other parts of the shell assume this. */
644 if (pipeline_pgrp != shell_pgrp)
645 pipeline_pgrp = 0;
646
647 newjob->flags = 0;
648 if (pipefail_opt)
649 newjob->flags |= J_PIPEFAIL;
650
651 /* Flag to see if in another pgrp. */
652 if (job_control)
653 newjob->flags |= J_JOBCONTROL;
654
655 /* Set the state of this pipeline. */
656 p = newjob->pipe;
657 any_running = any_stopped = 0;
658 do
659 {
660 any_running |= PRUNNING (p);
661 any_stopped |= PSTOPPED (p);
662 p = p->next;
663 }
664 while (p != newjob->pipe);
665
666 newjob->state = any_running ? JRUNNING : (any_stopped ? JSTOPPED : JDEAD);
667 newjob->wd = job_working_directory ();
668 newjob->deferred = deferred;
669
670 newjob->j_cleanup = (sh_vptrfunc_t *)NULL;
671 newjob->cleanarg = (PTR_T) NULL;
672
673 jobs[i] = newjob;
674 if (newjob->state == JDEAD && (newjob->flags & J_FOREGROUND))
675 setjstatus (i);
676 if (newjob->state == JDEAD)
677 {
678 js.c_reaped += n; /* wouldn't have been done since this was not part of a job */
679 js.j_ndead++;
680 }
681 js.c_injobs += n;
682
683 js.j_lastj = i;
684 js.j_njobs++;
685 }
686 else
687 newjob = (JOB *)NULL;
688
689 if (newjob)
690 js.j_lastmade = newjob;
691
692 if (async)
693 {
694 if (newjob)
695 {
696 newjob->flags &= ~J_FOREGROUND;
697 newjob->flags |= J_ASYNC;
698 js.j_lastasync = newjob;
699 }
700 reset_current ();
701 }
702 else
703 {
704 if (newjob)
705 {
706 newjob->flags |= J_FOREGROUND;
707 /*
708 * !!!!! NOTE !!!!! (chet@po.cwru.edu)
709 *
710 * The currently-accepted job control wisdom says to set the
711 * terminal's process group n+1 times in an n-step pipeline:
712 * once in the parent and once in each child. This is where
713 * the parent gives it away.
714 *
715 * Don't give the terminal away if this shell is an asynchronous
716 * subshell or if we're a (presumably non-interactive) shell running
717 * in the background.
718 *
719 */
720 /* 09/08/2023 - rely on child processes to set the terminal pgrp */
721 #if 0
722 if (job_control && newjob->pgrp && (subshell_environment&SUBSHELL_ASYNC) == 0 && running_in_background == 0)
723 maybe_give_terminal_to (shell_pgrp, newjob->pgrp, 0);
724 #endif
725 }
726 }
727
728 stop_making_children ();
729 UNBLOCK_CHILD (oset);
730 return (newjob ? i : js.j_current);
731 }
732
733 /* Functions to manage the list of exited background pids whose status has
734 been saved.
735
736 pidstat_table:
737
738 The current implementation is a hash table using a single (separate) arena
739 for storage that can be allocated and freed as a unit. The size of the hash
740 table is a multiple of PIDSTAT_TABLE_SZ (4096) and multiple PIDs that hash
741 to the same value are chained through the bucket_next and bucket_prev
742 pointers (basically coalesced hashing for collision resolution).
743
744 bgpids.storage:
745
746 All pid/status storage is done using the circular buffer bgpids.storage.
747 This must contain at least js.c_childmax entries. The circular buffer is
748 used to supply the ordered list Posix requires ("the last CHILD_MAX
749 processes"). To avoid searching the entire storage table for a given PID,
750 the hash table (pidstat_table) holds pointers into the storage arena and
751 uses a doubly-linked list of cells (bucket_next/bucket_prev, also pointers
752 into the arena) to implement collision resolution. */
753
754 /* The number of elements in bgpids.storage always has to be > js.c_childmax for
755 the circular buffer to work right. */
756 static void
757 bgp_resize (void)
758 {
759 ps_index_t nsize, nsize_cur, nsize_max;
760 ps_index_t psi;
761
762 if (bgpids.nalloc == 0)
763 {
764 /* invalidate hash table when bgpids table is reallocated */
765 for (psi = 0; psi < PIDSTAT_TABLE_SZ; psi++)
766 pidstat_table[psi] = NO_PIDSTAT;
767 nsize = BGPIDS_TABLE_SZ; /* should be power of 2 */
768 bgpids.head = 0;
769 }
770 else
771 nsize = bgpids.nalloc;
772
773 nsize_max = TYPE_MAXIMUM (ps_index_t);
774 nsize_cur = (ps_index_t)js.c_childmax;
775 if (nsize_cur < 0) /* overflow */
776 nsize_cur = MAX_CHILD_MAX;
777
778 while (nsize > 0 && nsize < nsize_cur) /* > 0 should catch overflow */
779 nsize <<= 1;
780 if (nsize > nsize_max || nsize <= 0) /* overflow? */
781 nsize = nsize_max;
782 if (nsize > MAX_CHILD_MAX)
783 nsize = nsize_max = MAX_CHILD_MAX; /* hard cap */
784
785 if (bgpids.nalloc < nsize_cur && bgpids.nalloc < nsize_max)
786 {
787 bgpids.storage = (struct pidstat *)xrealloc (bgpids.storage, nsize * sizeof (struct pidstat));
788
789 for (psi = bgpids.nalloc; psi < nsize; psi++)
790 bgpids.storage[psi].pid = NO_PID;
791
792 bgpids.nalloc = nsize;
793
794 }
795 else if (bgpids.head >= bgpids.nalloc) /* wrap around */
796 bgpids.head = 0;
797 }
798
799 static ps_index_t
800 bgp_getindex (void)
801 {
802 if (bgpids.nalloc < (ps_index_t)js.c_childmax || bgpids.head >= bgpids.nalloc)
803 bgp_resize ();
804
805 pshash_delindex (bgpids.head); /* XXX - clear before reusing */
806 return bgpids.head++;
807 }
808
809 static ps_index_t *
810 pshash_getbucket (pid_t pid)
811 {
812 unsigned long hash; /* XXX - u_bits32_t */
813
814 hash = pid * 0x9e370001UL;
815 return (&pidstat_table[hash % PIDSTAT_TABLE_SZ]);
816 }
817
818 static struct pidstat *
819 bgp_add (pid_t pid, int status)
820 {
821 ps_index_t *bucket, psi;
822 struct pidstat *ps;
823
824 /* bucket == existing chain of pids hashing to same value
825 psi = where were going to put this pid/status */
826
827 bucket = pshash_getbucket (pid); /* index into pidstat_table */
828 psi = bgp_getindex (); /* bgpids.head, index into storage */
829
830 /* XXX - what if psi == *bucket? */
831 if (psi == *bucket)
832 {
833 internal_debug ("hashed pid %d (pid %d) collides with bgpids.head, skipping", psi, pid);
834 bgpids.storage[psi].pid = NO_PID; /* make sure */
835 psi = bgp_getindex (); /* skip to next one */
836 }
837
838 ps = &bgpids.storage[psi];
839
840 ps->pid = pid;
841 ps->status = status;
842 ps->bucket_next = *bucket;
843 ps->bucket_prev = NO_PIDSTAT;
844
845 bgpids.npid++;
846
847 #if 0
848 if (bgpids.npid > js.c_childmax)
849 bgp_prune ();
850 #endif
851
852 if (ps->bucket_next != NO_PIDSTAT)
853 bgpids.storage[ps->bucket_next].bucket_prev = psi;
854
855 *bucket = psi; /* set chain head in hash table */
856
857 return ps;
858 }
859
860 static void
861 pshash_delindex (ps_index_t psi)
862 {
863 struct pidstat *ps;
864 ps_index_t *bucket;
865
866 ps = &bgpids.storage[psi];
867 if (ps->pid == NO_PID)
868 return;
869
870 if (ps->bucket_next != NO_PIDSTAT)
871 bgpids.storage[ps->bucket_next].bucket_prev = ps->bucket_prev;
872 if (ps->bucket_prev != NO_PIDSTAT)
873 bgpids.storage[ps->bucket_prev].bucket_next = ps->bucket_next;
874 else
875 {
876 bucket = pshash_getbucket (ps->pid);
877 *bucket = ps->bucket_next; /* deleting chain head in hash table */
878 }
879
880 /* clear out this cell, in case it gets reused. */
881 ps->pid = NO_PID;
882 ps->bucket_next = ps->bucket_prev = NO_PIDSTAT;
883 }
884
885 static int
886 bgp_delete (pid_t pid)
887 {
888 ps_index_t psi, orig_psi;
889
890 if (bgpids.storage == 0 || bgpids.nalloc == 0 || bgpids.npid == 0)
891 return 0;
892
893 /* Search chain using hash to find bucket in pidstat_table */
894 for (orig_psi = psi = *(pshash_getbucket (pid)); psi != NO_PIDSTAT; psi = bgpids.storage[psi].bucket_next)
895 {
896 if (bgpids.storage[psi].pid == pid)
897 break;
898 if (orig_psi == bgpids.storage[psi].bucket_next) /* catch reported bug */
899 {
900 internal_warning (_("bgp_delete: LOOP: psi (%d) == storage[psi].bucket_next"), psi);
901 return 0;
902 }
903 }
904
905 if (psi == NO_PIDSTAT)
906 return 0; /* not found */
907
908 #if 0
909 itrace("bgp_delete: deleting %d", pid);
910 #endif
911
912 pshash_delindex (psi); /* hash table management */
913
914 bgpids.npid--;
915 return 1;
916 }
917
918 /* Clear out the list of saved statuses */
919 static void
920 bgp_clear (void)
921 {
922 if (bgpids.storage == 0 || bgpids.nalloc == 0)
923 return;
924
925 free (bgpids.storage);
926
927 bgpids.storage = 0;
928 bgpids.nalloc = 0;
929 bgpids.head = 0;
930
931 bgpids.npid = 0;
932 }
933
934 /* Search for PID in the list of saved background pids; return its status if
935 found. If not found, return -1. We hash to the right spot in pidstat_table
936 and follow the bucket chain to the end. */
937 static int
938 bgp_search (pid_t pid)
939 {
940 ps_index_t psi, orig_psi;
941
942 if (bgpids.storage == 0 || bgpids.nalloc == 0 || bgpids.npid == 0)
943 return -1;
944
945 /* Search chain using hash to find bucket in pidstat_table */
946 for (orig_psi = psi = *(pshash_getbucket (pid)); psi != NO_PIDSTAT; psi = bgpids.storage[psi].bucket_next)
947 {
948 if (bgpids.storage[psi].pid == pid)
949 return (bgpids.storage[psi].status);
950 if (orig_psi == bgpids.storage[psi].bucket_next) /* catch reported bug */
951 {
952 internal_warning (_("bgp_search: LOOP: psi (%d) == storage[psi].bucket_next"), psi);
953 return -1;
954 }
955 }
956
957 return -1;
958 }
959
960 #if 0
961 static void
962 bgp_prune (void)
963 {
964 return;
965 }
966 #endif
967
968 /* External interface to bgp_add/bgp_search/bgp_delete; takes care of blocking
969 and unblocking SIGCHLD if needed. If retrieve_proc_status or delete_proc_status
970 is called with BLOCK non-zero, the caller must block and unblock SIGCHLD. */
971
972 void
973 save_proc_status (pid_t pid, int status)
974 {
975 sigset_t set, oset;
976
977 BLOCK_CHILD (set, oset);
978 bgp_add (pid, status);
979 UNBLOCK_CHILD (oset);
980 }
981
982 int
983 retrieve_proc_status (pid_t pid, int block)
984 {
985 int r;
986 sigset_t set, oset;
987
988 if (block)
989 BLOCK_CHILD (set, oset);
990 r = bgp_search (pid);
991 if (block)
992 UNBLOCK_CHILD (oset);
993 return r;
994 }
995
996 void
997 delete_proc_status (pid_t pid, int block)
998 {
999 sigset_t set, oset;
1000
1001 if (block)
1002 BLOCK_CHILD (set, oset);
1003 bgp_delete (pid);
1004 if (block)
1005 UNBLOCK_CHILD (oset);
1006 }
1007
1008 #if defined (PROCESS_SUBSTITUTION)
1009 /* Functions to add and remove PROCESS * children from the list of running
1010 asynchronous process substitutions. The list is currently a simple singly
1011 linked list of PROCESS *, so it works with the set of callers that want
1012 a child. subst.c:process_substitute adds to the list, the various wait*
1013 functions manipulate child->running and child->status, and processes are
1014 eventually removed from the list and added to the bgpids table. */
1015
1016 static void
1017 procsub_free (PROCESS *p)
1018 {
1019 FREE (p->command);
1020 free (p);
1021 }
1022
1023 PROCESS *
1024 procsub_add (PROCESS *p)
1025 {
1026 sigset_t set, oset;
1027
1028 BLOCK_CHILD (set, oset);
1029 if (procsubs.head == 0)
1030 {
1031 procsubs.head = procsubs.end = p;
1032 procsubs.nproc = 0;
1033 }
1034 else
1035 {
1036 procsubs.end->next = p;
1037 procsubs.end = p;
1038 }
1039 procsubs.nproc++;
1040 UNBLOCK_CHILD (oset);
1041
1042 return p;
1043 }
1044
1045 PROCESS *
1046 procsub_search (pid_t pid)
1047 {
1048 PROCESS *p;
1049 sigset_t set, oset;
1050
1051 BLOCK_CHILD (set, oset);
1052 for (p = procsubs.head; p; p = p->next)
1053 if (p->pid == pid)
1054 break;
1055 UNBLOCK_CHILD (oset);
1056
1057 return p;
1058 }
1059
1060 PROCESS *
1061 procsub_delete (pid_t pid)
1062 {
1063 PROCESS *p, *prev;
1064 sigset_t set, oset;
1065
1066 BLOCK_CHILD (set, oset);
1067 for (p = prev = procsubs.head; p; prev = p, p = p->next)
1068 if (p->pid == pid)
1069 {
1070 prev->next = p->next;
1071 break;
1072 }
1073
1074 if (p == 0)
1075 {
1076 UNBLOCK_CHILD (oset);
1077 return p;
1078 }
1079
1080 if (p == procsubs.head)
1081 procsubs.head = procsubs.head->next;
1082 else if (p == procsubs.end)
1083 procsubs.end = prev;
1084
1085 procsubs.nproc--;
1086 if (procsubs.nproc == 0)
1087 procsubs.head = procsubs.end = 0;
1088 else if (procsubs.nproc == 1) /* XXX */
1089 procsubs.end = procsubs.head;
1090
1091 /* this can't be called anywhere in a signal handling path */
1092 bgp_add (p->pid, process_exit_status (p->status));
1093 UNBLOCK_CHILD (oset);
1094 return (p);
1095 }
1096
1097 int
1098 procsub_waitpid (pid_t pid)
1099 {
1100 PROCESS *p;
1101 int r;
1102
1103 p = procsub_search (pid);
1104 if (p == 0)
1105 return -1;
1106 if (p->running == PS_DONE)
1107 return (p->status);
1108 r = wait_for (p->pid, 0);
1109 return (r); /* defer removing until later */
1110 }
1111
1112 void
1113 procsub_waitall (void)
1114 {
1115 PROCESS *p;
1116 int r;
1117
1118 for (p = procsubs.head; p; p = p->next)
1119 {
1120 if (p->running == PS_DONE)
1121 continue;
1122 r = wait_for (p->pid, 0);
1123 }
1124 }
1125
1126 void
1127 procsub_clear (void)
1128 {
1129 PROCESS *p, *ps;
1130 sigset_t set, oset;
1131
1132 BLOCK_CHILD (set, oset);
1133
1134 for (ps = procsubs.head; ps; )
1135 {
1136 p = ps;
1137 ps = ps->next;
1138 procsub_free (p);
1139 }
1140 procsubs.head = procsubs.end = 0;
1141 procsubs.nproc = 0;
1142 UNBLOCK_CHILD (oset);
1143 }
1144
1145 /* Must be called with SIGCHLD blocked. */
1146 void
1147 procsub_prune (void)
1148 {
1149 PROCESS *ohead, *oend, *ps, *p;
1150 int onproc;
1151
1152 if (procsubs.nproc == 0)
1153 return;
1154
1155 ohead = procsubs.head;
1156 oend = procsubs.end;
1157 onproc = procsubs.nproc;
1158
1159 procsubs.head = procsubs.end = 0;
1160 procsubs.nproc = 0;
1161
1162 for (p = ohead; p; )
1163 {
1164 ps = p->next;
1165 p->next = 0;
1166 if (p->running == PS_DONE)
1167 {
1168 bgp_add (p->pid, process_exit_status (p->status));
1169 procsub_free (p);
1170 }
1171 else
1172 procsub_add (p);
1173 p = ps;
1174 }
1175 }
1176 #endif
1177
1178 /* Reset the values of js.j_lastj and js.j_firstj after one or both have
1179 been deleted. The caller should check whether js.j_njobs is 0 before
1180 calling this. This wraps around, but the rest of the code does not. At
1181 this point, it should not matter. */
1182 static void
1183 reset_job_indices (void)
1184 {
1185 int old;
1186
1187 if (jobs[js.j_firstj] == 0)
1188 {
1189 old = js.j_firstj++;
1190 if (old >= js.j_jobslots)
1191 old = js.j_jobslots - 1;
1192 while (js.j_firstj != old)
1193 {
1194 if (js.j_firstj >= js.j_jobslots)
1195 js.j_firstj = 0;
1196 if (jobs[js.j_firstj] || js.j_firstj == old) /* needed if old == 0 */
1197 break;
1198 js.j_firstj++;
1199 }
1200 if (js.j_firstj == old)
1201 js.j_firstj = js.j_lastj = js.j_njobs = 0;
1202 }
1203 if (jobs[js.j_lastj] == 0)
1204 {
1205 old = js.j_lastj--;
1206 if (old < 0)
1207 old = 0;
1208 while (js.j_lastj != old)
1209 {
1210 if (js.j_lastj < 0)
1211 js.j_lastj = js.j_jobslots - 1;
1212 if (jobs[js.j_lastj] || js.j_lastj == old) /* needed if old == js.j_jobslots */
1213 break;
1214 js.j_lastj--;
1215 }
1216 if (js.j_lastj == old)
1217 js.j_firstj = js.j_lastj = js.j_njobs = 0;
1218 }
1219 }
1220
1221 /* Delete all DEAD jobs that the user had received notification about. */
1222 static void
1223 cleanup_dead_jobs (void)
1224 {
1225 register int i;
1226 int os;
1227
1228 if (js.j_jobslots == 0 || jobs_list_frozen)
1229 return;
1230
1231 QUEUE_SIGCHLD(os);
1232
1233 /* XXX could use js.j_firstj and js.j_lastj here */
1234 for (i = 0; i < js.j_jobslots; i++)
1235 {
1236 if (i < js.j_firstj && jobs[i])
1237 INTERNAL_DEBUG (("cleanup_dead_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
1238 if (i > js.j_lastj && jobs[i])
1239 INTERNAL_DEBUG(("cleanup_dead_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
1240
1241 if (jobs[i] == 0 || DEADJOB (i) == 0)
1242 continue; /* not a candidate */
1243 else if (IS_NOTIFIED (i))
1244 delete_job (i, 0); /* already notified */
1245 else if (IS_FOREGROUND (i) && job_killed_by_signal (i) == 0)
1246 delete_job (i, 0); /* we won't notify about this */
1247 }
1248
1249 #if defined (PROCESS_SUBSTITUTION)
1250 procsub_prune ();
1251 last_procsub_child = (PROCESS *)NULL;
1252 #endif
1253
1254 #if defined (COPROCESS_SUPPORT)
1255 coproc_reap ();
1256 #endif
1257
1258 UNQUEUE_SIGCHLD(os);
1259 }
1260
1261 static int
1262 processes_in_job (int job)
1263 {
1264 int nproc;
1265 register PROCESS *p;
1266
1267 nproc = 0;
1268 p = jobs[job]->pipe;
1269 do
1270 {
1271 p = p->next;
1272 nproc++;
1273 }
1274 while (p != jobs[job]->pipe);
1275
1276 return nproc;
1277 }
1278
1279 static void
1280 delete_old_job (pid_t pid)
1281 {
1282 PROCESS *p;
1283 int job;
1284
1285 job = find_job (pid, 0, &p);
1286 if (job != NO_JOB)
1287 {
1288 INTERNAL_DEBUG (("delete_old_job: found pid %d in job %d with state %d", pid, job, jobs[job]->state));
1289 if (JOBSTATE (job) == JDEAD)
1290 delete_job (job, DEL_NOBGPID);
1291 else
1292 {
1293 internal_debug (_("forked pid %d appears in running job %d"), pid, job+1);
1294 if (p)
1295 p->pid = 0;
1296 }
1297 }
1298 }
1299
1300 /* Reallocate and compress the jobs list. This returns with a jobs array
1301 whose size is a multiple of JOB_SLOTS and can hold the current number of
1302 jobs. Heuristics are used to minimize the number of new reallocs. */
1303 static void
1304 realloc_jobs_list (void)
1305 {
1306 sigset_t set, oset;
1307 int nsize, i, j, ncur, nprev;
1308 JOB **nlist;
1309
1310 ncur = nprev = NO_JOB;
1311 nsize = ((js.j_njobs + JOB_SLOTS - 1) / JOB_SLOTS);
1312 nsize *= JOB_SLOTS;
1313 i = js.j_njobs % JOB_SLOTS;
1314 if (i == 0 || i > (JOB_SLOTS >> 1))
1315 nsize += JOB_SLOTS;
1316
1317 BLOCK_CHILD (set, oset);
1318 nlist = (js.j_jobslots == nsize) ? jobs : (JOB **) xmalloc (nsize * sizeof (JOB *));
1319
1320 js.c_reaped = js.j_ndead = 0;
1321 for (i = j = 0; i < js.j_jobslots; i++)
1322 if (jobs[i])
1323 {
1324 if (i == js.j_current)
1325 ncur = j;
1326 if (i == js.j_previous)
1327 nprev = j;
1328 nlist[j++] = jobs[i];
1329 if (jobs[i]->state == JDEAD)
1330 {
1331 js.j_ndead++;
1332 js.c_reaped += processes_in_job (i);
1333 }
1334 }
1335
1336 #if 0
1337 itrace ("realloc_jobs_list: resize jobs list from %d to %d", js.j_jobslots, nsize);
1338 itrace ("realloc_jobs_list: j_lastj changed from %d to %d", js.j_lastj, (j > 0) ? j - 1 : 0);
1339 itrace ("realloc_jobs_list: j_njobs changed from %d to %d", js.j_njobs, j);
1340 itrace ("realloc_jobs_list: js.j_ndead %d js.c_reaped %d", js.j_ndead, js.c_reaped);
1341 #endif
1342
1343 js.j_firstj = 0;
1344 js.j_lastj = (j > 0) ? j - 1 : 0;
1345 js.j_njobs = j;
1346 js.j_jobslots = nsize;
1347
1348 /* Zero out remaining slots in new jobs list */
1349 for ( ; j < nsize; j++)
1350 nlist[j] = (JOB *)NULL;
1351
1352 if (jobs != nlist)
1353 {
1354 free (jobs);
1355 jobs = nlist;
1356 }
1357
1358 if (ncur != NO_JOB)
1359 js.j_current = ncur;
1360 if (nprev != NO_JOB)
1361 js.j_previous = nprev;
1362
1363 /* Need to reset these */
1364 if (js.j_current == NO_JOB || js.j_previous == NO_JOB || js.j_current > js.j_lastj || js.j_previous > js.j_lastj)
1365 reset_current ();
1366
1367 #if 0
1368 itrace ("realloc_jobs_list: reset js.j_current (%d) and js.j_previous (%d)", js.j_current, js.j_previous);
1369 #endif
1370
1371 UNBLOCK_CHILD (oset);
1372 }
1373
1374 /* Compact the jobs list by removing dead jobs. Assume that we have filled
1375 the jobs array to some predefined maximum. Called when the shell is not
1376 the foreground process (subshell_environment != 0). Returns the first
1377 available slot in the compacted list. If that value is js.j_jobslots, then
1378 the list needs to be reallocated. The jobs array may be in new memory if
1379 this returns > 0 and < js.j_jobslots. FLAGS is reserved for future use. */
1380 static int
1381 compact_jobs_list (int flags)
1382 {
1383 if (js.j_jobslots == 0 || jobs_list_frozen)
1384 return js.j_jobslots;
1385
1386 reap_dead_jobs ();
1387 realloc_jobs_list ();
1388
1389 #if 0
1390 itrace("compact_jobs_list: returning %d", (js.j_lastj || jobs[js.j_lastj]) ? js.j_lastj + 1 : 0);
1391 #endif
1392
1393 return ((js.j_lastj || jobs[js.j_lastj]) ? js.j_lastj + 1 : 0);
1394 }
1395
1396 /* Delete the job at INDEX from the job list. Must be called
1397 with SIGCHLD blocked. */
1398 void
1399 delete_job (int job_index, int dflags)
1400 {
1401 register JOB *temp;
1402 PROCESS *proc;
1403 int ndel;
1404
1405 if (js.j_jobslots == 0 || jobs_list_frozen)
1406 return;
1407
1408 if ((dflags & DEL_WARNSTOPPED) && subshell_environment == 0 && STOPPED (job_index))
1409 internal_warning (_("deleting stopped job %d with process group %ld"), job_index+1, (long)jobs[job_index]->pgrp);
1410 temp = jobs[job_index];
1411 if (temp == 0)
1412 return;
1413
1414 if ((dflags & DEL_NOBGPID) == 0 && (temp->flags & (J_ASYNC|J_FOREGROUND)) == J_ASYNC)
1415 {
1416 proc = find_last_proc (job_index, 0);
1417 if (proc)
1418 bgp_add (proc->pid, process_exit_status (proc->status));
1419 }
1420
1421 jobs[job_index] = (JOB *)NULL;
1422 if (temp == js.j_lastmade)
1423 js.j_lastmade = 0;
1424 else if (temp == js.j_lastasync)
1425 js.j_lastasync = 0;
1426
1427 free (temp->wd);
1428 ndel = discard_pipeline (temp->pipe);
1429
1430 js.c_injobs -= ndel;
1431 if (temp->state == JDEAD)
1432 {
1433 /* XXX - save_pipeline and restore_pipeline (e.g., for DEBUG trap) can
1434 mess with this total. */
1435 js.c_reaped -= ndel; /* assumes proc hadn't been reaped earlier */
1436 js.j_ndead--;
1437 if (js.c_reaped < 0)
1438 {
1439 INTERNAL_DEBUG (("delete_job (%d pgrp %d): js.c_reaped (%d) < 0 ndel = %d js.j_ndead = %d", job_index, temp->pgrp, js.c_reaped, ndel, js.j_ndead));
1440 js.c_reaped = 0;
1441 }
1442 }
1443
1444 if (temp->deferred)
1445 dispose_command (temp->deferred);
1446
1447 free (temp);
1448
1449 js.j_njobs--;
1450 if (js.j_njobs == 0)
1451 js.j_firstj = js.j_lastj = 0;
1452 else if (jobs[js.j_firstj] == 0 || jobs[js.j_lastj] == 0)
1453 reset_job_indices ();
1454
1455 if (job_index == js.j_current || job_index == js.j_previous)
1456 reset_current ();
1457 }
1458
1459 /* Must be called with SIGCHLD blocked. */
1460 void
1461 nohup_job (int job_index)
1462 {
1463 register JOB *temp;
1464
1465 if (js.j_jobslots == 0)
1466 return;
1467
1468 if (temp = jobs[job_index])
1469 temp->flags |= J_NOHUP;
1470 }
1471
1472 /* Get rid of the data structure associated with a process chain. */
1473 int
1474 discard_pipeline (PROCESS *chain)
1475 {
1476 register PROCESS *this, *next;
1477 int n;
1478
1479 this = chain;
1480 n = 0;
1481 do
1482 {
1483 next = this->next;
1484 FREE (this->command);
1485 free (this);
1486 n++;
1487 this = next;
1488 }
1489 while (this != chain);
1490
1491 return n;
1492 }
1493
1494 /* Add this process to the chain being built in the_pipeline.
1495 NAME is the command string that will be exec'ed later.
1496 PID is the process id of the child. */
1497 static void
1498 add_process (char *name, pid_t pid)
1499 {
1500 PROCESS *t, *p;
1501
1502 #if defined (RECYCLES_PIDS)
1503 int j;
1504 p = find_process (pid, 0, &j);
1505 if (p)
1506 {
1507 if (j == NO_JOB)
1508 internal_debug ("add_process: process %5ld (%s) in the_pipeline", (long)p->pid, p->command);
1509 if (PALIVE (p))
1510 internal_warning (_("add_process: pid %5ld (%s) marked as still alive"), (long)p->pid, p->command);
1511 p->running = PS_RECYCLED; /* mark as recycled */
1512 }
1513 #endif
1514
1515 t = (PROCESS *)xmalloc (sizeof (PROCESS));
1516 t->next = the_pipeline;
1517 t->pid = pid;
1518 WSTATUS (t->status) = 0;
1519 t->running = PS_RUNNING;
1520 t->command = name;
1521 the_pipeline = t;
1522
1523 if (t->next == 0)
1524 t->next = t;
1525 else
1526 {
1527 p = t->next;
1528 while (p->next != t->next)
1529 p = p->next;
1530 p->next = t;
1531 }
1532 }
1533
1534 /* Create a (dummy) PROCESS with NAME, PID, and STATUS, and make it the last
1535 process in jobs[JID]->pipe. Used by the lastpipe code. */
1536 void
1537 append_process (char *name, pid_t pid, int status, int jid)
1538 {
1539 PROCESS *t, *p;
1540
1541 t = (PROCESS *)xmalloc (sizeof (PROCESS));
1542 t->next = (PROCESS *)NULL;
1543 t->pid = pid;
1544 /* set process exit status using offset discovered by configure */
1545 t->status = (status & 0xff) << WEXITSTATUS_OFFSET;
1546 t->running = PS_DONE;
1547 t->command = name;
1548
1549 js.c_reaped++; /* XXX */
1550
1551 for (p = jobs[jid]->pipe; p->next != jobs[jid]->pipe; p = p->next)
1552 ;
1553 p->next = t;
1554 t->next = jobs[jid]->pipe;
1555 }
1556
1557 #if 0
1558 /* Take the last job and make it the first job. Must be called with
1559 SIGCHLD blocked. */
1560 int
1561 rotate_the_pipeline (void)
1562 {
1563 PROCESS *p;
1564
1565 if (the_pipeline->next == the_pipeline)
1566 return;
1567 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
1568 ;
1569 the_pipeline = p;
1570 }
1571
1572 /* Reverse the order of the processes in the_pipeline. Must be called with
1573 SIGCHLD blocked. */
1574 int
1575 reverse_the_pipeline (void)
1576 {
1577 PROCESS *p, *n;
1578
1579 if (the_pipeline->next == the_pipeline)
1580 return;
1581
1582 for (p = the_pipeline; p->next != the_pipeline; p = p->next)
1583 ;
1584 p->next = (PROCESS *)NULL;
1585
1586 n = REVERSE_LIST (the_pipeline, PROCESS *);
1587
1588 the_pipeline = n;
1589 for (p = the_pipeline; p->next; p = p->next)
1590 ;
1591 p->next = the_pipeline;
1592 }
1593 #endif
1594
1595 /* Map FUNC over the list of jobs. If FUNC returns non-zero,
1596 then it is time to stop mapping, and that is the return value
1597 for map_over_jobs. FUNC is called with a JOB, arg1, arg2,
1598 and INDEX. */
1599 static int
1600 map_over_jobs (sh_job_map_func_t *func, int arg1, int arg2)
1601 {
1602 register int i;
1603 int result;
1604 sigset_t set, oset;
1605
1606 if (js.j_jobslots == 0)
1607 return 0;
1608
1609 BLOCK_CHILD (set, oset);
1610
1611 /* XXX could use js.j_firstj here */
1612 for (i = result = 0; i < js.j_jobslots; i++)
1613 {
1614 if (i < js.j_firstj && jobs[i])
1615 INTERNAL_DEBUG (("map_over_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
1616 if (i > js.j_lastj && jobs[i])
1617 INTERNAL_DEBUG (("map_over_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
1618
1619 if (jobs[i])
1620 {
1621 result = (*func)(jobs[i], arg1, arg2, i);
1622 if (result)
1623 break;
1624 }
1625 }
1626
1627 UNBLOCK_CHILD (oset);
1628
1629 return (result);
1630 }
1631
1632 /* Cause all the jobs in the current pipeline to exit. */
1633 void
1634 terminate_current_pipeline (void)
1635 {
1636 PROCESS *p;
1637
1638 if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
1639 {
1640 killpg (pipeline_pgrp, SIGTERM);
1641 killpg (pipeline_pgrp, SIGCONT);
1642 killpg (pipeline_pgrp, SIGKILL);
1643 }
1644 else if (pipeline_pgrp && pipeline_pgrp == shell_pgrp && (p = the_pipeline))
1645 {
1646 do
1647 {
1648 kill (p->pid, SIGTERM);
1649 kill (p->pid, SIGCONT);
1650 kill (p->pid, SIGKILL);
1651 p = p->next;
1652 }
1653 while (p != the_pipeline);
1654 }
1655 }
1656
1657 /* Cause all stopped jobs to exit. */
1658 void
1659 terminate_stopped_jobs (void)
1660 {
1661 register int i;
1662
1663 /* XXX could use js.j_firstj here */
1664 for (i = 0; i < js.j_jobslots; i++)
1665 {
1666 if (jobs[i] && STOPPED (i))
1667 {
1668 killpg (jobs[i]->pgrp, SIGTERM);
1669 killpg (jobs[i]->pgrp, SIGCONT);
1670 }
1671 }
1672 }
1673
1674 /* Cause all jobs, running or stopped, to receive a hangup signal. If
1675 a job is marked J_NOHUP, don't send the SIGHUP. */
1676 void
1677 hangup_all_jobs (void)
1678 {
1679 register int i;
1680
1681 /* XXX could use js.j_firstj here */
1682 for (i = 0; i < js.j_jobslots; i++)
1683 {
1684 if (jobs[i])
1685 {
1686 if (jobs[i]->flags & J_NOHUP)
1687 continue;
1688 killpg (jobs[i]->pgrp, SIGHUP);
1689 if (STOPPED (i))
1690 killpg (jobs[i]->pgrp, SIGCONT);
1691 }
1692 }
1693 }
1694
1695 void
1696 kill_current_pipeline (void)
1697 {
1698 stop_making_children ();
1699 start_pipeline ();
1700 }
1701
1702 static PROCESS *
1703 find_pid_in_pipeline (pid_t pid, PROCESS *pipeline, int alive_only)
1704 {
1705 PROCESS *p;
1706
1707 p = pipeline;
1708 do
1709 {
1710 /* Return it if we found it. Don't ever return a recycled pid. */
1711 if (p->pid == pid && ((alive_only == 0 && PRECYCLED(p) == 0) || PALIVE(p)))
1712 return (p);
1713
1714 p = p->next;
1715 }
1716 while (p != pipeline);
1717 return ((PROCESS *)NULL);
1718 }
1719
1720 /* Return the pipeline that PID belongs to. Note that the pipeline
1721 doesn't have to belong to a job. Must be called with SIGCHLD blocked.
1722 If JOBP is non-null, return the index of the job containing PID, or
1723 NO_JOB if PID doesn't belong to an existing job. */
1724 static PROCESS *
1725 find_pipeline (pid_t pid, int alive_only, int *jobp)
1726 {
1727 int job;
1728 PROCESS *p;
1729 struct pipeline_saver *save;
1730
1731 /* See if this process is in the pipeline that we are building. */
1732 p = (PROCESS *)NULL;
1733 if (jobp)
1734 *jobp = NO_JOB;
1735
1736 if (the_pipeline && (p = find_pid_in_pipeline (pid, the_pipeline, alive_only)))
1737 return (p);
1738
1739 /* Is this process in a saved pipeline? */
1740 for (save = saved_pipeline; save; save = save->next)
1741 if (save->pipeline && (p = find_pid_in_pipeline (pid, save->pipeline, alive_only)))
1742 return (p);
1743
1744 #if defined (PROCESS_SUBSTITUTION)
1745 if (procsubs.nproc > 0 && (p = procsub_search (pid)) && ((alive_only == 0 && PRECYCLED(p) == 0) || PALIVE(p)))
1746 return (p);
1747 #endif
1748
1749 job = find_job (pid, alive_only, &p);
1750 if (jobp)
1751 *jobp = job;
1752 return (job == NO_JOB) ? (PROCESS *)NULL : jobs[job]->pipe;
1753 }
1754
1755 /* Return the PROCESS * describing PID. If JOBP is non-null return the index
1756 into the jobs array of the job containing PID or NO_JOB. Must be called
1757 with SIGCHLD blocked. */
1758 static PROCESS *
1759 find_process (pid_t pid, int alive_only, int *jobp)
1760 {
1761 PROCESS *p;
1762
1763 p = find_pipeline (pid, alive_only, jobp);
1764 while (p && p->pid != pid)
1765 p = p->next;
1766 return p;
1767 }
1768
1769 /* Return the job index that PID belongs to, or NO_JOB if it doesn't
1770 belong to any job. Must be called with SIGCHLD blocked. */
1771 static int
1772 find_job (pid_t pid, int alive_only, PROCESS **procp)
1773 {
1774 register int i;
1775 PROCESS *p;
1776
1777 /* XXX could use js.j_firstj here, and should check js.j_lastj */
1778 for (i = 0; i < js.j_jobslots; i++)
1779 {
1780 if (i < js.j_firstj && jobs[i])
1781 INTERNAL_DEBUG (("find_job: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
1782 if (i > js.j_lastj && jobs[i])
1783 INTERNAL_DEBUG (("find_job: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
1784
1785 if (jobs[i])
1786 {
1787 p = jobs[i]->pipe;
1788
1789 do
1790 {
1791 if (p->pid == pid && ((alive_only == 0 && PRECYCLED(p) == 0) || PALIVE(p)))
1792 {
1793 if (procp)
1794 *procp = p;
1795 return (i);
1796 }
1797
1798 p = p->next;
1799 }
1800 while (p != jobs[i]->pipe);
1801 }
1802 }
1803
1804 return (NO_JOB);
1805 }
1806
1807 /* Find a job given a PID. If BLOCK is non-zero, block SIGCHLD as
1808 required by find_job. */
1809 int
1810 get_job_by_pid (pid_t pid, int block, PROCESS **procp)
1811 {
1812 int job;
1813 sigset_t set, oset;
1814
1815 if (block)
1816 BLOCK_CHILD (set, oset);
1817
1818 job = find_job (pid, 0, procp);
1819
1820 if (block)
1821 UNBLOCK_CHILD (oset);
1822
1823 return job;
1824 }
1825
1826 /* Print descriptive information about the job with leader pid PID. */
1827 void
1828 describe_pid (pid_t pid)
1829 {
1830 int job;
1831 sigset_t set, oset;
1832
1833 BLOCK_CHILD (set, oset);
1834
1835 job = find_job (pid, 0, NULL);
1836
1837 if (job != NO_JOB)
1838 fprintf (stderr, "[%d] %ld\n", job + 1, (long)pid);
1839 else
1840 programming_error (_("describe_pid: %ld: no such pid"), (long)pid);
1841
1842 UNBLOCK_CHILD (oset);
1843 }
1844
1845 static char *
1846 j_strsignal (int s)
1847 {
1848 char *x;
1849
1850 x = strsignal (s);
1851 if (x == 0)
1852 {
1853 x = retcode_name_buffer;
1854 snprintf (x, sizeof(retcode_name_buffer), _("Signal %d"), s);
1855 }
1856 return x;
1857 }
1858
1859 static char *
1860 printable_job_status (int j, PROCESS *p, int format)
1861 {
1862 static char *temp;
1863 int es;
1864
1865 temp = _("Done");
1866
1867 if (STOPPED (j) && format == 0)
1868 {
1869 if (posixly_correct == 0 || p == 0 || (WIFSTOPPED (p->status) == 0))
1870 temp = _("Stopped");
1871 else
1872 {
1873 temp = retcode_name_buffer;
1874 snprintf (temp, sizeof(retcode_name_buffer), _("Stopped(%s)"), signal_name (WSTOPSIG (p->status)));
1875 }
1876 }
1877 else if (RUNNING (j))
1878 temp = _("Running");
1879 else
1880 {
1881 if (WIFSTOPPED (p->status))
1882 temp = j_strsignal (WSTOPSIG (p->status));
1883 else if (WIFSIGNALED (p->status))
1884 temp = j_strsignal (WTERMSIG (p->status));
1885 else if (WIFEXITED (p->status))
1886 {
1887 temp = retcode_name_buffer;
1888 es = WEXITSTATUS (p->status);
1889 if (es == 0)
1890 {
1891 strncpy (temp, _("Done"), sizeof (retcode_name_buffer) - 1);
1892 temp[sizeof (retcode_name_buffer) - 1] = '\0';
1893 }
1894 else if (posixly_correct)
1895 snprintf (temp, sizeof(retcode_name_buffer), _("Done(%d)"), es);
1896 else
1897 snprintf (temp, sizeof(retcode_name_buffer), _("Exit %d"), es);
1898 }
1899 else
1900 temp = _("Unknown status");
1901 }
1902
1903 return temp;
1904 }
1905
1906 /* This is the way to print out information on a job if you
1907 know the index. FORMAT is:
1908
1909 JLIST_NORMAL) [1]+ Running emacs
1910 JLIST_LONG ) [1]+ 2378 Running emacs
1911 -1 ) [1]+ 2378 emacs
1912
1913 JLIST_NORMAL) [1]+ Stopped ls | more
1914 JLIST_LONG ) [1]+ 2369 Stopped ls
1915 2367 | more
1916 JLIST_PID_ONLY)
1917 Just list the pid of the process group leader (really
1918 the process group).
1919 JLIST_CHANGED_ONLY)
1920 Use format JLIST_NORMAL, but list only jobs about which
1921 the user has not been notified. */
1922
1923 /* Print status for pipeline P. If JOB_INDEX is >= 0, it is the index into
1924 the JOBS array corresponding to this pipeline. FORMAT is as described
1925 above. Must be called with SIGCHLD blocked.
1926
1927 If you're printing a pipeline that's not in the jobs array, like the
1928 current pipeline as it's being created, pass -1 for JOB_INDEX */
1929 static void
1930 print_pipeline (PROCESS *p, int job_index, int format, FILE *stream)
1931 {
1932 PROCESS *first, *last, *show;
1933 int es, name_padding;
1934 char *temp;
1935
1936 if (p == 0)
1937 return;
1938
1939 first = last = p;
1940 while (last->next != first)
1941 last = last->next;
1942
1943 for (;;)
1944 {
1945 if (p != first)
1946 fprintf (stream, format ? " " : " |");
1947
1948 if (format != JLIST_STANDARD)
1949 fprintf (stream, "%5ld", (long)p->pid);
1950
1951 fprintf (stream, " ");
1952
1953 if (format > -1 && job_index >= 0)
1954 {
1955 show = format ? p : last;
1956 temp = printable_job_status (job_index, show, format);
1957
1958 if (p != first)
1959 {
1960 if (format)
1961 {
1962 if (show->running == first->running &&
1963 WSTATUS (show->status) == WSTATUS (first->status))
1964 temp = "";
1965 }
1966 else
1967 temp = (char *)NULL;
1968 }
1969
1970 if (temp)
1971 {
1972 fprintf (stream, "%s", temp);
1973
1974 es = STRLEN (temp);
1975 if (es == 0)
1976 es = 2; /* strlen ("| ") */
1977 name_padding = LONGEST_SIGNAL_DESC - es;
1978
1979 fprintf (stream, "%*s", name_padding, "");
1980
1981 if ((WIFSTOPPED (show->status) == 0) &&
1982 (WIFCONTINUED (show->status) == 0) &&
1983 WIFCORED (show->status))
1984 fprintf (stream, _("(core dumped) "));
1985 }
1986 }
1987
1988 if (p != first && format)
1989 fprintf (stream, "| ");
1990
1991 if (p->command)
1992 fprintf (stream, "%s", p->command);
1993
1994 if (p == last && job_index >= 0)
1995 {
1996 temp = current_working_directory ();
1997
1998 if (RUNNING (job_index) && (IS_FOREGROUND (job_index) == 0))
1999 fprintf (stream, " &");
2000
2001 if (strcmp (temp, jobs[job_index]->wd) != 0)
2002 fprintf (stream,
2003 _(" (wd: %s)"), polite_directory_format (jobs[job_index]->wd));
2004 }
2005
2006 if (format || (p == last))
2007 {
2008 /* We need to add a CR only if this is an interactive shell, and
2009 we're reporting the status of a completed job asynchronously.
2010 We can't really check whether this particular job is being
2011 reported asynchronously, so just add the CR if the shell is
2012 currently interactive and asynchronous notification is enabled. */
2013 if (asynchronous_notification && interactive)
2014 putc ('\r', stream);
2015 fprintf (stream, "\n");
2016 }
2017
2018 if (p == last)
2019 break;
2020 p = p->next;
2021 }
2022 fflush (stream);
2023 }
2024
2025 /* Print information to STREAM about jobs[JOB_INDEX] according to FORMAT.
2026 Must be called with SIGCHLD blocked or queued with queue_sigchld */
2027 static void
2028 pretty_print_job (int job_index, int format, FILE *stream)
2029 {
2030 register PROCESS *p;
2031
2032 /* Format only pid information about the process group leader? */
2033 if (format == JLIST_PID_ONLY)
2034 {
2035 fprintf (stream, "%ld\n", (long)jobs[job_index]->pipe->pid);
2036 return;
2037 }
2038
2039 if (format == JLIST_CHANGED_ONLY)
2040 {
2041 if (IS_NOTIFIED (job_index))
2042 return;
2043 format = JLIST_STANDARD;
2044 }
2045
2046 if (format != JLIST_NONINTERACTIVE)
2047 fprintf (stream, "[%d]%c ", job_index + 1,
2048 (job_index == js.j_current) ? '+':
2049 (job_index == js.j_previous) ? '-' : ' ');
2050
2051 if (format == JLIST_NONINTERACTIVE)
2052 format = JLIST_LONG;
2053
2054 p = jobs[job_index]->pipe;
2055
2056 print_pipeline (p, job_index, format, stream);
2057
2058 /* We have printed information about this job. When the job's
2059 status changes, waitchld () sets the notification flag to 0. */
2060 jobs[job_index]->flags |= J_NOTIFIED;
2061 }
2062
2063 static int
2064 print_job (JOB *job, int format, int state, int job_index)
2065 {
2066 if (state == -1 || (JOB_STATE)state == job->state)
2067 pretty_print_job (job_index, format, stdout);
2068 return (0);
2069 }
2070
2071 void
2072 list_one_job (JOB *job, int format, int ignore, int job_index)
2073 {
2074 pretty_print_job (job_index, format, stdout);
2075 cleanup_dead_jobs ();
2076 }
2077
2078 void
2079 list_stopped_jobs (int format)
2080 {
2081 cleanup_dead_jobs ();
2082 map_over_jobs (print_job, format, (int)JSTOPPED);
2083 }
2084
2085 void
2086 list_running_jobs (int format)
2087 {
2088 cleanup_dead_jobs ();
2089 map_over_jobs (print_job, format, (int)JRUNNING);
2090 }
2091
2092 /* List jobs. If FORMAT is non-zero, then the long form of the information
2093 is printed, else just a short version. */
2094 void
2095 list_all_jobs (int format)
2096 {
2097 cleanup_dead_jobs ();
2098 map_over_jobs (print_job, format, -1);
2099 }
2100
2101 /* Fork, handling errors. Returns the pid of the newly made child, or 0.
2102 COMMAND is just for remembering the name of the command; we don't do
2103 anything else with it. ASYNC_P says what to do with the tty. If
2104 non-zero, then don't give it away. */
2105 pid_t
2106 make_child (char *command, int flags)
2107 {
2108 int async_p;
2109 unsigned int forksleep;
2110 sigset_t set, oset, oset_copy;
2111 pid_t pid;
2112 SigHandler *oterm;
2113
2114 sigemptyset (&oset_copy);
2115 sigprocmask (SIG_BLOCK, (sigset_t *)NULL, &oset_copy);
2116 sigaddset (&oset_copy, SIGTERM);
2117
2118 /* Block SIGTERM here and unblock in child after fork resets the
2119 set of pending signals. */
2120 sigemptyset (&set);
2121 sigaddset (&set, SIGCHLD);
2122 sigaddset (&set, SIGINT);
2123 sigaddset (&set, SIGTERM);
2124
2125 sigemptyset (&oset);
2126 sigprocmask (SIG_BLOCK, &set, &oset);
2127
2128 /* Blocked in the parent, child will receive it after unblocking SIGTERM */
2129 if (interactive_shell)
2130 oterm = set_signal_handler (SIGTERM, SIG_DFL);
2131
2132 making_children ();
2133
2134 async_p = (flags & FORK_ASYNC);
2135 forksleep = 1;
2136
2137 /* If default_buffered_input is active, we are reading a script. If
2138 the command is asynchronous, we have already duplicated /dev/null
2139 as fd 0, but have not changed the buffered stream corresponding to
2140 the old fd 0. We don't want to sync the stream in this case. */
2141 if (default_buffered_input != -1 && (!async_p || default_buffered_input > 0))
2142 sync_buffered_stream (default_buffered_input);
2143
2144 /* Create the child, handle severe errors. Retry on EAGAIN. */
2145 while ((pid = fork ()) < 0 && errno == EAGAIN && forksleep < FORKSLEEP_MAX)
2146 {
2147 /* bash-4.2 */
2148 /* keep SIGTERM blocked until we reset the handler to SIG_IGN */
2149 sigprocmask (SIG_SETMASK, &oset_copy, (sigset_t *)NULL);
2150 /* If we can't create any children, try to reap some dead ones. */
2151 waitchld (-1, 0);
2152
2153 errno = EAGAIN; /* restore errno */
2154 sys_error ("fork: retry");
2155
2156 if (sleep (forksleep) != 0)
2157 break;
2158 forksleep <<= 1;
2159
2160 if (interrupt_state)
2161 break;
2162 sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL);
2163 }
2164
2165 if (pid != 0)
2166 if (interactive_shell)
2167 set_signal_handler (SIGTERM, oterm);
2168
2169 if (pid < 0)
2170 {
2171 sys_error ("fork");
2172
2173 /* Kill all of the processes in the current pipeline. */
2174 terminate_current_pipeline ();
2175
2176 /* Discard the current pipeline, if any. */
2177 if (the_pipeline)
2178 kill_current_pipeline ();
2179
2180 set_exit_status (EX_NOEXEC);
2181 throw_to_top_level (); /* Reset signals, etc. */
2182 }
2183
2184 if (pid == 0)
2185 {
2186 /* In the child. Give this child the right process group, set the
2187 signals to the default state for a new process. */
2188 pid_t mypid;
2189
2190 subshell_environment |= SUBSHELL_IGNTRAP;
2191
2192 /* If this ends up being changed to modify or use `command' in the
2193 child process, go back and change callers who free `command' in
2194 the child process when this returns. */
2195 mypid = getpid ();
2196
2197 /* Close default_buffered_input if it's > 0. We don't close it if it's
2198 0 because that's the file descriptor used when redirecting input,
2199 and it's wrong to close the file in that case. */
2200 unset_bash_input (0);
2201
2202 CLRINTERRUPT; /* XXX - children have their own interrupt state */
2203
2204 /* Restore top-level signal mask, including unblocking SIGTERM */
2205 restore_sigmask ();
2206
2207 if (job_control)
2208 {
2209 /* All processes in this pipeline belong in the same
2210 process group. */
2211
2212 if (pipeline_pgrp == 0) /* This is the first child. */
2213 pipeline_pgrp = mypid;
2214
2215 /* Check for running command in backquotes. */
2216 if (pipeline_pgrp == shell_pgrp)
2217 ignore_tty_job_signals ();
2218 else
2219 default_tty_job_signals ();
2220
2221 /* Set the process group before trying to mess with the terminal's
2222 process group. This is mandated by POSIX. */
2223 /* This is in accordance with the Posix 1003.1 standard,
2224 section B.7.2.4, which says that trying to set the terminal
2225 process group with tcsetpgrp() to an unused pgrp value (like
2226 this would have for the first child) is an error. Section
2227 B.4.3.3, p. 237 also covers this, in the context of job control
2228 shells. */
2229 if (setpgid (mypid, pipeline_pgrp) < 0)
2230 sys_error (_("child setpgid (%ld to %ld)"), (long)mypid, (long)pipeline_pgrp);
2231
2232 /* By convention (and assumption above), if
2233 pipeline_pgrp == shell_pgrp, we are making a child for
2234 command substitution.
2235 In this case, we don't want to give the terminal to the
2236 shell's process group (we could be in the middle of a
2237 pipeline, for example). */
2238 if ((flags & FORK_NOTERM) == 0 && async_p == 0 && pipeline_pgrp != shell_pgrp && ((subshell_environment&(SUBSHELL_ASYNC|SUBSHELL_PIPE)) == 0) && running_in_background == 0)
2239 give_terminal_to (pipeline_pgrp, 0);
2240
2241 #if defined (PGRP_PIPE)
2242 if (pipeline_pgrp == mypid)
2243 pipe_read (pgrp_pipe);
2244 #endif
2245 }
2246 else /* Without job control... */
2247 {
2248 if (pipeline_pgrp == 0)
2249 pipeline_pgrp = shell_pgrp;
2250
2251 /* If these signals are set to SIG_DFL, we encounter the curious
2252 situation of an interactive ^Z to a running process *working*
2253 and stopping the process, but being unable to do anything with
2254 that process to change its state. On the other hand, if they
2255 are set to SIG_IGN, jobs started from scripts do not stop when
2256 the shell running the script gets a SIGTSTP and stops. */
2257
2258 default_tty_job_signals ();
2259 }
2260
2261 #if defined (PGRP_PIPE)
2262 /* Release the process group pipe, since our call to setpgid ()
2263 is done. The last call to sh_closepipe is done in stop_pipeline. */
2264 sh_closepipe (pgrp_pipe);
2265 #endif /* PGRP_PIPE */
2266
2267 /* Don't set last_asynchronous_pid in the child */
2268
2269 #if defined (RECYCLES_PIDS)
2270 if (last_asynchronous_pid == mypid)
2271 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2272 last_asynchronous_pid = 1;
2273 #endif
2274 }
2275 else
2276 {
2277 /* In the parent. Remember the pid of the child just created
2278 as the proper pgrp if this is the first child. */
2279
2280 if (job_control)
2281 {
2282 if (pipeline_pgrp == 0)
2283 {
2284 pipeline_pgrp = pid;
2285 /* Don't twiddle terminal pgrps in the parent! This is the bug,
2286 not the good thing of twiddling them in the child! */
2287 /* give_terminal_to (pipeline_pgrp, 0); */
2288 }
2289 /* This is done on the recommendation of the Rationale section of
2290 the POSIX 1003.1 standard, where it discusses job control and
2291 shells. It is done to avoid possible race conditions. (Ref.
2292 1003.1 Rationale, section B.4.3.3, page 236). */
2293 setpgid (pid, pipeline_pgrp);
2294 }
2295 else
2296 {
2297 if (pipeline_pgrp == 0)
2298 pipeline_pgrp = shell_pgrp;
2299 }
2300
2301 /* Place all processes into the jobs array regardless of the
2302 state of job_control. */
2303 add_process (command, pid);
2304
2305 if (async_p)
2306 last_asynchronous_pid = pid;
2307 #if defined (RECYCLES_PIDS)
2308 else if (last_asynchronous_pid == pid)
2309 /* Avoid pid aliasing. 1 seems like a safe, unusual pid value. */
2310 last_asynchronous_pid = 1;
2311 #endif
2312
2313 /* Delete the saved status for any job containing this PID in case it's
2314 been reused. */
2315 delete_old_job (pid);
2316
2317 /* Perform the check for pid reuse unconditionally. Some systems reuse
2318 PIDs before giving a process CHILD_MAX/_SC_CHILD_MAX unique ones. */
2319 bgp_delete (pid); /* new process, discard any saved status */
2320
2321 last_made_pid = pid;
2322
2323 /* keep stats */
2324 js.c_totforked++;
2325 js.c_living++;
2326
2327 /* Unblock SIGTERM, SIGINT, and SIGCHLD unless creating a pipeline, in
2328 which case SIGCHLD remains blocked until all commands in the pipeline
2329 have been created (execute_cmd.c:execute_pipeline()). */
2330 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
2331 }
2332
2333 return (pid);
2334 }
2335
2336 /* These two functions are called only in child processes. */
2337 void
2338 ignore_tty_job_signals (void)
2339 {
2340 set_signal_handler (SIGTSTP, SIG_IGN);
2341 set_signal_handler (SIGTTIN, SIG_IGN);
2342 set_signal_handler (SIGTTOU, SIG_IGN);
2343 }
2344
2345 /* Reset the tty-generated job control signals to SIG_DFL unless that signal
2346 was ignored at entry to the shell, in which case we need to set it to
2347 SIG_IGN in the child. We can't rely on resetting traps, since the hard
2348 ignored signals can't be trapped. */
2349 void
2350 default_tty_job_signals (void)
2351 {
2352 if (signal_is_trapped (SIGTSTP) == 0 && signal_is_hard_ignored (SIGTSTP))
2353 set_signal_handler (SIGTSTP, SIG_IGN);
2354 else
2355 set_signal_handler (SIGTSTP, SIG_DFL);
2356
2357 if (signal_is_trapped (SIGTTIN) == 0 && signal_is_hard_ignored (SIGTTIN))
2358 set_signal_handler (SIGTTIN, SIG_IGN);
2359 else
2360 set_signal_handler (SIGTTIN, SIG_DFL);
2361
2362 if (signal_is_trapped (SIGTTOU) == 0 && signal_is_hard_ignored (SIGTTOU))
2363 set_signal_handler (SIGTTOU, SIG_IGN);
2364 else
2365 set_signal_handler (SIGTTOU, SIG_DFL);
2366 }
2367
2368 /* Called once in a parent process. */
2369 void
2370 get_original_tty_job_signals (void)
2371 {
2372 static int fetched = 0;
2373
2374 if (fetched == 0)
2375 {
2376 if (interactive_shell)
2377 {
2378 set_original_signal (SIGTSTP, SIG_DFL);
2379 set_original_signal (SIGTTIN, SIG_DFL);
2380 set_original_signal (SIGTTOU, SIG_DFL);
2381 }
2382 else
2383 {
2384 get_original_signal (SIGTSTP);
2385 get_original_signal (SIGTTIN);
2386 get_original_signal (SIGTTOU);
2387 }
2388 fetched = 1;
2389 }
2390 }
2391
2392 /* When we end a job abnormally, or if we stop a job, we set the tty to the
2393 state kept in here. When a job ends normally, we set the state in here
2394 to the state of the tty. */
2395
2396 static TTYSTRUCT shell_tty_info;
2397
2398 #if defined (NEW_TTY_DRIVER)
2399 static struct tchars shell_tchars;
2400 static struct ltchars shell_ltchars;
2401 #endif /* NEW_TTY_DRIVER */
2402
2403 #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
2404 /* Since the BSD tty driver does not allow us to change the tty modes
2405 while simultaneously waiting for output to drain and preserving
2406 typeahead, we have to drain the output ourselves before calling
2407 ioctl. We cheat by finding the length of the output queue, and
2408 using select to wait for an appropriate length of time. This is
2409 a hack, and should be labeled as such (it's a hastily-adapted
2410 mutation of a `usleep' implementation). It's only reason for
2411 existing is the flaw in the BSD tty driver. */
2412
2413 static int ttspeeds[] =
2414 {
2415 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
2416 1800, 2400, 4800, 9600, 19200, 38400
2417 };
2418
2419 static void
2420 draino (int fd, int ospeed)
2421 {
2422 register int delay = ttspeeds[ospeed];
2423 int n;
2424
2425 if (!delay)
2426 return;
2427
2428 while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
2429 {
2430 if (n > (delay / 100))
2431 {
2432 struct timeval tv;
2433
2434 n *= 10; /* 2 bits more for conservativeness. */
2435 tv.tv_sec = n / delay;
2436 tv.tv_usec = ((n % delay) * 1000000) / delay;
2437 select (fd, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv);
2438 }
2439 else
2440 break;
2441 }
2442 }
2443 #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
2444
2445 /* Return the fd from which we are actually getting input. */
2446 #define input_tty() (shell_tty != -1) ? shell_tty : fileno (stderr)
2447
2448 /* Fill the contents of shell_tty_info with the current tty info. */
2449 int
2450 get_tty_state (void)
2451 {
2452 int tty;
2453
2454 tty = input_tty ();
2455 if (tty != -1)
2456 {
2457 #if defined (NEW_TTY_DRIVER)
2458 ioctl (tty, TIOCGETP, &shell_tty_info);
2459 ioctl (tty, TIOCGETC, &shell_tchars);
2460 ioctl (tty, TIOCGLTC, &shell_ltchars);
2461 #endif /* NEW_TTY_DRIVER */
2462
2463 #if defined (TERMIO_TTY_DRIVER)
2464 ioctl (tty, TCGETA, &shell_tty_info);
2465 #endif /* TERMIO_TTY_DRIVER */
2466
2467 #if defined (TERMIOS_TTY_DRIVER)
2468 if (tcgetattr (tty, &shell_tty_info) < 0)
2469 {
2470 #if 0
2471 /* Only print an error message if we're really interactive at
2472 this time. */
2473 if (interactive)
2474 sys_error ("[%ld: %d (%d)] tcgetattr", (long)getpid (), shell_level, tty);
2475 #endif
2476 return -1;
2477 }
2478 #endif /* TERMIOS_TTY_DRIVER */
2479 if (check_window_size)
2480 get_new_window_size (0, (int *)0, (int *)0);
2481 }
2482 return 0;
2483 }
2484
2485 /* Make the current tty use the state in shell_tty_info. */
2486 int
2487 set_tty_state (void)
2488 {
2489 int tty;
2490
2491 tty = input_tty ();
2492 if (tty != -1)
2493 {
2494 #if defined (NEW_TTY_DRIVER)
2495 # if defined (DRAIN_OUTPUT)
2496 draino (tty, shell_tty_info.sg_ospeed);
2497 # endif /* DRAIN_OUTPUT */
2498 ioctl (tty, TIOCSETN, &shell_tty_info);
2499 ioctl (tty, TIOCSETC, &shell_tchars);
2500 ioctl (tty, TIOCSLTC, &shell_ltchars);
2501 #endif /* NEW_TTY_DRIVER */
2502
2503 #if defined (TERMIO_TTY_DRIVER)
2504 ioctl (tty, TCSETAW, &shell_tty_info);
2505 #endif /* TERMIO_TTY_DRIVER */
2506
2507 #if defined (TERMIOS_TTY_DRIVER)
2508 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
2509 {
2510 /* Only print an error message if we're really interactive at
2511 this time. */
2512 if (interactive)
2513 sys_error ("[%ld: %d (%d)] tcsetattr", (long)getpid (), shell_level, tty);
2514 return -1;
2515 }
2516 #endif /* TERMIOS_TTY_DRIVER */
2517 }
2518 return 0;
2519 }
2520
2521 /* Given an index into the jobs array JOB, return the PROCESS struct of the last
2522 process in that job's pipeline. This is the one whose exit status
2523 counts. Must be called with SIGCHLD blocked or queued. */
2524 static PROCESS *
2525 find_last_proc (int job, int block)
2526 {
2527 register PROCESS *p;
2528 sigset_t set, oset;
2529
2530 if (block)
2531 BLOCK_CHILD (set, oset);
2532
2533 p = jobs[job]->pipe;
2534 while (p && p->next != jobs[job]->pipe)
2535 p = p->next;
2536
2537 if (block)
2538 UNBLOCK_CHILD (oset);
2539
2540 return (p);
2541 }
2542
2543 static pid_t
2544 find_last_pid (int job, int block)
2545 {
2546 PROCESS *p;
2547
2548 p = find_last_proc (job, block);
2549 /* Possible race condition here. */
2550 return p->pid;
2551 }
2552
2553 /* Wait for a particular child of the shell to finish executing.
2554 This low-level function prints an error message if PID is not
2555 a child of this shell. It returns -1 if it fails, or whatever
2556 wait_for returns otherwise. If the child is not found in the
2557 jobs table, it returns 127. If FLAGS doesn't include JWAIT_PERROR,
2558 we suppress the error message if PID isn't found. */
2559
2560 int
2561 wait_for_single_pid (pid_t pid, int flags)
2562 {
2563 register PROCESS *child;
2564 sigset_t set, oset;
2565 int r, job, alive;
2566
2567 BLOCK_CHILD (set, oset);
2568 child = find_pipeline (pid, 0, (int *)NULL);
2569 UNBLOCK_CHILD (oset);
2570
2571 if (child == 0)
2572 {
2573 r = bgp_search (pid);
2574 if (r >= 0)
2575 return r;
2576 }
2577
2578 if (child == 0)
2579 {
2580 if (flags & JWAIT_PERROR)
2581 internal_error (_("wait: pid %ld is not a child of this shell"), (long)pid);
2582 return (257);
2583 }
2584
2585 alive = 0;
2586 do
2587 {
2588 r = wait_for (pid, 0);
2589 if ((flags & JWAIT_FORCE) == 0)
2590 break;
2591
2592 BLOCK_CHILD (set, oset);
2593 alive = PALIVE (child);
2594 UNBLOCK_CHILD (oset);
2595 }
2596 while (alive);
2597
2598 /* POSIX.2: if we just waited for a job, we can remove it from the jobs
2599 table. */
2600 BLOCK_CHILD (set, oset);
2601 job = find_job (pid, 0, NULL);
2602 if (job != NO_JOB && jobs[job] && DEADJOB (job))
2603 jobs[job]->flags |= J_NOTIFIED;
2604 UNBLOCK_CHILD (oset);
2605
2606 /* If running in posix mode, remove the job from the jobs table immediately */
2607 if (posixly_correct)
2608 {
2609 cleanup_dead_jobs ();
2610 bgp_delete (pid);
2611 }
2612
2613 /* Check for a trapped signal interrupting the wait builtin and jump out */
2614 CHECK_WAIT_INTR;
2615
2616 return r;
2617 }
2618
2619 /* Wait for all of the background processes started by this shell to finish. */
2620 int
2621 wait_for_background_pids (struct procstat *ps)
2622 {
2623 register int i, r;
2624 int any_stopped, check_async, njobs;
2625 sigset_t set, oset;
2626 pid_t pid;
2627
2628 for (njobs = any_stopped = 0, check_async = 1;;)
2629 {
2630 BLOCK_CHILD (set, oset);
2631
2632 /* find first running job; if none running in foreground, break */
2633 /* XXX could use js.j_firstj and js.j_lastj here */
2634 for (i = 0; i < js.j_jobslots; i++)
2635 {
2636 if (i < js.j_firstj && jobs[i])
2637 INTERNAL_DEBUG (("wait_for_background_pids: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
2638 if (i > js.j_lastj && jobs[i])
2639 INTERNAL_DEBUG (("wait_for_background_pids: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
2640
2641 if (jobs[i] && STOPPED (i))
2642 {
2643 builtin_warning ("job %d[%d] stopped", i+1, find_last_pid (i, 0));
2644 any_stopped = 1;
2645 }
2646
2647 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
2648 break;
2649 }
2650 if (i == js.j_jobslots)
2651 {
2652 UNBLOCK_CHILD (oset);
2653 break;
2654 }
2655
2656 /* now wait for the last pid in that job. */
2657 pid = find_last_pid (i, 0);
2658 UNBLOCK_CHILD (oset);
2659 QUIT;
2660 errno = 0; /* XXX */
2661 r = wait_for_single_pid (pid, JWAIT_PERROR);
2662 if (ps)
2663 {
2664 ps->pid = pid;
2665 ps->status = (r < 0 || r > 256) ? 127 : r;
2666 }
2667 if (r == -1 && errno == ECHILD)
2668 {
2669 /* If we're mistaken about job state, compensate. */
2670 check_async = 0;
2671 mark_all_jobs_as_dead ();
2672 }
2673 njobs++;
2674 }
2675
2676 #if defined (PROCESS_SUBSTITUTION)
2677 if (last_procsub_child && last_procsub_child->pid != NO_PID && last_procsub_child->pid == last_asynchronous_pid)
2678 procsub_waitpid (last_procsub_child->pid);
2679 reap_procsubs (); /* closes fd */
2680 #endif
2681
2682 /* POSIX.2 says the shell can discard the statuses of all completed jobs if
2683 `wait' is called with no arguments. */
2684 mark_dead_jobs_as_notified (1);
2685 cleanup_dead_jobs (); /* calls procsub_prune */
2686 bgp_clear ();
2687
2688 return njobs;
2689 }
2690
2691 /* Make OLD_SIGINT_HANDLER the SIGINT signal handler. */
2692 #define INVALID_SIGNAL_HANDLER (SigHandler *)wait_for_background_pids
2693 static SigHandler *old_sigint_handler = INVALID_SIGNAL_HANDLER;
2694
2695 /* The current SIGINT handler as set by restore_sigint_handler. Only valid
2696 immediately after restore_sigint_handler, used for continuations. */
2697 static SigHandler *cur_sigint_handler = INVALID_SIGNAL_HANDLER;
2698
2699 static int wait_sigint_received;
2700 static int child_caught_sigint;
2701
2702 int waiting_for_child;
2703
2704 /* Clean up state after longjmp to wait_intr_buf */
2705 void
2706 wait_sigint_cleanup (void)
2707 {
2708 queue_sigchld = 0;
2709 waiting_for_child = 0;
2710 restore_sigint_handler ();
2711 }
2712
2713 static void
2714 restore_sigint_handler (void)
2715 {
2716 cur_sigint_handler = old_sigint_handler;
2717 if (old_sigint_handler != INVALID_SIGNAL_HANDLER)
2718 {
2719 set_signal_handler (SIGINT, old_sigint_handler);
2720 old_sigint_handler = INVALID_SIGNAL_HANDLER;
2721 waiting_for_child = 0;
2722 }
2723 }
2724
2725 /* Handle SIGINT while we are waiting for children in a script to exit.
2726 The `wait' builtin should be interruptible, but all others should be
2727 effectively ignored (i.e. not cause the shell to exit). */
2728 static sighandler
2729 wait_sigint_handler (int sig)
2730 {
2731 SigHandler *sigint_handler;
2732
2733 if (this_shell_builtin && this_shell_builtin == wait_builtin)
2734 {
2735 set_exit_status (128+SIGINT);
2736 restore_sigint_handler ();
2737 /* If we got a SIGINT while in `wait', and SIGINT is trapped, do
2738 what POSIX.2 says (see builtins/wait.def for more info). */
2739 if (signal_is_trapped (SIGINT) &&
2740 ((sigint_handler = trap_to_sighandler (SIGINT)) == trap_handler))
2741 {
2742 trap_handler (SIGINT); /* set pending_traps[SIGINT] */
2743 wait_signal_received = SIGINT;
2744 if (wait_intr_flag)
2745 sh_longjmp (wait_intr_buf, 1);
2746 else
2747 /* Let CHECK_WAIT_INTR handle it in wait_for/waitchld */
2748 SIGRETURN (0);
2749 }
2750 else /* wait_builtin but signal not trapped, treat as interrupt */
2751 kill (getpid (), SIGINT);
2752 }
2753
2754 /* XXX - should this be interrupt_state? If it is, the shell will act
2755 as if it got the SIGINT interrupt. */
2756 if (waiting_for_child)
2757 wait_sigint_received = 1;
2758 else
2759 {
2760 set_exit_status (128+SIGINT);
2761 restore_sigint_handler ();
2762 if (cur_sigint_handler == INVALID_SIGNAL_HANDLER)
2763 set_sigint_handler (); /* XXX - only do this in one place */
2764 kill (getpid (), SIGINT);
2765 }
2766
2767 /* Otherwise effectively ignore the SIGINT and allow the running job to
2768 be killed. */
2769 SIGRETURN (0);
2770 }
2771
2772 static int
2773 process_exit_signal (WAIT status)
2774 {
2775 return (WIFSIGNALED (status) ? WTERMSIG (status) : 0);
2776 }
2777
2778 static int
2779 process_exit_status (WAIT status)
2780 {
2781 if (WIFSIGNALED (status))
2782 return (128 + WTERMSIG (status));
2783 else if (WIFSTOPPED (status) == 0)
2784 return (WEXITSTATUS (status));
2785 else
2786 return (EXECUTION_SUCCESS);
2787 }
2788
2789 static WAIT
2790 job_signal_status (int job)
2791 {
2792 register PROCESS *p;
2793 WAIT s;
2794
2795 p = jobs[job]->pipe;
2796 do
2797 {
2798 s = p->status;
2799 if (WIFSIGNALED(s) || WIFSTOPPED(s))
2800 break;
2801 p = p->next;
2802 }
2803 while (p != jobs[job]->pipe);
2804
2805 return s;
2806 }
2807
2808 /* Return the exit status of the last process in the pipeline for job JOB.
2809 This is the exit status of the entire job. */
2810 static WAIT
2811 raw_job_exit_status (int job)
2812 {
2813 register PROCESS *p;
2814 int fail;
2815 WAIT ret;
2816
2817 if (jobs[job]->flags & J_PIPEFAIL)
2818 {
2819 fail = 0;
2820 p = jobs[job]->pipe;
2821 do
2822 {
2823 if (WSTATUS (p->status) != EXECUTION_SUCCESS)
2824 fail = WSTATUS(p->status);
2825 p = p->next;
2826 }
2827 while (p != jobs[job]->pipe);
2828 WSTATUS (ret) = fail;
2829 return ret;
2830 }
2831
2832 for (p = jobs[job]->pipe; p->next != jobs[job]->pipe; p = p->next)
2833 ;
2834 return (p->status);
2835 }
2836
2837 /* Return the exit status of job JOB. This is the exit status of the last
2838 (rightmost) process in the job's pipeline, modified if the job was killed
2839 by a signal or stopped. */
2840 int
2841 job_exit_status (int job)
2842 {
2843 return (process_exit_status (raw_job_exit_status (job)));
2844 }
2845
2846 int
2847 job_exit_signal (int job)
2848 {
2849 return (process_exit_signal (raw_job_exit_status (job)));
2850 }
2851
2852 static int
2853 job_killed_by_signal (int job)
2854 {
2855 int termsig;
2856
2857 termsig = job_exit_signal (job);
2858 #if !defined (DONT_REPORT_SIGPIPE)
2859 return (termsig && termsig != SIGINT);
2860 #else
2861 return (termsig && termsig != SIGINT && termsig != SIGPIPE);
2862 #endif
2863 }
2864
2865 #define FIND_CHILD(pid, child) \
2866 do \
2867 { \
2868 child = find_pipeline (pid, 0, (int *)NULL); \
2869 if (child == 0) \
2870 { \
2871 give_terminal_to (shell_pgrp, 0); \
2872 UNBLOCK_CHILD (oset); \
2873 internal_error (_("wait_for: No record of process %ld"), (long)pid); \
2874 restore_sigint_handler (); \
2875 return (termination_state = 127); \
2876 } \
2877 } \
2878 while (0)
2879
2880 /* Wait for pid (one of our children) to terminate, then
2881 return the termination state. Returns 127 if PID is not found in
2882 the jobs table. Returns -1 if waitchld() returns -1, indicating
2883 that there are no unwaited-for child processes. */
2884 int
2885 wait_for (pid_t pid, int flags)
2886 {
2887 int job, termination_state, r;
2888 WAIT s;
2889 register PROCESS *child;
2890 sigset_t set, oset;
2891
2892 /* In the case that this code is interrupted, and we longjmp () out of it,
2893 we are relying on the code in throw_to_top_level () to restore the
2894 top-level signal mask. */
2895 child = 0;
2896 BLOCK_CHILD (set, oset);
2897
2898 /* Ignore interrupts while waiting for a job run without job control
2899 to finish. We don't want the shell to exit if an interrupt is
2900 received, only if one of the jobs run is killed via SIGINT. If
2901 job control is not set, the job will be run in the same pgrp as
2902 the shell, and the shell will see any signals the job gets. In
2903 fact, we want this set every time the waiting shell and the waited-
2904 for process are in the same process group, including command
2905 substitution. */
2906
2907 /* This is possibly a race condition -- should it go in stop_pipeline? */
2908 wait_sigint_received = child_caught_sigint = 0;
2909 if (job_control == 0 || (subshell_environment&SUBSHELL_COMSUB))
2910 {
2911 SigHandler *temp_sigint_handler;
2912
2913 temp_sigint_handler = old_sigint_handler;
2914 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
2915 if (old_sigint_handler == wait_sigint_handler)
2916 {
2917 internal_debug ("wait_for: recursively setting old_sigint_handler to wait_sigint_handler: running_trap = %d", running_trap);
2918 old_sigint_handler = temp_sigint_handler;
2919 }
2920 waiting_for_child = 0;
2921 if (old_sigint_handler == SIG_IGN)
2922 set_signal_handler (SIGINT, old_sigint_handler);
2923 }
2924
2925 termination_state = last_command_exit_value;
2926
2927 if (interactive && job_control == 0)
2928 QUIT;
2929 /* Check for terminating signals and exit the shell if we receive one */
2930 CHECK_TERMSIG;
2931
2932 /* Check for a trapped signal interrupting the wait builtin and jump out */
2933 CHECK_WAIT_INTR;
2934
2935 /* If we say wait_for (), then we have a record of this child somewhere.
2936 If it and none of its peers are running, don't call waitchld(). */
2937
2938 job = NO_JOB;
2939 do
2940 {
2941 if (pid != ANY_PID)
2942 FIND_CHILD (pid, child);
2943
2944 /* If this child is part of a job, then we are really waiting for the
2945 job to finish. Otherwise, we are waiting for the child to finish.
2946 We check for JDEAD in case the job state has been set by waitchld
2947 after receipt of a SIGCHLD. */
2948 if (job == NO_JOB && pid != ANY_PID) /* XXX -- && pid != ANY_PID ? */
2949 job = find_job (pid, 0, NULL);
2950
2951 /* waitchld() takes care of setting the state of the job. If the job
2952 has already exited before this is called, sigchld_handler will have
2953 called waitchld and the state will be set to JDEAD. */
2954
2955 if (pid == ANY_PID || PRUNNING(child) || (job != NO_JOB && RUNNING (job)))
2956 {
2957 int old_waiting;
2958
2959 queue_sigchld = 1;
2960 old_waiting = waiting_for_child;
2961 waiting_for_child = 1;
2962 /* XXX - probably not strictly necessary but we want to catch
2963 everything that happened before we switch the behavior of
2964 trap_handler to longjmp on a trapped signal (waiting_for_child) */
2965 CHECK_WAIT_INTR;
2966 r = waitchld (pid, 1); /* XXX */
2967 waiting_for_child = old_waiting;
2968 #if 0
2969 itrace("wait_for: blocking wait for %d returns %d child = %p", (int)pid, r, child);
2970 #endif
2971 queue_sigchld = 0;
2972 if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
2973 {
2974 termination_state = -1;
2975 /* XXX - restore sigint handler here */
2976 restore_sigint_handler ();
2977 goto wait_for_return;
2978 }
2979
2980 /* If child is marked as running, but waitpid() returns -1/ECHILD,
2981 there is something wrong. Somewhere, wait should have returned
2982 that child's pid. Mark the child as not running and the job,
2983 if it exists, as JDEAD. */
2984 if (r == -1 && errno == ECHILD)
2985 {
2986 if (child)
2987 {
2988 child->running = PS_DONE;
2989 WSTATUS (child->status) = 0; /* XXX -- can't find true status */
2990 }
2991 js.c_living = 0; /* no living child processes */
2992 if (job != NO_JOB)
2993 {
2994 jobs[job]->state = JDEAD;
2995 js.c_reaped++;
2996 js.j_ndead++;
2997 }
2998 if (pid == ANY_PID)
2999 {
3000 termination_state = -1;
3001 break;
3002 }
3003 }
3004 }
3005
3006 /* If the shell is interactive, and job control is disabled, see
3007 if the foreground process has died due to SIGINT and jump out
3008 of the wait loop if it has. waitchld has already restored the
3009 old SIGINT signal handler. */
3010 if (interactive && job_control == 0)
3011 QUIT;
3012 /* Check for terminating signals and exit the shell if we receive one */
3013 CHECK_TERMSIG;
3014
3015 /* Check for a trapped signal interrupting the wait builtin and jump out */
3016 CHECK_WAIT_INTR;
3017
3018 if (pid == ANY_PID)
3019 {
3020 /* XXX - could set child but we don't have a handle on what waitchld
3021 reaps. Leave termination_state alone. */
3022 restore_sigint_handler ();
3023 goto wait_for_return;
3024 }
3025 }
3026 while (PRUNNING (child) || (job != NO_JOB && RUNNING (job)));
3027
3028 /* Restore the original SIGINT signal handler before we return. */
3029 restore_sigint_handler ();
3030
3031 /* The exit state of the command is either the termination state of the
3032 child, or the termination state of the job. If a job, the status
3033 of the last child in the pipeline is the significant one. If the command
3034 or job was terminated by a signal, note that value also. */
3035 termination_state = (job != NO_JOB) ? job_exit_status (job)
3036 : (child ? process_exit_status (child->status) : EXECUTION_SUCCESS);
3037 last_command_exit_signal = (job != NO_JOB) ? job_exit_signal (job)
3038 : (child ? process_exit_signal (child->status) : 0);
3039
3040 /* XXX */
3041 if ((job != NO_JOB && JOBSTATE (job) == JSTOPPED) || (child && WIFSTOPPED (child->status)))
3042 termination_state = 128 + WSTOPSIG (child->status);
3043
3044 if (job == NO_JOB || IS_JOBCONTROL (job))
3045 {
3046 /* XXX - under what circumstances is a job not present in the jobs
3047 table (job == NO_JOB)?
3048 1. command substitution
3049
3050 In the case of command substitution, at least, it's probably not
3051 the right thing to give the terminal to the shell's process group,
3052 even though there is code in subst.c:command_substitute to work
3053 around it.
3054
3055 Things that don't:
3056 $PROMPT_COMMAND execution
3057 process substitution
3058 */
3059 #if 0
3060 if (job == NO_JOB)
3061 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp);
3062 #endif
3063 /* Don't modify terminal pgrp if we are running in background or a
3064 subshell. Make sure subst.c:command_substitute uses the same
3065 conditions to determine whether or not it should undo this and
3066 give the terminal to pipeline_pgrp. We don't give the terminal
3067 back to shell_pgrp if an async job in the background exits because
3068 we never gave it to that job in the first place. An async job in
3069 the foreground is one we started in the background and foregrounded
3070 with `fg', and gave it the terminal. */
3071 if ((flags & JWAIT_NOTERM) == 0 && running_in_background == 0 &&
3072 (job == NO_JOB || IS_ASYNC (job) == 0 || IS_FOREGROUND (job)) &&
3073 (subshell_environment & (SUBSHELL_ASYNC|SUBSHELL_PIPE)) == 0)
3074 give_terminal_to (shell_pgrp, 0);
3075 }
3076
3077 /* If the command did not exit cleanly, or the job is just
3078 being stopped, then reset the tty state back to what it
3079 was before this command. Reset the tty state and notify
3080 the user of the job termination only if the shell is
3081 interactive. Clean up any dead jobs in either case. */
3082 if (job != NO_JOB)
3083 {
3084 if (interactive_shell && subshell_environment == 0)
3085 {
3086 /* This used to use `child->status'. That's wrong, however, for
3087 pipelines. `child' is the first process in the pipeline. It's
3088 likely that the process we want to check for abnormal termination
3089 or stopping is the last process in the pipeline, especially if
3090 it's long-lived and the first process is short-lived. Since we
3091 know we have a job here, we can check all the processes in this
3092 job's pipeline and see if one of them stopped or terminated due
3093 to a signal. We might want to change this later to just check
3094 the last process in the pipeline. If no process exits due to a
3095 signal, S is left as the status of the last job in the pipeline. */
3096 s = job_signal_status (job);
3097
3098 if (WIFSIGNALED (s) || WIFSTOPPED (s))
3099 {
3100 set_tty_state ();
3101
3102 /* If the current job was stopped or killed by a signal, and
3103 the user has requested it, get a possibly new window size */
3104 if (check_window_size && (job == js.j_current || IS_FOREGROUND (job)))
3105 get_new_window_size (0, (int *)0, (int *)0);
3106 }
3107 else
3108 #if defined (READLINE)
3109 /* We don't want to get the entire tty state if we are running
3110 while readline is active or has changed the terminal, but we
3111 can handle window size changes during programmable completion,
3112 traps while readline is active, or a command bound using
3113 `bind -x'. */
3114 if (RL_ISSTATE(RL_STATE_COMPLETING|RL_STATE_DISPATCHING|RL_STATE_TERMPREPPED) != 0)
3115 {
3116 if (check_window_size)
3117 get_new_window_size (0, (int *)0, (int *)0);
3118 }
3119 else
3120 #endif
3121 get_tty_state ();
3122
3123 /* If job control is enabled, the job was started with job
3124 control, the job was the foreground job, and it was killed
3125 by SIGINT, then print a newline to compensate for the kernel
3126 printing the ^C without a trailing newline. */
3127 if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
3128 WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
3129 {
3130 /* If SIGINT is not trapped and the shell is in a for, while,
3131 until, or arithmetic for loop, or is executing a compound list,
3132 act as if the shell received SIGINT as well, so the loop or
3133 list can be broken. This doesn't call the SIGINT signal
3134 handler; maybe it should. */
3135 if (signal_is_trapped (SIGINT) == 0 && interrupt_execution)
3136 ADDINTERRUPT;
3137 /* Call any SIGINT trap handler if the shell is running a loop, so
3138 the loop can be broken. This seems more useful and matches the
3139 behavior when the shell is running a builtin command in a loop
3140 when it is interrupted. Change ADDINTERRUPT to
3141 trap_handler (SIGINT) to run the trap without interrupting the
3142 loop. */
3143 else if (signal_is_trapped (SIGINT) && loop_level)
3144 ADDINTERRUPT;
3145 /* If an interactive shell with job control enabled is sourcing
3146 a file, allow the interrupt to terminate the file sourcing. */
3147 else if (interactive_shell && signal_is_trapped (SIGINT) == 0 && sourcelevel)
3148 ADDINTERRUPT;
3149 else
3150 {
3151 putchar ('\n');
3152 fflush (stdout);
3153 }
3154 }
3155 }
3156 else if ((subshell_environment & (SUBSHELL_COMSUB|SUBSHELL_PIPE)) && wait_sigint_received)
3157 {
3158 /* If waiting for a job in a subshell started to do command
3159 substitution or to run a pipeline element that consists of
3160 something like a while loop or a for loop, simulate getting
3161 and being killed by the SIGINT to pass the status back to our
3162 parent. */
3163 if (child_caught_sigint == 0 && signal_is_trapped (SIGINT) == 0)
3164 {
3165 UNBLOCK_CHILD (oset);
3166 old_sigint_handler = set_signal_handler (SIGINT, SIG_DFL);
3167 if (old_sigint_handler == SIG_IGN)
3168 restore_sigint_handler ();
3169 else
3170 kill (getpid (), SIGINT);
3171 }
3172 }
3173 else if (interactive_shell == 0 && subshell_environment == 0 && IS_FOREGROUND (job))
3174 {
3175 s = job_signal_status (job);
3176
3177 /* If we are non-interactive, but job control is enabled, and the job
3178 died due to SIGINT, pretend we got the SIGINT */
3179 if (job_control && IS_JOBCONTROL (job) && WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
3180 {
3181 ADDINTERRUPT; /* For now */
3182 }
3183
3184 if (check_window_size)
3185 get_new_window_size (0, (int *)0, (int *)0);
3186 }
3187 else if (interactive_shell && interactive == 0 && check_window_size &&
3188 (subshell_environment & (SUBSHELL_PAREN|SUBSHELL_ASYNC)) == SUBSHELL_PAREN &&
3189 IS_FOREGROUND (job))
3190 /* Make checkwinsize work in foreground subshells started from
3191 interactive shells. */
3192 get_new_window_size (0, (int *)0, (int *)0);
3193
3194 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
3195 signal handler path */
3196 if (DEADJOB (job) && IS_FOREGROUND (job) /*&& subshell_environment == 0*/)
3197 setjstatus (job);
3198
3199 /* If this job is dead, notify the user of the status. If the shell
3200 is interactive, this will display a message on the terminal. If
3201 the shell is not interactive, make sure we turn on the notify bit
3202 so we don't get an unwanted message about the job's termination,
3203 and so delete_job really clears the slot in the jobs table. */
3204 notify_and_cleanup ();
3205 }
3206
3207 wait_for_return:
3208
3209 UNBLOCK_CHILD (oset);
3210
3211 return (termination_state);
3212 }
3213
3214 /* Wait for the last process in the pipeline for JOB. Returns whatever
3215 wait_for returns: the last process's termination state or -1 if there
3216 are no unwaited-for child processes or an error occurs. If FLAGS
3217 includes JWAIT_FORCE, we wait for the job to terminate, no just change
3218 state */
3219 int
3220 wait_for_job (int job, int flags, struct procstat *ps)
3221 {
3222 pid_t pid;
3223 int r, state;
3224 sigset_t set, oset;
3225
3226 BLOCK_CHILD(set, oset);
3227 state = JOBSTATE (job);
3228 if (state == JSTOPPED)
3229 internal_warning (_("wait_for_job: job %d is stopped"), job+1);
3230
3231 pid = find_last_pid (job, 0);
3232 UNBLOCK_CHILD(oset);
3233
3234 do
3235 {
3236 r = wait_for (pid, 0);
3237 if (r == -1 && errno == ECHILD)
3238 mark_all_jobs_as_dead ();
3239
3240 CHECK_WAIT_INTR;
3241
3242 if ((flags & JWAIT_FORCE) == 0)
3243 break;
3244
3245 BLOCK_CHILD (set, oset);
3246 state = (job != NO_JOB && jobs[job]) ? JOBSTATE (job) : JDEAD;
3247 UNBLOCK_CHILD (oset);
3248 }
3249 while (state != JDEAD);
3250
3251 /* POSIX.2: we can remove the job from the jobs table if we just waited
3252 for it. */
3253 BLOCK_CHILD (set, oset);
3254 if (job != NO_JOB && jobs[job] && DEADJOB (job))
3255 jobs[job]->flags |= J_NOTIFIED;
3256 UNBLOCK_CHILD (oset);
3257
3258 if (ps)
3259 {
3260 ps->pid = pid;
3261 ps->status = (r < 0) ? 127 : r;
3262 }
3263 return r;
3264 }
3265
3266 /* Wait for any background job started by this shell to finish. Very
3267 similar to wait_for_background_pids(). Returns the exit status of
3268 the next exiting job, -1 if there are no background jobs. The caller
3269 is responsible for translating -1 into the right return value. RPID,
3270 if non-null, gets the pid of the job's process leader. */
3271 int
3272 wait_for_any_job (int flags, struct procstat *ps)
3273 {
3274 pid_t pid;
3275 int i, r;
3276 sigset_t set, oset;
3277
3278 /* Allow funsubs to run this, but don't remove jobs from the jobs table. */
3279 if (jobs_list_frozen && executing_funsub == 0)
3280 return -1;
3281
3282 /* First see if there are any unnotified dead jobs that we can report on */
3283 BLOCK_CHILD (set, oset);
3284 for (i = 0; i < js.j_jobslots; i++)
3285 {
3286 if ((flags & JWAIT_WAITING) && jobs[i] && IS_WAITING (i) == 0)
3287 continue; /* if we don't want it, skip it */
3288 if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i) == 0 && IS_FOREGROUND (i) == 0)
3289 {
3290 return_job:
3291 r = job_exit_status (i);
3292 pid = find_last_pid (i, 0);
3293 if (ps)
3294 {
3295 ps->pid = pid;
3296 ps->status = r;
3297 }
3298 if (jobs_list_frozen == 0) /* must be running a funsub to get here */
3299 {
3300 notify_of_job_status (); /* XXX */
3301 #if 1 /* TAG: bash-5.3 kre@munnari.oz.au 01/30/2024 */
3302 delete_job (i, posixly_correct ? DEL_NOBGPID : 0);
3303 #else
3304 delete_job (i, 0);
3305 #endif
3306 }
3307 else
3308 jobs[i]->flags |= J_NOTIFIED; /* clean up later */
3309 #if defined (COPROCESS_SUPPORT)
3310 coproc_reap ();
3311 #endif
3312 UNBLOCK_CHILD (oset);
3313 return r;
3314 }
3315 }
3316 UNBLOCK_CHILD (oset);
3317
3318 /* At this point, we have no dead jobs in the jobs table. Wait until we
3319 get one, even if it takes multiple pids exiting. */
3320 for (;;)
3321 {
3322 /* Make sure there is a background job to wait for */
3323 BLOCK_CHILD (set, oset);
3324 for (i = 0; i < js.j_jobslots; i++)
3325 {
3326 if (jobs[i] && RUNNING (i) && IS_FOREGROUND (i) == 0)
3327 break;
3328 /* It's possible for there to be a dead job that was reaped when
3329 SIGCHLD was unblocked before this loop started. */
3330 else if ((flags & JWAIT_WAITING) && jobs[i] && IS_WAITING (i) == 0)
3331 continue;
3332 else if (jobs[i] && DEADJOB (i) && IS_NOTIFIED (i) == 0 && IS_FOREGROUND (i) == 0)
3333 goto return_job;
3334 }
3335
3336 if (i == js.j_jobslots)
3337 {
3338 UNBLOCK_CHILD (oset);
3339 return -1;
3340 }
3341
3342 UNBLOCK_CHILD (oset);
3343
3344 QUIT;
3345 CHECK_TERMSIG;
3346 CHECK_WAIT_INTR;
3347
3348 errno = 0;
3349 r = wait_for (ANY_PID, 0); /* special sentinel value for wait_for */
3350 if (r == -1 && errno == ECHILD)
3351 mark_all_jobs_as_dead ();
3352
3353 /* Now we see if we have any dead jobs and return the first one */
3354 BLOCK_CHILD (set, oset);
3355 for (i = 0; i < js.j_jobslots; i++)
3356 {
3357 if ((flags & JWAIT_WAITING) && jobs[i] && IS_WAITING (i) == 0)
3358 continue; /* if we don't want it, skip it */
3359 if (jobs[i] && DEADJOB (i))
3360 goto return_job;
3361 }
3362 UNBLOCK_CHILD (oset);
3363 }
3364
3365 return -1;
3366 }
3367
3368 /* Print info about dead jobs, and then delete them from the list
3369 of known jobs. This does not actually delete jobs when the
3370 shell is not interactive, because the dead jobs are not marked
3371 as notified. */
3372 void
3373 notify_and_cleanup (void)
3374 {
3375 if (jobs_list_frozen)
3376 return;
3377
3378 if (interactive || interactive_shell == 0 || sourcelevel)
3379 notify_of_job_status ();
3380
3381 cleanup_dead_jobs ();
3382 }
3383
3384 /* Make dead jobs disappear from the jobs array without notification.
3385 This is used when the shell is not interactive. */
3386 void
3387 reap_dead_jobs (void)
3388 {
3389 mark_dead_jobs_as_notified (0);
3390 cleanup_dead_jobs ();
3391 }
3392
3393 /* Return the next closest (chronologically) job to JOB which is in
3394 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
3395 there is no next recent job. */
3396 static int
3397 most_recent_job_in_state (int job, JOB_STATE state)
3398 {
3399 register int i, result;
3400 sigset_t set, oset;
3401
3402 BLOCK_CHILD (set, oset);
3403
3404 for (result = NO_JOB, i = job - 1; i >= 0; i--)
3405 {
3406 if (jobs[i] && (JOBSTATE (i) == state))
3407 {
3408 result = i;
3409 break;
3410 }
3411 }
3412
3413 UNBLOCK_CHILD (oset);
3414
3415 return (result);
3416 }
3417
3418 /* Return the newest *stopped* job older than JOB, or NO_JOB if not
3419 found. */
3420 static int
3421 job_last_stopped (int job)
3422 {
3423 return (most_recent_job_in_state (job, JSTOPPED));
3424 }
3425
3426 /* Return the newest *running* job older than JOB, or NO_JOB if not
3427 found. */
3428 static int
3429 job_last_running (int job)
3430 {
3431 return (most_recent_job_in_state (job, JRUNNING));
3432 }
3433
3434 /* Make JOB be the current job, and make previous be useful. Must be
3435 called with SIGCHLD blocked. */
3436 static void
3437 set_current_job (int job)
3438 {
3439 int candidate;
3440
3441 if (js.j_current != job)
3442 {
3443 js.j_previous = js.j_current;
3444 js.j_current = job;
3445 }
3446
3447 /* First choice for previous job is the old current job. */
3448 if (js.j_previous != js.j_current &&
3449 js.j_previous != NO_JOB &&
3450 jobs[js.j_previous] &&
3451 STOPPED (js.j_previous))
3452 return;
3453
3454 /* Second choice: Newest stopped job that is older than
3455 the current job. */
3456 candidate = NO_JOB;
3457 if (STOPPED (js.j_current))
3458 {
3459 candidate = job_last_stopped (js.j_current);
3460
3461 if (candidate != NO_JOB)
3462 {
3463 js.j_previous = candidate;
3464 return;
3465 }
3466 }
3467
3468 /* If we get here, there is either only one stopped job, in which case it is
3469 the current job and the previous job should be set to the newest running
3470 job, or there are only running jobs and the previous job should be set to
3471 the newest running job older than the current job. We decide on which
3472 alternative to use based on whether or not JOBSTATE(js.j_current) is
3473 JSTOPPED. */
3474
3475 candidate = RUNNING (js.j_current) ? job_last_running (js.j_current)
3476 : job_last_running (js.j_jobslots);
3477
3478 if (candidate != NO_JOB)
3479 {
3480 js.j_previous = candidate;
3481 return;
3482 }
3483
3484 /* There is only a single job, and it is both `+' and `-'. */
3485 js.j_previous = js.j_current;
3486 }
3487
3488 /* Make current_job be something useful, if it isn't already. */
3489
3490 /* Here's the deal: The newest non-running job should be `+', and the
3491 next-newest non-running job should be `-'. If there is only a single
3492 stopped job, the js.j_previous is the newest non-running job. If there
3493 are only running jobs, the newest running job is `+' and the
3494 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
3495
3496 static void
3497 reset_current (void)
3498 {
3499 int candidate;
3500
3501 if (js.j_jobslots && js.j_current != NO_JOB && jobs[js.j_current] && STOPPED (js.j_current))
3502 candidate = js.j_current;
3503 else
3504 {
3505 candidate = NO_JOB;
3506
3507 /* First choice: the previous job. */
3508 if (js.j_previous != NO_JOB && jobs[js.j_previous] && STOPPED (js.j_previous))
3509 candidate = js.j_previous;
3510
3511 /* Second choice: the most recently stopped job. */
3512 if (candidate == NO_JOB)
3513 candidate = job_last_stopped (js.j_jobslots);
3514
3515 /* Third choice: the newest running job. */
3516 if (candidate == NO_JOB)
3517 candidate = job_last_running (js.j_jobslots);
3518 }
3519
3520 /* If we found a job to use, then use it. Otherwise, there
3521 are no jobs period. */
3522 if (candidate != NO_JOB)
3523 set_current_job (candidate);
3524 else
3525 js.j_current = js.j_previous = NO_JOB;
3526 }
3527
3528 /* Set up the job structures so we know the job and its processes are
3529 all running. */
3530 static void
3531 set_job_running (int job)
3532 {
3533 register PROCESS *p;
3534
3535 /* Each member of the pipeline is now running. */
3536 p = jobs[job]->pipe;
3537
3538 do
3539 {
3540 if (WIFSTOPPED (p->status))
3541 p->running = PS_RUNNING; /* XXX - could be PS_STOPPED */
3542 p = p->next;
3543 }
3544 while (p != jobs[job]->pipe);
3545
3546 /* This means that the job is running. */
3547 JOBSTATE (job) = JRUNNING;
3548 }
3549
3550 /* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
3551 start the job in the background. JOB is a zero-based index into
3552 JOBS. Returns -1 if it is unable to start a job, and the return
3553 status of the job otherwise. */
3554 int
3555 start_job (int job, int foreground)
3556 {
3557 register PROCESS *p;
3558 int already_running;
3559 sigset_t set, oset;
3560 char *wd, *s;
3561 static TTYSTRUCT save_stty;
3562
3563 BLOCK_CHILD (set, oset);
3564
3565 if ((subshell_environment & SUBSHELL_COMSUB) && (pipeline_pgrp == shell_pgrp))
3566 {
3567 internal_error (_("%s: no current jobs"), this_command_name);
3568 UNBLOCK_CHILD (oset);
3569 return (-1);
3570 }
3571
3572 if (DEADJOB (job))
3573 {
3574 internal_error (_("%s: job has terminated"), this_command_name);
3575 UNBLOCK_CHILD (oset);
3576 return (-1);
3577 }
3578
3579 already_running = RUNNING (job);
3580
3581 if (foreground == 0 && already_running)
3582 {
3583 internal_error (_("%s: job %d already in background"), this_command_name, job + 1);
3584 UNBLOCK_CHILD (oset);
3585 return (0); /* XPG6/SUSv3 says this is not an error */
3586 }
3587
3588 wd = current_working_directory ();
3589
3590 /* You don't know about the state of this job. Do you? */
3591 jobs[job]->flags &= ~J_NOTIFIED;
3592
3593 if (foreground)
3594 {
3595 set_current_job (job);
3596 jobs[job]->flags |= J_FOREGROUND;
3597 }
3598
3599 /* Tell the outside world what we're doing. */
3600 p = jobs[job]->pipe;
3601
3602 if (foreground == 0)
3603 {
3604 /* POSIX.2 says `bg' doesn't give any indication about current or
3605 previous job. */
3606 if (posixly_correct == 0)
3607 s = (job == js.j_current) ? "+ ": ((job == js.j_previous) ? "- " : " ");
3608 else
3609 s = " ";
3610 printf ("[%d]%s", job + 1, s);
3611 }
3612
3613 do
3614 {
3615 printf ("%s%s",
3616 p->command ? p->command : "",
3617 p->next != jobs[job]->pipe? " | " : "");
3618 p = p->next;
3619 }
3620 while (p != jobs[job]->pipe);
3621
3622 if (foreground == 0)
3623 printf (" &");
3624
3625 if (strcmp (wd, jobs[job]->wd) != 0)
3626 printf (" (wd: %s)", polite_directory_format (jobs[job]->wd));
3627
3628 printf ("\n");
3629
3630 /* Run the job. */
3631 if (already_running == 0)
3632 jobs[job]->flags |= J_NOTIFIED;
3633
3634 /* Save the tty settings before we start the job in the foreground. */
3635 if (foreground)
3636 {
3637 get_tty_state ();
3638 save_stty = shell_tty_info;
3639 jobs[job]->flags &= ~J_ASYNC; /* no longer async */
3640 /* Give the terminal to this job. */
3641 if (IS_JOBCONTROL (job))
3642 give_terminal_to (jobs[job]->pgrp, 0);
3643 }
3644 else
3645 {
3646 jobs[job]->flags &= ~J_FOREGROUND;
3647 jobs[job]->flags |= J_ASYNC; /* running in background now */
3648 }
3649
3650 /* Change job state to running only if the kill SIGCONT succeeds or if kill
3651 says the process has terminated so we clean it up later. */
3652 if (killpg (jobs[job]->pgrp, SIGCONT) >= 0 || errno == ESRCH)
3653 set_job_running (job);
3654
3655 if (foreground)
3656 {
3657 pid_t pid;
3658 int st;
3659
3660 pid = find_last_pid (job, 0);
3661 UNBLOCK_CHILD (oset);
3662 st = wait_for (pid, 0);
3663 shell_tty_info = save_stty;
3664 set_tty_state ();
3665 return (st);
3666 }
3667 else
3668 {
3669 reset_current ();
3670 UNBLOCK_CHILD (oset);
3671 return (0);
3672 }
3673 }
3674
3675 /* Give PID SIGNAL. This determines what job the pid belongs to (if any).
3676 If PID does belong to a job, and the job is stopped, then CONTinue the
3677 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
3678 then kill the process group associated with PID. */
3679 int
3680 kill_pid (pid_t pid, int sig, int group)
3681 {
3682 register PROCESS *p;
3683 int job, result, negative;
3684 sigset_t set, oset;
3685
3686 if (pid < -1)
3687 {
3688 pid = -pid;
3689 group = negative = 1;
3690 }
3691 else
3692 negative = 0;
3693
3694 result = EXECUTION_SUCCESS;
3695 if (group)
3696 {
3697 BLOCK_CHILD (set, oset);
3698 p = find_pipeline (pid, 0, &job);
3699
3700 if (job != NO_JOB)
3701 {
3702 jobs[job]->flags &= ~J_NOTIFIED;
3703
3704 /* Kill process in backquotes or one started without job control? */
3705
3706 /* If we're passed a pid < -1, just call killpg and see what happens */
3707 if (negative && jobs[job]->pgrp == shell_pgrp)
3708 result = killpg (pid, sig);
3709 /* If we're killing using job control notification, for example,
3710 without job control active, we have to do things ourselves. */
3711 else if (jobs[job]->pgrp == shell_pgrp) /* XXX - IS_JOBCONTROL(job) == 0? */
3712 {
3713 p = jobs[job]->pipe;
3714 do
3715 {
3716 if (PALIVE (p) == 0)
3717 continue; /* avoid pid recycling problem */
3718 kill (p->pid, sig);
3719 if (PEXITED (p) && (sig == SIGTERM || sig == SIGHUP))
3720 kill (p->pid, SIGCONT);
3721 p = p->next;
3722 }
3723 while (p != jobs[job]->pipe);
3724 }
3725 else
3726 {
3727 result = killpg (jobs[job]->pgrp, sig);
3728 if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
3729 killpg (jobs[job]->pgrp, SIGCONT);
3730 /* If we're continuing a stopped job via kill rather than bg or
3731 fg, emulate the `bg' behavior. */
3732 if (p && STOPPED (job) && (sig == SIGCONT))
3733 {
3734 set_job_running (job);
3735 jobs[job]->flags &= ~J_FOREGROUND;
3736 jobs[job]->flags |= J_NOTIFIED;
3737 }
3738 }
3739 }
3740 else
3741 result = killpg (pid, sig);
3742
3743 UNBLOCK_CHILD (oset);
3744 }
3745 else
3746 result = kill (pid, sig);
3747
3748 return (result);
3749 }
3750
3751 /* sigchld_handler () flushes at least one of the children that we are
3752 waiting for. It gets run when we have gotten a SIGCHLD signal. */
3753 static sighandler
3754 sigchld_handler (int sig)
3755 {
3756 int n, oerrno;
3757
3758 oerrno = errno;
3759 REINSTALL_SIGCHLD_HANDLER;
3760 sigchld++;
3761 n = 0;
3762 if (queue_sigchld == 0)
3763 n = waitchld (-1, 0);
3764 errno = oerrno;
3765 SIGRETURN (n);
3766 }
3767
3768 /* waitchld() reaps dead or stopped children. It's called by wait_for and
3769 sigchld_handler, and runs until there aren't any children terminating any
3770 more.
3771 If BLOCK is 1, this is to be a blocking wait for a single child, although
3772 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
3773 the number of children reaped, or -1 if there are no unwaited-for child
3774 processes. */
3775 static int
3776 waitchld (pid_t wpid, int block)
3777 {
3778 WAIT status;
3779 PROCESS *child;
3780 pid_t pid;
3781 int ind;
3782
3783 int call_set_current, last_stopped_job, job, children_exited, waitpid_flags;
3784 static int wcontinued = WCONTINUED; /* run-time fix for glibc problem */
3785
3786 call_set_current = children_exited = 0;
3787 last_stopped_job = NO_JOB;
3788
3789 do
3790 {
3791 /* We don't want to be notified about jobs stopping if job control
3792 is not active. XXX - was interactive_shell instead of job_control */
3793 waitpid_flags = (job_control && subshell_environment == 0)
3794 ? (WUNTRACED|wcontinued)
3795 : 0;
3796 if (sigchld || block == 0)
3797 waitpid_flags |= WNOHANG;
3798
3799 /* Check for terminating signals and exit the shell if we receive one */
3800 CHECK_TERMSIG;
3801 /* Check for a trapped signal interrupting the wait builtin and jump out */
3802 CHECK_WAIT_INTR;
3803
3804 if (block == 1 && queue_sigchld == 0 && (waitpid_flags & WNOHANG) == 0)
3805 {
3806 internal_warning (_("waitchld: turning on WNOHANG to avoid indefinite block"));
3807 waitpid_flags |= WNOHANG;
3808 }
3809
3810 pid = WAITPID (-1, &status, waitpid_flags);
3811
3812 #if 0
3813 if (wpid != -1 && block)
3814 itrace("waitchld: blocking waitpid returns %d", pid);
3815 #endif
3816 #if 0
3817 if (wpid != -1)
3818 itrace("waitchld: %s waitpid returns %d", block?"blocking":"non-blocking", pid);
3819 #endif
3820 /* WCONTINUED may be rejected by waitpid as invalid even when defined */
3821 if (wcontinued && pid < 0 && errno == EINVAL)
3822 {
3823 wcontinued = 0;
3824 continue; /* jump back to the test and retry without WCONTINUED */
3825 }
3826
3827 /* The check for WNOHANG is to make sure we decrement sigchld only
3828 if it was non-zero before we called waitpid. */
3829 if (sigchld > 0 && (waitpid_flags & WNOHANG))
3830 sigchld--;
3831
3832 /* If waitpid returns -1 with errno == ECHILD, there are no more
3833 unwaited-for child processes of this shell. */
3834 if (pid < 0 && errno == ECHILD)
3835 {
3836 if (children_exited == 0)
3837 return -1;
3838 else
3839 break;
3840 }
3841
3842 #if 0
3843 itrace("waitchld: waitpid returns %d block = %d children_exited = %d", pid, block, children_exited);
3844 #endif
3845 /* If waitpid returns 0, there are running children. If it returns -1,
3846 the only other error POSIX says it can return is EINTR. */
3847 CHECK_TERMSIG;
3848 CHECK_WAIT_INTR;
3849
3850 /* If waitpid returns -1/EINTR and the shell saw a SIGINT, then we
3851 assume the child has blocked or handled SIGINT. In that case, we
3852 require the child to actually die due to SIGINT to act on the
3853 SIGINT we received; otherwise we assume the child handled it and
3854 let it go. */
3855 if (pid < 0 && errno == EINTR && wait_sigint_received)
3856 child_caught_sigint = 1;
3857
3858 if (pid <= 0)
3859 continue; /* jumps right to the test */
3860
3861 /* Linux kernels appear to signal the parent but not interrupt the
3862 waitpid() (or restart it even without SA_RESTART) on SIGINT, so if
3863 we saw a SIGINT and the process exited or died due to some other
3864 signal, assume the child caught the SIGINT. */
3865 if (wait_sigint_received && (WIFSIGNALED (status) == 0 || WTERMSIG (status) != SIGINT))
3866 child_caught_sigint = 1;
3867
3868 /* If the child process did die due to SIGINT, forget our assumption
3869 that it caught or otherwise handled it. */
3870 if (WIFSIGNALED (status) && WTERMSIG (status) == SIGINT)
3871 child_caught_sigint = 0;
3872
3873 /* children_exited is used to run traps on SIGCHLD. We don't want to
3874 run the trap if a process is just being continued. */
3875 if (WIFCONTINUED(status) == 0)
3876 {
3877 children_exited++;
3878 js.c_living--;
3879 }
3880
3881 /* Locate our PROCESS for this pid. */
3882 child = find_process (pid, 1, &job); /* want living procs only */
3883
3884 #if defined (COPROCESS_SUPPORT)
3885 coproc_pidchk (pid, WSTATUS(status));
3886 #endif
3887
3888 #if defined (PROCESS_SUBSTITUTION)
3889 /* Only manipulate the list of process substitutions while SIGCHLD
3890 is blocked. We only use this as a hint that we can remove FIFOs
3891 or close file descriptors corresponding to terminated process
3892 substitutions. */
3893 if ((ind = find_procsub_child (pid)) >= 0)
3894 set_procsub_status (ind, pid, WSTATUS (status));
3895 #endif
3896
3897 /* It is not an error to have a child terminate that we did
3898 not have a record of. This child could have been part of
3899 a pipeline in backquote substitution. Even so, I'm not
3900 sure child is ever non-zero. */
3901 if (child == 0)
3902 {
3903 if (WIFEXITED (status) || WIFSIGNALED (status))
3904 js.c_reaped++;
3905 continue;
3906 }
3907
3908 /* Remember status, and whether or not the process is running. */
3909 child->status = status;
3910 child->running = WIFCONTINUED(status) ? PS_RUNNING : PS_DONE;
3911
3912 if (PEXITED (child))
3913 {
3914 js.c_totreaped++;
3915 if (job != NO_JOB)
3916 js.c_reaped++;
3917 }
3918
3919 if (job == NO_JOB)
3920 continue;
3921
3922 call_set_current += set_job_status_and_cleanup (job);
3923
3924 if (STOPPED (job))
3925 last_stopped_job = job;
3926 else if (DEADJOB (job) && last_stopped_job == job)
3927 last_stopped_job = NO_JOB;
3928 }
3929 while ((sigchld || block == 0) && pid > (pid_t)0);
3930
3931 /* If a job was running and became stopped, then set the current
3932 job. Otherwise, don't change a thing. */
3933 if (call_set_current)
3934 {
3935 if (last_stopped_job != NO_JOB)
3936 set_current_job (last_stopped_job);
3937 else
3938 reset_current ();
3939 }
3940
3941 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3942 if (children_exited &&
3943 (signal_is_trapped (SIGCHLD) || trap_list[SIGCHLD] == (char *)IMPOSSIBLE_TRAP_HANDLER) &&
3944 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
3945 {
3946 if (posixly_correct && this_shell_builtin && this_shell_builtin == wait_builtin)
3947 {
3948 /* This was trap_handler (SIGCHLD) but that can lose traps if
3949 children_exited > 1 */
3950 queue_sigchld_trap (children_exited);
3951 wait_signal_received = SIGCHLD;
3952 /* If we're in a signal handler, let CHECK_WAIT_INTR pick it up;
3953 run_pending_traps will call run_sigchld_trap later */
3954 if (sigchld == 0 && wait_intr_flag)
3955 sh_longjmp (wait_intr_buf, 1);
3956 }
3957 /* If not in posix mode and not executing the wait builtin, queue the
3958 signal for later handling. Run the trap immediately if we are
3959 executing the wait builtin, but don't break out of `wait'. */
3960 else if (sigchld) /* called from signal handler */
3961 queue_sigchld_trap (children_exited);
3962 else if (signal_in_progress (SIGCHLD))
3963 queue_sigchld_trap (children_exited);
3964 else if (trap_list[SIGCHLD] == (char *)IMPOSSIBLE_TRAP_HANDLER)
3965 queue_sigchld_trap (children_exited);
3966 else if (running_trap)
3967 queue_sigchld_trap (children_exited);
3968 else if (this_shell_builtin == wait_builtin)
3969 {
3970 int o;
3971 o = jobs_list_frozen;
3972 jobs_list_frozen = 1;
3973 run_sigchld_trap (children_exited); /* XXX */
3974 jobs_list_frozen = o;
3975 }
3976 else
3977 queue_sigchld_trap (children_exited);
3978 }
3979
3980 /* We have successfully recorded the useful information about this process
3981 that has just changed state. If we notify asynchronously, and the job
3982 that this process belongs to is no longer running, then notify the user
3983 of that fact now. */
3984 if (asynchronous_notification && interactive && executing_builtin == 0)
3985 notify_of_job_status ();
3986
3987 return (children_exited);
3988 }
3989
3990 /* Set the status of JOB and perform any necessary cleanup if the job is
3991 marked as JDEAD.
3992
3993 Currently, the cleanup activity is restricted to handling any SIGINT
3994 received while waiting for a foreground job to finish. */
3995 static int
3996 set_job_status_and_cleanup (int job)
3997 {
3998 PROCESS *child;
3999 int tstatus, job_state, any_stopped, any_tstped, call_set_current;
4000 SigHandler *temp_handler;
4001
4002 child = jobs[job]->pipe;
4003 jobs[job]->flags &= ~J_NOTIFIED;
4004
4005 call_set_current = 0;
4006
4007 /*
4008 * COMPUTE JOB STATUS
4009 */
4010
4011 /* If all children are not running, but any of them is stopped, then
4012 the job is stopped, not dead. */
4013 job_state = any_stopped = any_tstped = 0;
4014 do
4015 {
4016 job_state |= PRUNNING (child);
4017 #if 0
4018 if (PEXITED (child) && (WIFSTOPPED (child->status)))
4019 #else
4020 /* Only checking for WIFSTOPPED now, not for PS_DONE */
4021 if (PSTOPPED (child))
4022 #endif
4023 {
4024 any_stopped = 1;
4025 any_tstped |= job_control && (WSTOPSIG (child->status) == SIGTSTP);
4026 }
4027 child = child->next;
4028 }
4029 while (child != jobs[job]->pipe);
4030
4031 /* If job_state != 0, the job is still running, so don't bother with
4032 setting the process exit status and job state unless we're
4033 transitioning from stopped to running. */
4034 if (job_state != 0 && JOBSTATE(job) != JSTOPPED)
4035 return 0;
4036
4037 /*
4038 * SET JOB STATUS
4039 */
4040
4041 /* The job is either stopped or dead. Set the state of the job accordingly. */
4042 if (any_stopped)
4043 {
4044 jobs[job]->state = JSTOPPED;
4045 jobs[job]->flags &= ~J_FOREGROUND;
4046 call_set_current++;
4047 /* Suspending a job with SIGTSTP breaks all active loops. */
4048 if (any_tstped && loop_level)
4049 breaking = loop_level;
4050 }
4051 else if (job_state != 0) /* was stopped, now running */
4052 {
4053 jobs[job]->state = JRUNNING;
4054 call_set_current++;
4055 }
4056 else
4057 {
4058 jobs[job]->state = JDEAD;
4059 js.j_ndead++;
4060
4061 #if 0
4062 if (IS_FOREGROUND (job))
4063 setjstatus (job);
4064 #endif
4065
4066 /* If this job has a cleanup function associated with it, call it
4067 with `cleanarg' as the single argument, then set the function
4068 pointer to NULL so it is not inadvertently called twice. The
4069 cleanup function is responsible for deallocating cleanarg. */
4070 if (jobs[job]->j_cleanup)
4071 {
4072 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
4073 jobs[job]->j_cleanup = (sh_vptrfunc_t *)NULL;
4074 }
4075 }
4076
4077 /*
4078 * CLEANUP
4079 *
4080 * Currently, we just do special things if we got a SIGINT while waiting
4081 * for a foreground job to complete
4082 */
4083
4084 if (JOBSTATE (job) == JDEAD)
4085 {
4086 /* If we're running a shell script and we get a SIGINT with a
4087 SIGINT trap handler, but the foreground job handles it and
4088 does not exit due to SIGINT, run the trap handler but do not
4089 otherwise act as if we got the interrupt. */
4090 if (wait_sigint_received && interactive_shell == 0 &&
4091 child_caught_sigint && IS_FOREGROUND (job) &&
4092 signal_is_trapped (SIGINT))
4093 {
4094 int old_frozen;
4095 wait_sigint_received = 0;
4096 last_command_exit_value = process_exit_status (child->status);
4097
4098 old_frozen = jobs_list_frozen;
4099 jobs_list_frozen = 1;
4100 tstatus = maybe_call_trap_handler (SIGINT);
4101 jobs_list_frozen = old_frozen;
4102 }
4103
4104 /* If the foreground job is killed by SIGINT when job control is not
4105 active, we need to perform some special handling.
4106
4107 The check of wait_sigint_received is a way to determine if the
4108 SIGINT came from the keyboard (in which case the shell has already
4109 seen it, and wait_sigint_received is non-zero, because keyboard
4110 signals are sent to process groups) or via kill(2) to the foreground
4111 process by another process (or itself). If the shell did receive the
4112 SIGINT, it needs to perform normal SIGINT processing. XXX - should
4113 this change its behavior depending on whether the last command in an
4114 pipeline exited due to SIGINT, or any process in the pipeline? Right
4115 now it does this if any process in the pipeline exits due to SIGINT. */
4116 else if (wait_sigint_received &&
4117 child_caught_sigint == 0 &&
4118 IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
4119 {
4120 int old_frozen;
4121
4122 wait_sigint_received = 0;
4123
4124 /* If SIGINT is trapped, set the exit status so that the trap
4125 handler can see it. */
4126 if (signal_is_trapped (SIGINT))
4127 last_command_exit_value = process_exit_status (child->status);
4128
4129 /* If the signal is trapped, let the trap handler get it no matter
4130 what and simply return if the trap handler returns.
4131 maybe_call_trap_handler() may cause dead jobs to be removed from
4132 the job table because of a call to execute_command. We work
4133 around this by setting JOBS_LIST_FROZEN. */
4134 old_frozen = jobs_list_frozen;
4135 jobs_list_frozen = 1;
4136 tstatus = maybe_call_trap_handler (SIGINT);
4137 jobs_list_frozen = old_frozen;
4138 if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
4139 {
4140 /* wait_sigint_handler () has already seen SIGINT and
4141 allowed the wait builtin to jump out. We need to
4142 call the original SIGINT handler, if necessary. If
4143 the original handler is SIG_DFL, we need to resend
4144 the signal to ourselves. */
4145
4146 temp_handler = old_sigint_handler;
4147
4148 /* Bogus. If we've reset the signal handler as the result
4149 of a trap caught on SIGINT, then old_sigint_handler
4150 will point to trap_handler, which now knows nothing about
4151 SIGINT (if we reset the sighandler to the default).
4152 In this case, we have to fix things up. What a crock. */
4153 if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
4154 temp_handler = trap_to_sighandler (SIGINT);
4155 restore_sigint_handler ();
4156 if (temp_handler == SIG_DFL)
4157 termsig_handler (SIGINT); /* XXX */
4158 else if (temp_handler != SIG_IGN)
4159 (*temp_handler) (SIGINT);
4160 }
4161 }
4162 }
4163
4164 return call_set_current;
4165 }
4166
4167 /* Build the array of values for the $PIPESTATUS variable from the set of
4168 exit statuses of all processes in the job J. */
4169 static void
4170 setjstatus (int j)
4171 {
4172 #if defined (ARRAY_VARS)
4173 register int i;
4174 register PROCESS *p;
4175
4176 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
4177 ;
4178 i++;
4179 if (statsize < i)
4180 {
4181 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
4182 statsize = i;
4183 }
4184 i = 0;
4185 p = jobs[j]->pipe;
4186 do
4187 {
4188 pstatuses[i++] = process_exit_status (p->status);
4189 p = p->next;
4190 }
4191 while (p != jobs[j]->pipe);
4192
4193 pstatuses[i] = -1; /* sentinel */
4194 set_pipestatus_array (pstatuses, i);
4195 #endif
4196 }
4197
4198 void
4199 run_sigchld_trap (int nchild)
4200 {
4201 char *trap_command;
4202 int i;
4203
4204 /* Turn off the trap list during the call to parse_and_execute ()
4205 to avoid potentially infinite recursive calls. Preserve the
4206 values of last_command_exit_value, last_made_pid, and the_pipeline
4207 around the execution of the trap commands. */
4208 trap_command = savestring (trap_list[SIGCHLD]);
4209
4210 begin_unwind_frame ("SIGCHLD trap");
4211 unwind_protect_int (last_command_exit_value);
4212 unwind_protect_int (last_command_exit_signal);
4213 unwind_protect_var (last_made_pid);
4214 unwind_protect_int (jobs_list_frozen);
4215 unwind_protect_pointer (the_pipeline);
4216 unwind_protect_pointer (subst_assign_varlist);
4217 unwind_protect_pointer (this_shell_builtin);
4218 unwind_protect_pointer (temporary_env);
4219
4220 /* We have to add the commands this way because they will be run
4221 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
4222 to reference freed memory. */
4223 add_unwind_protect (xfree, trap_command);
4224 add_unwind_protect (uw_maybe_set_sigchld_trap, trap_command);
4225
4226 subst_assign_varlist = (WORD_LIST *)NULL;
4227 the_pipeline = (PROCESS *)NULL;
4228 temporary_env = 0; /* traps should not run with temporary env */
4229
4230 running_trap = SIGCHLD + 1;
4231
4232 set_impossible_sigchld_trap ();
4233 for (i = 0; i < nchild; i++)
4234 {
4235 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST|SEVAL_RESETLINE|SEVAL_NOOPTIMIZE);
4236 }
4237
4238 run_unwind_frame ("SIGCHLD trap");
4239 running_trap = 0;
4240 }
4241
4242 /* Function to call when you want to notify people of changes
4243 in job status. This prints out all jobs which are pending
4244 notification to stderr, and marks those printed as already
4245 notified, thus making them candidates for cleanup. */
4246 static void
4247 notify_of_job_status (void)
4248 {
4249 register int job, termsig;
4250 char *dir;
4251 sigset_t set, oset;
4252 WAIT s;
4253
4254 if (jobs == 0 || js.j_jobslots == 0)
4255 return;
4256
4257 if (old_ttou != 0)
4258 {
4259 sigemptyset (&set);
4260 sigaddset (&set, SIGCHLD);
4261 sigaddset (&set, SIGTTOU);
4262 sigemptyset (&oset);
4263 sigprocmask (SIG_BLOCK, &set, &oset);
4264 }
4265 else
4266 queue_sigchld++;
4267
4268 /* XXX could use js.j_firstj here */
4269 for (job = 0, dir = NULL; job < js.j_jobslots; job++)
4270 {
4271 if (jobs[job] && IS_NOTIFIED (job) == 0)
4272 {
4273 s = raw_job_exit_status (job);
4274 termsig = WTERMSIG (s);
4275
4276 /* POSIX.2 says we have to hang onto the statuses of at most the
4277 last CHILD_MAX background processes if the shell is running a
4278 script. If the shell is running a script, either from a file
4279 or standard input, don't print anything unless the job was
4280 killed by a signal. */
4281 if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
4282 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
4283 continue;
4284
4285 /* If job control is disabled, don't print the status messages.
4286 Mark dead jobs as notified so that they get cleaned up. If
4287 startup_state == 2 and subshell_environment has the
4288 SUBSHELL_COMSUB bit turned on, we were started to run a command
4289 substitution, so don't print anything.
4290 Otherwise, if the shell is not interactive, POSIX says that `jobs'
4291 is the only way to notify of job status. */
4292 if ((job_control == 0 && interactive_shell) ||
4293 (startup_state == 2 && (subshell_environment & SUBSHELL_COMSUB)) ||
4294 (startup_state == 2 && posixly_correct && (subshell_environment & SUBSHELL_COMSUB) == 0))
4295 {
4296 /* POSIX.2 compatibility: if the shell is not interactive,
4297 hang onto the job corresponding to the last asynchronous
4298 pid until the user has been notified of its status or does
4299 a `wait'. */
4300 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job, 0) != last_asynchronous_pid)))
4301 jobs[job]->flags |= J_NOTIFIED;
4302 continue;
4303 }
4304
4305 /* Print info on jobs that are running in the background,
4306 and on foreground jobs that were killed by anything
4307 except SIGINT (and possibly SIGPIPE). */
4308 switch (JOBSTATE (job))
4309 {
4310 case JDEAD:
4311 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
4312 termsig != SIGINT &&
4313 #if defined (DONT_REPORT_SIGTERM)
4314 termsig != SIGTERM &&
4315 #endif
4316 #if defined (DONT_REPORT_SIGPIPE)
4317 termsig != SIGPIPE &&
4318 #endif
4319 signal_is_trapped (termsig) == 0)
4320 {
4321 /* Don't print `0' for a line number. */
4322 fprintf (stderr, _("%s: line %d: "), get_name_for_error (), (line_number == 0) ? 1 : line_number);
4323 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
4324 }
4325 else if (IS_FOREGROUND (job))
4326 {
4327 #if !defined (DONT_REPORT_SIGPIPE)
4328 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
4329 #else
4330 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
4331 #endif
4332 {
4333 fprintf (stderr, "%s", j_strsignal (termsig));
4334
4335 if (WIFCORED (s))
4336 fprintf (stderr, _(" (core dumped)"));
4337
4338 fprintf (stderr, "\n");
4339 }
4340 jobs[job]->flags |= J_NOTIFIED;
4341 }
4342 else if (job_control)
4343 {
4344 if (dir == 0)
4345 dir = current_working_directory ();
4346 pretty_print_job (job, JLIST_STANDARD, stderr);
4347 if (dir && strcmp (dir, jobs[job]->wd) != 0)
4348 fprintf (stderr,
4349 _("(wd now: %s)\n"), polite_directory_format (dir));
4350 }
4351
4352 /* This is where we set J_NOTIFIED for background jobs in
4353 non-interactive shells without job control enabled that are
4354 killed by SIGINT or SIGTERM (DONT_REPORT_SIGTERM) or SIGPIPE
4355 (DONT_REPORT_SIGPIPE) as long as those signals are not
4356 trapped, or that exit cleanly.
4357 Interactive shells without job control enabled are handled
4358 above. */
4359 /* XXX - if we want to arrange to keep these jobs in the jobs
4360 list, instead of making them eligible to move to bgpids,
4361 this is where to change things. */
4362 jobs[job]->flags |= J_NOTIFIED;
4363 break;
4364
4365 case JSTOPPED:
4366 fprintf (stderr, "\n");
4367 if (dir == 0)
4368 dir = current_working_directory ();
4369 pretty_print_job (job, JLIST_STANDARD, stderr);
4370 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
4371 fprintf (stderr,
4372 _("(wd now: %s)\n"), polite_directory_format (dir));
4373 jobs[job]->flags |= J_NOTIFIED;
4374 break;
4375
4376 case JRUNNING:
4377 case JMIXED:
4378 break;
4379
4380 default:
4381 programming_error ("notify_of_job_status");
4382 }
4383 }
4384 }
4385 if (old_ttou != 0)
4386 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
4387 else
4388 queue_sigchld--;
4389 }
4390
4391 /* Initialize the job control mechanism, and set up the tty stuff. */
4392 int
4393 initialize_job_control (int force)
4394 {
4395 pid_t t;
4396 int t_errno, tty_sigs;
4397
4398 t_errno = -1;
4399 shell_pgrp = getpgid (0);
4400
4401 if (shell_pgrp == -1)
4402 {
4403 sys_error (_("initialize_job_control: getpgrp failed"));
4404 exit (1);
4405 }
4406
4407 /* We can only have job control if we are interactive unless we force it. */
4408 if (interactive == 0 && force == 0)
4409 {
4410 job_control = 0;
4411 original_pgrp = NO_PID;
4412 shell_tty = fileno (stderr);
4413 terminal_pgrp = tcgetpgrp (shell_tty); /* for checking later */
4414 }
4415 else
4416 {
4417 shell_tty = -1;
4418
4419 /* If forced_interactive is set, we skip the normal check that stderr
4420 is attached to a tty, so we need to check here. If it's not, we
4421 need to see whether we have a controlling tty by opening /dev/tty,
4422 since trying to use job control tty pgrp manipulations on a non-tty
4423 is going to fail. */
4424 if (forced_interactive && isatty (fileno (stderr)) == 0)
4425 shell_tty = open ("/dev/tty", O_RDWR|O_NONBLOCK);
4426
4427 /* Get our controlling terminal. If job_control is set, or
4428 interactive is set, then this is an interactive shell no
4429 matter where fd 2 is directed. */
4430 if (shell_tty == -1)
4431 shell_tty = dup (fileno (stderr)); /* fd 2 */
4432
4433 if (shell_tty != -1)
4434 shell_tty = move_to_high_fd (shell_tty, 1, -1);
4435
4436 /* Compensate for a bug in systems that compiled the BSD
4437 rlogind with DEBUG defined, like NeXT and Alliant. */
4438 if (shell_pgrp == 0)
4439 {
4440 shell_pgrp = getpid ();
4441 setpgid (0, shell_pgrp);
4442 if (shell_tty != -1)
4443 tcsetpgrp (shell_tty, shell_pgrp);
4444 }
4445
4446 tty_sigs = 0;
4447 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
4448 {
4449 if (shell_pgrp != terminal_pgrp)
4450 {
4451 SigHandler *ottin;
4452
4453 CHECK_TERMSIG;
4454 ottin = set_signal_handler (SIGTTIN, SIG_DFL);
4455 kill (0, SIGTTIN);
4456 set_signal_handler (SIGTTIN, ottin);
4457 if (tty_sigs++ > 16)
4458 {
4459 sys_error (_("initialize_job_control: no job control in background"));
4460 job_control = 0;
4461 original_pgrp = terminal_pgrp; /* for eventual give_terminal_to */
4462 goto just_bail;
4463 }
4464 continue;
4465 }
4466 break;
4467 }
4468
4469 if (terminal_pgrp == -1)
4470 t_errno = errno;
4471
4472 /* Make sure that we are using the new line discipline. */
4473 if (set_new_line_discipline (shell_tty) < 0)
4474 {
4475 sys_error (_("initialize_job_control: line discipline"));
4476 job_control = 0;
4477 }
4478 else
4479 {
4480 original_pgrp = shell_pgrp;
4481 shell_pgrp = getpid ();
4482
4483 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
4484 {
4485 sys_error (_("initialize_job_control: setpgid"));
4486 shell_pgrp = original_pgrp;
4487 }
4488
4489 job_control = 1;
4490
4491 /* If (and only if) we just set our process group to our pid,
4492 thereby becoming a process group leader, and the terminal
4493 is not in the same process group as our (new) process group,
4494 then set the terminal's process group to our (new) process
4495 group. If that fails, set our process group back to what it
4496 was originally (so we can still read from the terminal) and
4497 turn off job control. */
4498 if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
4499 {
4500 if (give_terminal_to (shell_pgrp, 0) < 0)
4501 {
4502 t_errno = errno;
4503 setpgid (0, original_pgrp);
4504 shell_pgrp = original_pgrp;
4505 errno = t_errno;
4506 sys_error (_("cannot set terminal process group (%d)"), shell_pgrp);
4507 job_control = 0;
4508 }
4509 }
4510
4511 if (job_control && ((t = tcgetpgrp (shell_tty)) == -1 || t != shell_pgrp))
4512 {
4513 if (t_errno != -1)
4514 errno = t_errno;
4515 sys_error (_("cannot set terminal process group (%d)"), t);
4516 job_control = 0;
4517 }
4518 }
4519 if (job_control == 0)
4520 internal_error (_("no job control in this shell"));
4521 }
4522
4523 just_bail:
4524 running_in_background = terminal_pgrp != shell_pgrp;
4525
4526 if (shell_tty != fileno (stderr))
4527 SET_CLOSE_ON_EXEC (shell_tty);
4528
4529 set_signal_handler (SIGCHLD, sigchld_handler);
4530
4531 change_flag ('m', job_control ? '-' : '+');
4532
4533 if (interactive)
4534 get_tty_state ();
4535
4536 set_maxchild (0);
4537
4538 return job_control;
4539 }
4540
4541 #ifdef DEBUG
4542 void
4543 debug_print_pgrps (void)
4544 {
4545 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
4546 (long)original_pgrp, (long)shell_pgrp, (long)terminal_pgrp);
4547 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
4548 shell_tty, (long)tcgetpgrp (shell_tty), (long)getpgid(0));
4549 itrace("pipeline_pgrp -> %ld", (long)pipeline_pgrp);
4550 }
4551 #endif
4552
4553 /* Set the line discipline to the best this system has to offer.
4554 Return -1 if this is not possible. */
4555 static int
4556 set_new_line_discipline (int tty)
4557 {
4558 #if defined (NEW_TTY_DRIVER)
4559 int ldisc;
4560
4561 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
4562 return (-1);
4563
4564 if (ldisc != NTTYDISC)
4565 {
4566 ldisc = NTTYDISC;
4567
4568 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
4569 return (-1);
4570 }
4571 return (0);
4572 #endif /* NEW_TTY_DRIVER */
4573
4574 #if defined (TERMIO_TTY_DRIVER)
4575 # if defined (TERMIO_LDISC) && (NTTYDISC)
4576 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
4577 return (-1);
4578
4579 if (shell_tty_info.c_line != NTTYDISC)
4580 {
4581 shell_tty_info.c_line = NTTYDISC;
4582 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
4583 return (-1);
4584 }
4585 # endif /* TERMIO_LDISC && NTTYDISC */
4586 return (0);
4587 #endif /* TERMIO_TTY_DRIVER */
4588
4589 #if defined (TERMIOS_TTY_DRIVER)
4590 # if defined (TERMIOS_LDISC) && defined (NTTYDISC)
4591 if (tcgetattr (tty, &shell_tty_info) < 0)
4592 return (-1);
4593
4594 if (shell_tty_info.c_line != NTTYDISC)
4595 {
4596 shell_tty_info.c_line = NTTYDISC;
4597 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
4598 return (-1);
4599 }
4600 # endif /* TERMIOS_LDISC && NTTYDISC */
4601 return (0);
4602 #endif /* TERMIOS_TTY_DRIVER */
4603
4604 #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
4605 return (-1);
4606 #endif
4607 }
4608
4609 /* Setup this shell to handle C-C, etc. */
4610 void
4611 initialize_job_signals (void)
4612 {
4613 if (interactive)
4614 {
4615 set_signal_handler (SIGINT, sigint_sighandler);
4616 set_signal_handler (SIGTSTP, SIG_IGN);
4617 set_signal_handler (SIGTTOU, SIG_IGN);
4618 set_signal_handler (SIGTTIN, SIG_IGN);
4619 }
4620 else if (job_control)
4621 {
4622 old_tstp = set_signal_handler (SIGTSTP, sigstop_sighandler);
4623 old_ttin = set_signal_handler (SIGTTIN, sigstop_sighandler);
4624 old_ttou = set_signal_handler (SIGTTOU, sigstop_sighandler);
4625 }
4626 /* Leave disposition unmodified for non-interactive shells without job
4627 control. */
4628 }
4629
4630 /* Here we handle CONT signals. */
4631 static sighandler
4632 sigcont_sighandler (int sig)
4633 {
4634 initialize_job_signals ();
4635 set_signal_handler (SIGCONT, old_cont);
4636 kill (getpid (), SIGCONT);
4637
4638 SIGRETURN (0);
4639 }
4640
4641 /* Here we handle stop signals while we are running not as a login shell. */
4642 static sighandler
4643 sigstop_sighandler (int sig)
4644 {
4645 set_signal_handler (SIGTSTP, old_tstp);
4646 set_signal_handler (SIGTTOU, old_ttou);
4647 set_signal_handler (SIGTTIN, old_ttin);
4648
4649 old_cont = set_signal_handler (SIGCONT, sigcont_sighandler);
4650
4651 give_terminal_to (shell_pgrp, 0);
4652
4653 kill (getpid (), sig);
4654
4655 SIGRETURN (0);
4656 }
4657
4658 /* Give the terminal to PGRP. */
4659 int
4660 give_terminal_to (pid_t pgrp, int force)
4661 {
4662 sigset_t set, oset;
4663 int r, e;
4664
4665 r = 0;
4666 if (job_control || force)
4667 {
4668 sigemptyset (&set);
4669 sigaddset (&set, SIGTTOU);
4670 sigaddset (&set, SIGTTIN);
4671 sigaddset (&set, SIGTSTP);
4672 sigaddset (&set, SIGCHLD);
4673 sigemptyset (&oset);
4674 sigprocmask (SIG_BLOCK, &set, &oset);
4675
4676 if (tcsetpgrp (shell_tty, pgrp) < 0)
4677 {
4678 /* Maybe we should print an error message? */
4679 #if 0
4680 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
4681 shell_tty, (long)getpid(), (long)pgrp);
4682 #endif
4683 r = -1;
4684 e = errno;
4685 }
4686 else
4687 terminal_pgrp = pgrp;
4688 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
4689 }
4690
4691 if (r == -1)
4692 errno = e;
4693
4694 return r;
4695 }
4696
4697 /* Give terminal to NPGRP iff it's currently owned by OPGRP. FLAGS are the
4698 flags to pass to give_terminal_to(). */
4699 static int
4700 maybe_give_terminal_to (pid_t opgrp, pid_t npgrp, int flags)
4701 {
4702 int tpgrp;
4703
4704 tpgrp = tcgetpgrp (shell_tty);
4705 if (tpgrp < 0 && errno == ENOTTY)
4706 return -1;
4707 if (tpgrp == npgrp)
4708 {
4709 terminal_pgrp = npgrp;
4710 return 0;
4711 }
4712 else if (tpgrp != opgrp)
4713 {
4714 internal_debug ("%d: maybe_give_terminal_to: terminal pgrp == %d shell pgrp = %d new pgrp = %d in_background = %d", (int)getpid(), tpgrp, opgrp, npgrp, running_in_background);
4715 return -1;
4716 }
4717 else
4718 return (give_terminal_to (npgrp, flags));
4719 }
4720
4721 /* Clear out any jobs in the job array. This is intended to be used by
4722 children of the shell, who should not have any job structures as baggage
4723 when they start executing (forking subshells for parenthesized execution
4724 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
4725 is nonzero, only running jobs are removed from the table. */
4726 void
4727 delete_all_jobs (int running_only)
4728 {
4729 register int i;
4730 sigset_t set, oset;
4731
4732 BLOCK_CHILD (set, oset);
4733
4734 /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
4735 if (js.j_jobslots)
4736 {
4737 js.j_current = js.j_previous = NO_JOB;
4738
4739 /* XXX could use js.j_firstj here */
4740 for (i = 0; i < js.j_jobslots; i++)
4741 {
4742 if (i < js.j_firstj && jobs[i])
4743 INTERNAL_DEBUG (("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
4744 if (i > js.j_lastj && jobs[i])
4745 INTERNAL_DEBUG (("delete_all_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
4746
4747 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
4748 /* We don't want to add any of these pids to bgpids. If running_only
4749 is non-zero, we don't want to add running jobs to the list.
4750 If we are interested in all jobs, not just running jobs, and
4751 we are going to clear the bgpids list below (bgp_clear()), we
4752 don't need to bother. */
4753 delete_job (i, DEL_WARNSTOPPED|DEL_NOBGPID);
4754 }
4755 if (running_only == 0)
4756 {
4757 free ((char *)jobs);
4758 js.j_jobslots = 0;
4759 js.j_firstj = js.j_lastj = js.j_njobs = js.j_ndead = 0;
4760 js.c_reaped = js.c_injobs = js.c_living = 0;
4761 }
4762 }
4763
4764 if (running_only == 0)
4765 bgp_clear ();
4766
4767 UNBLOCK_CHILD (oset);
4768 }
4769
4770 /* Mark all jobs in the job array so that they don't get a SIGHUP when the
4771 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
4772 void
4773 nohup_all_jobs (int running_only)
4774 {
4775 register int i;
4776 sigset_t set, oset;
4777
4778 BLOCK_CHILD (set, oset);
4779
4780 if (js.j_jobslots)
4781 {
4782 /* XXX could use js.j_firstj here */
4783 for (i = 0; i < js.j_jobslots; i++)
4784 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
4785 nohup_job (i);
4786 }
4787
4788 UNBLOCK_CHILD (oset);
4789 }
4790
4791 int
4792 count_all_jobs (void)
4793 {
4794 int i, n;
4795 sigset_t set, oset;
4796
4797 /* This really counts all non-dead jobs. */
4798 BLOCK_CHILD (set, oset);
4799 /* XXX could use js.j_firstj here */
4800 for (i = n = 0; i < js.j_jobslots; i++)
4801 {
4802 if (i < js.j_firstj && jobs[i])
4803 INTERNAL_DEBUG (("count_all_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
4804 if (i > js.j_lastj && jobs[i])
4805 INTERNAL_DEBUG (("count_all_jobs: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
4806
4807 if (jobs[i] && DEADJOB(i) == 0)
4808 n++;
4809 }
4810 UNBLOCK_CHILD (oset);
4811 return n;
4812 }
4813
4814 static void
4815 mark_all_jobs_as_dead (void)
4816 {
4817 register int i;
4818 sigset_t set, oset;
4819
4820 if (js.j_jobslots == 0)
4821 return;
4822
4823 BLOCK_CHILD (set, oset);
4824
4825 /* XXX could use js.j_firstj here */
4826 for (i = js.j_ndead = 0; i < js.j_jobslots; i++)
4827 if (jobs[i])
4828 {
4829 jobs[i]->state = JDEAD;
4830 js.j_ndead++;
4831 }
4832
4833 UNBLOCK_CHILD (oset);
4834 }
4835
4836 /* Mark all dead jobs as notified, so delete_job () cleans them out
4837 of the job table properly. POSIX.2 says we need to save the
4838 status of the last CHILD_MAX jobs, so we count the number of dead
4839 jobs and mark only enough as notified to save CHILD_MAX statuses. */
4840 static void
4841 mark_dead_jobs_as_notified (int force)
4842 {
4843 register int i, ndead, ndeadproc;
4844 sigset_t set, oset;
4845
4846 if (js.j_jobslots == 0)
4847 return;
4848
4849 BLOCK_CHILD (set, oset);
4850
4851 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
4852 around; just run through the array. */
4853 if (force)
4854 {
4855 /* XXX could use js.j_firstj here */
4856 for (i = 0; i < js.j_jobslots; i++)
4857 {
4858 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
4859 jobs[i]->flags |= J_NOTIFIED;
4860 }
4861 UNBLOCK_CHILD (oset);
4862 return;
4863 }
4864
4865 /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
4866 array with the corresponding not marked as notified. This is a better
4867 way to avoid pid aliasing and reuse problems than keeping the POSIX-
4868 mandated CHILD_MAX jobs around. delete_job() takes care of keeping the
4869 bgpids list regulated. */
4870
4871 /* Count the number of dead jobs */
4872 /* XXX could use js.j_firstj here */
4873 for (i = ndead = ndeadproc = 0; i < js.j_jobslots; i++)
4874 {
4875 if (i < js.j_firstj && jobs[i])
4876 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
4877 if (i > js.j_lastj && jobs[i])
4878 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
4879
4880 if (jobs[i] && DEADJOB (i))
4881 {
4882 ndead++;
4883 ndeadproc += processes_in_job (i);
4884 }
4885 }
4886
4887 # if 0
4888 if (ndeadproc != js.c_reaped)
4889 itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc, js.c_reaped);
4890 # endif
4891 if (ndead != js.j_ndead)
4892 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead, js.j_ndead));
4893
4894 if (js.c_childmax < 0)
4895 set_maxchild (0);
4896
4897 /* Don't do anything if the number of dead processes is less than CHILD_MAX
4898 and we're not forcing a cleanup. */
4899 if (ndeadproc <= js.c_childmax)
4900 {
4901 UNBLOCK_CHILD (oset);
4902 return;
4903 }
4904
4905 #if 0
4906 itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js.c_childmax, ndead, ndeadproc);
4907 #endif
4908
4909 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
4910 the list. This isn't exactly right yet; changes need to be made
4911 to stop_pipeline so we don't mark the newer jobs after we've
4912 created CHILD_MAX slots in the jobs array. This needs to be
4913 integrated with a way to keep the jobs array from growing without
4914 bound. Maybe we wrap back around to 0 after we reach some max
4915 limit, and there are sufficient job slots free (keep track of total
4916 size of jobs array (js.j_jobslots) and running count of number of jobs
4917 in jobs array. Then keep a job index corresponding to the `oldest job'
4918 and start this loop there, wrapping around as necessary. In effect,
4919 we turn the list into a circular buffer. */
4920 /* XXX could use js.j_firstj here */
4921 for (i = 0; i < js.j_jobslots; i++)
4922 {
4923 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
4924 {
4925 if (i < js.j_firstj && jobs[i])
4926 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i, js.j_firstj));
4927 if (i > js.j_lastj && jobs[i])
4928 INTERNAL_DEBUG (("mark_dead_jobs_as_notified: job %d non-null after js.j_lastj (%d)", i, js.j_lastj));
4929
4930 /* If marking this job as notified would drop us down below
4931 child_max, don't mark it so we can keep at least child_max
4932 statuses. XXX -- need to check what Posix actually says
4933 about keeping statuses. */
4934 if ((ndeadproc -= processes_in_job (i)) <= js.c_childmax)
4935 break;
4936 jobs[i]->flags |= J_NOTIFIED;
4937 }
4938 }
4939
4940 UNBLOCK_CHILD (oset);
4941 }
4942
4943 /* Here to allow other parts of the shell (like the trap stuff) to
4944 freeze and unfreeze the jobs list. */
4945 int
4946 freeze_jobs_list (void)
4947 {
4948 int o;
4949
4950 o = jobs_list_frozen;
4951 jobs_list_frozen = 1;
4952 return o;
4953 }
4954
4955 int
4956 unfreeze_jobs_list (void)
4957 {
4958 int o;
4959
4960 o = jobs_list_frozen;
4961 jobs_list_frozen = 0;
4962 return 0;
4963 }
4964
4965 void
4966 set_jobs_list_frozen (int s)
4967 {
4968 jobs_list_frozen = s;
4969 }
4970
4971 int
4972 jobs_list_frozen_status (void)
4973 {
4974 return jobs_list_frozen;
4975 }
4976
4977 /* Allow or disallow job control to take place. Returns the old value
4978 of job_control. */
4979 int
4980 set_job_control (int arg)
4981 {
4982 int old;
4983
4984 old = job_control;
4985 job_control = arg;
4986
4987 if (terminal_pgrp == NO_PID && shell_tty >= 0)
4988 terminal_pgrp = tcgetpgrp (shell_tty);
4989
4990 /* If we're turning on job control we're going to want to know the shell's
4991 process group. */
4992 if (job_control != old && job_control)
4993 shell_pgrp = getpgid (0);
4994
4995 running_in_background = (terminal_pgrp != shell_pgrp);
4996
4997 #if 0
4998 if (interactive_shell == 0 && running_in_background == 0 && job_control != old)
4999 {
5000 if (job_control)
5001 initialize_job_signals ();
5002 else
5003 default_tty_job_signals ();
5004 }
5005 #endif
5006
5007 /* If we're turning on job control, reset pipeline_pgrp so make_child will
5008 put new child processes into the right pgrp */
5009 if (job_control != old && job_control)
5010 pipeline_pgrp = 0;
5011
5012 return (old);
5013 }
5014
5015 /* Turn off all traces of job control. This is run by children of the shell
5016 which are going to do shellsy things, like wait (), etc. */
5017 void
5018 without_job_control (void)
5019 {
5020 stop_making_children ();
5021 start_pipeline ();
5022 #if defined (PGRP_PIPE)
5023 sh_closepipe (pgrp_pipe);
5024 #endif
5025 delete_all_jobs (0);
5026 set_job_control (0);
5027 original_pgrp = NO_PID;
5028 }
5029
5030 /* If this shell is interactive, terminate all stopped jobs and
5031 restore the original terminal process group. This is done
5032 before the `exec' builtin calls shell_execve. */
5033 void
5034 end_job_control (void)
5035 {
5036 if (job_control)
5037 terminate_stopped_jobs ();
5038
5039 if (original_pgrp >= 0 && terminal_pgrp != original_pgrp)
5040 give_terminal_to (original_pgrp, 1);
5041
5042 if (original_pgrp >= 0 && setpgid (0, original_pgrp) == 0)
5043 shell_pgrp = original_pgrp;
5044 }
5045
5046 int
5047 job_control_active_p (void)
5048 {
5049 return (job_control && original_pgrp != shell_pgrp && shell_pgrp == terminal_pgrp);
5050 }
5051
5052 /* Restart job control by closing shell tty and reinitializing. This is
5053 called after an exec fails in an interactive shell and we do not exit. */
5054 void
5055 restart_job_control (void)
5056 {
5057 if (shell_tty != -1)
5058 close (shell_tty);
5059 initialize_job_control (0);
5060 }
5061
5062 /* Set the maximum number of background children we keep track of to NCHILD.
5063 If the caller passes NCHILD as 0 or -1, this ends up setting it to
5064 LMAXCHILD, which is initialized the first time through. */
5065 void
5066 set_maxchild (int nchild)
5067 {
5068 static int lmaxchild = -1;
5069
5070 /* Initialize once. */
5071 if (lmaxchild < 0)
5072 {
5073 errno = 0;
5074 lmaxchild = getmaxchild ();
5075 if (lmaxchild < 0 && errno == 0)
5076 lmaxchild = MAX_CHILD_MAX; /* assume unlimited */
5077 }
5078 if (lmaxchild < 0)
5079 lmaxchild = DEFAULT_CHILD_MAX;
5080
5081 /* Clamp value we set. Minimum is what Posix requires, maximum is defined
5082 above as MAX_CHILD_MAX. */
5083 if (nchild < lmaxchild)
5084 nchild = lmaxchild;
5085 else if (nchild > MAX_CHILD_MAX)
5086 nchild = MAX_CHILD_MAX;
5087
5088 js.c_childmax = nchild;
5089 }
5090
5091 /* Set the handler to run when the shell receives a SIGCHLD signal. */
5092 void
5093 set_sigchld_handler (void)
5094 {
5095 set_signal_handler (SIGCHLD, sigchld_handler);
5096 }
5097
5098 #if defined (PGRP_PIPE)
5099 /* Read from the read end of a pipe. This is how the process group leader
5100 blocks until all of the processes in a pipeline have been made. */
5101 static void
5102 pipe_read (int *pp)
5103 {
5104 char ch;
5105
5106 if (pp[1] >= 0)
5107 {
5108 close (pp[1]);
5109 pp[1] = -1;
5110 }
5111
5112 if (pp[0] >= 0)
5113 {
5114 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
5115 ;
5116 }
5117 }
5118
5119 /* Functional interface closes our local-to-job-control pipes. */
5120 void
5121 close_pgrp_pipe (void)
5122 {
5123 sh_closepipe (pgrp_pipe);
5124 }
5125
5126 void
5127 save_pgrp_pipe (int *p, int clear)
5128 {
5129 p[0] = pgrp_pipe[0];
5130 p[1] = pgrp_pipe[1];
5131 if (clear)
5132 pgrp_pipe[0] = pgrp_pipe[1] = -1;
5133 }
5134
5135 void
5136 restore_pgrp_pipe (int *p)
5137 {
5138 pgrp_pipe[0] = p[0];
5139 pgrp_pipe[1] = p[1];
5140 }
5141
5142 #endif /* PGRP_PIPE */