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