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

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

Applied bash31-007

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