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

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

Applied bash31-008

  • Property svn:eol-style set to native
File size: 102.5 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 {
2255 old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
2256 if (old_sigint_handler == SIG_IGN)
2257 set_signal_handler (SIGINT, old_sigint_handler);
2258 }
2259
2260 termination_state = last_command_exit_value;
2261
2262 if (interactive && job_control == 0)
2263 QUIT;
2264
2265 /* If we say wait_for (), then we have a record of this child somewhere.
2266 If it and none of its peers are running, don't call waitchld(). */
2267
2268 job = NO_JOB;
2269 do
2270 {
2271 FIND_CHILD (pid, child);
2272
2273 /* If this child is part of a job, then we are really waiting for the
2274 job to finish. Otherwise, we are waiting for the child to finish.
2275 We check for JDEAD in case the job state has been set by waitchld
2276 after receipt of a SIGCHLD. */
2277 if (job == NO_JOB)
2278 job = find_job (pid, 0, NULL);
2279
2280 /* waitchld() takes care of setting the state of the job. If the job
2281 has already exited before this is called, sigchld_handler will have
2282 called waitchld and the state will be set to JDEAD. */
2283
2284 if (PRUNNING(child) || (job != NO_JOB && RUNNING (job)))
2285 {
2286#if defined (WAITPID_BROKEN) /* SCOv4 */
2287 sigset_t suspend_set;
2288 sigemptyset (&suspend_set);
2289 sigsuspend (&suspend_set);
2290#else /* !WAITPID_BROKEN */
2291# if defined (MUST_UNBLOCK_CHLD)
2292 struct sigaction act, oact;
2293 sigset_t nullset, chldset;
2294
2295 sigemptyset (&nullset);
2296 sigemptyset (&chldset);
2297 sigprocmask (SIG_SETMASK, &nullset, &chldset);
2298 act.sa_handler = SIG_DFL;
2299 sigemptyset (&act.sa_mask);
2300 sigemptyset (&oact.sa_mask);
2301 act.sa_flags = 0;
2302 sigaction (SIGCHLD, &act, &oact);
2303# endif
2304 queue_sigchld = 1;
2305 r = waitchld (pid, 1);
2306# if defined (MUST_UNBLOCK_CHLD)
2307 sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
2308 sigprocmask (SIG_SETMASK, &chldset, (sigset_t *)NULL);
2309# endif
2310 queue_sigchld = 0;
2311 if (r == -1 && errno == ECHILD && this_shell_builtin == wait_builtin)
2312 {
2313 termination_state = -1;
2314 goto wait_for_return;
2315 }
2316
2317 /* If child is marked as running, but waitpid() returns -1/ECHILD,
2318 there is something wrong. Somewhere, wait should have returned
2319 that child's pid. Mark the child as not running and the job,
2320 if it exists, as JDEAD. */
2321 if (r == -1 && errno == ECHILD)
2322 {
2323 child->running = PS_DONE;
2324 child->status = 0; /* XXX -- can't find true status */
2325 if (job != NO_JOB)
2326 {
2327 jobs[job]->state = JDEAD;
2328 js.c_reaped++;
2329 js.j_ndead++;
2330 }
2331 }
2332#endif /* WAITPID_BROKEN */
2333 }
2334
2335 /* If the shell is interactive, and job control is disabled, see
2336 if the foreground process has died due to SIGINT and jump out
2337 of the wait loop if it has. waitchld has already restored the
2338 old SIGINT signal handler. */
2339 if (interactive && job_control == 0)
2340 QUIT;
2341 }
2342 while (PRUNNING (child) || (job != NO_JOB && RUNNING (job)));
2343
2344 /* The exit state of the command is either the termination state of the
2345 child, or the termination state of the job. If a job, the status
2346 of the last child in the pipeline is the significant one. If the command
2347 or job was terminated by a signal, note that value also. */
2348 termination_state = (job != NO_JOB) ? job_exit_status (job)
2349 : process_exit_status (child->status);
2350 last_command_exit_signal = (job != NO_JOB) ? job_exit_signal (job)
2351 : process_exit_signal (child->status);
2352
2353 /* XXX */
2354 if ((job != NO_JOB && JOBSTATE (job) == JSTOPPED) || WIFSTOPPED (child->status))
2355 termination_state = 128 + WSTOPSIG (child->status);
2356
2357 if (job == NO_JOB || IS_JOBCONTROL (job))
2358 {
2359 /* XXX - under what circumstances is a job not present in the jobs
2360 table (job == NO_JOB)?
2361 1. command substitution
2362
2363 In the case of command substitution, at least, it's probably not
2364 the right thing to give the terminal to the shell's process group,
2365 even though there is code in subst.c:command_substitute to work
2366 around it.
2367
2368 Things that don't:
2369 $PROMPT_COMMAND execution
2370 process substitution
2371 */
2372#if 0
2373if (job == NO_JOB)
2374 itrace("wait_for: job == NO_JOB, giving the terminal to shell_pgrp (%ld)", (long)shell_pgrp);
2375#endif
2376
2377 give_terminal_to (shell_pgrp, 0);
2378 }
2379
2380 /* If the command did not exit cleanly, or the job is just
2381 being stopped, then reset the tty state back to what it
2382 was before this command. Reset the tty state and notify
2383 the user of the job termination only if the shell is
2384 interactive. Clean up any dead jobs in either case. */
2385 if (job != NO_JOB)
2386 {
2387 if (interactive_shell && subshell_environment == 0)
2388 {
2389 /* This used to use `child->status'. That's wrong, however, for
2390 pipelines. `child' is the first process in the pipeline. It's
2391 likely that the process we want to check for abnormal termination
2392 or stopping is the last process in the pipeline, especially if
2393 it's long-lived and the first process is short-lived. Since we
2394 know we have a job here, we can check all the processes in this
2395 job's pipeline and see if one of them stopped or terminated due
2396 to a signal. We might want to change this later to just check
2397 the last process in the pipeline. If no process exits due to a
2398 signal, S is left as the status of the last job in the pipeline. */
2399 p = jobs[job]->pipe;
2400 do
2401 {
2402 s = p->status;
2403 if (WIFSIGNALED(s) || WIFSTOPPED(s))
2404 break;
2405 p = p->next;
2406 }
2407 while (p != jobs[job]->pipe);
2408
2409 if (WIFSIGNALED (s) || WIFSTOPPED (s))
2410 {
2411 set_tty_state ();
2412
2413 /* If the current job was stopped or killed by a signal, and
2414 the user has requested it, get a possibly new window size */
2415 if (check_window_size && (job == js.j_current || IS_FOREGROUND (job)))
2416 get_new_window_size (0, (int *)0, (int *)0);
2417 }
2418 else
2419 get_tty_state ();
2420
2421 /* If job control is enabled, the job was started with job
2422 control, the job was the foreground job, and it was killed
2423 by SIGINT, then print a newline to compensate for the kernel
2424 printing the ^C without a trailing newline. */
2425 if (job_control && IS_JOBCONTROL (job) && IS_FOREGROUND (job) &&
2426 WIFSIGNALED (s) && WTERMSIG (s) == SIGINT)
2427 {
2428 /* If SIGINT is not trapped and the shell is in a for, while,
2429 or until loop, act as if the shell received SIGINT as
2430 well, so the loop can be broken. This doesn't call the
2431 SIGINT signal handler; maybe it should. */
2432 if (signal_is_trapped (SIGINT) == 0 && loop_level)
2433 ADDINTERRUPT;
2434 else
2435 {
2436 putchar ('\n');
2437 fflush (stdout);
2438 }
2439 }
2440 }
2441
2442 /* Moved here from set_job_status_and_cleanup, which is in the SIGCHLD
2443 signal handler path */
2444 if (DEADJOB (job) && IS_FOREGROUND (job) /*&& subshell_environment == 0*/)
2445 setjstatus (job);
2446
2447 /* If this job is dead, notify the user of the status. If the shell
2448 is interactive, this will display a message on the terminal. If
2449 the shell is not interactive, make sure we turn on the notify bit
2450 so we don't get an unwanted message about the job's termination,
2451 and so delete_job really clears the slot in the jobs table. */
2452 notify_and_cleanup ();
2453 }
2454
2455wait_for_return:
2456
2457 UNBLOCK_CHILD (oset);
2458
2459 /* Restore the original SIGINT signal handler before we return. */
2460 restore_sigint_handler ();
2461
2462 return (termination_state);
2463}
2464
2465/* Wait for the last process in the pipeline for JOB. Returns whatever
2466 wait_for returns: the last process's termination state or -1 if there
2467 are no unwaited-for child processes or an error occurs. */
2468int
2469wait_for_job (job)
2470 int job;
2471{
2472 pid_t pid;
2473 int r;
2474 sigset_t set, oset;
2475
2476 BLOCK_CHILD(set, oset);
2477 if (JOBSTATE (job) == JSTOPPED)
2478 internal_warning (_("wait_for_job: job %d is stopped"), job+1);
2479
2480 pid = find_last_pid (job, 0);
2481 UNBLOCK_CHILD(oset);
2482 r = wait_for (pid);
2483
2484 /* POSIX.2: we can remove the job from the jobs table if we just waited
2485 for it. */
2486 BLOCK_CHILD (set, oset);
2487 if (job != NO_JOB && jobs[job] && DEADJOB (job))
2488 jobs[job]->flags |= J_NOTIFIED;
2489 UNBLOCK_CHILD (oset);
2490
2491 return r;
2492}
2493
2494/* Print info about dead jobs, and then delete them from the list
2495 of known jobs. This does not actually delete jobs when the
2496 shell is not interactive, because the dead jobs are not marked
2497 as notified. */
2498void
2499notify_and_cleanup ()
2500{
2501 if (jobs_list_frozen)
2502 return;
2503
2504 if (interactive || interactive_shell == 0 || sourcelevel)
2505 notify_of_job_status ();
2506
2507 cleanup_dead_jobs ();
2508}
2509
2510/* Make dead jobs disappear from the jobs array without notification.
2511 This is used when the shell is not interactive. */
2512void
2513reap_dead_jobs ()
2514{
2515 mark_dead_jobs_as_notified (0);
2516 cleanup_dead_jobs ();
2517}
2518
2519/* Return the next closest (chronologically) job to JOB which is in
2520 STATE. STATE can be JSTOPPED, JRUNNING. NO_JOB is returned if
2521 there is no next recent job. */
2522static int
2523most_recent_job_in_state (job, state)
2524 int job;
2525 JOB_STATE state;
2526{
2527 register int i, result;
2528 sigset_t set, oset;
2529
2530 BLOCK_CHILD (set, oset);
2531
2532 for (result = NO_JOB, i = job - 1; i >= 0; i--)
2533 {
2534 if (jobs[i] && (JOBSTATE (i) == state))
2535 {
2536 result = i;
2537 break;
2538 }
2539 }
2540
2541 UNBLOCK_CHILD (oset);
2542
2543 return (result);
2544}
2545
2546/* Return the newest *stopped* job older than JOB, or NO_JOB if not
2547 found. */
2548static int
2549job_last_stopped (job)
2550 int job;
2551{
2552 return (most_recent_job_in_state (job, JSTOPPED));
2553}
2554
2555/* Return the newest *running* job older than JOB, or NO_JOB if not
2556 found. */
2557static int
2558job_last_running (job)
2559 int job;
2560{
2561 return (most_recent_job_in_state (job, JRUNNING));
2562}
2563
2564/* Make JOB be the current job, and make previous be useful. Must be
2565 called with SIGCHLD blocked. */
2566static void
2567set_current_job (job)
2568 int job;
2569{
2570 int candidate;
2571
2572 if (js.j_current != job)
2573 {
2574 js.j_previous = js.j_current;
2575 js.j_current = job;
2576 }
2577
2578 /* First choice for previous job is the old current job. */
2579 if (js.j_previous != js.j_current &&
2580 js.j_previous != NO_JOB &&
2581 jobs[js.j_previous] &&
2582 STOPPED (js.j_previous))
2583 return;
2584
2585 /* Second choice: Newest stopped job that is older than
2586 the current job. */
2587 candidate = NO_JOB;
2588 if (STOPPED (js.j_current))
2589 {
2590 candidate = job_last_stopped (js.j_current);
2591
2592 if (candidate != NO_JOB)
2593 {
2594 js.j_previous = candidate;
2595 return;
2596 }
2597 }
2598
2599 /* If we get here, there is either only one stopped job, in which case it is
2600 the current job and the previous job should be set to the newest running
2601 job, or there are only running jobs and the previous job should be set to
2602 the newest running job older than the current job. We decide on which
2603 alternative to use based on whether or not JOBSTATE(js.j_current) is
2604 JSTOPPED. */
2605
2606 candidate = RUNNING (js.j_current) ? job_last_running (js.j_current)
2607 : job_last_running (js.j_jobslots);
2608
2609 if (candidate != NO_JOB)
2610 {
2611 js.j_previous = candidate;
2612 return;
2613 }
2614
2615 /* There is only a single job, and it is both `+' and `-'. */
2616 js.j_previous = js.j_current;
2617}
2618
2619/* Make current_job be something useful, if it isn't already. */
2620
2621/* Here's the deal: The newest non-running job should be `+', and the
2622 next-newest non-running job should be `-'. If there is only a single
2623 stopped job, the js.j_previous is the newest non-running job. If there
2624 are only running jobs, the newest running job is `+' and the
2625 next-newest running job is `-'. Must be called with SIGCHLD blocked. */
2626
2627static void
2628reset_current ()
2629{
2630 int candidate;
2631
2632 if (js.j_jobslots && js.j_current != NO_JOB && jobs[js.j_current] && STOPPED (js.j_current))
2633 candidate = js.j_current;
2634 else
2635 {
2636 candidate = NO_JOB;
2637
2638 /* First choice: the previous job. */
2639 if (js.j_previous != NO_JOB && jobs[js.j_previous] && STOPPED (js.j_previous))
2640 candidate = js.j_previous;
2641
2642 /* Second choice: the most recently stopped job. */
2643 if (candidate == NO_JOB)
2644 candidate = job_last_stopped (js.j_jobslots);
2645
2646 /* Third choice: the newest running job. */
2647 if (candidate == NO_JOB)
2648 candidate = job_last_running (js.j_jobslots);
2649 }
2650
2651 /* If we found a job to use, then use it. Otherwise, there
2652 are no jobs period. */
2653 if (candidate != NO_JOB)
2654 set_current_job (candidate);
2655 else
2656 js.j_current = js.j_previous = NO_JOB;
2657}
2658
2659/* Set up the job structures so we know the job and its processes are
2660 all running. */
2661static void
2662set_job_running (job)
2663 int job;
2664{
2665 register PROCESS *p;
2666
2667 /* Each member of the pipeline is now running. */
2668 p = jobs[job]->pipe;
2669
2670 do
2671 {
2672 if (WIFSTOPPED (p->status))
2673 p->running = PS_RUNNING; /* XXX - could be PS_STOPPED */
2674 p = p->next;
2675 }
2676 while (p != jobs[job]->pipe);
2677
2678 /* This means that the job is running. */
2679 JOBSTATE (job) = JRUNNING;
2680}
2681
2682/* Start a job. FOREGROUND if non-zero says to do that. Otherwise,
2683 start the job in the background. JOB is a zero-based index into
2684 JOBS. Returns -1 if it is unable to start a job, and the return
2685 status of the job otherwise. */
2686int
2687start_job (job, foreground)
2688 int job, foreground;
2689{
2690 register PROCESS *p;
2691 int already_running;
2692 sigset_t set, oset;
2693 char *wd, *s;
2694 static TTYSTRUCT save_stty;
2695
2696 BLOCK_CHILD (set, oset);
2697
2698 if (DEADJOB (job))
2699 {
2700 internal_error (_("%s: job has terminated"), this_command_name);
2701 UNBLOCK_CHILD (oset);
2702 return (-1);
2703 }
2704
2705 already_running = RUNNING (job);
2706
2707 if (foreground == 0 && already_running)
2708 {
2709 internal_error (_("%s: job %d already in background"), this_command_name, job + 1);
2710 UNBLOCK_CHILD (oset);
2711 return (0); /* XPG6/SUSv3 says this is not an error */
2712 }
2713
2714 wd = current_working_directory ();
2715
2716 /* You don't know about the state of this job. Do you? */
2717 jobs[job]->flags &= ~J_NOTIFIED;
2718
2719 if (foreground)
2720 {
2721 set_current_job (job);
2722 jobs[job]->flags |= J_FOREGROUND;
2723 }
2724
2725 /* Tell the outside world what we're doing. */
2726 p = jobs[job]->pipe;
2727
2728 if (foreground == 0)
2729 {
2730 /* POSIX.2 says `bg' doesn't give any indication about current or
2731 previous job. */
2732 if (posixly_correct == 0)
2733 s = (job == js.j_current) ? "+ ": ((job == js.j_previous) ? "- " : " ");
2734 else
2735 s = " ";
2736 printf ("[%d]%s", job + 1, s);
2737 }
2738
2739 do
2740 {
2741 printf ("%s%s",
2742 p->command ? p->command : "",
2743 p->next != jobs[job]->pipe? " | " : "");
2744 p = p->next;
2745 }
2746 while (p != jobs[job]->pipe);
2747
2748 if (foreground == 0)
2749 printf (" &");
2750
2751 if (strcmp (wd, jobs[job]->wd) != 0)
2752 printf (" (wd: %s)", polite_directory_format (jobs[job]->wd));
2753
2754 printf ("\n");
2755
2756 /* Run the job. */
2757 if (already_running == 0)
2758 set_job_running (job);
2759
2760 /* Save the tty settings before we start the job in the foreground. */
2761 if (foreground)
2762 {
2763 get_tty_state ();
2764 save_stty = shell_tty_info;
2765 /* Give the terminal to this job. */
2766 if (IS_JOBCONTROL (job))
2767 give_terminal_to (jobs[job]->pgrp, 0);
2768 }
2769 else
2770 jobs[job]->flags &= ~J_FOREGROUND;
2771
2772 /* If the job is already running, then don't bother jump-starting it. */
2773 if (already_running == 0)
2774 {
2775 jobs[job]->flags |= J_NOTIFIED;
2776 killpg (jobs[job]->pgrp, SIGCONT);
2777 }
2778
2779 if (foreground)
2780 {
2781 pid_t pid;
2782 int s;
2783
2784 pid = find_last_pid (job, 0);
2785 UNBLOCK_CHILD (oset);
2786 s = wait_for (pid);
2787 shell_tty_info = save_stty;
2788 set_tty_state ();
2789 return (s);
2790 }
2791 else
2792 {
2793 reset_current ();
2794 UNBLOCK_CHILD (oset);
2795 return (0);
2796 }
2797}
2798
2799/* Give PID SIGNAL. This determines what job the pid belongs to (if any).
2800 If PID does belong to a job, and the job is stopped, then CONTinue the
2801 job after giving it SIGNAL. Returns -1 on failure. If GROUP is non-null,
2802 then kill the process group associated with PID. */
2803int
2804kill_pid (pid, sig, group)
2805 pid_t pid;
2806 int sig, group;
2807{
2808 register PROCESS *p;
2809 int job, result, negative;
2810 sigset_t set, oset;
2811
2812 if (pid < -1)
2813 {
2814 pid = -pid;
2815 group = negative = 1;
2816 }
2817 else
2818 negative = 0;
2819
2820 result = EXECUTION_SUCCESS;
2821 if (group)
2822 {
2823 BLOCK_CHILD (set, oset);
2824 p = find_pipeline (pid, 0, &job);
2825
2826 if (job != NO_JOB)
2827 {
2828 jobs[job]->flags &= ~J_NOTIFIED;
2829
2830 /* Kill process in backquotes or one started without job control? */
2831
2832 /* If we're passed a pid < -1, just call killpg and see what happens */
2833 if (negative && jobs[job]->pgrp == shell_pgrp)
2834 result = killpg (pid, sig);
2835 /* If we're killing using job control notification, for example,
2836 without job control active, we have to do things ourselves. */
2837 else if (jobs[job]->pgrp == shell_pgrp)
2838 {
2839 p = jobs[job]->pipe;
2840 do
2841 {
2842 if (PALIVE (p) == 0)
2843 continue; /* avoid pid recycling problem */
2844 kill (p->pid, sig);
2845 if (PEXITED (p) && (sig == SIGTERM || sig == SIGHUP))
2846 kill (p->pid, SIGCONT);
2847 p = p->next;
2848 }
2849 while (p != jobs[job]->pipe);
2850 }
2851 else
2852 {
2853 result = killpg (jobs[job]->pgrp, sig);
2854 if (p && STOPPED (job) && (sig == SIGTERM || sig == SIGHUP))
2855 killpg (jobs[job]->pgrp, SIGCONT);
2856 /* If we're continuing a stopped job via kill rather than bg or
2857 fg, emulate the `bg' behavior. */
2858 if (p && STOPPED (job) && (sig == SIGCONT))
2859 {
2860 set_job_running (job);
2861 jobs[job]->flags &= ~J_FOREGROUND;
2862 jobs[job]->flags |= J_NOTIFIED;
2863 }
2864 }
2865 }
2866 else
2867 result = killpg (pid, sig);
2868
2869 UNBLOCK_CHILD (oset);
2870 }
2871 else
2872 result = kill (pid, sig);
2873
2874 return (result);
2875}
2876
2877/* sigchld_handler () flushes at least one of the children that we are
2878 waiting for. It gets run when we have gotten a SIGCHLD signal. */
2879static sighandler
2880sigchld_handler (sig)
2881 int sig;
2882{
2883 int n, oerrno;
2884
2885 oerrno = errno;
2886 REINSTALL_SIGCHLD_HANDLER;
2887 sigchld++;
2888 n = 0;
2889 if (queue_sigchld == 0)
2890 n = waitchld (-1, 0);
2891 errno = oerrno;
2892 SIGRETURN (n);
2893}
2894
2895/* waitchld() reaps dead or stopped children. It's called by wait_for and
2896 sigchld_handler, and runs until there aren't any children terminating any
2897 more.
2898 If BLOCK is 1, this is to be a blocking wait for a single child, although
2899 an arriving SIGCHLD could cause the wait to be non-blocking. It returns
2900 the number of children reaped, or -1 if there are no unwaited-for child
2901 processes. */
2902static int
2903waitchld (wpid, block)
2904 pid_t wpid;
2905 int block;
2906{
2907 WAIT status;
2908 PROCESS *child;
2909 pid_t pid;
2910 int call_set_current, last_stopped_job, job, children_exited, waitpid_flags;
2911 static int wcontinued = WCONTINUED; /* run-time fix for glibc problem */
2912
2913 call_set_current = children_exited = 0;
2914 last_stopped_job = NO_JOB;
2915
2916 do
2917 {
2918 /* We don't want to be notified about jobs stopping if job control
2919 is not active. XXX - was interactive_shell instead of job_control */
2920 waitpid_flags = (job_control && subshell_environment == 0)
2921 ? (WUNTRACED|wcontinued)
2922 : 0;
2923 if (sigchld || block == 0)
2924 waitpid_flags |= WNOHANG;
2925 pid = WAITPID (-1, &status, waitpid_flags);
2926
2927 /* WCONTINUED may be rejected by waitpid as invalid even when defined */
2928 if (wcontinued && pid < 0 && errno == EINVAL)
2929 {
2930 wcontinued = 0;
2931 continue; /* jump back to the test and retry without WCONTINUED */
2932 }
2933
2934 /* The check for WNOHANG is to make sure we decrement sigchld only
2935 if it was non-zero before we called waitpid. */
2936 if (sigchld > 0 && (waitpid_flags & WNOHANG))
2937 sigchld--;
2938
2939 /* If waitpid returns -1 with errno == ECHILD, there are no more
2940 unwaited-for child processes of this shell. */
2941 if (pid < 0 && errno == ECHILD)
2942 {
2943 if (children_exited == 0)
2944 return -1;
2945 else
2946 break;
2947 }
2948
2949 /* If waitpid returns 0, there are running children. If it returns -1,
2950 the only other error POSIX says it can return is EINTR. */
2951 if (pid <= 0)
2952 continue; /* jumps right to the test */
2953
2954 /* children_exited is used to run traps on SIGCHLD. We don't want to
2955 run the trap if a process is just being continued. */
2956 if (WIFCONTINUED(status) == 0)
2957 children_exited++;
2958
2959 /* Locate our PROCESS for this pid. */
2960 child = find_process (pid, 1, &job); /* want living procs only */
2961
2962 /* It is not an error to have a child terminate that we did
2963 not have a record of. This child could have been part of
2964 a pipeline in backquote substitution. Even so, I'm not
2965 sure child is ever non-zero. */
2966 if (child == 0)
2967 continue;
2968
2969 /* Remember status, and whether or not the process is running. */
2970 child->status = status;
2971 child->running = WIFCONTINUED(status) ? PS_RUNNING : PS_DONE;
2972
2973 if (PEXITED (child))
2974 {
2975 js.c_totreaped++;
2976 if (job != NO_JOB)
2977 js.c_reaped++;
2978 }
2979
2980 if (job == NO_JOB)
2981 continue;
2982
2983 call_set_current += set_job_status_and_cleanup (job);
2984
2985 if (STOPPED (job))
2986 last_stopped_job = job;
2987 else if (DEADJOB (job) && last_stopped_job == job)
2988 last_stopped_job = NO_JOB;
2989 }
2990 while ((sigchld || block == 0) && pid > (pid_t)0);
2991
2992 /* If a job was running and became stopped, then set the current
2993 job. Otherwise, don't change a thing. */
2994 if (call_set_current)
2995 {
2996 if (last_stopped_job != NO_JOB)
2997 set_current_job (last_stopped_job);
2998 else
2999 reset_current ();
3000 }
3001
3002 /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
3003 if (job_control && signal_is_trapped (SIGCHLD) && children_exited &&
3004 trap_list[SIGCHLD] != (char *)IGNORE_SIG)
3005 run_sigchld_trap (children_exited);
3006
3007 /* We have successfully recorded the useful information about this process
3008 that has just changed state. If we notify asynchronously, and the job
3009 that this process belongs to is no longer running, then notify the user
3010 of that fact now. */
3011 if (asynchronous_notification && interactive)
3012 notify_of_job_status ();
3013
3014 return (children_exited);
3015}
3016
3017/* Set the status of JOB and perform any necessary cleanup if the job is
3018 marked as JDEAD.
3019
3020 Currently, the cleanup activity is restricted to handling any SIGINT
3021 received while waiting for a foreground job to finish. */
3022static int
3023set_job_status_and_cleanup (job)
3024 int job;
3025{
3026 PROCESS *child;
3027 int tstatus, job_state, any_stopped, any_tstped, call_set_current;
3028 SigHandler *temp_handler;
3029
3030 child = jobs[job]->pipe;
3031 jobs[job]->flags &= ~J_NOTIFIED;
3032
3033 call_set_current = 0;
3034
3035 /*
3036 * COMPUTE JOB STATUS
3037 */
3038
3039 /* If all children are not running, but any of them is stopped, then
3040 the job is stopped, not dead. */
3041 job_state = any_stopped = any_tstped = 0;
3042 do
3043 {
3044 job_state |= PRUNNING (child);
3045#if 0
3046 if (PEXITED (child) && (WIFSTOPPED (child->status)))
3047#else
3048 /* Only checking for WIFSTOPPED now, not for PS_DONE */
3049 if (PSTOPPED (child))
3050#endif
3051 {
3052 any_stopped = 1;
3053 any_tstped |= interactive && job_control &&
3054 (WSTOPSIG (child->status) == SIGTSTP);
3055 }
3056 child = child->next;
3057 }
3058 while (child != jobs[job]->pipe);
3059
3060 /* If job_state != 0, the job is still running, so don't bother with
3061 setting the process exit status and job state unless we're
3062 transitioning from stopped to running. */
3063 if (job_state != 0 && JOBSTATE(job) != JSTOPPED)
3064 return 0;
3065
3066 /*
3067 * SET JOB STATUS
3068 */
3069
3070 /* The job is either stopped or dead. Set the state of the job accordingly. */
3071 if (any_stopped)
3072 {
3073 jobs[job]->state = JSTOPPED;
3074 jobs[job]->flags &= ~J_FOREGROUND;
3075 call_set_current++;
3076 /* Suspending a job with SIGTSTP breaks all active loops. */
3077 if (any_tstped && loop_level)
3078 breaking = loop_level;
3079 }
3080 else if (job_state != 0) /* was stopped, now running */
3081 {
3082 jobs[job]->state = JRUNNING;
3083 call_set_current++;
3084 }
3085 else
3086 {
3087 jobs[job]->state = JDEAD;
3088 js.j_ndead++;
3089
3090#if 0
3091 if (IS_FOREGROUND (job))
3092 setjstatus (job);
3093#endif
3094
3095 /* If this job has a cleanup function associated with it, call it
3096 with `cleanarg' as the single argument, then set the function
3097 pointer to NULL so it is not inadvertently called twice. The
3098 cleanup function is responsible for deallocating cleanarg. */
3099 if (jobs[job]->j_cleanup)
3100 {
3101 (*jobs[job]->j_cleanup) (jobs[job]->cleanarg);
3102 jobs[job]->j_cleanup = (sh_vptrfunc_t *)NULL;
3103 }
3104 }
3105
3106 /*
3107 * CLEANUP
3108 *
3109 * Currently, we just do special things if we got a SIGINT while waiting
3110 * for a foreground job to complete
3111 */
3112
3113 if (JOBSTATE (job) == JDEAD)
3114 {
3115 /* If we're running a shell script and we get a SIGINT with a
3116 SIGINT trap handler, but the foreground job handles it and
3117 does not exit due to SIGINT, run the trap handler but do not
3118 otherwise act as if we got the interrupt. */
3119 if (wait_sigint_received && interactive_shell == 0 &&
3120 WIFSIGNALED (child->status) == 0 && IS_FOREGROUND (job) &&
3121 signal_is_trapped (SIGINT))
3122 {
3123 int old_frozen;
3124 wait_sigint_received = 0;
3125 last_command_exit_value = process_exit_status (child->status);
3126
3127 old_frozen = jobs_list_frozen;
3128 jobs_list_frozen = 1;
3129 tstatus = maybe_call_trap_handler (SIGINT);
3130 jobs_list_frozen = old_frozen;
3131 }
3132
3133 /* If the foreground job is killed by SIGINT when job control is not
3134 active, we need to perform some special handling.
3135
3136 The check of wait_sigint_received is a way to determine if the
3137 SIGINT came from the keyboard (in which case the shell has already
3138 seen it, and wait_sigint_received is non-zero, because keyboard
3139 signals are sent to process groups) or via kill(2) to the foreground
3140 process by another process (or itself). If the shell did receive the
3141 SIGINT, it needs to perform normal SIGINT processing. */
3142 else if (wait_sigint_received && (WTERMSIG (child->status) == SIGINT) &&
3143 IS_FOREGROUND (job) && IS_JOBCONTROL (job) == 0)
3144 {
3145 int old_frozen;
3146
3147 wait_sigint_received = 0;
3148
3149 /* If SIGINT is trapped, set the exit status so that the trap
3150 handler can see it. */
3151 if (signal_is_trapped (SIGINT))
3152 last_command_exit_value = process_exit_status (child->status);
3153
3154 /* If the signal is trapped, let the trap handler get it no matter
3155 what and simply return if the trap handler returns.
3156 maybe_call_trap_handler() may cause dead jobs to be removed from
3157 the job table because of a call to execute_command. We work
3158 around this by setting JOBS_LIST_FROZEN. */
3159 old_frozen = jobs_list_frozen;
3160 jobs_list_frozen = 1;
3161 tstatus = maybe_call_trap_handler (SIGINT);
3162 jobs_list_frozen = old_frozen;
3163 if (tstatus == 0 && old_sigint_handler != INVALID_SIGNAL_HANDLER)
3164 {
3165 /* wait_sigint_handler () has already seen SIGINT and
3166 allowed the wait builtin to jump out. We need to
3167 call the original SIGINT handler, if necessary. If
3168 the original handler is SIG_DFL, we need to resend
3169 the signal to ourselves. */
3170
3171 temp_handler = old_sigint_handler;
3172
3173 /* Bogus. If we've reset the signal handler as the result
3174 of a trap caught on SIGINT, then old_sigint_handler
3175 will point to trap_handler, which now knows nothing about
3176 SIGINT (if we reset the sighandler to the default).
3177 In this case, we have to fix things up. What a crock. */
3178 if (temp_handler == trap_handler && signal_is_trapped (SIGINT) == 0)
3179 temp_handler = trap_to_sighandler (SIGINT);
3180 restore_sigint_handler ();
3181 if (temp_handler == SIG_DFL)
3182 termination_unwind_protect (SIGINT);
3183 else if (temp_handler != SIG_IGN)
3184 (*temp_handler) (SIGINT);
3185 }
3186 }
3187 }
3188
3189 return call_set_current;
3190}
3191
3192/* Build the array of values for the $PIPESTATUS variable from the set of
3193 exit statuses of all processes in the job J. */
3194static void
3195setjstatus (j)
3196 int j;
3197{
3198#if defined (ARRAY_VARS)
3199 register int i;
3200 register PROCESS *p;
3201
3202 for (i = 1, p = jobs[j]->pipe; p->next != jobs[j]->pipe; p = p->next, i++)
3203 ;
3204 i++;
3205 if (statsize < i)
3206 {
3207 pstatuses = (int *)xrealloc (pstatuses, i * sizeof (int));
3208 statsize = i;
3209 }
3210 i = 0;
3211 p = jobs[j]->pipe;
3212 do
3213 {
3214 pstatuses[i++] = process_exit_status (p->status);
3215 p = p->next;
3216 }
3217 while (p != jobs[j]->pipe);
3218
3219 pstatuses[i] = -1; /* sentinel */
3220 set_pipestatus_array (pstatuses, i);
3221#endif
3222}
3223
3224static void
3225run_sigchld_trap (nchild)
3226 int nchild;
3227{
3228 char *trap_command;
3229 int i;
3230
3231 /* Turn off the trap list during the call to parse_and_execute ()
3232 to avoid potentially infinite recursive calls. Preserve the
3233 values of last_command_exit_value, last_made_pid, and the_pipeline
3234 around the execution of the trap commands. */
3235 trap_command = savestring (trap_list[SIGCHLD]);
3236
3237 begin_unwind_frame ("SIGCHLD trap");
3238 unwind_protect_int (last_command_exit_value);
3239 unwind_protect_int (last_command_exit_signal);
3240 unwind_protect_var (last_made_pid);
3241 unwind_protect_int (interrupt_immediately);
3242 unwind_protect_int (jobs_list_frozen);
3243 unwind_protect_pointer (the_pipeline);
3244 unwind_protect_pointer (subst_assign_varlist);
3245
3246 /* We have to add the commands this way because they will be run
3247 in reverse order of adding. We don't want maybe_set_sigchld_trap ()
3248 to reference freed memory. */
3249 add_unwind_protect (xfree, trap_command);
3250 add_unwind_protect (maybe_set_sigchld_trap, trap_command);
3251
3252 subst_assign_varlist = (WORD_LIST *)NULL;
3253 the_pipeline = (PROCESS *)NULL;
3254
3255 restore_default_signal (SIGCHLD);
3256 jobs_list_frozen = 1;
3257 for (i = 0; i < nchild; i++)
3258 {
3259 interrupt_immediately = 1;
3260 parse_and_execute (savestring (trap_command), "trap", SEVAL_NOHIST|SEVAL_RESETLINE);
3261 }
3262
3263 run_unwind_frame ("SIGCHLD trap");
3264}
3265
3266/* Function to call when you want to notify people of changes
3267 in job status. This prints out all jobs which are pending
3268 notification to stderr, and marks those printed as already
3269 notified, thus making them candidates for cleanup. */
3270static void
3271notify_of_job_status ()
3272{
3273 register int job, termsig;
3274 char *dir;
3275 sigset_t set, oset;
3276 WAIT s;
3277
3278 if (jobs == 0 || js.j_jobslots == 0)
3279 return;
3280
3281 if (old_ttou != 0)
3282 {
3283 sigemptyset (&set);
3284 sigaddset (&set, SIGCHLD);
3285 sigaddset (&set, SIGTTOU);
3286 sigemptyset (&oset);
3287 sigprocmask (SIG_BLOCK, &set, &oset);
3288 }
3289 else
3290 queue_sigchld++;
3291
3292 /* XXX could use js.j_firstj here */
3293 for (job = 0, dir = (char *)NULL; job < js.j_jobslots; job++)
3294 {
3295 if (jobs[job] && IS_NOTIFIED (job) == 0)
3296 {
3297 s = raw_job_exit_status (job);
3298 termsig = WTERMSIG (s);
3299
3300 /* POSIX.2 says we have to hang onto the statuses of at most the
3301 last CHILD_MAX background processes if the shell is running a
3302 script. If the shell is running a script, either from a file
3303 or standard input, don't print anything unless the job was
3304 killed by a signal. */
3305 if (startup_state == 0 && WIFSIGNALED (s) == 0 &&
3306 ((DEADJOB (job) && IS_FOREGROUND (job) == 0) || STOPPED (job)))
3307 continue;
3308
3309#if 0
3310 /* If job control is disabled, don't print the status messages.
3311 Mark dead jobs as notified so that they get cleaned up. If
3312 startup_state == 2, we were started to run `-c command', so
3313 don't print anything. */
3314 if ((job_control == 0 && interactive_shell) || startup_state == 2)
3315#else
3316 /* If job control is disabled, don't print the status messages.
3317 Mark dead jobs as notified so that they get cleaned up. If
3318 startup_state == 2 and subshell_environment has the
3319 SUBSHELL_COMSUB bit turned on, we were started to run a command
3320 substitution, so don't print anything. */
3321 if ((job_control == 0 && interactive_shell) ||
3322 (startup_state == 2 && (subshell_environment & SUBSHELL_COMSUB)))
3323#endif
3324 {
3325 /* POSIX.2 compatibility: if the shell is not interactive,
3326 hang onto the job corresponding to the last asynchronous
3327 pid until the user has been notified of its status or does
3328 a `wait'. */
3329 if (DEADJOB (job) && (interactive_shell || (find_last_pid (job, 0) != last_asynchronous_pid)))
3330 jobs[job]->flags |= J_NOTIFIED;
3331 continue;
3332 }
3333
3334 /* Print info on jobs that are running in the background,
3335 and on foreground jobs that were killed by anything
3336 except SIGINT (and possibly SIGPIPE). */
3337 switch (JOBSTATE (job))
3338 {
3339 case JDEAD:
3340 if (interactive_shell == 0 && termsig && WIFSIGNALED (s) &&
3341 termsig != SIGINT &&
3342#if defined (DONT_REPORT_SIGPIPE)
3343 termsig != SIGPIPE &&
3344#endif
3345 signal_is_trapped (termsig) == 0)
3346 {
3347 /* Don't print `0' for a line number. */
3348 fprintf (stderr, "%s: line %d: ", get_name_for_error (), (line_number == 0) ? 1 : line_number);
3349 pretty_print_job (job, JLIST_NONINTERACTIVE, stderr);
3350 }
3351 else if (IS_FOREGROUND (job))
3352 {
3353#if !defined (DONT_REPORT_SIGPIPE)
3354 if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
3355#else
3356 if (termsig && WIFSIGNALED (s) && termsig != SIGINT && termsig != SIGPIPE)
3357#endif
3358 {
3359 fprintf (stderr, "%s", j_strsignal (termsig));
3360
3361 if (WIFCORED (s))
3362 fprintf (stderr, " (core dumped)");
3363
3364 fprintf (stderr, "\n");
3365 }
3366 }
3367 else if (job_control) /* XXX job control test added */
3368 {
3369 if (dir == 0)
3370 dir = current_working_directory ();
3371 pretty_print_job (job, JLIST_STANDARD, stderr);
3372 if (dir && strcmp (dir, jobs[job]->wd) != 0)
3373 fprintf (stderr,
3374 "(wd now: %s)\n", polite_directory_format (dir));
3375 }
3376
3377 jobs[job]->flags |= J_NOTIFIED;
3378 break;
3379
3380 case JSTOPPED:
3381 fprintf (stderr, "\n");
3382 if (dir == 0)
3383 dir = current_working_directory ();
3384 pretty_print_job (job, JLIST_STANDARD, stderr);
3385 if (dir && (strcmp (dir, jobs[job]->wd) != 0))
3386 fprintf (stderr,
3387 "(wd now: %s)\n", polite_directory_format (dir));
3388 jobs[job]->flags |= J_NOTIFIED;
3389 break;
3390
3391 case JRUNNING:
3392 case JMIXED:
3393 break;
3394
3395 default:
3396 programming_error ("notify_of_job_status");
3397 }
3398 }
3399 }
3400 if (old_ttou != 0)
3401 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
3402 else
3403 queue_sigchld--;
3404}
3405
3406/* Initialize the job control mechanism, and set up the tty stuff. */
3407int
3408initialize_job_control (force)
3409 int force;
3410{
3411 shell_pgrp = getpgid (0);
3412
3413 if (shell_pgrp == -1)
3414 {
3415 sys_error ("initialize_job_control: getpgrp failed");
3416 exit (1);
3417 }
3418
3419 /* We can only have job control if we are interactive. */
3420 if (interactive == 0)
3421 {
3422 job_control = 0;
3423 original_pgrp = NO_PID;
3424 shell_tty = fileno (stderr);
3425 }
3426 else
3427 {
3428 /* Get our controlling terminal. If job_control is set, or
3429 interactive is set, then this is an interactive shell no
3430 matter where fd 2 is directed. */
3431 shell_tty = dup (fileno (stderr)); /* fd 2 */
3432
3433 shell_tty = move_to_high_fd (shell_tty, 1, -1);
3434
3435 /* Compensate for a bug in systems that compiled the BSD
3436 rlogind with DEBUG defined, like NeXT and Alliant. */
3437 if (shell_pgrp == 0)
3438 {
3439 shell_pgrp = getpid ();
3440 setpgid (0, shell_pgrp);
3441 tcsetpgrp (shell_tty, shell_pgrp);
3442 }
3443
3444 while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
3445 {
3446 if (shell_pgrp != terminal_pgrp)
3447 {
3448 SigHandler *ottin;
3449
3450 ottin = set_signal_handler(SIGTTIN, SIG_DFL);
3451 kill (0, SIGTTIN);
3452 set_signal_handler (SIGTTIN, ottin);
3453 continue;
3454 }
3455 break;
3456 }
3457
3458 /* Make sure that we are using the new line discipline. */
3459 if (set_new_line_discipline (shell_tty) < 0)
3460 {
3461 sys_error ("initialize_job_control: line discipline");
3462 job_control = 0;
3463 }
3464 else
3465 {
3466 original_pgrp = shell_pgrp;
3467 shell_pgrp = getpid ();
3468
3469 if ((original_pgrp != shell_pgrp) && (setpgid (0, shell_pgrp) < 0))
3470 {
3471 sys_error ("initialize_job_control: setpgid");
3472 shell_pgrp = original_pgrp;
3473 }
3474
3475 job_control = 1;
3476
3477 /* If (and only if) we just set our process group to our pid,
3478 thereby becoming a process group leader, and the terminal
3479 is not in the same process group as our (new) process group,
3480 then set the terminal's process group to our (new) process
3481 group. If that fails, set our process group back to what it
3482 was originally (so we can still read from the terminal) and
3483 turn off job control. */
3484 if (shell_pgrp != original_pgrp && shell_pgrp != terminal_pgrp)
3485 {
3486 if (give_terminal_to (shell_pgrp, 0) < 0)
3487 {
3488 setpgid (0, original_pgrp);
3489 shell_pgrp = original_pgrp;
3490 job_control = 0;
3491 }
3492 }
3493 }
3494 if (job_control == 0)
3495 internal_error (_("no job control in this shell"));
3496 }
3497
3498 if (shell_tty != fileno (stderr))
3499 SET_CLOSE_ON_EXEC (shell_tty);
3500
3501 set_signal_handler (SIGCHLD, sigchld_handler);
3502
3503 change_flag ('m', job_control ? '-' : '+');
3504
3505 if (interactive)
3506 get_tty_state ();
3507
3508 if (js.c_childmax < 0)
3509 js.c_childmax = getmaxchild ();
3510 if (js.c_childmax < 0)
3511 js.c_childmax = DEFAULT_CHILD_MAX;
3512
3513 return job_control;
3514}
3515
3516#ifdef DEBUG
3517void
3518debug_print_pgrps ()
3519{
3520 itrace("original_pgrp = %ld shell_pgrp = %ld terminal_pgrp = %ld",
3521 (long)original_pgrp, (long)shell_pgrp, (long)terminal_pgrp);
3522 itrace("tcgetpgrp(%d) -> %ld, getpgid(0) -> %ld",
3523 shell_tty, (long)tcgetpgrp (shell_tty), (long)getpgid(0));
3524}
3525#endif
3526
3527/* Set the line discipline to the best this system has to offer.
3528 Return -1 if this is not possible. */
3529static int
3530set_new_line_discipline (tty)
3531 int tty;
3532{
3533#if defined (NEW_TTY_DRIVER)
3534 int ldisc;
3535
3536 if (ioctl (tty, TIOCGETD, &ldisc) < 0)
3537 return (-1);
3538
3539 if (ldisc != NTTYDISC)
3540 {
3541 ldisc = NTTYDISC;
3542
3543 if (ioctl (tty, TIOCSETD, &ldisc) < 0)
3544 return (-1);
3545 }
3546 return (0);
3547#endif /* NEW_TTY_DRIVER */
3548
3549#if defined (TERMIO_TTY_DRIVER)
3550# if defined (TERMIO_LDISC) && (NTTYDISC)
3551 if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
3552 return (-1);
3553
3554 if (shell_tty_info.c_line != NTTYDISC)
3555 {
3556 shell_tty_info.c_line = NTTYDISC;
3557 if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
3558 return (-1);
3559 }
3560# endif /* TERMIO_LDISC && NTTYDISC */
3561 return (0);
3562#endif /* TERMIO_TTY_DRIVER */
3563
3564#if defined (TERMIOS_TTY_DRIVER)
3565# if defined (TERMIOS_LDISC) && defined (NTTYDISC)
3566 if (tcgetattr (tty, &shell_tty_info) < 0)
3567 return (-1);
3568
3569 if (shell_tty_info.c_line != NTTYDISC)
3570 {
3571 shell_tty_info.c_line = NTTYDISC;
3572 if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
3573 return (-1);
3574 }
3575# endif /* TERMIOS_LDISC && NTTYDISC */
3576 return (0);
3577#endif /* TERMIOS_TTY_DRIVER */
3578
3579#if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
3580 return (-1);
3581#endif
3582}
3583
3584/* Setup this shell to handle C-C, etc. */
3585void
3586initialize_job_signals ()
3587{
3588 if (interactive)
3589 {
3590 set_signal_handler (SIGINT, sigint_sighandler);
3591 set_signal_handler (SIGTSTP, SIG_IGN);
3592 set_signal_handler (SIGTTOU, SIG_IGN);
3593 set_signal_handler (SIGTTIN, SIG_IGN);
3594 }
3595 else if (job_control)
3596 {
3597 old_tstp = set_signal_handler (SIGTSTP, sigstop_sighandler);
3598 old_ttin = set_signal_handler (SIGTTIN, sigstop_sighandler);
3599 old_ttou = set_signal_handler (SIGTTOU, sigstop_sighandler);
3600 }
3601 /* Leave these things alone for non-interactive shells without job
3602 control. */
3603}
3604
3605/* Here we handle CONT signals. */
3606static sighandler
3607sigcont_sighandler (sig)
3608 int sig;
3609{
3610 initialize_job_signals ();
3611 set_signal_handler (SIGCONT, old_cont);
3612 kill (getpid (), SIGCONT);
3613
3614 SIGRETURN (0);
3615}
3616
3617/* Here we handle stop signals while we are running not as a login shell. */
3618static sighandler
3619sigstop_sighandler (sig)
3620 int sig;
3621{
3622 set_signal_handler (SIGTSTP, old_tstp);
3623 set_signal_handler (SIGTTOU, old_ttou);
3624 set_signal_handler (SIGTTIN, old_ttin);
3625
3626 old_cont = set_signal_handler (SIGCONT, sigcont_sighandler);
3627
3628 give_terminal_to (shell_pgrp, 0);
3629
3630 kill (getpid (), sig);
3631
3632 SIGRETURN (0);
3633}
3634
3635/* Give the terminal to PGRP. */
3636int
3637give_terminal_to (pgrp, force)
3638 pid_t pgrp;
3639 int force;
3640{
3641 sigset_t set, oset;
3642 int r;
3643
3644 r = 0;
3645 if (job_control || force)
3646 {
3647 sigemptyset (&set);
3648 sigaddset (&set, SIGTTOU);
3649 sigaddset (&set, SIGTTIN);
3650 sigaddset (&set, SIGTSTP);
3651 sigaddset (&set, SIGCHLD);
3652 sigemptyset (&oset);
3653 sigprocmask (SIG_BLOCK, &set, &oset);
3654
3655 if (tcsetpgrp (shell_tty, pgrp) < 0)
3656 {
3657 /* Maybe we should print an error message? */
3658#if 0
3659 sys_error ("tcsetpgrp(%d) failed: pid %ld to pgrp %ld",
3660 shell_tty, (long)getpid(), (long)pgrp);
3661#endif
3662 r = -1;
3663 }
3664 else
3665 terminal_pgrp = pgrp;
3666 sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
3667 }
3668
3669 return r;
3670}
3671
3672/* Clear out any jobs in the job array. This is intended to be used by
3673 children of the shell, who should not have any job structures as baggage
3674 when they start executing (forking subshells for parenthesized execution
3675 and functions with pipes are the two that spring to mind). If RUNNING_ONLY
3676 is nonzero, only running jobs are removed from the table. */
3677void
3678delete_all_jobs (running_only)
3679 int running_only;
3680{
3681 register int i;
3682 sigset_t set, oset;
3683
3684 BLOCK_CHILD (set, oset);
3685
3686 /* XXX - need to set j_lastj, j_firstj appropriately if running_only != 0. */
3687 if (js.j_jobslots)
3688 {
3689 js.j_current = js.j_previous = NO_JOB;
3690
3691 /* XXX could use js.j_firstj here */
3692 for (i = 0; i < js.j_jobslots; i++)
3693 {
3694#if defined (DEBUG)
3695 if (i < js.j_firstj && jobs[i])
3696 itrace("delete_all_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
3697#endif
3698 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3699 delete_job (i, 1);
3700 }
3701 if (running_only == 0)
3702 {
3703 free ((char *)jobs);
3704 js.j_jobslots = 0;
3705 js.j_firstj = js.j_lastj = js.j_njobs = 0;
3706 }
3707 }
3708
3709 if (running_only == 0)
3710 bgp_clear ();
3711
3712 UNBLOCK_CHILD (oset);
3713}
3714
3715/* Mark all jobs in the job array so that they don't get a SIGHUP when the
3716 shell gets one. If RUNNING_ONLY is nonzero, mark only running jobs. */
3717void
3718nohup_all_jobs (running_only)
3719 int running_only;
3720{
3721 register int i;
3722 sigset_t set, oset;
3723
3724 BLOCK_CHILD (set, oset);
3725
3726 if (js.j_jobslots)
3727 {
3728 /* XXX could use js.j_firstj here */
3729 for (i = 0; i < js.j_jobslots; i++)
3730 if (jobs[i] && (running_only == 0 || (running_only && RUNNING(i))))
3731 nohup_job (i);
3732 }
3733
3734 UNBLOCK_CHILD (oset);
3735}
3736
3737int
3738count_all_jobs ()
3739{
3740 int i, n;
3741 sigset_t set, oset;
3742
3743 /* This really counts all non-dead jobs. */
3744 BLOCK_CHILD (set, oset);
3745 /* XXX could use js.j_firstj here */
3746 for (i = n = 0; i < js.j_jobslots; i++)
3747 {
3748#if defined (DEBUG)
3749 if (i < js.j_firstj && jobs[i])
3750 itrace("count_all_jobs: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
3751#endif
3752 if (jobs[i] && DEADJOB(i) == 0)
3753 n++;
3754 }
3755 UNBLOCK_CHILD (oset);
3756 return n;
3757}
3758
3759static void
3760mark_all_jobs_as_dead ()
3761{
3762 register int i;
3763 sigset_t set, oset;
3764
3765 if (js.j_jobslots == 0)
3766 return;
3767
3768 BLOCK_CHILD (set, oset);
3769
3770 /* XXX could use js.j_firstj here */
3771 for (i = 0; i < js.j_jobslots; i++)
3772 if (jobs[i])
3773 {
3774 jobs[i]->state = JDEAD;
3775 js.j_ndead++;
3776 }
3777
3778 UNBLOCK_CHILD (oset);
3779}
3780
3781/* Mark all dead jobs as notified, so delete_job () cleans them out
3782 of the job table properly. POSIX.2 says we need to save the
3783 status of the last CHILD_MAX jobs, so we count the number of dead
3784 jobs and mark only enough as notified to save CHILD_MAX statuses. */
3785static void
3786mark_dead_jobs_as_notified (force)
3787 int force;
3788{
3789 register int i, ndead, ndeadproc;
3790 sigset_t set, oset;
3791
3792 if (js.j_jobslots == 0)
3793 return;
3794
3795 BLOCK_CHILD (set, oset);
3796
3797 /* If FORCE is non-zero, we don't have to keep CHILD_MAX statuses
3798 around; just run through the array. */
3799 if (force)
3800 {
3801 /* XXX could use js.j_firstj here */
3802 for (i = 0; i < js.j_jobslots; i++)
3803 {
3804 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
3805 jobs[i]->flags |= J_NOTIFIED;
3806 }
3807 UNBLOCK_CHILD (oset);
3808 return;
3809 }
3810
3811 /* Mark enough dead jobs as notified to keep CHILD_MAX processes left in the
3812 array with the corresponding not marked as notified. This is a better
3813 way to avoid pid aliasing and reuse problems than keeping the POSIX-
3814 mandated CHILD_MAX jobs around. delete_job() takes care of keeping the
3815 bgpids list regulated. */
3816
3817 /* Count the number of dead jobs */
3818 /* XXX could use js.j_firstj here */
3819 for (i = ndead = ndeadproc = 0; i < js.j_jobslots; i++)
3820 {
3821#if defined (DEBUG)
3822 if (i < js.j_firstj && jobs[i])
3823 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
3824#endif
3825 if (jobs[i] && DEADJOB (i))
3826 {
3827 ndead++;
3828 ndeadproc += processes_in_job (i);
3829 }
3830 }
3831
3832#ifdef DEBUG
3833 if (ndeadproc != js.c_reaped)
3834 itrace("mark_dead_jobs_as_notified: ndeadproc (%d) != js.c_reaped (%d)", ndeadproc, js.c_reaped);
3835 if (ndead != js.j_ndead)
3836 itrace("mark_dead_jobs_as_notified: ndead (%d) != js.j_ndead (%d)", ndead, js.j_ndead);
3837#endif
3838
3839 if (js.c_childmax < 0)
3840 js.c_childmax = getmaxchild ();
3841 if (js.c_childmax < 0)
3842 js.c_childmax = DEFAULT_CHILD_MAX;
3843
3844 /* Don't do anything if the number of dead processes is less than CHILD_MAX
3845 and we're not forcing a cleanup. */
3846 if (ndeadproc <= js.c_childmax)
3847 {
3848 UNBLOCK_CHILD (oset);
3849 return;
3850 }
3851
3852#if 0
3853itrace("mark_dead_jobs_as_notified: child_max = %d ndead = %d ndeadproc = %d", js.c_childmax, ndead, ndeadproc);
3854#endif
3855
3856 /* Mark enough dead jobs as notified that we keep CHILD_MAX jobs in
3857 the list. This isn't exactly right yet; changes need to be made
3858 to stop_pipeline so we don't mark the newer jobs after we've
3859 created CHILD_MAX slots in the jobs array. This needs to be
3860 integrated with a way to keep the jobs array from growing without
3861 bound. Maybe we wrap back around to 0 after we reach some max
3862 limit, and there are sufficient job slots free (keep track of total
3863 size of jobs array (js.j_jobslots) and running count of number of jobs
3864 in jobs array. Then keep a job index corresponding to the `oldest job'
3865 and start this loop there, wrapping around as necessary. In effect,
3866 we turn the list into a circular buffer. */
3867 /* XXX could use js.j_firstj here */
3868 for (i = 0; i < js.j_jobslots; i++)
3869 {
3870 if (jobs[i] && DEADJOB (i) && (interactive_shell || (find_last_pid (i, 0) != last_asynchronous_pid)))
3871 {
3872#if defined (DEBUG)
3873 if (i < js.j_firstj && jobs[i])
3874 itrace("mark_dead_jobs_as_notified: job %d non-null before js.j_firstj (%d)", i, js.j_firstj);
3875#endif
3876 /* If marking this job as notified would drop us down below
3877 child_max, don't mark it so we can keep at least child_max
3878 statuses. XXX -- need to check what Posix actually says
3879 about keeping statuses. */
3880 if ((ndeadproc -= processes_in_job (i)) <= js.c_childmax)
3881 break;
3882 jobs[i]->flags |= J_NOTIFIED;
3883 }
3884 }
3885
3886 UNBLOCK_CHILD (oset);
3887}
3888
3889/* Here to allow other parts of the shell (like the trap stuff) to
3890 unfreeze the jobs list. */
3891void
3892unfreeze_jobs_list ()
3893{
3894 jobs_list_frozen = 0;
3895}
3896
3897/* Allow or disallow job control to take place. Returns the old value
3898 of job_control. */
3899int
3900set_job_control (arg)
3901 int arg;
3902{
3903 int old;
3904
3905 old = job_control;
3906 job_control = arg;
3907
3908 /* If we're turning on job control, reset pipeline_pgrp so make_child will
3909 put new child processes into the right pgrp */
3910 if (job_control != old && job_control)
3911 pipeline_pgrp = 0;
3912
3913 return (old);
3914}
3915
3916/* Turn off all traces of job control. This is run by children of the shell
3917 which are going to do shellsy things, like wait (), etc. */
3918void
3919without_job_control ()
3920{
3921 stop_making_children ();
3922 start_pipeline ();
3923#if defined (PGRP_PIPE)
3924 pipe_close (pgrp_pipe);
3925#endif
3926 delete_all_jobs (0);
3927 set_job_control (0);
3928}
3929
3930/* If this shell is interactive, terminate all stopped jobs and
3931 restore the original terminal process group. This is done
3932 before the `exec' builtin calls shell_execve. */
3933void
3934end_job_control ()
3935{
3936 if (interactive_shell) /* XXX - should it be interactive? */
3937 {
3938 terminate_stopped_jobs ();
3939
3940 if (original_pgrp >= 0)
3941 give_terminal_to (original_pgrp, 1);
3942 }
3943
3944 if (original_pgrp >= 0)
3945 setpgid (0, original_pgrp);
3946}
3947
3948/* Restart job control by closing shell tty and reinitializing. This is
3949 called after an exec fails in an interactive shell and we do not exit. */
3950void
3951restart_job_control ()
3952{
3953 if (shell_tty != -1)
3954 close (shell_tty);
3955 initialize_job_control (0);
3956}
3957
3958/* Set the handler to run when the shell receives a SIGCHLD signal. */
3959void
3960set_sigchld_handler ()
3961{
3962 set_signal_handler (SIGCHLD, sigchld_handler);
3963}
3964
3965#if defined (PGRP_PIPE)
3966/* Read from the read end of a pipe. This is how the process group leader
3967 blocks until all of the processes in a pipeline have been made. */
3968static void
3969pipe_read (pp)
3970 int *pp;
3971{
3972 char ch;
3973
3974 if (pp[1] >= 0)
3975 {
3976 close (pp[1]);
3977 pp[1] = -1;
3978 }
3979
3980 if (pp[0] >= 0)
3981 {
3982 while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
3983 ;
3984 }
3985}
3986
3987/* Close the read and write ends of PP, an array of file descriptors. */
3988static void
3989pipe_close (pp)
3990 int *pp;
3991{
3992 if (pp[0] >= 0)
3993 close (pp[0]);
3994
3995 if (pp[1] >= 0)
3996 close (pp[1]);
3997
3998 pp[0] = pp[1] = -1;
3999}
4000
4001/* Functional interface closes our local-to-job-control pipes. */
4002void
4003close_pgrp_pipe ()
4004{
4005 pipe_close (pgrp_pipe);
4006}
4007
4008#endif /* PGRP_PIPE */
Note: See TracBrowser for help on using the repository browser.