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