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