e5e8d2c0a52572bad60bfefb3f0c323d33d5ee7a
[platform/upstream/bash.git] / nojobs.c
1 /* The thing that makes children, remembers them, and contains wait loops. */
2
3 /* This file works under BSD, System V, minix, and Posix systems. */
4
5 /* Copyright (C) 1987, 1989, 1992 Free Software Foundation, Inc.
6
7    This file is part of GNU Bash, the Bourne Again SHell.
8
9    Bash is free software; you can redistribute it and/or modify it under
10    the terms of the GNU General Public License as published by the Free
11    Software Foundation; either version 1, or (at your option) any later
12    version.
13
14    Bash is distributed in the hope that it will be useful, but WITHOUT ANY
15    WARRANTY; without even the implied warranty of MERCHANTABILITY or
16    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17    for more details.
18
19    You should have received a copy of the GNU General Public License along
20    with Bash; see the file COPYING.  If not, write to the Free Software
21    Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
22
23 #include <stdio.h>
24 #include "bashtypes.h"
25 #include <signal.h>
26 #include <setjmp.h>
27 #include <errno.h>
28
29 #include "config.h"
30 #include "command.h"
31 #include "general.h"
32 #include "filecntl.h"
33 #include "jobs.h"
34 #include "externs.h"
35 #include "error.h"
36
37 #if defined (BUFFERED_INPUT)
38 #  include "input.h"
39 #endif
40
41 #if !defined (USG) && !defined (_POSIX_VERSION)
42 #  include <sgtty.h>
43 #else
44 #  if defined (_POSIX_VERSION)
45 #    include <termios.h>
46 #  else
47 #    include <termio.h>
48 #    if !defined (AIXRT)
49 #      include <sys/ttold.h>
50 #    endif /* !AIXRT */
51 #  endif /* !POSIX_VERSION */
52 #endif /* USG && _POSIX_VERSION */
53
54 #if !defined (SIGABRT)
55 #  define SIGABRT SIGIOT
56 #endif /* !SIGABRT */
57
58 #if defined (USG) || defined (_POSIX_VERSION)
59 #  define killpg(pg, sig)               kill(-(pg),(sig))
60 #endif /* USG || _POSIX_VERSION */
61
62 #if defined (USG)
63 #  define siginterrupt(sig, code)
64 #endif /* USG */
65
66 #if defined (_POSIX_VERSION)
67 #  define WAITPID(pid, statusp, options) waitpid (pid, statusp, options)
68 #else
69 #  define WAITPID(pid, statusp, options) wait (statusp)
70 #endif /* !_POSIX_VERSION */
71
72 #if !defined (errno)
73 extern int errno;
74 #endif /* !errno */
75
76 extern int interactive, interactive_shell, login_shell;
77 extern int subshell_environment;
78 extern int last_command_exit_value;
79 #if defined (_POSIX_VERSION)
80 extern sigset_t top_level_mask;
81 #endif
82
83 pid_t last_made_pid = NO_PID;
84 pid_t last_asynchronous_pid = NO_PID;
85
86 /* Call this when you start making children. */
87 int already_making_children = 0;
88
89 #if defined (_POSIX_VERSION)
90 static void reap_zombie_children ();
91 #endif
92
93 struct proc_status {
94   pid_t pid;
95   int status;   /* Exit status of PID or 128 + fatal signal number */
96 };
97
98 static struct proc_status *pid_list = (struct proc_status *)NULL;
99 static int pid_list_size = 0;
100
101 #define PROC_BAD -1
102 #define PROC_STILL_ALIVE -2
103
104 /* Allocate new, or grow existing PID_LIST. */
105 static void
106 alloc_pid_list ()
107 {
108   register int i;
109   int old = pid_list_size;
110
111   pid_list_size += 10;
112   pid_list = (struct proc_status *)
113     xrealloc (pid_list, pid_list_size * sizeof (struct proc_status));
114
115   /* None of the newly allocated slots have process id's yet. */
116   for (i = old; i < pid_list_size; i++)
117     pid_list[i].pid = NO_PID;  
118 }
119
120 /* Return the offset within the PID_LIST array of an empty slot.  This can
121    create new slots if all of the existing slots are taken. */
122 static int
123 find_proc_slot ()
124 {
125   register int i;
126
127   for (i = 0; i < pid_list_size; i++)
128     if (pid_list[i].pid == NO_PID)
129       return (i);
130
131   if (i == pid_list_size)
132     alloc_pid_list ();
133
134   return (i);
135 }
136
137 /* Return the offset within the PID_LIST array of a slot containing PID,
138    or the value NO_PID if the pid wasn't found. */
139 static int
140 find_index_by_pid (pid)
141      pid_t pid;
142 {
143   register int i;
144
145   for (i = 0; i < pid_list_size; i++)
146     if (pid_list[i].pid == pid)
147       return (i);
148
149   return (NO_PID);
150 }
151
152 /* Return the status of PID as looked up in the PID_LIST array.  A
153    return value of PROC_BAD indicates that PID wasn't found. */
154 static int
155 find_status_by_pid (pid)
156      pid_t pid;
157 {
158   int i;
159
160   i = find_index_by_pid (pid);
161   if (i == NO_PID)
162     return (PROC_BAD);
163   return (pid_list[i].status);
164 }
165
166 /* Give PID the status value STATUS in the PID_LIST array. */
167 static void
168 set_pid_status (pid, status)
169      pid_t pid;
170      WAIT status;
171 {
172   int slot;
173
174   slot = find_index_by_pid (pid);
175   if (slot == NO_PID)
176     return;
177
178   if (WIFSIGNALED (status))
179     pid_list[slot].status = 128 + WTERMSIG (status);
180   else
181     pid_list[slot].status = WEXITSTATUS (status);
182 }
183
184 static void
185 add_pid (pid)
186      pid_t pid;
187 {
188   int slot;
189
190   slot = find_proc_slot ();
191   pid_list[slot].pid = pid;
192   pid_list[slot].status = PROC_STILL_ALIVE;
193 }
194
195 int
196 cleanup_dead_jobs ()
197 {
198   register int i;
199
200 #if defined (_POSIX_VERSION)
201   reap_zombie_children ();
202 #endif
203
204   for (i = 0; i < pid_list_size; i++)
205     if (pid_list[i].status != PROC_STILL_ALIVE)
206       pid_list[i].pid = NO_PID;
207 }
208
209 /* Initialize the job control mechanism, and set up the tty stuff. */
210 initialize_jobs ()
211 {
212   get_tty_state ();
213 }
214
215 #if !defined (READLINE) && defined (TIOCGWINSZ) && defined (SIGWINCH)
216 static SigHandler *old_winch;
217
218 static sighandler
219 sigwinch_sighandler (sig)
220      int sig;
221 {
222   struct winsize win;
223
224 #if defined (USG) && !defined (_POSIX_VERSION)
225   set_signal_handler (SIGWINCH, sigwinch_sighandler);
226 #endif /* USG && !_POSIX_VERSION */
227   if ((ioctl (0, TIOCGWINSZ, &win) == 0) &&
228       win.ws_row > 0 && win.ws_col > 0)
229     set_lines_and_columns (win.ws_row, win.ws_col);
230 }
231 #endif /* !READLINE && TIOCGWINSZ && SIGWINCH */
232
233 /* Setup this shell to handle C-C, etc. */
234 void
235 initialize_job_signals ()
236 {
237   set_signal_handler (SIGINT, sigint_sighandler);
238 #if !defined (READLINE) && defined (TIOCGWINSZ) && defined (SIGWINCH)
239   set_signal_handler (SIGWINCH, sigwinch_sighandler);
240 #endif /* !READLINE && TIOCGWINSZ && SIGWINCH */
241
242   /* If this is a login shell we don't wish to be disturbed by
243      stop signals. */
244   if (login_shell)
245     {
246 #if defined (SIGTSTP)
247       set_signal_handler (SIGTSTP, SIG_IGN);
248       set_signal_handler (SIGTTOU, SIG_IGN);
249       set_signal_handler (SIGTTIN, SIG_IGN);
250 #endif
251     }
252 }
253
254 #if defined (_POSIX_VERSION)
255 /* Collect the status of all zombie children so that their system
256    resources can be deallocated. */
257 static void
258 reap_zombie_children ()
259 {
260 #if defined (WNOHANG)
261   pid_t pid;
262   WAIT status;
263
264   while ((pid = waitpid (-1, (int *)&status, WNOHANG)) > 0)
265     set_pid_status (pid, status);
266 #endif /* WNOHANG */
267 }
268 #endif /* _POSIX_VERSION */
269
270 /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
271    COMMAND is just for remembering the name of the command; we don't do
272    anything else with it.  ASYNC_P says what to do with the tty.  If
273    non-zero, then don't give it away. */
274 pid_t
275 make_child (command, async_p)
276      char *command;
277      int async_p;
278 {
279   pid_t pid;
280 #if defined (_POSIX_VERSION)
281   int retry = 1;
282 #endif /* _POSIX_VERSION */
283
284   /* Discard saved memory. */
285   if (command)  
286     free (command);
287
288   start_pipeline ();
289
290 #if defined (BUFFERED_INPUT)
291   /* If default_buffered_input is active, we are reading a script.  If
292      the command is asynchronous, we have already duplicated /dev/null
293      as fd 0, but have not changed the buffered stream corresponding to
294      the old fd 0.  We don't want to sync the stream in this case. */
295   if (default_buffered_input != -1 &&
296       (!async_p || default_buffered_input > 0))
297     sync_buffered_stream (default_buffered_input);
298 #endif /* BUFFERED_INPUT */
299
300   /* Create the child, handle severe errors. */
301 #if defined (_POSIX_VERSION)
302   retry_fork:
303 #endif /* _POSIX_VERSION */
304
305   if ((pid = fork ()) < 0)
306     {
307 #if defined (_POSIX_VERSION)
308       /* Posix systems with a non-blocking waitpid () system call available
309          get another chance after zombies are reaped. */
310       if (errno == EAGAIN && retry)
311         {
312           reap_zombie_children ();
313           retry = 0;
314           goto retry_fork;
315         }
316 #endif /* _POSIX_VERSION */
317
318       internal_error ("fork: %s", strerror (errno));
319
320       throw_to_top_level ();
321     }
322  
323   if (pid == 0)
324     {
325 #if defined (BUFFERED_INPUT)
326       if (default_buffered_input > 0)
327         {
328           close_buffered_fd (default_buffered_input);
329           default_buffered_input = bash_input.location.buffered_fd = -1;
330         }
331 #endif /* BUFFERED_INPUT */
332
333 #if defined (_POSIX_VERSION)
334       /* Restore top-level signal mask. */
335       sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
336 #endif
337
338       /* Ignore INT and QUIT in asynchronous children. */
339       if (async_p)
340         {
341 #if 0
342           /* This now done by setup_async_signals (). */
343           set_signal_handler (SIGINT, SIG_IGN);
344           set_signal_handler (SIGQUIT, SIG_IGN);
345 #endif
346           last_asynchronous_pid = getpid ();
347         }
348
349 #if defined (SIGTSTP)
350       set_signal_handler (SIGTSTP, SIG_DFL);
351       set_signal_handler (SIGTTIN, SIG_DFL);
352       set_signal_handler (SIGTTOU, SIG_DFL);
353 #endif
354     }
355   else
356     {
357       /* In the parent. */
358
359       last_made_pid = pid;
360
361       if (async_p)
362         last_asynchronous_pid = pid;
363
364       add_pid (pid);
365     }
366   return (pid);
367 }
368
369 /* Wait for a single pid (PID) and return its exit status. */
370 wait_for_single_pid (pid)
371      pid_t pid;
372 {
373   pid_t got_pid;
374   WAIT status;
375   int pstatus;
376
377   pstatus = find_status_by_pid (pid);
378
379   if (pstatus == PROC_BAD)
380     return (127);
381
382   if (pstatus != PROC_STILL_ALIVE)
383     return (pstatus);
384
385   siginterrupt (SIGINT, 1);
386   while ((got_pid = WAITPID (pid, &status, 0)) != pid)
387     {
388       if (got_pid < 0)
389         {
390           if (errno != EINTR && errno != ECHILD)
391             {
392               siginterrupt (SIGINT, 0);
393               file_error ("wait");
394             }
395           break;
396         }
397       else if (got_pid > 0)
398         set_pid_status (got_pid, status);
399     }
400
401   set_pid_status (got_pid, status);
402   siginterrupt (SIGINT, 0);
403   QUIT;
404
405   if (WIFSIGNALED (status))
406     return (128 + WTERMSIG (status));
407   else
408     return (WEXITSTATUS (status));
409 }
410
411 /* Wait for all of the shell's children to exit. */
412 void
413 wait_for_background_pids ()
414 {
415   pid_t got_pid;
416   WAIT status;
417
418   /* If we aren't using job control, we let the kernel take care of the
419      bookkeeping for us.  wait () will return -1 and set errno to ECHILD 
420      when there are no more unwaited-for child processes on both
421      4.2 BSD-based and System V-based systems. */
422
423   siginterrupt (SIGINT, 1);
424
425   /* Wait for ECHILD */
426   while ((got_pid = WAITPID (-1, &status, 0)) != -1)
427     set_pid_status (got_pid, status);
428
429   if (errno != EINTR && errno != ECHILD)
430     {
431       siginterrupt (SIGINT, 0);
432       file_error("wait");
433     }
434
435   siginterrupt (SIGINT, 0);
436   QUIT;
437 }
438
439 /* Handle SIGINT while we are waiting for children in a script to exit.
440    All interrupts are effectively ignored by the shell, but allowed to
441    kill a running job. */
442 static sighandler
443 wait_sigint_handler (sig)
444      int sig;
445 {
446 #if 0
447   /* Run a trap handler if one has been defined. */
448   maybe_call_trap_handler (sig);
449 #endif
450
451 #if !defined (VOID_SIGHANDLER)
452   return (0);
453 #endif /* !VOID_SIGHANDLER */
454 }
455
456 /* Wait for pid (one of our children) to terminate.  This is called only
457    by the execution code in execute_cmd.c. */
458 int
459 wait_for (pid)
460      pid_t pid;
461 {
462   int return_val, pstatus;
463   pid_t got_pid;
464   WAIT status;
465   SigHandler *old_sigint_handler;
466
467   pstatus = find_status_by_pid (pid);
468
469   if (pstatus == PROC_BAD)
470     return (0);
471
472   if (pstatus != PROC_STILL_ALIVE)
473     return (pstatus);
474
475   /* If we are running a script, ignore SIGINT while we're waiting for
476      a child to exit.  The loop below does some of this, but not all. */
477   if (!interactive_shell)
478     old_sigint_handler = set_signal_handler (SIGINT, wait_sigint_handler);
479
480   while ((got_pid = WAITPID (-1, &status, 0)) != pid) /* XXX was pid now -1 */
481     {
482       if (got_pid < 0 && errno == ECHILD)
483         {
484 #if !defined (_POSIX_VERSION)
485           status.w_termsig = status.w_retcode = 0;
486 #else
487           status = 0;
488 #endif /* _POSIX_VERSION */
489           break;
490         }
491       else if (got_pid < 0 && errno != EINTR)
492         programming_error ("got errno %d while waiting for %d", errno, pid);
493       else if (got_pid > 0)
494         set_pid_status (got_pid, status);
495     }
496
497   set_pid_status (got_pid, status);
498
499 #if defined (_POSIX_VERSION)
500   if (got_pid >= 0)
501     reap_zombie_children ();
502 #endif /* _POSIX_VERSION */
503
504   if (!interactive_shell)
505     {
506       set_signal_handler (SIGINT, old_sigint_handler);
507       /* If the job exited because of SIGINT, make sure the shell acts as if
508          it had received one also. */
509       if (WIFSIGNALED (status) && (WTERMSIG (status) == SIGINT))
510         {
511           if (maybe_call_trap_handler (SIGINT) == 0)
512             (*old_sigint_handler) (SIGINT);
513         }
514     }
515             
516   /* Default return value. */
517   /* ``a full 8 bits of status is returned'' */
518   if (WIFSIGNALED (status))
519     return_val = 128 + WTERMSIG (status);
520   else
521     return_val = WEXITSTATUS (status);
522                             
523   if (!WIFSTOPPED (status) && WIFSIGNALED (status) &&
524       (WTERMSIG (status) != SIGINT))
525     {
526       fprintf (stderr, "%s", strsignal (WTERMSIG (status)));
527       if (WIFCORED (status))
528         fprintf (stderr, " (core dumped)");
529       fprintf (stderr, "\n");
530     }
531
532   if (interactive_shell && !subshell_environment)
533     {
534       if (WIFSIGNALED (status) || WIFSTOPPED (status))
535         set_tty_state ();
536       else
537         get_tty_state ();
538     }
539
540   return (return_val);
541 }
542
543 /* Give PID SIGNAL.  This determines what job the pid belongs to (if any).
544    If PID does belong to a job, and the job is stopped, then CONTinue the
545    job after giving it SIGNAL.  Returns -1 on failure.  If GROUP is non-null,
546    then kill the process group associated with PID. */
547 int
548 kill_pid (pid, signal, group)
549      pid_t pid;
550      int signal, group;
551 {
552   int result;
553
554   if (group)
555     result = killpg (pid, signal);
556   else
557     result = kill (pid, signal);
558
559   return (result);
560 }
561
562 #if defined (_POSIX_VERSION)
563 static struct termios shell_tty_info;
564 #else
565 #  if defined (USG)
566 static struct termio shell_tty_info;
567 #  else
568 static struct sgttyb shell_tty_info;
569 #  endif /* USG */
570 #endif /* _POSIX_VERSION */
571
572 static int got_tty_state = 0;
573
574 /* Fill the contents of shell_tty_info with the current tty info. */
575 get_tty_state ()
576 {
577   int tty = open ("/dev/tty", O_RDONLY);
578   if (tty != -1)
579     {
580 #if defined (_POSIX_VERSION)
581       tcgetattr (tty, &shell_tty_info);
582 #else
583 #  if defined (USG)
584       ioctl (tty, TCGETA, &shell_tty_info);
585 #  else
586       ioctl (tty, TIOCGETP, &shell_tty_info);
587 #  endif
588 #endif
589       close (tty);
590       got_tty_state = 1;
591     }
592 }
593
594 /* Make the current tty use the state in shell_tty_info. */
595 set_tty_state ()
596 {
597   int tty = open ("/dev/tty", O_RDONLY);
598   if (tty != -1)
599     {
600       if (!got_tty_state)
601         {
602           close (tty);
603           return;
604         }
605 #if defined (_POSIX_VERSION)
606       tcsetattr (tty, TCSADRAIN, &shell_tty_info);
607 #else
608 #  if defined (USG)
609       ioctl (tty, TCSETAW, &shell_tty_info);  /* Wait for output, no flush */
610 #  else
611       ioctl (tty, TIOCSETN, &shell_tty_info);
612 #  endif
613 #endif
614       close (tty);
615     }
616 }
617
618 /* Give the terminal to PGRP.  */
619 give_terminal_to (pgrp)
620      pid_t pgrp;
621 {
622 }
623
624 /* Stop a pipeline. */
625 stop_pipeline (async, ignore)
626      int async;
627      COMMAND *ignore;
628 {
629   already_making_children = 0;
630 }
631
632 void
633 start_pipeline ()
634 {
635   already_making_children = 1;
636 }
637
638 /* Print descriptive information about the job with leader pid PID. */
639 void
640 describe_pid (pid)
641      pid_t pid;
642 {
643   fprintf (stderr, "%d\n", (int) pid);
644 }