source: trunk/essentials/app-shells/bash/jobs.c@ 3232

Last change on this file since 3232 was 3232, checked in by bird, 18 years ago

Applied Brendan's patches.

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