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