home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / tos / bash / bash-108 / bash-108.zoo / bash-1.08 / jobs.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-22  |  50.7 KB  |  2,171 lines

  1. /* The thing that makes children, remembers them, and contains wait loops. */
  2.  
  3. /* This file works with both POSIX and BSD systems. */
  4.  
  5. /* Copyright (C) 1989 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. /* Something that can be ignored. */
  24. #define IGNORE_ARG (char *)0
  25.  
  26. #include "config.h"
  27.  
  28. #if !defined (JOB_CONTROL)
  29. #include "nojobs.c"
  30. #else /* JOB_CONTROL */
  31.  
  32. #include "trap.h"
  33. #include <stdio.h>
  34. #include <signal.h>
  35. #include <errno.h>
  36. #include <sys/types.h>
  37.  
  38. #if !defined (USG) || defined (HAVE_RESOURCE)
  39. #include <sys/time.h>
  40. #endif /* USG */
  41.  
  42. #if !defined (_POSIX_VERSION)
  43. #  if defined (HAVE_RESOURCE)
  44. #    include <sys/resource.h>
  45. #  endif
  46. #endif /* _POSIX_VERSION */
  47.  
  48. #include <sys/file.h>
  49. #include <fcntl.h>
  50. #include <sys/ioctl.h>
  51. #include <sys/param.h>
  52.  
  53. /* Terminal handling stuff, to save and restore tty state. */
  54. #define NEW_TTY_DRIVER
  55.  
  56. /* Define this if your output is getting swallowed.  It's a no-op on
  57.    machines with the termio or termios tty drivers. */
  58. /* #define DRAIN_OUTPUT */
  59.  
  60. #if defined (_POSIX_VERSION)
  61. #  undef NEW_TTY_DRIVER
  62. #  define TERMIOS_TTY_DRIVER
  63. #else /* !_POSIX_VERSION */
  64. #  if defined (USG) || defined (hpux) || defined (Xenix) || defined (sgi)
  65. #    undef NEW_TTY_DRIVER
  66. #    define TERMIO_TTY_DRIVER
  67. #  endif /* USG | hpux | Xenix | sgi */
  68. #endif /* !_POSIX_VERSION */
  69.  
  70. /* Include the right header file for the specific type of terminal
  71.    handler installed on this system. */
  72. #if defined (NEW_TTY_DRIVER)
  73. #include <sgtty.h>
  74. #endif
  75.  
  76. #if defined (TERMIO_TTY_DRIVER)
  77. #include <termio.h>
  78. #endif
  79.  
  80. #if defined (TERMIOS_TTY_DRIVER)
  81. #include <termios.h>
  82. #endif
  83.  
  84. /* For the TIOCGPGRP and TIOCSPGRP ioctl parameters on HP-UX */
  85.  
  86. #if defined (hpux) && !defined (TERMIOS_TTY_DRIVER)
  87. #include <bsdtty.h>
  88. #endif /* hpux && !TERMIOS_TTY_DRIVER */
  89.  
  90. #include "shell.h"
  91. #include "jobs.h"
  92.  
  93. /* Not all systems define errno in errno.h. */
  94. extern int errno;
  95. extern int interactive;
  96. extern pid_t last_pid ();
  97. extern char *shell_name;
  98.  
  99. /* The array of known jobs. */
  100. JOB **jobs = (JOB **)NULL;
  101.  
  102. /* The number of slots currently allocated to JOBS. */
  103. int job_slots = 0;
  104.  
  105. /* The number of additional slots to allocate when we run out. */
  106. #define JOB_SLOTS 5
  107.  
  108. /* The controlling tty for this shell. */
  109. int shell_tty = -1;
  110.  
  111. /* The shell's process group. */
  112. pid_t shell_pgrp = (pid_t)-1;
  113.  
  114. /* The terminal's process group. */
  115. pid_t terminal_pgrp = (pid_t)-1;
  116.  
  117. /* The process group of the shell's parent. */
  118. pid_t original_pgrp = (pid_t)-1;
  119.  
  120. /* The process group of the pipeline currently being made. */
  121. pid_t pipeline_pgrp = (pid_t)0;
  122.  
  123. /* Pipes which each shell uses to communicate with the process group leader
  124.    until all of the processes in a pipeline have been started.  Then the
  125.    process leader is allowed to continue. */
  126. int pgrp_pipe[2] = { -1, -1 };
  127.  
  128. /* The job which is current; i.e. the one that `%+' stands for. */
  129. int current_job = NO_JOB;
  130.  
  131. /* The previous job; i.e. the one that `%-' stands for. */
  132. int previous_job = NO_JOB;
  133.  
  134. /* Last child made by the shell.  */
  135. pid_t last_made_pid = (pid_t)-1;
  136.  
  137. /* Pid of the last asynchronous child. */
  138. pid_t last_asynchronous_pid = (pid_t)-1;
  139.  
  140. /* Non-zero allows asynchronous job notification.  If not set,
  141.    then job state notification only takes place just before a
  142.    prompt is printed. */
  143. int asynchronous_notification = 0;
  144.  
  145. /* The pipeline currently being built. */
  146. PROCESS *the_pipeline = (PROCESS *)NULL;
  147.  
  148. /* If this is non-zero, do job control. */
  149. int job_control = 1;
  150.  
  151. /* Call this when you start making children. */
  152. int already_making_children = 0;
  153.  
  154. sighandler flush_child ();    /* forward definition */
  155.  
  156. #if !defined (_POSIX_VERSION)
  157.  
  158. /* These are definitions to map POSIX 1003.1 functions onto existing BSD
  159.    library functions and system calls. */
  160. #define setpgid(pid, pgrp)    setpgrp (pid, pgrp)
  161. #define tcsetpgrp(fd, pgrp)    ioctl ((fd), TIOCSPGRP, &(pgrp))
  162.  
  163. pid_t
  164. tcgetpgrp (fd)
  165.      int fd;
  166. {
  167.   pid_t pgrp;
  168.  
  169.   /* ioctl will handle setting errno correctly. */
  170.   if (ioctl (fd, TIOCGPGRP, &pgrp) < 0)
  171.     return (-1);
  172.   return (pgrp);
  173. }
  174.  
  175. /* Perform OPERATION on NEWSET, perhaps leaving information in OLDSET. */
  176. sigprocmask (operation, newset, oldset)
  177.      int operation, *newset, *oldset;
  178. {
  179.   switch (operation)
  180.     {
  181.     case SIG_BLOCK:
  182.       *oldset = sigblock (*newset);
  183.       break;
  184.  
  185.     case SIG_SETMASK:
  186.       sigsetmask (*newset);
  187.       break;
  188.  
  189.     default:
  190.       report_error ("Bad code in jobs.c: sigprocmask");
  191.     }
  192. }
  193. #endif /* !_POSIX_VERSION */
  194.  
  195. /* Return the working directory for the current process. */
  196. static char *
  197. job_working_directory ()
  198. {
  199.   extern char *get_working_directory ();
  200.   char *dir;
  201.  
  202.   dir = get_string_value ("PWD");
  203.   if (dir)
  204.     return (savestring (dir));
  205.  
  206.   dir = get_working_directory ("");
  207.   if (dir)
  208.     return (dir);
  209.  
  210.   return (savestring ("<unknown>"));
  211. }
  212.  
  213. making_children ()
  214. {
  215.   if (already_making_children)
  216.     return;
  217.  
  218.   already_making_children = 1;
  219.   start_pipeline ();
  220. }
  221.  
  222. stop_making_children ()
  223. {
  224.   already_making_children = 0;
  225. }
  226.  
  227. /* Start building a pipeline.  */
  228. start_pipeline ()
  229. {
  230.   if (the_pipeline)
  231.     {
  232.       discard_pipeline (the_pipeline);
  233.       the_pipeline = (PROCESS *)NULL;
  234.       pipeline_pgrp = 0;
  235.       pipe_close (pgrp_pipe);
  236.     }
  237.  
  238.   if (job_control)
  239.     {
  240.       if (pipe (pgrp_pipe) == -1)
  241.     report_error ("start_pipeline: pgrp pipe");
  242.     }
  243. }
  244.  
  245. /* Stop building a pipeline.  Install the process list in the job array.
  246.    This returns the index of the newly installed job.
  247.    DEFERRED is a command structure to be executed upon satisfactory
  248.    execution exit of this pipeline. */
  249. int
  250. stop_pipeline (async, deferred)
  251.      int async;
  252.      COMMAND *deferred;
  253. {
  254.   register int i, j;
  255.   JOB *newjob = (JOB *)NULL;
  256.   char *get_string_value ();
  257.   sigset_t set, oset;
  258.  
  259.   BLOCK_CHILD (set, oset);
  260.  
  261.   /* The parent closes the process group synchronization pipe. */
  262.   pipe_close (pgrp_pipe);
  263.  
  264.   cleanup_dead_jobs ();
  265.  
  266.   if (!job_slots)
  267.     {
  268.       jobs =
  269.     (JOB **)xmalloc ((1 + (job_slots = JOB_SLOTS)) * sizeof (JOB *));
  270.  
  271.       /* Now blank out these new entries. */
  272.       for (i = 0; i < job_slots; i++)
  273.     jobs[i] = (JOB *)NULL;
  274.     }
  275.  
  276.   /* Scan from the last slot backward, looking for the next free one. */
  277.   for (i = job_slots; i; i--)
  278.     if (jobs[i - 1])
  279.       break;
  280.  
  281.   /* Do we need more room? */
  282.   if (i == job_slots)
  283.     {
  284.       jobs = (JOB **)realloc
  285.     (jobs, (1 + (job_slots += JOB_SLOTS)) * sizeof (JOB *));
  286.  
  287.       for (j = i; j < job_slots; j++)
  288.     jobs[j] = (JOB *)NULL;
  289.     }
  290.  
  291.   /* Add the current pipeline to the job list. */
  292.   if (the_pipeline)
  293.     {
  294.       register PROCESS *p;
  295.  
  296.       newjob = (JOB *)xmalloc (sizeof (JOB));
  297.  
  298.       for (p = the_pipeline; p->next != the_pipeline; p = p->next);
  299.       p->next = (PROCESS *)NULL;
  300.       newjob->pipe = (PROCESS *)reverse_list (the_pipeline);
  301.       for (p = newjob->pipe; p->next; p = p->next);
  302.       p->next = newjob->pipe;
  303.  
  304.       the_pipeline = (PROCESS *)NULL;
  305.       newjob->pgrp = pipeline_pgrp;
  306.       pipeline_pgrp = 0;
  307.  
  308.       /* Flag to see if in another pgrp. */
  309.       newjob->job_control = job_control;
  310.  
  311.       /* Set the state of this pipeline. */
  312.       {
  313.     register PROCESS *p = newjob->pipe;
  314.     register int any_alive = 0;
  315.     register int any_stopped = 0;
  316.  
  317.     do
  318.       {
  319.         any_alive |= p->running;
  320.         any_stopped |= WIFSTOPPED (p->status);
  321.         p = p->next;
  322.       }
  323.     while (p != newjob->pipe);
  324.  
  325.     if (any_alive)
  326.       {
  327.         newjob->state = JRUNNING;
  328.       }
  329.     else
  330.       {
  331.         if (any_stopped)
  332.           newjob->state = JSTOPPED;
  333.         else
  334.           newjob->state = JDEAD;
  335.       }
  336.       }
  337.  
  338.       newjob->notified = 0;
  339.       newjob->wd = job_working_directory ();
  340.       newjob->deferred = deferred;
  341.  
  342.       jobs[i] = newjob;
  343.     }
  344.  
  345.   if (async)
  346.     {
  347.       if (newjob)
  348.     newjob->foreground = 0;
  349.       reset_current ();
  350.     }
  351.   else
  352.     {
  353.       if (newjob)
  354.     {
  355.       newjob->foreground = 1;
  356.       /*
  357.        *        !!!!! NOTE !!!!!  (chet@ins.cwru.edu)
  358.        *
  359.        * The currently-accepted job control wisdom says to set the
  360.        * terminal's process group n+1 times in an n-step pipeline:
  361.        * once in the parent and once in each child.  This is where
  362.        * the parent gives it away.
  363.        *
  364.        */
  365.       if (job_control && newjob->pgrp)
  366.         give_terminal_to (newjob->pgrp);
  367.     }
  368.     }
  369.  
  370.   stop_making_children ();
  371.   UNBLOCK_CHILD (oset);
  372.   return (current_job);
  373. }
  374.  
  375. /* Delete all DEAD jobs that the user had received notification about. */
  376. cleanup_dead_jobs ()
  377. {
  378.   register int i;
  379.   sigset_t set, oset;
  380.  
  381.   BLOCK_CHILD (set, oset);
  382.  
  383.   for (i = 0; i < job_slots; i++)
  384.     if (jobs[i] && JOBSTATE (i) == JDEAD && jobs[i]->notified)
  385.       delete_job (i);
  386.  
  387.   UNBLOCK_CHILD (oset);
  388. }
  389.  
  390. /* Delete the job at INDEX from the job list. */
  391. delete_job (index)
  392.      int index;
  393. {
  394.   register JOB *temp = jobs[index];
  395.  
  396.   if (index == current_job || index == previous_job)
  397.     reset_current ();
  398.  
  399.   jobs[index] = (JOB *)NULL;
  400.  
  401.   free (temp->wd);
  402.   discard_pipeline (temp->pipe);
  403.  
  404.   if (temp->deferred)
  405.     dispose_command (temp->deferred);
  406.  
  407.   free (temp);
  408. }
  409.  
  410. /* Get rid of the data structure associated with a process chain. */
  411. discard_pipeline (chain)
  412.      register PROCESS *chain;
  413. {
  414.   register PROCESS *this, *next;
  415.  
  416.   this = chain;
  417.   do
  418.     {
  419.       next = this->next;
  420.       if (this->command)
  421.     free (this->command);
  422.       free (this);
  423.       this = next;
  424.     }
  425.   while (this != chain);
  426. }
  427.  
  428. /* Add this process to the chain being built in the_pipeline.
  429.    NAME is the command string that will be exec'ed later.
  430.    PID is the process id of the child. */
  431. add_process (name, pid)
  432.      char *name;
  433.      pid_t pid;
  434. {
  435.   PROCESS *t = (PROCESS *)xmalloc (sizeof (PROCESS));
  436.  
  437.   t->next = the_pipeline;
  438.   t->pid = pid;
  439.   WSTATUS (t->status) = 0;
  440.   t->running = 1;
  441.   t->command = name;
  442.   the_pipeline = t;
  443.  
  444.   if (!(t->next))
  445.     {
  446.       t->next = t;
  447.     }
  448.   else
  449.     {
  450.       register PROCESS *p = t->next;
  451.  
  452.       while (p->next != t->next) p = p->next;
  453.       p->next = t;
  454.     }
  455. }
  456.  
  457. /* Map FUNC over the list of jobs.  If FUNC returns non-zero,
  458.    then it is time to stop mapping, and that is the return value
  459.    for map_over_jobs.  FUNC is called with a JOB, arg1, arg2,
  460.    and INDEX. */
  461. map_over_jobs (func, arg1, arg2)
  462.      Function *func;
  463. {
  464.   register int i;
  465.  
  466.   for (i = 0; i < job_slots; i++)
  467.     {
  468.       if (jobs[i])
  469.     {
  470.       int result = (*func)(jobs[i], arg1, arg2, i);
  471.       if (result)
  472.         return (result);
  473.     }
  474.     }
  475.   return (0);
  476. }
  477.  
  478. /* Cause all the jobs in the current pipeline to exit. */
  479. terminate_current_pipeline ()
  480. {
  481.   if (pipeline_pgrp && pipeline_pgrp != shell_pgrp)
  482.     {
  483.       killpg (pipeline_pgrp, SIGTERM);
  484.       killpg (pipeline_pgrp, SIGCONT);
  485.     }
  486. }
  487.  
  488. kill_current_pipeline ()
  489. {
  490.   stop_making_children ();
  491.   start_pipeline ();
  492. }
  493.  
  494. /* Return the pipeline that PID belongs to.  Note that the pipeline
  495.    doesn't have to belong to a job. */
  496. PROCESS *
  497. find_pipeline (pid)
  498.      pid_t pid;
  499. {
  500.   int job;
  501.  
  502.   /* See if this process is in the pipeline that we are building. */
  503.   if (the_pipeline)
  504.     {
  505.       register PROCESS *p = the_pipeline;
  506.  
  507.       do
  508.     {
  509.       /* Return it if we found it. */
  510.       if (p->pid == pid)
  511.         return (p);
  512.  
  513.       p = p->next;
  514.     }
  515.       while (p != the_pipeline);
  516.     }
  517.  
  518.   job = find_job (pid);
  519.  
  520.   if (job == NO_JOB)
  521.     return ((PROCESS *)NULL);
  522.   else
  523.     return (jobs[job]->pipe);
  524. }
  525.  
  526. /* Return the job index that PID belongs to, or NO_JOB if it doesn't
  527.    belong to any job. */
  528. int
  529. find_job (pid)
  530.      pid_t pid;
  531. {
  532.   register int i;
  533.   register PROCESS *p;
  534.  
  535.   for (i = 0; i < job_slots; i++)
  536.     {
  537.       if (jobs[i])
  538.     {
  539.       p = jobs[i]->pipe;
  540.  
  541.       do
  542.         {
  543.           if (p->pid == pid)
  544.         return (i);
  545.  
  546.           p = p->next;
  547.         }
  548.       while (p != jobs[i]->pipe);
  549.     }
  550.     }
  551.  
  552.   return (NO_JOB);
  553. }
  554.  
  555. /* Print descriptive information about the job with leader pid PID. */
  556. describe_pid (pid)
  557.      pid_t pid;
  558. {
  559.   int job;
  560.   sigset_t set, oset;
  561.  
  562.   BLOCK_CHILD (set, oset);
  563.  
  564.   job = find_job (pid);
  565.       
  566.   if (job != NO_JOB)
  567.     printf ("[%d] %d\n", job + 1, pid);
  568.   else
  569.     programming_error ("describe_pid: No such pid (%d)!\n", pid);
  570.  
  571.   UNBLOCK_CHILD (oset);
  572. }
  573.  
  574.  
  575. /* This is the way to print out information on a job if you
  576.    know the index.  FORMAT is:
  577.  
  578.     0)   [1]+ Running           emacs
  579.     1)   [1]+ 2378 Running      emacs
  580.    -1)   [1]+ 2378              emacs
  581.  
  582.     0)   [1]+ Stopped           ls | more
  583.     1)   [1]+ 2369 Stopped      ls
  584.           2367            | more
  585.     2)    Just list the pid of the process group leader (really the process
  586.     group). */
  587. pretty_print_job (index, format, stream)
  588.      int index, format;
  589.      FILE *stream;
  590. {
  591.   register PROCESS *p, *first, *last;
  592.   int name_padding;
  593.   char retcode_name_buffer[20];
  594.   sigset_t set, oset;
  595.  
  596.   BLOCK_CHILD (set, oset);
  597.  
  598.   /* format == 2 means print out only the pid information about the process
  599.      group leader. */  
  600.   if (format == 2)
  601.     {
  602.       fprintf (stream, "%d\n", jobs[index]->pipe->pid);
  603.       UNBLOCK_CHILD (oset);
  604.       return;
  605.     }
  606.  
  607.   fprintf (stream, "[%d]%c ", index + 1,
  608.        (index == current_job) ? '+':
  609.        (index == previous_job) ? '-' : ' ');
  610.  
  611.   first = last = p = jobs[index]->pipe;
  612.   while (last->next != first)
  613.     last = last->next;
  614.  
  615.   for (;;)
  616.     {
  617.       if (p != first)
  618.     fprintf (stream, format ? "     " : " |");
  619.  
  620.       if (format)
  621.     fprintf (stream, "%d", p->pid);
  622.  
  623.       fprintf (stream, " ");
  624.  
  625.       if (format > -1)
  626.     {
  627.       extern char *sys_siglist[];
  628.       PROCESS *show = format ? p : last;
  629.       char *temp = "Done";
  630.  
  631.       if (JOBSTATE (index) == JSTOPPED && !format)
  632.         temp = "Stopped";
  633.  
  634.       if (JOBSTATE (index) == JRUNNING)
  635.         temp = "Running";
  636.       else
  637.         {
  638.         if (WIFSTOPPED (show->status))
  639.           temp = sys_siglist[WSTOPSIG (show->status)];
  640.         else if (WIFSIGNALED (show->status))
  641.           temp = sys_siglist[WTERMSIG (show->status)];
  642.         else if (WIFEXITED (show->status))
  643.           {
  644.             temp = retcode_name_buffer;
  645.             sprintf (temp, "Exit %d", WEXITSTATUS (show->status));
  646.           }
  647.         else
  648.           temp = "Unknown status";
  649.         }
  650.  
  651.       if (p != first)
  652.         {
  653.           if (format)
  654.         {
  655.           if (show->running == first->running &&
  656.               WSTATUS (show->status) == WSTATUS (first->status))
  657.             temp = "";
  658.         }
  659.           else
  660.         temp = (char *)NULL;
  661.         }
  662.  
  663.       if (temp)
  664.         {
  665.           fprintf (stream, "%s", temp);
  666.  
  667.           if (strlen (temp))
  668.         name_padding = LONGEST_SIGNAL_DESC - strlen (temp);
  669.           else
  670.         name_padding = LONGEST_SIGNAL_DESC - 2; /* strlen ("| ") */
  671.  
  672.           fprintf (stream, "%*s", name_padding, "");
  673.  
  674.           if ((!WIFSTOPPED (show->status)) && (WIFCORED (show->status)))
  675.         fprintf (stream, "(core dumped) ");
  676.         }
  677.     }
  678.  
  679.       if (p != first && format)
  680.     fprintf (stream, "| ");
  681.  
  682.       fprintf (stream, "%s", p->command);
  683.  
  684.       if (p == last) 
  685.     {
  686.       char *wd = job_working_directory ();
  687.  
  688.       if (JOBSTATE (index) == JRUNNING && jobs[index]->foreground == 0)
  689.         fprintf (stream, " &");
  690.  
  691.       if (strcmp (wd, jobs[index]->wd) != 0)
  692.         fprintf (stream,
  693.              "  (wd: %s)", polite_directory_format (jobs[index]->wd));
  694.       free (wd);
  695.     }
  696.  
  697.       if (format || (p == last))
  698.     fprintf (stream, "\r\n");
  699.  
  700.       if (p == last)
  701.     break;
  702.       p = p->next;
  703.     }
  704.  
  705.   fflush (stream);
  706.   UNBLOCK_CHILD (oset);
  707. }
  708.  
  709. list_one_job (job, format, ignore, index)
  710.      JOB *job;
  711.      int format, ignore, index;
  712. {
  713.   pretty_print_job (index, format, stdout);
  714.   return (0);
  715. }
  716.  
  717. /* List jobs.  If FORMAT is non-zero, then the long form of the information
  718.    is printed, else just a short version. */
  719. list_jobs (format)
  720.      int format;
  721. {
  722.   cleanup_dead_jobs ();
  723.   map_over_jobs (list_one_job, format, (int)IGNORE_ARG);
  724. }
  725.  
  726. /* Fork, handling errors.  Returns the pid of the newly made child, or 0.
  727.    COMMAND is just for remembering the name of the command; we don't do
  728.    anything else with it.  ASYNC_P says what to do with the tty.  If
  729.    non-zero, then don't give it away. */
  730. pid_t
  731. make_child (command, async_p)
  732.      char *command;
  733.      int async_p;
  734. {
  735.   pid_t pid;
  736.   sigset_t set, oset;
  737.  
  738.   sigemptyset (&set);
  739.   sigaddset (&set, SIGCHLD);
  740.   sigaddset (&set, SIGINT);
  741.   sigemptyset (&oset);
  742.   sigprocmask (SIG_BLOCK, &set, &oset);
  743.  
  744.   making_children ();
  745.  
  746.   /* Make new environment array if neccessary. */
  747.   maybe_make_export_env ();
  748.  
  749.   /* Create the child, handle severe errors. */
  750.   if ((pid = fork ()) < 0)
  751.     {
  752.       extern sighandler throw_to_top_level ();
  753.  
  754.       /* Unblock SIGINT, SIGCHLD. */
  755.       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  756.  
  757.       report_error ("fork: %s", (char *)strerror (errno));
  758.  
  759.       /* Kill all of the processes in the current pipeline. */
  760.       terminate_current_pipeline ();
  761.  
  762.       /* Discard the current pipeline, if any. */
  763.       if (the_pipeline)
  764.     kill_current_pipeline ();
  765.  
  766.       throw_to_top_level ();
  767.     }
  768.  
  769.   if (!pid)
  770.     {
  771.       /* In the child.  Give this child the right process group, set the
  772.      signals to the default state for a new process. */
  773.       pid_t mine = getpid ();
  774.  
  775.       /* Give these signals the values they had when this shell was
  776.      started. */
  777.       restore_default_signal (SIGINT);
  778.       restore_default_signal (SIGQUIT);
  779.       restore_default_signal (SIGTERM);
  780.  
  781.       /* Cancel traps, in trap.c. */
  782.       restore_original_signals ();
  783.  
  784.       if (job_control)
  785.     {
  786.       /* All processes in this pipeline belong in the same
  787.          process group. */
  788.  
  789.       if (!pipeline_pgrp)    /* Then this is the first child. */
  790.         pipeline_pgrp = mine;
  791.  
  792.       /* Check for running command in backquotes. */
  793.       if (pipeline_pgrp == shell_pgrp)
  794.         {
  795.           signal (SIGTSTP, SIG_IGN);
  796.           signal (SIGTTOU, SIG_IGN);
  797.           signal (SIGTTIN, SIG_IGN);
  798.         }
  799.       else
  800.         {
  801.           signal (SIGTSTP, SIG_DFL);
  802.           signal (SIGTTOU, SIG_DFL);
  803.           signal (SIGTTIN, SIG_DFL);
  804.         }
  805.       
  806.       /* Set the process group before trying to mess with the terminal's
  807.          process group.  This is mandated by POSIX. */
  808.       if (setpgid (0, pipeline_pgrp) < 0)
  809.         fprintf (stderr, "%s: child setpgid (%d to %d) error %d: %s\n",
  810.              shell_name, mine, pipeline_pgrp, errno,
  811.              (char *)strerror (errno));
  812.  
  813.       /* If mypid == pipeline_pgrp, this process is a process group
  814.          leader.  Set the terminal to be owned by the pipeline
  815.          process group, then wait until the other pipeline processes
  816.          have been created.  We wait by letting the OS block in read (). */
  817.       if (pipeline_pgrp == mine)
  818.         {
  819.           if (!async_p)
  820.         give_terminal_to (pipeline_pgrp);
  821.  
  822.           pipe_read (pgrp_pipe);
  823.         }
  824.     }
  825.       else            /* Without job control... */
  826.     {
  827.       if (!pipeline_pgrp)
  828.         pipeline_pgrp = shell_pgrp;
  829.  
  830.       signal (SIGTSTP, SIG_DFL);
  831.       signal (SIGTTOU, SIG_DFL);
  832.       signal (SIGTTIN, SIG_DFL);
  833.  
  834.       if (async_p)
  835.         {
  836.           signal (SIGINT, SIG_IGN);
  837.           signal (SIGQUIT, SIG_IGN);
  838.         }
  839.     }
  840.  
  841.       /* Release the process group pipe, since our call to setpgid () 
  842.      is done.  The last call to pipe_close is done in stop_pipeline. */
  843.       pipe_close (pgrp_pipe);
  844.  
  845.       if (async_p)
  846.     last_asynchronous_pid = getpid ();
  847.     }
  848.   else
  849.     {
  850.       /* In the parent.  Remember the pid of the child just created
  851.      as the proper pgrp if this is the first child. */
  852.  
  853.       if (job_control)
  854.     {
  855.       if (!pipeline_pgrp)
  856.         {
  857.           pipeline_pgrp = pid;
  858.           /* Don't twiddle terminal pgrps in the parent!  This is the bug,
  859.          not the good thing of twiddling them in the child! */
  860.           /* give_terminal_to (pipeline_pgrp); */
  861.         }
  862.       /* This is done on the recommendation of the Rationale section of
  863.          the POSIX 1003.1 standard, where it discusses job control and
  864.          shells.  It is done to avoid possible race conditions. (Ref.
  865.          1003.1 Rationale, section B.4.3.3, page 236). */
  866.       setpgid (pid, pipeline_pgrp);
  867.     }
  868.       else
  869.     {
  870.       if (!pipeline_pgrp)
  871.         pipeline_pgrp = shell_pgrp;
  872.     }
  873.  
  874.       /* Place all processes into the jobs array regardless of the
  875.      state of job_control. */
  876.       add_process (command, pid);
  877.  
  878.       if (async_p)
  879.     last_asynchronous_pid = pid;
  880.  
  881.       last_made_pid = pid;
  882.     }
  883.  
  884.   sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  885.   return (pid);
  886. }
  887.  
  888. /* When we end a job abnormally, or if we stop a job, we set the tty to the
  889.    state kept in here.  When a job ends normally, we set the state in here
  890.    to the state of the tty. */
  891.  
  892. #if defined (NEW_TTY_DRIVER)
  893. static struct sgttyb shell_tty_info;
  894. static struct tchars shell_tchars;
  895. static struct ltchars shell_ltchars;
  896. #endif /* NEW_TTY_DRIVER */
  897.  
  898. #if defined (TERMIO_TTY_DRIVER)
  899. static struct termio shell_tty_info;
  900. #endif /* TERMIO_TTY_DRIVER */
  901.  
  902. #if defined (TERMIOS_TTY_DRIVER)
  903. static struct termios shell_tty_info;
  904. #endif /* TERMIOS_TTY_DRIVER */
  905.  
  906. #if defined (NEW_TTY_DRIVER) && defined (DRAIN_OUTPUT)
  907. /* Since the BSD tty driver does not allow us to change the tty modes
  908.    while simultaneously waiting for output to drain and preserving
  909.    typeahead, we have to drain the output ourselves before calling
  910.    ioctl.  We cheat by finding the length of the output queue, and
  911.    using select to wait for an appropriate length of time.  This is
  912.    a hack, and should be labeled as such (it's a hastily-adapted
  913.    mutation of a `usleep' implementation).  It's only reason for
  914.    existing is the flaw in the BSD tty driver. */
  915.  
  916. static int ttspeeds[] =
  917. {
  918.   0, 50, 75, 110, 134, 150, 200, 300, 600, 1200,
  919.   1800, 2400, 4800, 9600, 19200, 38400
  920. };
  921.  
  922. static void
  923. draino (fd, ospeed)
  924.      int fd, ospeed;
  925. {
  926.   register int delay = ttspeeds[ospeed];
  927.   int n;
  928.  
  929.   if (!delay)
  930.     return;
  931.  
  932.   while ((ioctl (fd, TIOCOUTQ, &n) == 0) && n)
  933.     {
  934.       if (n > (delay / 100))
  935.     {
  936.       struct timeval tv;
  937.  
  938.       n *= 10;        /* 2 bits more for conservativeness. */
  939.       tv.tv_sec = n / delay;
  940.       tv.tv_usec = ((n % delay) * 1000000) / delay;
  941.       select (fd, 0, (fd_set *) 0, (fd_set *) 0, (fd_set *) 0, &tv);
  942.     }
  943.       else
  944.     break;
  945.     }
  946. }
  947. #endif /* NEW_TTY_DRIVER && DRAIN_OUTPUT */
  948.  
  949. /* Return the fd from which we are actually getting input.  Should be
  950.    inlined by the compiler. */
  951. static int
  952. input_tty ()
  953. {
  954.   int tty = shell_tty;
  955.  
  956.   if (tty == -1)
  957.     tty = fileno (stdin);
  958.  
  959.   return (tty);
  960. }
  961.  
  962. /* Fill the contents of shell_tty_info with the current tty info. */
  963. get_tty_state ()
  964. {
  965.   int tty = input_tty ();
  966.  
  967.   if (tty != -1)
  968.     {
  969. #if defined (NEW_TTY_DRIVER)
  970.       ioctl (tty, TIOCGETP, &shell_tty_info);
  971.       ioctl (tty, TIOCGETC, &shell_tchars);
  972.       ioctl (tty, TIOCGLTC, &shell_ltchars);
  973. #endif /* NEW_TTY_DRIVER */
  974.  
  975. #if defined (TERMIO_TTY_DRIVER)
  976.       ioctl (tty, TCGETA, &shell_tty_info);
  977. #endif /* TERMIO_TTY_DRIVER */
  978.  
  979. #if defined (TERMIOS_TTY_DRIVER)
  980.       if (tcgetattr (tty, &shell_tty_info) < 0)
  981.     {
  982.       extern int shell_level;
  983.  
  984.       fprintf (stderr, "%s: [%d: %d] tcgetattr: %s\n", shell_name,
  985.            getpid (), shell_level, (char *)strerror (errno));
  986.     }
  987. #endif /* TERMIOS_TTY_DRIVER */
  988.     }
  989. }
  990.  
  991. /* Make the current tty use the state in shell_tty_info. */
  992. set_tty_state ()
  993. {
  994.   int tty = input_tty ();
  995.  
  996.   if (tty != -1)
  997.     {
  998. #if defined (NEW_TTY_DRIVER)
  999. #  if defined (DRAIN_OUTPUT)
  1000.       draino (tty, shell_tty_info.sg_ospeed);
  1001. #  endif /* DRAIN_OUTPUT */
  1002.       ioctl (tty, TIOCSETN, &shell_tty_info);
  1003.       ioctl (tty, TIOCSETC, &shell_tchars);
  1004.       ioctl (tty, TIOCSLTC, &shell_ltchars);
  1005. #endif /* NEW_TTY_DRIVER */
  1006.  
  1007. #if defined (TERMIO_TTY_DRIVER)
  1008.       ioctl (tty, TCSETAW, &shell_tty_info);
  1009. #endif /* TERMIO_TTY_DRIVER */
  1010.  
  1011. #if defined (TERMIOS_TTY_DRIVER)
  1012.       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
  1013.     {
  1014.       extern int shell_level;
  1015.  
  1016.       fprintf (stderr, "%s: [%d: %d] tcsetattr: %s\n", shell_name,
  1017.            getpid (), shell_level, (char *)strerror (errno));
  1018.     }
  1019. #endif /* TERMIOS_TTY_DRIVER */
  1020.     }
  1021. }
  1022.  
  1023. /* Given an index into the jobs array JOB, return the pid of the last
  1024.    process in that job's pipeline.  This is the one whose exit status
  1025.    counts. */
  1026. pid_t
  1027. last_pid (job)
  1028.      int job;
  1029. {
  1030.   register PROCESS *p;
  1031.   sigset_t set, oset;
  1032.  
  1033.   BLOCK_CHILD (set, oset);
  1034.  
  1035.   p = jobs[job]->pipe;
  1036.   while (p->next != jobs[job]->pipe)
  1037.     p = p->next;
  1038.  
  1039.   UNBLOCK_CHILD (oset);
  1040.   return (p->pid);
  1041. }
  1042.  
  1043. /* Wait for a particular child of the shell to finish executing.
  1044.    This low-level function prints an error message if PID is not
  1045.    a child of this shell.  It returns -1 if it fails, or 0 if not. */
  1046. int
  1047. wait_for_single_pid (pid)
  1048.      pid_t pid;
  1049. {
  1050.   register PROCESS *child;
  1051.  
  1052.   child = find_pipeline (pid);
  1053.  
  1054.   if (!child)
  1055.     {
  1056.       report_error ("wait: pid %d is not a child of this shell", pid);
  1057.       return (-1);
  1058.     }
  1059.  
  1060.   return (wait_for (pid));
  1061. }
  1062.  
  1063. /* Wait for all of the backgrounds of this shell to finish. */
  1064. void
  1065. wait_for_background_pids ()
  1066. {
  1067.   while (1)
  1068.     {
  1069.       register int i, count = 0;
  1070.       sigset_t set, oset;
  1071.  
  1072.       BLOCK_CHILD (set, oset);
  1073.  
  1074.       for (i = 0; i < job_slots; i++)
  1075.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !(jobs[i]->foreground))
  1076.       {
  1077.         count++;
  1078.         break;
  1079.       }
  1080.  
  1081.       if (!count)
  1082.     {
  1083.       UNBLOCK_CHILD (oset);
  1084.       break;
  1085.     }
  1086.  
  1087.       for (i = 0; i < job_slots; i++)
  1088.     if (jobs[i] && (JOBSTATE (i) == JRUNNING) && !jobs[i]->foreground)
  1089.       {
  1090.         pid_t pid = last_pid (i);
  1091.         UNBLOCK_CHILD (oset);
  1092.         QUIT;
  1093.         wait_for_single_pid (pid);
  1094.         break;
  1095.       }
  1096.     }
  1097. }
  1098.  
  1099. /* Wait for pid (one of our children) to terminate, then
  1100.    return the termination state. */
  1101. int
  1102. wait_for (pid)
  1103.      pid_t pid;
  1104. {
  1105.   int job, termination_state;
  1106.   register PROCESS *child;
  1107.   extern char *sys_siglist[];
  1108.   sigset_t set, oset;
  1109.  
  1110.   BLOCK_CHILD (set, oset);
  1111.  
  1112.   /* If we say wait_for (), then we have a record of this child somewhere.
  1113.      If this child and all of its peers are not running, then don't
  1114.      sigpause (), since there is no need to. */
  1115.  wait_loop:
  1116.  
  1117.   /* If the shell is running interactively, and the shell is the foreground
  1118.      process (e.g. executing a `wait' command) then let the user C-c out. */
  1119.   if (interactive && (terminal_pgrp == shell_pgrp))
  1120.     QUIT;
  1121.  
  1122.   child = find_pipeline (pid);
  1123.  
  1124.   if (!child)
  1125.     {
  1126.       give_terminal_to (shell_pgrp);
  1127.       UNBLOCK_CHILD (oset);
  1128.       programming_error ("wait_for: No record of pid %d", pid);
  1129.     }
  1130.  
  1131.   /* If this child is part of a job, then we are really waiting for the
  1132.      job to finish.  Otherwise, we are waiting for the child to finish. */
  1133.  
  1134.   job = find_job (pid);
  1135.  
  1136.   if (job != NO_JOB)
  1137.     {
  1138.       register int job_state = 0, any_stopped = 0;
  1139.       register PROCESS *p = jobs[job]->pipe;
  1140.  
  1141.       do
  1142.     {
  1143.       job_state |= p->running;
  1144.       if (!p->running)
  1145.         any_stopped |= WIFSTOPPED (p->status);
  1146.       p = p->next;
  1147.     }
  1148.       while (p != jobs[job]->pipe);
  1149.  
  1150.       if (job_state == 0)
  1151.     {
  1152.       if (any_stopped)
  1153.         jobs[job]->state = JSTOPPED;
  1154.       else
  1155.         jobs[job]->state = JDEAD;
  1156.     }
  1157.     }
  1158.  
  1159.   if (child->running ||
  1160.       ((job != NO_JOB) && (JOBSTATE (job) == JRUNNING)))
  1161.     {
  1162. #if !defined (M_UNIX)
  1163.       sigset_t set;
  1164.  
  1165.       sigemptyset (&set);
  1166.       sigsuspend (&set);
  1167. #else /* SCO Unix */
  1168.       struct sigaction act, oact;
  1169.  
  1170.       act.sa_handler = SIG_DFL;
  1171.       sigemptyset (&act.sa_mask);
  1172.       act.sa_flags = 0;
  1173.  
  1174.       sigaction (SIGCHLD, &act, &oact);
  1175.       flush_child (0);
  1176.       sigaction (SIGCHLD, &oact, (struct sigaction *)NULL);
  1177. #endif /* !M_UNIX */
  1178.  
  1179.       goto wait_loop;
  1180.     }
  1181.  
  1182.   /* The exit state of the command is either the termination state of the
  1183.      child, or the termination state of the job.  If a job, the status
  1184.      of the last child in the pipeline is the significant one. */
  1185.  
  1186.   if (job != NO_JOB)
  1187.     {
  1188.       register PROCESS *p = jobs[job]->pipe;
  1189.  
  1190.       while (p->next != jobs[job]->pipe)
  1191.     p = p->next;
  1192.       if (WIFSIGNALED (p->status))
  1193.     termination_state = 128 + WTERMSIG (p->status);
  1194.       else
  1195.     termination_state = WEXITSTATUS (p->status);
  1196.     }
  1197.   else
  1198.     {
  1199.       if (WIFSIGNALED (child->status))
  1200.     termination_state = 128 + WTERMSIG (child->status);
  1201.       else
  1202.     termination_state = WEXITSTATUS (child->status);
  1203.     }
  1204.  
  1205.   if (job == NO_JOB || jobs[job]->job_control)
  1206.     give_terminal_to (shell_pgrp);
  1207.  
  1208.   /* If the command did not exit cleanly, or the job is just
  1209.      being stopped, then reset the tty state back to what it
  1210.      was before this command.  Do this only if the shell is
  1211.      interactive. */
  1212.   if (job != NO_JOB && interactive)
  1213.     {
  1214.       if (WIFSIGNALED (child->status) || WIFSTOPPED (child->status))
  1215.     set_tty_state ();
  1216.       else
  1217.     get_tty_state ();
  1218.  
  1219.       notify_and_cleanup ();
  1220.     }
  1221.  
  1222.  wait_exit:
  1223.   UNBLOCK_CHILD (oset);
  1224.   return (termination_state);
  1225. }
  1226.  
  1227. /* Wait for the last process in the pipeline for JOB. */
  1228. int
  1229. wait_for_job (job)
  1230.      int job;
  1231. {
  1232.   pid_t pid = last_pid (job);
  1233.   return (wait_for (pid));
  1234. }
  1235.  
  1236. /* Print info about dead jobs, and then delete them from the list
  1237.    of known jobs. */
  1238. notify_and_cleanup ()
  1239. {
  1240.   if (interactive)
  1241.     notify_of_job_status ();
  1242.   cleanup_dead_jobs ();
  1243. }
  1244.  
  1245. /* Return the next closest (chronologically) job to JOB which is in
  1246.    STATE.  STATE can be JSTOPPED, JRUNNING.  NO_JOB is returned if
  1247.    there is no next recent job. */
  1248. static int
  1249. most_recent_job_in_state (job, state)
  1250.      int job;
  1251.      JOB_STATE state;
  1252. {
  1253.   register int i;
  1254.   sigset_t set, oset;
  1255.  
  1256.   BLOCK_CHILD (set, oset);
  1257.  
  1258.   for (i = job - 1; i >= 0; i--)
  1259.     {
  1260.       if (jobs[i])
  1261.     {
  1262.       if (JOBSTATE (i) == state)
  1263.         {
  1264.           /* Found it! */
  1265.           UNBLOCK_CHILD (oset);
  1266.           return (i);
  1267.         }
  1268.     }
  1269.     }
  1270.   UNBLOCK_CHILD (oset);
  1271.   return (NO_JOB);
  1272. }
  1273.  
  1274. /* Return the newest *stopped* job older than JOB, or NO_JOB if not
  1275.    found. */
  1276. static int
  1277. last_stopped_job (job)
  1278.      int job;
  1279. {
  1280.   return (most_recent_job_in_state (job, JSTOPPED));
  1281. }
  1282.  
  1283. /* Return the newest *running* job older than JOB, or NO_JOB if not
  1284.    found. */
  1285. static int
  1286. last_running_job (job)
  1287.      int job;
  1288. {
  1289.   return (most_recent_job_in_state (job, JRUNNING));
  1290. }
  1291.  
  1292. /* Make JOB be the current job, and make previous be useful. */
  1293. set_current_job (job)
  1294.      int job;
  1295. {
  1296.   int candidate = NO_JOB;
  1297.  
  1298.   if (current_job != job)
  1299.     {
  1300.       previous_job = current_job;
  1301.       current_job = job;
  1302.     }
  1303.  
  1304.   /* First choice for previous_job is the old current_job. */
  1305.   if (previous_job != current_job &&
  1306.       previous_job != NO_JOB &&
  1307.       jobs[previous_job] &&
  1308.       JOBSTATE (previous_job) == JSTOPPED)
  1309.     return;
  1310.  
  1311.   /* Second choice:  Newest stopped job that is older than
  1312.      the current job. */
  1313.   if (JOBSTATE (current_job) == JSTOPPED)
  1314.     {
  1315.       candidate = last_stopped_job (current_job);
  1316.  
  1317.       if (candidate != NO_JOB)
  1318.     {
  1319.       previous_job = candidate;
  1320.       return;
  1321.     }
  1322.     }
  1323.  
  1324.   /* If we get here, there is either only one stopped job, in which case it is
  1325.      the current job and the previous job should be set to the newest running
  1326.      job, or there are only running jobs and the previous job should be set to
  1327.      the newest running job older than the current job.  We decide on which
  1328.      alternative to use based on whether or not JOBSTATE(current_job) is
  1329.      JSTOPPED. */
  1330.  
  1331.   if (JOBSTATE (current_job) == JRUNNING)
  1332.     candidate = last_running_job (current_job);
  1333.   else
  1334.     candidate = last_running_job (job_slots);
  1335.  
  1336.   if (candidate != NO_JOB)
  1337.     {
  1338.       previous_job = candidate;
  1339.       return;
  1340.     }
  1341.  
  1342.   /* There is only a single job, and it is both `+' and `-'. */
  1343.   previous_job = current_job;
  1344. }
  1345.  
  1346. /* Make current_job be something useful, if it isn't already. */
  1347.  
  1348. /* Here's the deal:  The newest non-running job should be `+', and the
  1349.    next-newest non-running job should be `-'.  If there is only a single
  1350.    stopped job, the previous_job is the newest non-running job.  If there
  1351.    are only running jobs, the newest running job is `+' and the
  1352.    next-newest running job is `-'. */
  1353.  
  1354. reset_current ()
  1355. {
  1356.   int candidate = NO_JOB;
  1357.  
  1358.   if (current_job != NO_JOB &&
  1359.       job_slots && jobs[current_job] &&
  1360.       JOBSTATE (current_job) == JSTOPPED)
  1361.     {
  1362.       candidate = current_job;
  1363.     }
  1364.   else
  1365.     {
  1366.       /* First choice: the previous job! */
  1367.       if (previous_job != NO_JOB && jobs[previous_job] &&
  1368.       JOBSTATE (previous_job) == JSTOPPED)
  1369.     candidate = previous_job;
  1370.  
  1371.       /* Second choice: the most recently stopped job. */
  1372.       if (candidate == NO_JOB)
  1373.     candidate = last_stopped_job (job_slots);
  1374.  
  1375.       if (candidate == NO_JOB)
  1376.     {
  1377.       /* Third choice: the newest running job. */
  1378.       candidate = last_running_job (job_slots);
  1379.     }
  1380.     }
  1381.  
  1382.   /* If we found a job to use, then use it.  Otherwise, there
  1383.      are no jobs period. */
  1384.   if (candidate != NO_JOB)
  1385.     set_current_job (candidate);
  1386.   else
  1387.     current_job = previous_job = NO_JOB;
  1388. }
  1389.  
  1390. /* Start a job.  FOREGROUND if non-zero says to do that.  Otherwise,
  1391.    start the job in the background.  JOB is a zero-based index into
  1392.    JOBS.  Returns zero if it is unable to start a job. */
  1393. int
  1394. start_job (job, foreground)
  1395.      int job, foreground;
  1396. {
  1397.   register PROCESS *p;
  1398.   int already_running;
  1399.   sigset_t set, oset;
  1400.   char *wd;
  1401. #if defined (NEW_TTY_DRIVER)
  1402.   static struct sgttyb save_stty;
  1403. #endif
  1404.  
  1405. #if defined (TERMIO_TTY_DRIVER)
  1406.   static struct termio save_stty;
  1407. #endif
  1408.  
  1409. #if defined (TERMIOS_TTY_DRIVER)
  1410.   static struct termios save_stty;
  1411. #endif
  1412.  
  1413.   BLOCK_CHILD (set, oset);
  1414.   already_running = (JOBSTATE (job) == JRUNNING);
  1415.  
  1416.   if (!foreground && already_running)
  1417.     {
  1418.       extern char *this_command_name;
  1419.  
  1420.       report_error ("%s: bg background job?", this_command_name);
  1421.       UNBLOCK_CHILD (oset);
  1422.       return (0);
  1423.     }
  1424.  
  1425.   wd = job_working_directory ();
  1426.  
  1427.   /* You don't know about the state of this job.  Do you? */
  1428.   jobs[job]->notified = 0;
  1429.  
  1430.   if (foreground)
  1431.     {
  1432.       set_current_job (job);
  1433.       jobs[job]->foreground = 1;
  1434.     }
  1435.  
  1436.   /* Tell the outside world what we're doing. */
  1437.   p = jobs[job]->pipe;
  1438.  
  1439.   if (!foreground)
  1440.     fprintf (stderr, "[%d]%c ", job + 1,
  1441.        (job == current_job) ? '+': ((job == previous_job) ? '-' : ' '));
  1442.  
  1443.   do
  1444.     {
  1445.       fprintf (stderr, "%s%s",
  1446.            p->command, p->next != jobs[job]->pipe? " | " : "");
  1447.       p = p->next;
  1448.     }
  1449.   while (p != jobs[job]->pipe);
  1450.  
  1451.   if (!foreground)
  1452.     fprintf (stderr, " &");
  1453.       
  1454.   if (strcmp (wd, jobs[job]->wd) != 0)
  1455.     fprintf (stderr, "    (wd: %s)", polite_directory_format (jobs[job]->wd));
  1456.  
  1457.   fprintf (stderr, "\n");
  1458.   
  1459.   free (wd);
  1460.  
  1461.   /* Run the job. */
  1462.   if (!already_running)
  1463.     {
  1464.       /* Each member of the pipeline is now running. */
  1465.       p = jobs[job]->pipe;
  1466.  
  1467.       do
  1468.     {
  1469.       if (WIFSTOPPED (p->status))
  1470.         p->running = 1;
  1471.       p = p->next;
  1472.     }
  1473.       while (p != jobs[job]->pipe);
  1474.  
  1475.       /* This means that the job is running. */
  1476.       JOBSTATE (job) = JRUNNING;
  1477.     }
  1478.  
  1479.   /* Save the tty settings before we start the job in the foreground. */
  1480.   if (foreground)
  1481.     {
  1482.       get_tty_state ();
  1483.       save_stty = shell_tty_info;
  1484.     }
  1485.  
  1486.   /* Give the terminal to this job. */
  1487.   if (foreground)
  1488.     {
  1489.       if (jobs[job]->job_control)
  1490.     give_terminal_to (jobs[job]->pgrp);
  1491.     }
  1492.   else
  1493.     jobs[job]->foreground = 0;
  1494.  
  1495.   /* If the job is already running, then don't bother jump-starting it. */
  1496.   if (!already_running)
  1497.     {
  1498.       jobs[job]->notified = 1;
  1499.       killpg (jobs[job]->pgrp, SIGCONT);
  1500.     }
  1501.  
  1502.   UNBLOCK_CHILD (oset);
  1503.  
  1504.   if (foreground)
  1505.     {
  1506.       pid_t pid = last_pid (job);
  1507.       int s = wait_for (pid);
  1508.  
  1509.       shell_tty_info = save_stty;
  1510.       set_tty_state ();
  1511.       return (!s);
  1512.     }
  1513.   else
  1514.     reset_current ();
  1515.  
  1516.   return (1);
  1517. }
  1518.  
  1519. /* Give PID SIGNAL.  This determines what job the pid belongs to (if any).
  1520.    If PID does belong to a job, and the job is stopped, then CONTinue the
  1521.    job after giving it SIGNAL.  Returns -1 on failure.  If GROUP is non-null,
  1522.    then kill the process group associated with PID. */
  1523. int
  1524. kill_pid (pid, signal, group)
  1525.      pid_t pid;
  1526.      int signal, group;
  1527. {
  1528.   register PROCESS *p;
  1529.   int job, result = EXECUTION_SUCCESS;
  1530.   sigset_t set, oset;
  1531.  
  1532.   BLOCK_CHILD (set, oset);
  1533.   p = find_pipeline (pid);
  1534.   job = find_job (pid);
  1535.  
  1536.   if (group)
  1537.     {
  1538.       if (job != NO_JOB)
  1539.     {
  1540.       jobs[job]->notified = 0;
  1541.  
  1542.       /* Kill process in backquotes or one started without job control? */
  1543.       if (jobs[job]->pgrp == shell_pgrp)
  1544.         {
  1545.           p = jobs[job]->pipe;
  1546.  
  1547.           do
  1548.         {
  1549.           kill (pid, signal);
  1550.           if (!p->running && (signal == SIGTERM || signal == SIGHUP))
  1551.             kill (pid, SIGCONT);
  1552.           p = p->next;
  1553.         } while (p != jobs[job]->pipe);
  1554.         }
  1555.       else
  1556.         {
  1557.           result = killpg (jobs[job]->pgrp, signal);
  1558.           if (p && (JOBSTATE (job) == JSTOPPED) &&
  1559.           (signal == SIGTERM || signal == SIGHUP))
  1560.         killpg (jobs[job]->pgrp, SIGCONT);
  1561.         }
  1562.     }
  1563.       else
  1564.     {
  1565.       result = killpg (pid, signal);
  1566.     }
  1567.     }
  1568.   else
  1569.     {
  1570.       result = kill (pid, signal);
  1571.     }
  1572.   UNBLOCK_CHILD (oset);
  1573.   return (result);
  1574. }
  1575.  
  1576. /* Flush_child () flushes at least one of the children that we are waiting for.
  1577.    It gets run when we have gotten a SIGCHLD signal, and stops when there
  1578.    aren't any children terminating any more.  If SIG is 0, this is to be a
  1579.    blocking wait for a single child.  It is here to get around SCO Unix's
  1580.    broken sigsuspend (). */
  1581. sighandler
  1582. flush_child (sig)
  1583.      int sig;
  1584. {
  1585.   WAIT status;
  1586.   PROCESS *child;
  1587.   pid_t pid;
  1588.   int call_set_current = 0, last_stopped_job = NO_JOB;
  1589.   int children_exited = 0;
  1590. #if !defined (_POSIX_VERSION) && defined (HAVE_RESOURCE)
  1591.   struct rusage rusage;
  1592. #endif /* !_POSIX_VERSION && HAVE_RESOURCE */
  1593.  
  1594.   do
  1595.     {
  1596.       /* waitpid () is broken on Ultrix MIPS machines
  1597.      (DECstations, DECsystems). */
  1598. #if defined (Ultrix) && defined (_POSIX_VERSION)
  1599.       pid = wait3 ((union wait *) &status, (WNOHANG | WUNTRACED),
  1600.            (struct rusage *)0);
  1601. #else /* !(Ultrix && POSIX) */
  1602. # if defined (_POSIX_VERSION)
  1603.       pid = waitpid ((pid_t) -1, &status,
  1604.              sig ? (WNOHANG | WUNTRACED) : WUNTRACED);
  1605. # else /* !_POSIX_VERSION */
  1606. #  if defined (hpux)
  1607.       pid = wait3 (&status, (WNOHANG | WUNTRACED), (int *)0);
  1608. #  else /* ! hpux (all other machines) */
  1609.       pid = wait3 (&status, (WNOHANG | WUNTRACED), &rusage);
  1610. #  endif /* !hpux (all other machines) */
  1611. # endif /* !_POSIX_VERSION */
  1612. #endif /* !(Ultrix && POSIX) */
  1613.  
  1614.       if (pid > 0)
  1615.     {
  1616. #if !defined (_POSIX_VERSION) && defined (hpux)
  1617.       /* Reinstall the signal handler.  That's what HPUX makes us do. */
  1618.       signal (SIGCHLD, flush_child);
  1619. #endif
  1620.       /* Locate our PROCESS for this pid. */
  1621.       child = find_pipeline (pid);
  1622.  
  1623.       /* It is not an error to have a child terminate that we did
  1624.          not have a record of.  This child could have been part of
  1625.          a pipeline in backquote substitution. */
  1626.       if (child)
  1627.         {
  1628.           int job = find_job (pid);
  1629.  
  1630.           while (child->pid != pid)
  1631.         child = child->next;
  1632.  
  1633.           /* Remember status, and fact that process is not running. */
  1634.           child->status = status;
  1635.           child->running = 0;
  1636.  
  1637.           if (job != NO_JOB)
  1638.         {
  1639.           int job_state = 0;
  1640.           int any_stopped = 0;
  1641.  
  1642.           child = jobs[job]->pipe;
  1643.           jobs[job]->notified = 0;
  1644.           
  1645.           /* If all children are not running, but any of them is
  1646.              stopped, then the job is stopped, not dead. */
  1647.           do
  1648.            {
  1649.               job_state |= child->running;
  1650.               if (!child->running)
  1651.             any_stopped |= (WIFSTOPPED (child->status));
  1652.               child = child->next;
  1653.             }
  1654.           while (child != jobs[job]->pipe);
  1655.  
  1656.           if (job_state == 0)
  1657.             {
  1658.               if (any_stopped)
  1659.             {
  1660.               jobs[job]->state = JSTOPPED;
  1661.               jobs[job]->foreground = 0;
  1662.               call_set_current++;
  1663.               last_stopped_job = job;
  1664.             }
  1665.               else
  1666.             {
  1667.               jobs[job]->state = JDEAD;
  1668.  
  1669.               if (job == last_stopped_job)
  1670.                 last_stopped_job = NO_JOB;
  1671.  
  1672.               /* If this job was not started with job control,
  1673.                  then the shell has already seen the SIGINT, since
  1674.                  the process groups are the same.  In that case,
  1675.                  don't send the SIGINT to the shell; it will
  1676.                  surprise people to have a stray interrupt
  1677.                  arriving some time after they killed the job. */
  1678.  
  1679.               if (jobs[job]->foreground &&
  1680.                   (jobs[job]->job_control || interactive) &&
  1681.                   WTERMSIG (jobs[job]->pipe->status) == SIGINT)
  1682.                 kill (getpid (), SIGINT);
  1683.  
  1684.             }
  1685.             }
  1686.         }
  1687.         }
  1688.       /* If we have caught a child, and a trap was set for SIGCHLD, then
  1689.          bump up the count of the number of children that have exited,
  1690.          so we know how many times to call it. */
  1691.       children_exited++;
  1692.     }
  1693.     }
  1694. #if defined (M_UNIX)
  1695.   while (sig && pid > (pid_t)0);   /* Hack for SCO, see earlier comment. */
  1696. #else
  1697.   while (pid > (pid_t)0);
  1698. #endif /* M_UNIX */
  1699.  
  1700.   /* If a job was running and became stopped, then set the current
  1701.      job.  Otherwise, don't change a thing. */
  1702.   if (call_set_current)
  1703.     if (last_stopped_job != NO_JOB)
  1704.       set_current_job (last_stopped_job);
  1705.     else
  1706.       reset_current ();
  1707.  
  1708.   /* Call a SIGCHLD trap handler for each child that exits, if one is set. */
  1709.   {
  1710.     extern char *trap_list[];
  1711.  
  1712.     if ((trap_list[SIGCHLD] != (char *)DEFAULT_SIG) &&
  1713.     (trap_list[SIGCHLD] != (char *)IGNORE_SIG))
  1714.       {
  1715.     extern int last_command_exit_value;
  1716.     /* It's quite dangerous to do this from a signal handler, so
  1717.        we turn off the trap list temporarily while we parse and
  1718.        execute the command.  This will protect us against (potentially
  1719.        infinite) recursive calls.  We also preserve $? around the
  1720.        execution of trap commands, by saving and restoring the value
  1721.        of last_command_exit_value. */
  1722.  
  1723.     char *trap_command = trap_list[SIGCHLD];
  1724.     int old_exit_value = last_command_exit_value;
  1725.     trap_list[SIGCHLD] = (char *)DEFAULT_SIG;
  1726.     while (children_exited--)
  1727.       parse_and_execute (savestring (trap_command), "trap");
  1728.     trap_list[SIGCHLD] = trap_command;
  1729.     last_command_exit_value = old_exit_value;
  1730.       }
  1731.   }
  1732.  
  1733.   /* We have successfully recorded the useful information about this process
  1734.      that has just changed state.  If we notify asynchronously, and the job
  1735.      that this process belongs to is no longer running, then notify the user
  1736.      of that fact now. */
  1737.   if (asynchronous_notification && interactive)
  1738.     notify_of_job_status ();
  1739. }
  1740.  
  1741. /* Function to call when you want to notify people of changes
  1742.    in job status.  This prints out all jobs which are pending
  1743.    notification to stderr, and marks those printed as already
  1744.    notified, thus making them candidates for cleanup. */
  1745. notify_of_job_status ()
  1746. {
  1747.   extern char *sys_siglist[];
  1748.   register int job, termsig;
  1749.   char *dir = job_working_directory ();
  1750.   sigset_t set, oset;
  1751.  
  1752.   sigemptyset (&set);
  1753.   sigaddset (&set, SIGCHLD);
  1754.   sigaddset (&set, SIGTTOU);
  1755.   sigemptyset (&oset);
  1756.   sigprocmask (SIG_BLOCK, &set, &oset);
  1757.  
  1758.   for (job = 0; job < job_slots; job++)
  1759.     {
  1760.       if (jobs[job] && jobs[job]->notified == 0)
  1761.     {
  1762.       WAIT s;
  1763.  
  1764.       s = jobs[job]->pipe->status;
  1765.       termsig = WTERMSIG (s);
  1766.  
  1767.       switch (JOBSTATE (job))
  1768.         {
  1769.           /* Print info on jobs that are running in the background,
  1770.          and on foreground jobs that were killed by anything
  1771.          except SIGINT. */
  1772.  
  1773.         case JDEAD:
  1774.  
  1775.           if (jobs[job]->foreground)
  1776.         {
  1777.           if (termsig && WIFSIGNALED (s) && termsig != SIGINT)
  1778.             {
  1779.               fprintf (stderr, "%s", sys_siglist[termsig]);
  1780.  
  1781.               if (WIFCORED (s))
  1782.             fprintf (stderr, " (core dumped)");
  1783.  
  1784.               fprintf (stderr, "\n");
  1785.             }
  1786.         }
  1787.           else
  1788.         {
  1789.           pretty_print_job (job, 0, stderr);
  1790.           if (dir && strcmp (dir, jobs[job]->wd) != 0)
  1791.             fprintf (stderr,
  1792.                  "(wd now: %s)\n", polite_directory_format (dir));
  1793.         }
  1794.           jobs[job]->notified = 1;
  1795.           break;
  1796.  
  1797.         case JSTOPPED:
  1798.           fprintf (stderr, "\n");
  1799.           pretty_print_job (job, 0, stderr);
  1800.           if (dir && (strcmp (dir, jobs[job]->wd) != 0))
  1801.         fprintf (stderr,
  1802.              "(wd now: %s)\n", polite_directory_format (dir));
  1803.           jobs[job]->notified = 1;
  1804.           break;
  1805.  
  1806.         case JRUNNING:
  1807.         case JMIXED:
  1808.           break;
  1809.  
  1810.         default:
  1811.           programming_error ("notify_of_job_status");
  1812.         }
  1813.     }
  1814.     }
  1815.   free (dir);
  1816.   sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  1817. }
  1818.  
  1819. /* getpgrp () varies between systems.  Even systems that clain to be Posix.1
  1820.    compatible lie sometimes (Ultrix, SunOS4). */
  1821. #if defined (_POSIX_VERSION)
  1822. #  if !defined (Ultrix) && !defined (SunOS4)
  1823. #    define getpgid(p) getpgrp ()
  1824. #  else
  1825. #    define getpgid(p) getpgrp (p)
  1826. #  endif /* Ultrix || SunOS4 */
  1827. #else
  1828. #  define getpgid(p) getpgrp(p)
  1829. #endif /* _POSIX_VERSION */
  1830.  
  1831. /* Initialize the job control mechanism, and set up the tty stuff. */
  1832. initialize_jobs ()
  1833. {
  1834.   /* Ultrix and SunOS4 lie about their POSIXness.  This call to getpgrp ()
  1835.      could be much uglier. */
  1836.   shell_pgrp = getpgid (0);
  1837.  
  1838.   if (shell_pgrp == -1)
  1839.     {
  1840.       fprintf (stderr, "%s: initialize_jobs: getpgrp failed: %s\n",
  1841.            shell_name, (char *)strerror (errno));
  1842.       exit (1);
  1843.     }
  1844.  
  1845.   /* We can only have job control if we are interactive?
  1846.      I guess that makes sense. */
  1847.  
  1848.   if (!interactive)
  1849.     {
  1850.       job_control = 0;
  1851.     }
  1852.   else
  1853.     {
  1854.       /* Make sure that we are using the new line discipline. */
  1855.  
  1856.       /* Get our controlling terminal.  If job_control is set, or
  1857.      interactive is set, then this is an interactive shell no
  1858.      matter what opening /dev/tty returns.  (It sometimes says
  1859.      the wrong thing.) */
  1860. #if !defined (M_UNIX) /* SCO Unix fails attempting job control on /dev/tty. */
  1861.       if ((shell_tty = open ("/dev/tty", O_RDWR, 0666)) < 0)
  1862. #endif /* !M_UNIX */
  1863.     shell_tty = dup (fileno (stdin));
  1864.  
  1865.       /* Find the highest unused file descriptor we can. */
  1866.       {
  1867.     int ignore, nds = getdtablesize ();
  1868.  
  1869.     while (--nds > 3)
  1870.       {
  1871.         if (fcntl (nds, F_GETFD, &ignore) == -1)
  1872.           break;
  1873.       }
  1874.  
  1875.     if (shell_tty != nds && (dup2 (shell_tty, nds) != -1))
  1876.       {
  1877.         if (shell_tty != fileno (stdin))
  1878.           close (shell_tty);
  1879.         shell_tty = nds;
  1880.       }
  1881.       }
  1882.  
  1883. #if defined (NeXT)
  1884.       /* Compensate for a bug in NeXT 2.0 /usr/etc/rlogind. */
  1885.       if (shell_pgrp == 0)
  1886.     {
  1887.       shell_pgrp = getpid ();
  1888.       setpgid (0, shell_pgrp);
  1889.       tcsetpgrp (shell_tty, shell_pgrp);
  1890.     }
  1891. #endif /* NeXT */
  1892.  
  1893.       while ((terminal_pgrp = tcgetpgrp (shell_tty)) != -1)
  1894.     {
  1895.       if (shell_pgrp != terminal_pgrp)
  1896.         {
  1897.           SigHandler *old_ttin = (SigHandler *)signal (SIGTTIN, SIG_DFL);
  1898.           kill (0, SIGTTIN);
  1899.           signal (SIGTTIN, old_ttin);
  1900.           continue;
  1901.         }
  1902.       break;
  1903.     }
  1904.  
  1905.       if (set_new_line_discipline (shell_tty) < 0)
  1906.     {
  1907.       fprintf (stderr, "%s: initialize_jobs: line discipline: %s",
  1908.            shell_name, (char *)strerror (errno));
  1909.       job_control = 0;
  1910.     }
  1911.       else
  1912.     {
  1913.       original_pgrp = shell_pgrp;
  1914.       shell_pgrp = getpid ();
  1915.  
  1916.       if ((original_pgrp != shell_pgrp) &&
  1917.           (setpgid (0, shell_pgrp) < 0))
  1918.         {
  1919.           fprintf (stderr, "%s: initialize_jobs: setpgid: %s\n",
  1920.                shell_name, (char *)strerror (errno));
  1921.  
  1922.           shell_pgrp = original_pgrp;
  1923.         }
  1924.  
  1925.       job_control = 1;
  1926.       give_terminal_to (shell_pgrp);
  1927.     }
  1928.     }
  1929.  
  1930.   if (shell_tty != fileno (stdin))
  1931.     SET_CLOSE_ON_EXEC (shell_tty);
  1932.  
  1933. #if !defined (_POSIX_VERSION)
  1934.   signal (SIGCHLD, flush_child);
  1935. #else
  1936.   /* Some Posix job control implementations (like SCO 3.2.x) set signals to
  1937.      call sigaction with NOCLDSTOP set in sa_flags.  Make sure we get
  1938.      signalled on child status changes by using sigaction instead of
  1939.      signal. */
  1940.   {
  1941.     struct sigaction act;
  1942.     act.sa_handler = flush_child;
  1943.     sigemptyset (&act.sa_mask);
  1944.     sigaddset (&act.sa_mask, SIGCHLD);
  1945.     act.sa_flags = 0;
  1946.     sigaction (SIGCHLD, &act, (struct sigaction *)NULL);
  1947.   }
  1948. #endif /* _POSIX_VERSION */
  1949.  
  1950.   change_flag_char ('m', job_control ? '-' : '+');
  1951.  
  1952.   if (interactive)
  1953.     get_tty_state ();
  1954. }
  1955.  
  1956. /* Set the line discipline to the best this system has to offer.
  1957.    Return -1 if this is not possible. */
  1958. int
  1959. set_new_line_discipline (tty)
  1960.      int tty;
  1961. {
  1962. #if defined (NEW_TTY_DRIVER)
  1963.   int ldisc;
  1964.  
  1965.   if (ioctl (tty, TIOCGETD, &ldisc) < 0)
  1966.     return (-1);
  1967.  
  1968.   if (ldisc != NTTYDISC)
  1969.     {
  1970.       ldisc = NTTYDISC;
  1971.  
  1972.       if (ioctl (tty, TIOCSETD, &ldisc) < 0)
  1973.     return (-1);
  1974.     }
  1975.   return (0);
  1976. #endif /* NEW_TTY_DRIVER */
  1977.  
  1978. #if defined (TERMIO_TTY_DRIVER)
  1979. #  if defined (NTTYDISC)
  1980.   if (ioctl (tty, TCGETA, &shell_tty_info) < 0)
  1981.     return (-1);
  1982.  
  1983.   if (shell_tty_info.c_line != NTTYDISC)
  1984.     {
  1985.       shell_tty_info.c_line = NTTYDISC;
  1986.       if (ioctl (tty, TCSETAW, &shell_tty_info) < 0)
  1987.     return (-1);
  1988.     }
  1989. #endif /* NTTYDISC */
  1990.   return (0);
  1991. #endif /* TERMIO_TTY_DRIVER */
  1992.  
  1993. #if defined (TERMIOS_TTY_DRIVER)
  1994. #if defined (Ultrix) || defined (SunOS4)
  1995.   if (tcgetattr (tty, &shell_tty_info) < 0)
  1996.     return (-1);
  1997.  
  1998.   if (shell_tty_info.c_line != NTTYDISC)
  1999.     {
  2000.       shell_tty_info.c_line = NTTYDISC;
  2001.       if (tcsetattr (tty, TCSADRAIN, &shell_tty_info) < 0)
  2002.     return (-1);
  2003.     }
  2004. #endif /* Ultrix || SunOS4 */
  2005.   return (0);
  2006. #endif /* TERMIOS_TTY_DRIVER */
  2007.  
  2008. #if !defined (NEW_TTY_DRIVER) && !defined (TERMIO_TTY_DRIVER) && !defined (TERMIOS_TTY_DRIVER)
  2009.   return (-1);
  2010. #endif
  2011. }
  2012.  
  2013. /* Allow or disallow job control to take place. */
  2014. set_job_control (arg)
  2015.      int arg;
  2016. {
  2017.   job_control = arg;
  2018. }
  2019.  
  2020. static SigHandler *old_tstp, *old_ttou, *old_ttin;
  2021. static SigHandler *old_cont = (SigHandler *)SIG_DFL;
  2022.  
  2023. /* Setup this shell to handle C-C, etc. */
  2024. initialize_job_signals ()
  2025. {
  2026.   sighandler sigint_sighandler ();
  2027.  
  2028.   signal (SIGINT, sigint_sighandler);
  2029.   signal (SIGQUIT, SIG_IGN);
  2030.  
  2031.   if (interactive)
  2032.     {
  2033.       signal (SIGTSTP, SIG_IGN);
  2034.       signal (SIGTTOU, SIG_IGN);
  2035.       signal (SIGTTIN, SIG_IGN);
  2036.     }
  2037.   else if (job_control)
  2038.     {
  2039.       static sighandler stop_signal_handler ();
  2040.  
  2041.       old_tstp = (SigHandler *)signal (SIGTSTP, stop_signal_handler);
  2042.       old_ttou = (SigHandler *)signal (SIGTTOU, stop_signal_handler);
  2043.       old_ttin = (SigHandler *)signal (SIGTTIN, stop_signal_handler);
  2044.     }
  2045.   /* Leave these things alone for non-interactive shells without job
  2046.      control. */
  2047. }
  2048.  
  2049. /* Here we handle CONT signals. */
  2050. static sighandler
  2051. cont_signal_handler (sig)
  2052.      int sig;
  2053. {
  2054.   initialize_job_signals ();
  2055.   signal (SIGCONT, old_cont);
  2056.   kill (getpid (), SIGCONT);
  2057. }
  2058.  
  2059. /* Here we handle stop signals while we are running not as a login shell. */
  2060. static sighandler
  2061. stop_signal_handler (sig)
  2062.      int sig;
  2063. {
  2064.   signal (SIGTSTP, old_tstp);
  2065.   signal (SIGTTOU, old_ttou);
  2066.   signal (SIGTTIN, old_ttin);
  2067.  
  2068.   old_cont = (SigHandler *)signal (SIGCONT, cont_signal_handler);
  2069.  
  2070.   give_terminal_to (shell_pgrp);
  2071.  
  2072.   kill (getpid (), sig);
  2073. }
  2074.  
  2075. /* Give the terminal to PGRP.  */
  2076. give_terminal_to (pgrp)
  2077.      pid_t pgrp;
  2078. {
  2079.   sigset_t set, oset;
  2080.  
  2081.   if (job_control)
  2082.     {
  2083.       sigemptyset (&set);
  2084.       sigaddset (&set, SIGTTOU);
  2085.       sigaddset (&set, SIGTTIN);
  2086.       sigaddset (&set, SIGTSTP);
  2087.       sigaddset (&set, SIGCHLD);
  2088.       sigemptyset (&oset);
  2089.       sigprocmask (SIG_BLOCK, &set, &oset);
  2090.  
  2091.       if (tcsetpgrp (shell_tty, pgrp) < 0)
  2092.     {
  2093.       /* Maybe we should print an error message? */
  2094.     }
  2095.       else
  2096.     terminal_pgrp = pgrp;
  2097.  
  2098.       sigprocmask (SIG_SETMASK, &oset, (sigset_t *)NULL);
  2099.     }
  2100. }
  2101.  
  2102. /* Clear out any jobs in the job array.  This is intended to be used by
  2103.    children of the shell, who should not have any job structures as baggage
  2104.    when they start executing (forking subshells for parenthesized execution
  2105.    and functions with pipes are the two that spring to mind). */
  2106. delete_all_jobs ()
  2107. {
  2108.   if (job_slots)
  2109.     {
  2110.       register int i;
  2111.  
  2112.       for (i = 0; i < job_slots; i++)
  2113.     if (jobs[i] != (JOB *) NULL)
  2114.       delete_job (i);
  2115.  
  2116.       free ((char *)jobs);
  2117.       job_slots = 0;
  2118.     }
  2119. }
  2120.  
  2121. /* Turn off all traces of job control.  This is run by children of the shell
  2122.    which are going to do shellsy things, like wait (), etc. */
  2123. without_job_control ()
  2124. {
  2125.   stop_making_children ();
  2126.   start_pipeline ();
  2127.   delete_all_jobs ();
  2128.   set_job_control (0);
  2129. }
  2130.  
  2131. /* Read from the read end of a pipe.  This is how the process group leader
  2132.    blocks until all of the processes in a pipeline have been made. */
  2133. pipe_read (pp)
  2134.      int *pp;
  2135. {
  2136.   char ch;
  2137.  
  2138.   if (pp[1] >= 0)
  2139.     {
  2140.       close (pp[1]);
  2141.       pp[1] = -1;
  2142.     }
  2143.  
  2144.   if (pp[0] >= 0)
  2145.     {
  2146.       while (read (pp[0], &ch, 1) == -1 && errno == EINTR)
  2147.     continue;
  2148.     }
  2149. }
  2150.  
  2151. /* Close the read and write ends of PP, an array of file descriptors. */
  2152. pipe_close (pp)
  2153.      int *pp;
  2154. {
  2155.   if (pp[0] >= 0)
  2156.     close (pp[0]);
  2157.  
  2158.   if (pp[1] >= 0)
  2159.     close (pp[1]);
  2160.  
  2161.   pp[0] = pp[1] = -1;
  2162. }
  2163.  
  2164. /* Functional interface closes our local-to-job-control pipes. */
  2165. close_pgrp_pipe ()
  2166. {
  2167.   pipe_close (pgrp_pipe);
  2168. }
  2169.  
  2170. #endif /* JOB_CONTROL */
  2171.