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