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