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