source: vendor/bash/3.1-p17/jobs.c@ 3274

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

Applied bash31-009

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