(linenum→info "unix/slp.c:2238")

glibc/2.7/manual/job.texi

    1: @node Job Control, Name Service Switch, Processes, Top
    2: @c %MENU% All about process groups and sessions
    3: @chapter Job Control
    4: 
    5: @cindex process groups
    6: @cindex job control
    7: @cindex job
    8: @cindex session
    9: @dfn{Job control} refers to the protocol for allowing a user to move
   10: between multiple @dfn{process groups} (or @dfn{jobs}) within a single
   11: @dfn{login session}.  The job control facilities are set up so that
   12: appropriate behavior for most programs happens automatically and they
   13: need not do anything special about job control.  So you can probably
   14: ignore the material in this chapter unless you are writing a shell or
   15: login program.
   16: 
   17: You need to be familiar with concepts relating to process creation
   18: (@pxref{Process Creation Concepts}) and signal handling (@pxref{Signal
   19: Handling}) in order to understand this material presented in this
   20: chapter.
   21: 
   22: @menu
   23: * Concepts of Job Control::     Jobs can be controlled by a shell.
   24: * Job Control is Optional::     Not all POSIX systems support job control.
   25: * Controlling Terminal::        How a process gets its controlling terminal.
   26: * Access to the Terminal::      How processes share the controlling terminal.
   27: * Orphaned Process Groups::     Jobs left after the user logs out.
   28: * Implementing a Shell::        What a shell must do to implement job control.
   29: * Functions for Job Control::   Functions to control process groups.
   30: @end menu
   31: 
   32: @node Concepts of Job Control, Job Control is Optional,  , Job Control
   33: @section Concepts of Job Control
   34: 
   35: @cindex shell
   36: The fundamental purpose of an interactive shell is to read
   37: commands from the user's terminal and create processes to execute the
   38: programs specified by those commands.  It can do this using the
   39: @code{fork} (@pxref{Creating a Process}) and @code{exec}
   40: (@pxref{Executing a File}) functions.
   41: 
   42: A single command may run just one process---but often one command uses
   43: several processes.  If you use the @samp{|} operator in a shell command,
   44: you explicitly request several programs in their own processes.  But
   45: even if you run just one program, it can use multiple processes
   46: internally.  For example, a single compilation command such as @samp{cc
   47: -c foo.c} typically uses four processes (though normally only two at any
   48: given time).  If you run @code{make}, its job is to run other programs
   49: in separate processes.
   50: 
   51: The processes belonging to a single command are called a @dfn{process
   52: group} or @dfn{job}.  This is so that you can operate on all of them at
   53: once.  For example, typing @kbd{C-c} sends the signal @code{SIGINT} to
   54: terminate all the processes in the foreground process group.
   55: 
   56: @cindex session
   57: A @dfn{session} is a larger group of processes.  Normally all the
   58: processes that stem from a single login belong to the same session.
   59: 
   60: Every process belongs to a process group.  When a process is created, it
   61: becomes a member of the same process group and session as its parent
   62: process.  You can put it in another process group using the
   63: @code{setpgid} function, provided the process group belongs to the same
   64: session.
   65: 
   66: @cindex session leader
   67: The only way to put a process in a different session is to make it the
   68: initial process of a new session, or a @dfn{session leader}, using the
   69: @code{setsid} function.  This also puts the session leader into a new
   70: process group, and you can't move it out of that process group again.
   71: 
   72: Usually, new sessions are created by the system login program, and the
   73: session leader is the process running the user's login shell.
   74: 
   75: @cindex controlling terminal
   76: A shell that supports job control must arrange to control which job can
   77: use the terminal at any time.  Otherwise there might be multiple jobs
   78: trying to read from the terminal at once, and confusion about which
   79: process should receive the input typed by the user.  To prevent this,
   80: the shell must cooperate with the terminal driver using the protocol
   81: described in this chapter.
   82: 
   83: @cindex foreground job
   84: @cindex background job
   85: The shell can give unlimited access to the controlling terminal to only
   86: one process group at a time.  This is called the @dfn{foreground job} on
   87: that controlling terminal.  Other process groups managed by the shell
   88: that are executing without such access to the terminal are called
   89: @dfn{background jobs}.
   90: 
   91: @cindex stopped job
   92: If a background job needs to read from its controlling
   93: terminal, it is @dfn{stopped} by the terminal driver; if the
   94: @code{TOSTOP} mode is set, likewise for writing.  The user can stop
   95: a foreground job by typing the SUSP character (@pxref{Special
   96: Characters}) and a program can stop any job by sending it a
   97: @code{SIGSTOP} signal.  It's the responsibility of the shell to notice
   98: when jobs stop, to notify the user about them, and to provide mechanisms
   99: for allowing the user to interactively continue stopped jobs and switch
  100: jobs between foreground and background.
  101: 
  102: @xref{Access to the Terminal}, for more information about I/O to the
  103: controlling terminal,
  104: 
  105: @node Job Control is Optional, Controlling Terminal, Concepts of Job Control , Job Control
  106: @section Job Control is Optional
  107: @cindex job control is optional
  108: 
  109: Not all operating systems support job control.  The GNU system does
  110: support job control, but if you are using the GNU library on some other
  111: system, that system may not support job control itself.
  112: 
  113: You can use the @code{_POSIX_JOB_CONTROL} macro to test at compile-time
  114: whether the system supports job control.  @xref{System Options}.
  115: 
  116: If job control is not supported, then there can be only one process
  117: group per session, which behaves as if it were always in the foreground.
  118: The functions for creating additional process groups simply fail with
  119: the error code @code{ENOSYS}.
  120: 
  121: The macros naming the various job control signals (@pxref{Job Control
  122: Signals}) are defined even if job control is not supported.  However,
  123: the system never generates these signals, and attempts to send a job
  124: control signal or examine or specify their actions report errors or do
  125: nothing.
  126: 
  127: 
  128: @node Controlling Terminal, Access to the Terminal, Job Control is Optional, Job Control
  129: @section Controlling Terminal of a Process
  130: 
  131: One of the attributes of a process is its controlling terminal.  Child
  132: processes created with @code{fork} inherit the controlling terminal from
  133: their parent process.  In this way, all the processes in a session
  134: inherit the controlling terminal from the session leader.  A session
  135: leader that has control of a terminal is called the @dfn{controlling
  136: process} of that terminal.
  137: 
  138: @cindex controlling process
  139: You generally do not need to worry about the exact mechanism used to
  140: allocate a controlling terminal to a session, since it is done for you
  141: by the system when you log in.
  142: @c ??? How does GNU system let a process get a ctl terminal.
  143: 
  144: An individual process disconnects from its controlling terminal when it
  145: calls @code{setsid} to become the leader of a new session.
  146: @xref{Process Group Functions}.
  147: 
  148: @c !!! explain how it gets a new one (by opening any terminal)
  149: @c ??? How you get a controlling terminal is system-dependent.
  150: @c We should document how this will work in the GNU system when it is decided.
  151: @c What Unix does is not clean and I don't think GNU should use that.
  152: 
  153: @node Access to the Terminal, Orphaned Process Groups, Controlling Terminal, Job Control
  154: @section Access to the Controlling Terminal
  155: @cindex controlling terminal, access to
  156: 
  157: Processes in the foreground job of a controlling terminal have
  158: unrestricted access to that terminal; background processes do not.  This
  159: section describes in more detail what happens when a process in a
  160: background job tries to access its controlling terminal.
  161: 
  162: @cindex @code{SIGTTIN}, from background job
  163: When a process in a background job tries to read from its controlling
  164: terminal, the process group is usually sent a @code{SIGTTIN} signal.
  165: This normally causes all of the processes in that group to stop (unless
  166: they handle the signal and don't stop themselves).  However, if the
  167: reading process is ignoring or blocking this signal, then @code{read}
  168: fails with an @code{EIO} error instead.
  169: 
  170: @cindex @code{SIGTTOU}, from background job
  171: Similarly, when a process in a background job tries to write to its
  172: controlling terminal, the default behavior is to send a @code{SIGTTOU}
  173: signal to the process group.  However, the behavior is modified by the
  174: @code{TOSTOP} bit of the local modes flags (@pxref{Local Modes}).  If
  175: this bit is not set (which is the default), then writing to the
  176: controlling terminal is always permitted without sending a signal.
  177: Writing is also permitted if the @code{SIGTTOU} signal is being ignored
  178: or blocked by the writing process.
  179: 
  180: Most other terminal operations that a program can do are treated as
  181: reading or as writing.  (The description of each operation should say
  182: which.)
  183: 
  184: For more information about the primitive @code{read} and @code{write}
  185: functions, see @ref{I/O Primitives}.
  186: 
  187: 
  188: @node Orphaned Process Groups, Implementing a Shell, Access to the Terminal, Job Control
  189: @section Orphaned Process Groups
  190: @cindex orphaned process group
  191: 
  192: When a controlling process terminates, its terminal becomes free and a
  193: new session can be established on it.  (In fact, another user could log
  194: in on the terminal.)  This could cause a problem if any processes from
  195: the old session are still trying to use that terminal.
  196: 
  197: To prevent problems, process groups that continue running even after the
  198: session leader has terminated are marked as @dfn{orphaned process
  199: groups}.
  200: 
  201: When a process group becomes an orphan, its processes are sent a
  202: @code{SIGHUP} signal.  Ordinarily, this causes the processes to
  203: terminate.  However, if a program ignores this signal or establishes a
  204: handler for it (@pxref{Signal Handling}), it can continue running as in
  205: the orphan process group even after its controlling process terminates;
  206: but it still cannot access the terminal any more.
  207: 
  208: @node Implementing a Shell, Functions for Job Control, Orphaned Process Groups, Job Control
  209: @section Implementing a Job Control Shell
  210: 
  211: This section describes what a shell must do to implement job control, by
  212: presenting an extensive sample program to illustrate the concepts
  213: involved.
  214: 
  215: @iftex
  216: @itemize @bullet
  217: @item
  218: @ref{Data Structures}, introduces the example and presents
  219: its primary data structures.
  220: 
  221: @item
  222: @ref{Initializing the Shell}, discusses actions which the shell must
  223: perform to prepare for job control.
  224: 
  225: @item
  226: @ref{Launching Jobs}, includes information about how to create jobs
  227: to execute commands.
  228: 
  229: @item
  230: @ref{Foreground and Background}, discusses what the shell should
  231: do differently when launching a job in the foreground as opposed to
  232: a background job.
  233: 
  234: @item
  235: @ref{Stopped and Terminated Jobs}, discusses reporting of job status
  236: back to the shell.
  237: 
  238: @item
  239: @ref{Continuing Stopped Jobs}, tells you how to continue jobs that
  240: have been stopped.
  241: 
  242: @item
  243: @ref{Missing Pieces}, discusses other parts of the shell.
  244: @end itemize
  245: @end iftex
  246: 
  247: @menu
  248: * Data Structures::             Introduction to the sample shell.
  249: * Initializing the Shell::      What the shell must do to take
  250:                                  responsibility for job control.
  251: * Launching Jobs::              Creating jobs to execute commands.
  252: * Foreground and Background::   Putting a job in foreground of background.
  253: * Stopped and Terminated Jobs::  Reporting job status.
  254: * Continuing Stopped Jobs::     How to continue a stopped job in
  255:                                  the foreground or background.
  256: * Missing Pieces::              Other parts of the shell.
  257: @end menu
  258: 
  259: @node Data Structures, Initializing the Shell,  , Implementing a Shell
  260: @subsection Data Structures for the Shell
  261: 
  262: All of the program examples included in this chapter are part of
  263: a simple shell program.  This section presents data structures
  264: and utility functions which are used throughout the example.
  265: 
  266: The sample shell deals mainly with two data structures.  The
  267: @code{job} type contains information about a job, which is a
  268: set of subprocesses linked together with pipes.  The @code{process} type
  269: holds information about a single subprocess.  Here are the relevant
  270: data structure declarations:
  271: 
  272: @smallexample
  273: @group
  274: /* @r{A process is a single process.}  */
  275: typedef struct process
  276: @{
  277:   struct process *next;       /* @r{next process in pipeline} */
  278:   char **argv;                /* @r{for exec} */
  279:   pid_t pid;                  /* @r{process ID} */
  280:   char completed;             /* @r{true if process has completed} */
  281:   char stopped;               /* @r{true if process has stopped} */
  282:   int status;                 /* @r{reported status value} */
  283: @} process;
  284: @end group
  285: 
  286: @group
  287: /* @r{A job is a pipeline of processes.}  */
  288: typedef struct job
  289: @{
  290:   struct job *next;           /* @r{next active job} */
  291:   char *command;              /* @r{command line, used for messages} */
  292:   process *first_process;     /* @r{list of processes in this job} */
  293:   pid_t pgid;                 /* @r{process group ID} */
  294:   char notified;              /* @r{true if user told about stopped job} */
  295:   struct termios tmodes;      /* @r{saved terminal modes} */
  296:   int stdin, stdout, stderr;  /* @r{standard i/o channels} */
  297: @} job;
  298: 
  299: /* @r{The active jobs are linked into a list.  This is its head.}   */
  300: job *first_job = NULL;
  301: @end group
  302: @end smallexample
  303: 
  304: Here are some utility functions that are used for operating on @code{job}
  305: objects.
  306: 
  307: @smallexample
  308: @group
  309: /* @r{Find the active job with the indicated @var{pgid}.}  */
  310: job *
  311: find_job (pid_t pgid)
  312: @{
  313:   job *j;
  314: 
  315:   for (j = first_job; j; j = j->next)
  316:     if (j->pgid == pgid)
  317:       return j;
  318:   return NULL;
  319: @}
  320: @end group
  321: 
  322: @group
  323: /* @r{Return true if all processes in the job have stopped or completed.}  */
  324: int
  325: job_is_stopped (job *j)
  326: @{
  327:   process *p;
  328: 
  329:   for (p = j->first_process; p; p = p->next)
  330:     if (!p->completed && !p->stopped)
  331:       return 0;
  332:   return 1;
  333: @}
  334: @end group
  335: 
  336: @group
  337: /* @r{Return true if all processes in the job have completed.}  */
  338: int
  339: job_is_completed (job *j)
  340: @{
  341:   process *p;
  342: 
  343:   for (p = j->first_process; p; p = p->next)
  344:     if (!p->completed)
  345:       return 0;
  346:   return 1;
  347: @}
  348: @end group
  349: @end smallexample
  350: 
  351: 
  352: @node Initializing the Shell, Launching Jobs, Data Structures, Implementing a Shell
  353: @subsection Initializing the Shell
  354: @cindex job control, enabling
  355: @cindex subshell
  356: 
  357: When a shell program that normally performs job control is started, it
  358: has to be careful in case it has been invoked from another shell that is
  359: already doing its own job control.
  360: 
  361: A subshell that runs interactively has to ensure that it has been placed
  362: in the foreground by its parent shell before it can enable job control
  363: itself.  It does this by getting its initial process group ID with the
  364: @code{getpgrp} function, and comparing it to the process group ID of the
  365: current foreground job associated with its controlling terminal (which
  366: can be retrieved using the @code{tcgetpgrp} function).
  367: 
  368: If the subshell is not running as a foreground job, it must stop itself
  369: by sending a @code{SIGTTIN} signal to its own process group.  It may not
  370: arbitrarily put itself into the foreground; it must wait for the user to
  371: tell the parent shell to do this.  If the subshell is continued again,
  372: it should repeat the check and stop itself again if it is still not in
  373: the foreground.
  374: 
  375: @cindex job control, enabling
  376: Once the subshell has been placed into the foreground by its parent
  377: shell, it can enable its own job control.  It does this by calling
  378: @code{setpgid} to put itself into its own process group, and then
  379: calling @code{tcsetpgrp} to place this process group into the
  380: foreground.
  381: 
  382: When a shell enables job control, it should set itself to ignore all the
  383: job control stop signals so that it doesn't accidentally stop itself.
  384: You can do this by setting the action for all the stop signals to
  385: @code{SIG_IGN}.
  386: 
  387: A subshell that runs non-interactively cannot and should not support job
  388: control.  It must leave all processes it creates in the same process
  389: group as the shell itself; this allows the non-interactive shell and its
  390: child processes to be treated as a single job by the parent shell.  This
  391: is easy to do---just don't use any of the job control primitives---but
  392: you must remember to make the shell do it.
  393: 
  394: 
  395: Here is the initialization code for the sample shell that shows how to
  396: do all of this.
  397: 
  398: @smallexample
  399: /* @r{Keep track of attributes of the shell.}  */
  400: 
  401: #include <sys/types.h>
  402: #include <termios.h>
  403: #include <unistd.h>
  404: 
  405: pid_t shell_pgid;
  406: struct termios shell_tmodes;
  407: int shell_terminal;
  408: int shell_is_interactive;
  409: 
  410: 
  411: /* @r{Make sure the shell is running interactively as the foreground job}
  412:    @r{before proceeding.} */
  413: 
  414: void
  415: init_shell ()
  416: @{
  417: 
  418:   /* @r{See if we are running interactively.}  */
  419:   shell_terminal = STDIN_FILENO;
  420:   shell_is_interactive = isatty (shell_terminal);
  421: 
  422:   if (shell_is_interactive)
  423:     @{
  424:       /* @r{Loop until we are in the foreground.}  */
  425:       while (tcgetpgrp (shell_terminal) != (shell_pgid = getpgrp ()))
  426:         kill (- shell_pgid, SIGTTIN);
  427: 
  428:       /* @r{Ignore interactive and job-control signals.}  */
  429:       signal (SIGINT, SIG_IGN);
  430:       signal (SIGQUIT, SIG_IGN);
  431:       signal (SIGTSTP, SIG_IGN);
  432:       signal (SIGTTIN, SIG_IGN);
  433:       signal (SIGTTOU, SIG_IGN);
  434:       signal (SIGCHLD, SIG_IGN);
  435: 
  436:       /* @r{Put ourselves in our own process group.}  */
  437:       shell_pgid = getpid ();
  438:       if (setpgid (shell_pgid, shell_pgid) < 0)
  439:         @{
  440:           perror ("Couldn't put the shell in its own process group");
  441:           exit (1);
  442:         @}
  443: 
  444:       /* @r{Grab control of the terminal.}  */
  445:       tcsetpgrp (shell_terminal, shell_pgid);
  446: 
  447:       /* @r{Save default terminal attributes for shell.}  */
  448:       tcgetattr (shell_terminal, &shell_tmodes);
  449:     @}
  450: @}
  451: @end smallexample
  452: 
  453: 
  454: @node Launching Jobs, Foreground and Background, Initializing the Shell, Implementing a Shell
  455: @subsection Launching Jobs
  456: @cindex launching jobs
  457: 
  458: Once the shell has taken responsibility for performing job control on
  459: its controlling terminal, it can launch jobs in response to commands
  460: typed by the user.
  461: 
  462: To create the processes in a process group, you use the same @code{fork}
  463: and @code{exec} functions described in @ref{Process Creation Concepts}.
  464: Since there are multiple child processes involved, though, things are a
  465: little more complicated and you must be careful to do things in the
  466: right order.  Otherwise, nasty race conditions can result.
  467: 
  468: You have two choices for how to structure the tree of parent-child
  469: relationships among the processes.  You can either make all the
  470: processes in the process group be children of the shell process, or you
  471: can make one process in group be the ancestor of all the other processes
  472: in that group.  The sample shell program presented in this chapter uses
  473: the first approach because it makes bookkeeping somewhat simpler.
  474: 
  475: @cindex process group leader
  476: @cindex process group ID
  477: As each process is forked, it should put itself in the new process group
  478: by calling @code{setpgid}; see @ref{Process Group Functions}.  The first
  479: process in the new group becomes its @dfn{process group leader}, and its
  480: process ID becomes the @dfn{process group ID} for the group.
  481: 
  482: @cindex race conditions, relating to job control
  483: The shell should also call @code{setpgid} to put each of its child
  484: processes into the new process group.  This is because there is a
  485: potential timing problem: each child process must be put in the process
  486: group before it begins executing a new program, and the shell depends on
  487: having all the child processes in the group before it continues
  488: executing.  If both the child processes and the shell call
  489: @code{setpgid}, this ensures that the right things happen no matter which
  490: process gets to it first.
  491: 
  492: If the job is being launched as a foreground job, the new process group
  493: also needs to be put into the foreground on the controlling terminal
  494: using @code{tcsetpgrp}.  Again, this should be done by the shell as well
  495: as by each of its child processes, to avoid race conditions.
  496: 
  497: The next thing each child process should do is to reset its signal
  498: actions.
  499: 
  500: During initialization, the shell process set itself to ignore job
  501: control signals; see @ref{Initializing the Shell}.  As a result, any child
  502: processes it creates also ignore these signals by inheritance.  This is
  503: definitely undesirable, so each child process should explicitly set the
  504: actions for these signals back to @code{SIG_DFL} just after it is forked.
  505: 
  506: Since shells follow this convention, applications can assume that they
  507: inherit the correct handling of these signals from the parent process.
  508: But every application has a responsibility not to mess up the handling
  509: of stop signals.  Applications that disable the normal interpretation of
  510: the SUSP character should provide some other mechanism for the user to
  511: stop the job.  When the user invokes this mechanism, the program should
  512: send a @code{SIGTSTP} signal to the process group of the process, not
  513: just to the process itself.  @xref{Signaling Another Process}.
  514: 
  515: Finally, each child process should call @code{exec} in the normal way.
  516: This is also the point at which redirection of the standard input and
  517: output channels should be handled.  @xref{Duplicating Descriptors},
  518: for an explanation of how to do this.
  519: 
  520: Here is the function from the sample shell program that is responsible
  521: for launching a program.  The function is executed by each child process
  522: immediately after it has been forked by the shell, and never returns.
  523: 
  524: @smallexample
  525: void
  526: launch_process (process *p, pid_t pgid,
  527:                 int infile, int outfile, int errfile,
  528:                 int foreground)
  529: @{
  530:   pid_t pid;
  531: 
  532:   if (shell_is_interactive)
  533:     @{
  534:       /* @r{Put the process into the process group and give the process group}
  535:          @r{the terminal, if appropriate.}
  536:          @r{This has to be done both by the shell and in the individual}
  537:          @r{child processes because of potential race conditions.}  */
  538:       pid = getpid ();
  539:       if (pgid == 0) pgid = pid;
  540:       setpgid (pid, pgid);
  541:       if (foreground)
  542:         tcsetpgrp (shell_terminal, pgid);
  543: 
  544:       /* @r{Set the handling for job control signals back to the default.}  */
  545:       signal (SIGINT, SIG_DFL);
  546:       signal (SIGQUIT, SIG_DFL);
  547:       signal (SIGTSTP, SIG_DFL);
  548:       signal (SIGTTIN, SIG_DFL);
  549:       signal (SIGTTOU, SIG_DFL);
  550:       signal (SIGCHLD, SIG_DFL);
  551:     @}
  552: 
  553:   /* @r{Set the standard input/output channels of the new process.}  */
  554:   if (infile != STDIN_FILENO)
  555:     @{
  556:       dup2 (infile, STDIN_FILENO);
  557:       close (infile);
  558:     @}
  559:   if (outfile != STDOUT_FILENO)
  560:     @{
  561:       dup2 (outfile, STDOUT_FILENO);
  562:       close (outfile);
  563:     @}
  564:   if (errfile != STDERR_FILENO)
  565:     @{
  566:       dup2 (errfile, STDERR_FILENO);
  567:       close (errfile);
  568:     @}
  569: 
  570:   /* @r{Exec the new process.  Make sure we exit.}  */
  571:   execvp (p->argv[0], p->argv);
  572:   perror ("execvp");
  573:   exit (1);
  574: @}
  575: @end smallexample
  576: 
  577: If the shell is not running interactively, this function does not do
  578: anything with process groups or signals.  Remember that a shell not
  579: performing job control must keep all of its subprocesses in the same
  580: process group as the shell itself.
  581: 
  582: Next, here is the function that actually launches a complete job.
  583: After creating the child processes, this function calls some other
  584: functions to put the newly created job into the foreground or background;
  585: these are discussed in @ref{Foreground and Background}.
  586: 
  587: @smallexample
  588: void
  589: launch_job (job *j, int foreground)
  590: @{
  591:   process *p;
  592:   pid_t pid;
  593:   int mypipe[2], infile, outfile;
  594: 
  595:   infile = j->stdin;
  596:   for (p = j->first_process; p; p = p->next)
  597:     @{
  598:       /* @r{Set up pipes, if necessary.}  */
  599:       if (p->next)
  600:         @{
  601:           if (pipe (mypipe) < 0)
  602:             @{
  603:               perror ("pipe");
  604:               exit (1);
  605:             @}
  606:           outfile = mypipe[1];
  607:         @}
  608:       else
  609:         outfile = j->stdout;
  610: 
  611:       /* @r{Fork the child processes.}  */
  612:       pid = fork ();
  613:       if (pid == 0)
  614:         /* @r{This is the child process.}  */
  615:         launch_process (p, j->pgid, infile,
  616:                         outfile, j->stderr, foreground);
  617:       else if (pid < 0)
  618:         @{
  619:           /* @r{The fork failed.}  */
  620:           perror ("fork");
  621:           exit (1);
  622:         @}
  623:       else
  624:         @{
  625:           /* @r{This is the parent process.}  */
  626:           p->pid = pid;
  627:           if (shell_is_interactive)
  628:             @{
  629:               if (!j->pgid)
  630:                 j->pgid = pid;
  631:               setpgid (pid, j->pgid);
  632:             @}
  633:         @}
  634: 
  635:       /* @r{Clean up after pipes.}  */
  636:       if (infile != j->stdin)
  637:         close (infile);
  638:       if (outfile != j->stdout)
  639:         close (outfile);
  640:       infile = mypipe[0];
  641:     @}
  642: 
  643:   format_job_info (j, "launched");
  644: 
  645:   if (!shell_is_interactive)
  646:     wait_for_job (j);
  647:   else if (foreground)
  648:     put_job_in_foreground (j, 0);
  649:   else
  650:     put_job_in_background (j, 0);
  651: @}
  652: @end smallexample
  653: 
  654: 
  655: @node Foreground and Background, Stopped and Terminated Jobs, Launching Jobs, Implementing a Shell
  656: @subsection Foreground and Background
  657: 
  658: Now let's consider what actions must be taken by the shell when it
  659: launches a job into the foreground, and how this differs from what
  660: must be done when a background job is launched.
  661: 
  662: @cindex foreground job, launching
  663: When a foreground job is launched, the shell must first give it access
  664: to the controlling terminal by calling @code{tcsetpgrp}.  Then, the
  665: shell should wait for processes in that process group to terminate or
  666: stop.  This is discussed in more detail in @ref{Stopped and Terminated
  667: Jobs}.
  668: 
  669: When all of the processes in the group have either completed or stopped,
  670: the shell should regain control of the terminal for its own process
  671: group by calling @code{tcsetpgrp} again.  Since stop signals caused by
  672: I/O from a background process or a SUSP character typed by the user
  673: are sent to the process group, normally all the processes in the job
  674: stop together.
  675: 
  676: The foreground job may have left the terminal in a strange state, so the
  677: shell should restore its own saved terminal modes before continuing.  In
  678: case the job is merely stopped, the shell should first save the current
  679: terminal modes so that it can restore them later if the job is
  680: continued.  The functions for dealing with terminal modes are
  681: @code{tcgetattr} and @code{tcsetattr}; these are described in
  682: @ref{Terminal Modes}.
  683: 
  684: Here is the sample shell's function for doing all of this.
  685: 
  686: @smallexample
  687: @group
  688: /* @r{Put job @var{j} in the foreground.  If @var{cont} is nonzero,}
  689:    @r{restore the saved terminal modes and send the process group a}
  690:    @r{@code{SIGCONT} signal to wake it up before we block.}  */
  691: 
  692: void
  693: put_job_in_foreground (job *j, int cont)
  694: @{
  695:   /* @r{Put the job into the foreground.}  */
  696:   tcsetpgrp (shell_terminal, j->pgid);
  697: @end group
  698: 
  699: @group
  700:   /* @r{Send the job a continue signal, if necessary.}  */
  701:   if (cont)
  702:     @{
  703:       tcsetattr (shell_terminal, TCSADRAIN, &j->tmodes);
  704:       if (kill (- j->pgid, SIGCONT) < 0)
  705:         perror ("kill (SIGCONT)");
  706:     @}
  707: @end group
  708: 
  709:   /* @r{Wait for it to report.}  */
  710:   wait_for_job (j);
  711: 
  712:   /* @r{Put the shell back in the foreground.}  */
  713:   tcsetpgrp (shell_terminal, shell_pgid);
  714: 
  715: @group
  716:   /* @r{Restore the shell's terminal modes.}  */
  717:   tcgetattr (shell_terminal, &j->tmodes);
  718:   tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes);
  719: @}
  720: @end group
  721: @end smallexample
  722: 
  723: @cindex background job, launching
  724: If the process group is launched as a background job, the shell should
  725: remain in the foreground itself and continue to read commands from
  726: the terminal.
  727: 
  728: In the sample shell, there is not much that needs to be done to put
  729: a job into the background.  Here is the function it uses:
  730: 
  731: @smallexample
  732: /* @r{Put a job in the background.  If the cont argument is true, send}
  733:    @r{the process group a @code{SIGCONT} signal to wake it up.}  */
  734: 
  735: void
  736: put_job_in_background (job *j, int cont)
  737: @{
  738:   /* @r{Send the job a continue signal, if necessary.}  */
  739:   if (cont)
  740:     if (kill (-j->pgid, SIGCONT) < 0)
  741:       perror ("kill (SIGCONT)");
  742: @}
  743: @end smallexample
  744: 
  745: 
  746: @node Stopped and Terminated Jobs, Continuing Stopped Jobs, Foreground and Background, Implementing a Shell
  747: @subsection Stopped and Terminated Jobs
  748: 
  749: @cindex stopped jobs, detecting
  750: @cindex terminated jobs, detecting
  751: When a foreground process is launched, the shell must block until all of
  752: the processes in that job have either terminated or stopped.  It can do
  753: this by calling the @code{waitpid} function; see @ref{Process
  754: Completion}.  Use the @code{WUNTRACED} option so that status is reported
  755: for processes that stop as well as processes that terminate.
  756: 
  757: The shell must also check on the status of background jobs so that it
  758: can report terminated and stopped jobs to the user; this can be done by
  759: calling @code{waitpid} with the @code{WNOHANG} option.  A good place to
  760: put a such a check for terminated and stopped jobs is just before
  761: prompting for a new command.
  762: 
  763: @cindex @code{SIGCHLD}, handling of
  764: The shell can also receive asynchronous notification that there is
  765: status information available for a child process by establishing a
  766: handler for @code{SIGCHLD} signals.  @xref{Signal Handling}.
  767: 
  768: In the sample shell program, the @code{SIGCHLD} signal is normally
  769: ignored.  This is to avoid reentrancy problems involving the global data
  770: structures the shell manipulates.  But at specific times when the shell
  771: is not using these data structures---such as when it is waiting for
  772: input on the terminal---it makes sense to enable a handler for
  773: @code{SIGCHLD}.  The same function that is used to do the synchronous