This is Info file libc.info, produced by Makeinfo version 1.67 from the
input file libc.texinfo.

   This file documents the GNU C library.

   This is Edition 0.07 DRAFT, last updated 4 Oct 1996, of `The GNU C
Library Reference Manual', for Version 2.00 Beta.

   Copyright (C) 1993, '94, '95, '96 Free Software Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU Library General Public License" is
included exactly as in the original, and provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the text of the translation of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.


File: libc.info,  Node: Orphaned Process Groups,  Next: Implementing a Shell,  Prev: Access to the Terminal,  Up: Job Control

Orphaned Process Groups
=======================

   When a controlling process terminates, its terminal becomes free and
a new session can be established on it.  (In fact, another user could
log in on the terminal.)  This could cause a problem if any processes
from the old session are still trying to use that terminal.

   To prevent problems, process groups that continue running even after
the session leader has terminated are marked as "orphaned process
groups".

   When a process group becomes an orphan, its processes are sent a
`SIGHUP' signal.  Ordinarily, this causes the processes to terminate.
However, if a program ignores this signal or establishes a handler for
it (*note Signal Handling::.), it can continue running as in the orphan
process group even after its controlling process terminates; but it
still cannot access the terminal any more.


File: libc.info,  Node: Implementing a Shell,  Next: Functions for Job Control,  Prev: Orphaned Process Groups,  Up: Job Control

Implementing a Job Control Shell
================================

   This section describes what a shell must do to implement job
control, by presenting an extensive sample program to illustrate the
concepts involved.

* Menu:

* Data Structures::             Introduction to the sample shell.
* Initializing the Shell::      What the shell must do to take
				 responsibility for job control.
* Launching Jobs::              Creating jobs to execute commands.
* Foreground and Background::   Putting a job in foreground of background.
* Stopped and Terminated Jobs::  Reporting job status.
* Continuing Stopped Jobs::     How to continue a stopped job in
				 the foreground or background.
* Missing Pieces::              Other parts of the shell.


File: libc.info,  Node: Data Structures,  Next: Initializing the Shell,  Up: Implementing a Shell

Data Structures for the Shell
-----------------------------

   All of the program examples included in this chapter are part of a
simple shell program.  This section presents data structures and
utility functions which are used throughout the example.

   The sample shell deals mainly with two data structures.  The `job'
type contains information about a job, which is a set of subprocesses
linked together with pipes.  The `process' type holds information about
a single subprocess.  Here are the relevant data structure declarations:

     /* A process is a single process.  */
     typedef struct process
     {
       struct process *next;       /* next process in pipeline */
       char **argv;                /* for exec */
       pid_t pid;                  /* process ID */
       char completed;             /* true if process has completed */
       char stopped;               /* true if process has stopped */
       int status;                 /* reported status value */
     } process;

     /* A job is a pipeline of processes.  */
     typedef struct job
     {
       struct job *next;           /* next active job */
       char *command;              /* command line, used for messages */
       process *first_process;     /* list of processes in this job */
       pid_t pgid;                 /* process group ID */
       char notified;              /* true if user told about stopped job */
       struct termios tmodes;      /* saved terminal modes */
       int stdin, stdout, stderr;  /* standard i/o channels */
     } job;
     
     /* The active jobs are linked into a list.  This is its head.   */
     job *first_job = NULL;

   Here are some utility functions that are used for operating on `job'
objects.

     /* Find the active job with the indicated PGID.  */
     job *
     find_job (pid_t pgid)
     {
       job *j;
     
       for (j = first_job; j; j = j->next)
         if (j->pgid == pgid)
           return j;
       return NULL;
     }

     /* Return true if all processes in the job have stopped or completed.  */
     int
     job_is_stopped (job *j)
     {
       process *p;
     
       for (p = j->first_process; p; p = p->next)
         if (!p->completed && !p->stopped)
           return 0;
       return 1;
     }

     /* Return true if all processes in the job have completed.  */
     int
     job_is_completed (job *j)
     {
       process *p;
     
       for (p = j->first_process; p; p = p->next)
         if (!p->completed)
           return 0;
       return 1;
     }


File: libc.info,  Node: Initializing the Shell,  Next: Launching Jobs,  Prev: Data Structures,  Up: Implementing a Shell

Initializing the Shell
----------------------

   When a shell program that normally performs job control is started,
it has to be careful in case it has been invoked from another shell
that is already doing its own job control.

   A subshell that runs interactively has to ensure that it has been
placed in the foreground by its parent shell before it can enable job
control itself.  It does this by getting its initial process group ID
with the `getpgrp' function, and comparing it to the process group ID
of the current foreground job associated with its controlling terminal
(which can be retrieved using the `tcgetpgrp' function).

   If the subshell is not running as a foreground job, it must stop
itself by sending a `SIGTTIN' signal to its own process group.  It may
not arbitrarily put itself into the foreground; it must wait for the
user to tell the parent shell to do this.  If the subshell is continued
again, it should repeat the check and stop itself again if it is still
not in the foreground.

   Once the subshell has been placed into the foreground by its parent
shell, it can enable its own job control.  It does this by calling
`setpgid' to put itself into its own process group, and then calling
`tcsetpgrp' to place this process group into the foreground.

   When a shell enables job control, it should set itself to ignore all
the job control stop signals so that it doesn't accidentally stop
itself.  You can do this by setting the action for all the stop signals
to `SIG_IGN'.

   A subshell that runs non-interactively cannot and should not support
job control.  It must leave all processes it creates in the same process
group as the shell itself; this allows the non-interactive shell and its
child processes to be treated as a single job by the parent shell.  This
is easy to do--just don't use any of the job control primitives--but
you must remember to make the shell do it.

   Here is the initialization code for the sample shell that shows how
to do all of this.

     /* Keep track of attributes of the shell.  */
     
     #include <sys/types.h>
     #include <termios.h>
     #include <unistd.h>
     
     pid_t shell_pgid;
     struct termios shell_tmodes;
     int shell_terminal;
     int shell_is_interactive;
     
     
     /* Make sure the shell is running interactively as the foreground job
        before proceeding. */
     
     void
     init_shell ()
     {
     
       /* See if we are running interactively.  */
       shell_terminal = STDIN_FILENO;
       shell_is_interactive = isatty (shell_terminal);
     
       if (shell_is_interactive)
         {
           /* Loop until we are in the foreground.  */
           while (tcgetpgrp (shell_terminal) != (shell_pgid = getpgrp ()))
             kill (- shell_pgid, SIGTTIN);
     
           /* Ignore interactive and job-control signals.  */
           signal (SIGINT, SIG_IGN);
           signal (SIGQUIT, SIG_IGN);
           signal (SIGTSTP, SIG_IGN);
           signal (SIGTTIN, SIG_IGN);
           signal (SIGTTOU, SIG_IGN);
           signal (SIGCHLD, SIG_IGN);
     
           /* Put ourselves in our own process group.  */
           shell_pgid = getpid ();
           if (setpgid (shell_pgid, shell_pgid) < 0)
             {
               perror ("Couldn't put the shell in its own process group");
               exit (1);
             }
     
           /* Grab control of the terminal.  */
           tcsetpgrp (shell_terminal, shell_pgid);
     
           /* Save default terminal attributes for shell.  */
           tcgetattr (shell_terminal, &shell_tmodes);
         }
     }


File: libc.info,  Node: Launching Jobs,  Next: Foreground and Background,  Prev: Initializing the Shell,  Up: Implementing a Shell

Launching Jobs
--------------

   Once the shell has taken responsibility for performing job control on
its controlling terminal, it can launch jobs in response to commands
typed by the user.

   To create the processes in a process group, you use the same `fork'
and `exec' functions described in *Note Process Creation Concepts::.
Since there are multiple child processes involved, though, things are a
little more complicated and you must be careful to do things in the
right order.  Otherwise, nasty race conditions can result.

   You have two choices for how to structure the tree of parent-child
relationships among the processes.  You can either make all the
processes in the process group be children of the shell process, or you
can make one process in group be the ancestor of all the other processes
in that group.  The sample shell program presented in this chapter uses
the first approach because it makes bookkeeping somewhat simpler.

   As each process is forked, it should put itself in the new process
group by calling `setpgid'; see *Note Process Group Functions::.  The
first process in the new group becomes its "process group leader", and
its process ID becomes the "process group ID" for the group.

   The shell should also call `setpgid' to put each of its child
processes into the new process group.  This is because there is a
potential timing problem: each child process must be put in the process
group before it begins executing a new program, and the shell depends on
having all the child processes in the group before it continues
executing.  If both the child processes and the shell call `setpgid',
this ensures that the right things happen no matter which process gets
to it first.

   If the job is being launched as a foreground job, the new process
group also needs to be put into the foreground on the controlling
terminal using `tcsetpgrp'.  Again, this should be done by the shell as
well as by each of its child processes, to avoid race conditions.

   The next thing each child process should do is to reset its signal
actions.

   During initialization, the shell process set itself to ignore job
control signals; see *Note Initializing the Shell::.  As a result, any
child processes it creates also ignore these signals by inheritance.
This is definitely undesirable, so each child process should explicitly
set the actions for these signals back to `SIG_DFL' just after it is
forked.

   Since shells follow this convention, applications can assume that
they inherit the correct handling of these signals from the parent
process.  But every application has a responsibility not to mess up the
handling of stop signals.  Applications that disable the normal
interpretation of the SUSP character should provide some other
mechanism for the user to stop the job.  When the user invokes this
mechanism, the program should send a `SIGTSTP' signal to the process
group of the process, not just to the process itself.  *Note Signaling
Another Process::.

   Finally, each child process should call `exec' in the normal way.
This is also the point at which redirection of the standard input and
output channels should be handled.  *Note Duplicating Descriptors::,
for an explanation of how to do this.

   Here is the function from the sample shell program that is
responsible for launching a program.  The function is executed by each
child process immediately after it has been forked by the shell, and
never returns.

     void
     launch_process (process *p, pid_t pgid,
                     int infile, int outfile, int errfile,
                     int foreground)
     {
       pid_t pid;
     
       if (shell_is_interactive)
         {
           /* Put the process into the process group and give the process group
              the terminal, if appropriate.
              This has to be done both by the shell and in the individual
              child processes because of potential race conditions.  */
           pid = getpid ();
           if (pgid == 0) pgid = pid;
           setpgid (pid, pgid);
           if (foreground)
             tcsetpgrp (shell_terminal, pgid);
     
           /* Set the handling for job control signals back to the default.  */
           signal (SIGINT, SIG_DFL);
           signal (SIGQUIT, SIG_DFL);
           signal (SIGTSTP, SIG_DFL);
           signal (SIGTTIN, SIG_DFL);
           signal (SIGTTOU, SIG_DFL);
           signal (SIGCHLD, SIG_DFL);
         }
     
       /* Set the standard input/output channels of the new process.  */
       if (infile != STDIN_FILENO)
         {
           dup2 (infile, STDIN_FILENO);
           close (infile);
         }
       if (outfile != STDOUT_FILENO)
         {
           dup2 (outfile, STDOUT_FILENO);
           close (outfile);
         }
       if (errfile != STDERR_FILENO)
         {
           dup2 (errfile, STDERR_FILENO);
           close (errfile);
         }
     
       /* Exec the new process.  Make sure we exit.  */
       execvp (p->argv[0], p->argv);
       perror ("execvp");
       exit (1);
     }

   If the shell is not running interactively, this function does not do
anything with process groups or signals.  Remember that a shell not
performing job control must keep all of its subprocesses in the same
process group as the shell itself.

   Next, here is the function that actually launches a complete job.
After creating the child processes, this function calls some other
functions to put the newly created job into the foreground or
background; these are discussed in *Note Foreground and Background::.

     void
     launch_job (job *j, int foreground)
     {
       process *p;
       pid_t pid;
       int mypipe[2], infile, outfile;
     
       infile = j->stdin;
       for (p = j->first_process; p; p = p->next)
         {
           /* Set up pipes, if necessary.  */
           if (p->next)
             {
               if (pipe (mypipe) < 0)
                 {
                   perror ("pipe");
                   exit (1);
                 }
               outfile = mypipe[1];
             }
           else
             outfile = j->stdout;
     
           /* Fork the child processes.  */
           pid = fork ();
           if (pid == 0)
             /* This is the child process.  */
             launch_process (p, j->pgid, infile,
                             outfile, j->stderr, foreground);
           else if (pid < 0)
             {
               /* The fork failed.  */
               perror ("fork");
               exit (1);
             }
           else
             {
               /* This is the parent process.  */
               p->pid = pid;
               if (shell_is_interactive)
                 {
                   if (!j->pgid)
                     j->pgid = pid;
                   setpgid (pid, j->pgid);
                 }
             }
     
           /* Clean up after pipes.  */
           if (infile != j->stdin)
             close (infile);
           if (outfile != j->stdout)
             close (outfile);
           infile = mypipe[0];
         }
     
       format_job_info (j, "launched");
     
       if (!shell_is_interactive)
         wait_for_job (j);
       else if (foreground)
         put_job_in_foreground (j, 0);
       else
         put_job_in_background (j, 0);
     }


File: libc.info,  Node: Foreground and Background,  Next: Stopped and Terminated Jobs,  Prev: Launching Jobs,  Up: Implementing a Shell

Foreground and Background
-------------------------

   Now let's consider what actions must be taken by the shell when it
launches a job into the foreground, and how this differs from what must
be done when a background job is launched.

   When a foreground job is launched, the shell must first give it
access to the controlling terminal by calling `tcsetpgrp'.  Then, the
shell should wait for processes in that process group to terminate or
stop.  This is discussed in more detail in *Note Stopped and Terminated
Jobs::.

   When all of the processes in the group have either completed or
stopped, the shell should regain control of the terminal for its own
process group by calling `tcsetpgrp' again.  Since stop signals caused
by I/O from a background process or a SUSP character typed by the user
are sent to the process group, normally all the processes in the job
stop together.

   The foreground job may have left the terminal in a strange state, so
the shell should restore its own saved terminal modes before
continuing.  In case the job is merely been stopped, the shell should
first save the current terminal modes so that it can restore them later
if the job is continued.  The functions for dealing with terminal modes
are `tcgetattr' and `tcsetattr'; these are described in *Note Terminal
Modes::.

   Here is the sample shell's function for doing all of this.

     /* Put job J in the foreground.  If CONT is nonzero,
        restore the saved terminal modes and send the process group a
        `SIGCONT' signal to wake it up before we block.  */
     
     void
     put_job_in_foreground (job *j, int cont)
     {
       /* Put the job into the foreground.  */
       tcsetpgrp (shell_terminal, j->pgid);

     /* Send the job a continue signal, if necessary.  */
       if (cont)
         {
           tcsetattr (shell_terminal, TCSADRAIN, &j->tmodes);
           if (kill (- j->pgid, SIGCONT) < 0)
             perror ("kill (SIGCONT)");
         }
     
       /* Wait for it to report.  */
       wait_for_job (j);
     
       /* Put the shell back in the foreground.  */
       tcsetpgrp (shell_terminal, shell_pgid);
     /* Restore the shell's terminal modes.  */
       tcgetattr (shell_terminal, &j->tmodes);
       tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes);
     }

   If the process group is launched as a background job, the shell
should remain in the foreground itself and continue to read commands
from the terminal.

   In the sample shell, there is not much that needs to be done to put
a job into the background.  Here is the function it uses:

     /* Put a job in the background.  If the cont argument is true, send
        the process group a `SIGCONT' signal to wake it up.  */
     
     void
     put_job_in_background (job *j, int cont)
     {
       /* Send the job a continue signal, if necessary.  */
       if (cont)
         if (kill (-j->pgid, SIGCONT) < 0)
           perror ("kill (SIGCONT)");
     }


File: libc.info,  Node: Stopped and Terminated Jobs,  Next: Continuing Stopped Jobs,  Prev: Foreground and Background,  Up: Implementing a Shell

Stopped and Terminated Jobs
---------------------------

   When a foreground process is launched, the shell must block until
all of the processes in that job have either terminated or stopped.  It
can do this by calling the `waitpid' function; see *Note Process
Completion::.  Use the `WUNTRACED' option so that status is reported
for processes that stop as well as processes that terminate.

   The shell must also check on the status of background jobs so that it
can report terminated and stopped jobs to the user; this can be done by
calling `waitpid' with the `WNOHANG' option.  A good place to put a
such a check for terminated and stopped jobs is just before prompting
for a new command.

   The shell can also receive asynchronous notification that there is
status information available for a child process by establishing a
handler for `SIGCHLD' signals.  *Note Signal Handling::.

   In the sample shell program, the `SIGCHLD' signal is normally
ignored.  This is to avoid reentrancy problems involving the global data
structures the shell manipulates.  But at specific times when the shell
is not using these data structures--such as when it is waiting for
input on the terminal--it makes sense to enable a handler for
`SIGCHLD'.  The same function that is used to do the synchronous status
checks (`do_job_notification', in this case) can also be called from
within this handler.

   Here are the parts of the sample shell program that deal with
checking the status of jobs and reporting the information to the user.

     /* Store the status of the process PID that was returned by waitpid.
        Return 0 if all went well, nonzero otherwise.  */
     
     int
     mark_process_status (pid_t pid, int status)
     {
       job *j;
       process *p;

     if (pid > 0)
         {
           /* Update the record for the process.  */
           for (j = first_job; j; j = j->next)
             for (p = j->first_process; p; p = p->next)
               if (p->pid == pid)
                 {
                   p->status = status;
                   if (WIFSTOPPED (status))
                     p->stopped = 1;
                   else
                     {
                       p->completed = 1;
                       if (WIFSIGNALED (status))
                         fprintf (stderr, "%d: Terminated by signal %d.\n",
                                  (int) pid, WTERMSIG (p->status));
                     }
                   return 0;
                  }
           fprintf (stderr, "No child process %d.\n", pid);
           return -1;
         }

     else if (pid == 0 || errno == ECHILD)
         /* No processes ready to report.  */
         return -1;
       else {
         /* Other weird errors.  */
         perror ("waitpid");
         return -1;
       }
     }

     /* Check for processes that have status information available,
        without blocking.  */
     
     void
     update_status (void)
     {
       int status;
       pid_t pid;
     
       do
         pid = waitpid (WAIT_ANY, &status, WUNTRACED|WNOHANG);
       while (!mark_process_status (pid, status));
     }

     /* Check for processes that have status information available,
        blocking until all processes in the given job have reported.  */
     
     void
     wait_for_job (job *j)
     {
       int status;
       pid_t pid;
     
       do
         pid = waitpid (WAIT_ANY, &status, WUNTRACED);
       while (!mark_process_status (pid, status)
              && !job_is_stopped (j)
              && !job_is_completed (j));
     }

     /* Format information about job status for the user to look at.  */
     
     void
     format_job_info (job *j, const char *status)
     {
       fprintf (stderr, "%ld (%s): %s\n", (long)j->pgid, status, j->command);
     }

     /* Notify the user about stopped or terminated jobs.
        Delete terminated jobs from the active job list.  */
     
     void
     do_job_notification (void)
     {
       job *j, *jlast, *jnext;
       process *p;
     
       /* Update status information for child processes.  */
       update_status ();
     
       jlast = NULL;
       for (j = first_job; j; j = jnext)
         {
           jnext = j->next;
     
           /* If all processes have completed, tell the user the job has
              completed and delete it from the list of active jobs.  */
           if (job_is_completed (j)) {
             format_job_info (j, "completed");
             if (jlast)
               jlast->next = jnext;
             else
               first_job = jnext;
             free_job (j);
           }
     
           /* Notify the user about stopped jobs,
              marking them so that we won't do this more than once.  */
           else if (job_is_stopped (j) && !j->notified) {
             format_job_info (j, "stopped");
             j->notified = 1;
             jlast = j;
           }
     
           /* Don't say anything about jobs that are still running.  */
           else
             jlast = j;
         }
     }


File: libc.info,  Node: Continuing Stopped Jobs,  Next: Missing Pieces,  Prev: Stopped and Terminated Jobs,  Up: Implementing a Shell

Continuing Stopped Jobs
-----------------------

   The shell can continue a stopped job by sending a `SIGCONT' signal
to its process group.  If the job is being continued in the foreground,
the shell should first invoke `tcsetpgrp' to give the job access to the
terminal, and restore the saved terminal settings.  After continuing a
job in the foreground, the shell should wait for the job to stop or
complete, as if the job had just been launched in the foreground.

   The sample shell program handles both newly created and continued
jobs with the same pair of functions, `put_job_in_foreground' and
`put_job_in_background'.  The definitions of these functions were given
in *Note Foreground and Background::.  When continuing a stopped job, a
nonzero value is passed as the CONT argument to ensure that the
`SIGCONT' signal is sent and the terminal modes reset, as appropriate.

   This leaves only a function for updating the shell's internal
bookkeeping about the job being continued:

     /* Mark a stopped job J as being running again.  */
     
     void
     mark_job_as_running (job *j)
     {
       Process *p;
     
       for (p = j->first_process; p; p = p->next)
         p->stopped = 0;
       j->notified = 0;
     }

     /* Continue the job J.  */
     
     void
     continue_job (job *j, int foreground)
     {
       mark_job_as_running (j);
       if (foreground)
         put_job_in_foreground (j, 1);
       else
         put_job_in_background (j, 1);
     }


File: libc.info,  Node: Missing Pieces,  Prev: Continuing Stopped Jobs,  Up: Implementing a Shell

The Missing Pieces
------------------

   The code extracts for the sample shell included in this chapter are
only a part of the entire shell program.  In particular, nothing at all
has been said about how `job' and `program' data structures are
allocated and initialized.

   Most real shells provide a complex user interface that has support
for a command language; variables; abbreviations, substitutions, and
pattern matching on file names; and the like.  All of this is far too
complicated to explain here!  Instead, we have concentrated on showing
how to implement the core process creation and job control functions
that can be called from such a shell.

   Here is a table summarizing the major entry points we have presented:

`void init_shell (void)'
     Initialize the shell's internal state.  *Note Initializing the
     Shell::.

`void launch_job (job *J, int FOREGROUND)'
     Launch the job J as either a foreground or background job.  *Note
     Launching Jobs::.

`void do_job_notification (void)'
     Check for and report any jobs that have terminated or stopped.
     Can be called synchronously or within a handler for `SIGCHLD'
     signals.  *Note Stopped and Terminated Jobs::.

`void continue_job (job *J, int FOREGROUND)'
     Continue the job J.  *Note Continuing Stopped Jobs::.

   Of course, a real shell would also want to provide other functions
for managing jobs.  For example, it would be useful to have commands to
list all active jobs or to send a signal (such as `SIGKILL') to a job.


File: libc.info,  Node: Functions for Job Control,  Prev: Implementing a Shell,  Up: Job Control

Functions for Job Control
=========================

   This section contains detailed descriptions of the functions relating
to job control.

* Menu:

* Identifying the Terminal::    Determining the controlling terminal's name.
* Process Group Functions::     Functions for manipulating process groups.
* Terminal Access Functions::   Functions for controlling terminal access.


File: libc.info,  Node: Identifying the Terminal,  Next: Process Group Functions,  Up: Functions for Job Control

Identifying the Controlling Terminal
------------------------------------

   You can use the `ctermid' function to get a file name that you can
use to open the controlling terminal.  In the GNU library, it returns
the same string all the time: `"/dev/tty"'.  That is a special "magic"
file name that refers to the controlling terminal of the current
process (if it has one).  To find the name of the specific terminal
device, use `ttyname'; *note Is It a Terminal::..

   The function `ctermid' is declared in the header file `stdio.h'.

 - Function: char * ctermid (char *STRING)
     The `ctermid' function returns a string containing the file name of
     the controlling terminal for the current process.  If STRING is
     not a null pointer, it should be an array that can hold at least
     `L_ctermid' characters; the string is returned in this array.
     Otherwise, a pointer to a string in a static area is returned,
     which might get overwritten on subsequent calls to this function.

     An empty string is returned if the file name cannot be determined
     for any reason.  Even if a file name is returned, access to the
     file it represents is not guaranteed.

 - Macro: int L_ctermid
     The value of this macro is an integer constant expression that
     represents the size of a string large enough to hold the file name
     returned by `ctermid'.

   See also the `isatty' and `ttyname' functions, in *Note Is It a
Terminal::.


File: libc.info,  Node: Process Group Functions,  Next: Terminal Access Functions,  Prev: Identifying the Terminal,  Up: Functions for Job Control

Process Group Functions
-----------------------

   Here are descriptions of the functions for manipulating process
groups.  Your program should include the header files `sys/types.h' and
`unistd.h' to use these functions.

 - Function: pid_t setsid (void)
     The `setsid' function creates a new session.  The calling process
     becomes the session leader, and is put in a new process group whose
     process group ID is the same as the process ID of that process.
     There are initially no other processes in the new process group,
     and no other process groups in the new session.

     This function also makes the calling process have no controlling
     terminal.

     The `setsid' function returns the new process group ID of the
     calling process if successful.  A return value of `-1' indicates an
     error.  The following `errno' error conditions are defined for this
     function:

    `EPERM'
          The calling process is already a process group leader, or
          there is already another process group around that has the
          same process group ID.

   The `getpgrp' function has two definitions: one derived from BSD
Unix, and one from the POSIX.1 standard.  The feature test macros you
have selected (*note Feature Test Macros::.) determine which definition
you get.  Specifically, you get the BSD version if you define
`_BSD_SOURCE'; otherwise, you get the POSIX version if you define
`_POSIX_SOURCE' or `_GNU_SOURCE'.  Programs written for old BSD systems
will not include `unistd.h', which defines `getpgrp' specially under
`_BSD_SOURCE'.  You must link such programs with the `-lbsd-compat'
option to get the BSD definition.

 - POSIX.1 Function: pid_t getpgrp (void)
     The POSIX.1 definition of `getpgrp' returns the process group ID of
     the calling process.

 - BSD Function: pid_t getpgrp (pid_t PID)
     The BSD definition of `getpgrp' returns the process group ID of the
     process PID.  You can supply a value of `0' for the PID argument
     to get information about the calling process.

 - Function: int setpgid (pid_t PID, pid_t PGID)
     The `setpgid' function puts the process PID into the process group
     PGID.  As a special case, either PID or PGID can be zero to
     indicate the process ID of the calling process.

     This function fails on a system that does not support job control.
     *Note Job Control is Optional::, for more information.

     If the operation is successful, `setpgid' returns zero.  Otherwise
     it returns `-1'.  The following `errno' error conditions are
     defined for this function:

    `EACCES'
          The child process named by PID has executed an `exec'
          function since it was forked.

    `EINVAL'
          The value of the PGID is not valid.

    `ENOSYS'
          The system doesn't support job control.

    `EPERM'
          The process indicated by the PID argument is a session leader,
          or is not in the same session as the calling process, or the
          value of the PGID argument doesn't match a process group ID
          in the same session as the calling process.

    `ESRCH'
          The process indicated by the PID argument is not the calling
          process or a child of the calling process.

 - Function: int setpgrp (pid_t PID, pid_t PGID)
     This is the BSD Unix name for `setpgid'.  Both functions do exactly
     the same thing.


File: libc.info,  Node: Terminal Access Functions,  Prev: Process Group Functions,  Up: Functions for Job Control

Functions for Controlling Terminal Access
-----------------------------------------

   These are the functions for reading or setting the foreground
process group of a terminal.  You should include the header files
`sys/types.h' and `unistd.h' in your application to use these functions.

   Although these functions take a file descriptor argument to specify
the terminal device, the foreground job is associated with the terminal
file itself and not a particular open file descriptor.

 - Function: pid_t tcgetpgrp (int FILEDES)
     This function returns the process group ID of the foreground
     process group associated with the terminal open on descriptor
     FILEDES.

     If there is no foreground process group, the return value is a
     number greater than `1' that does not match the process group ID
     of any existing process group.  This can happen if all of the
     processes in the job that was formerly the foreground job have
     terminated, and no other job has yet been moved into the
     foreground.

     In case of an error, a value of `-1' is returned.  The following
     `errno' error conditions are defined for this function:

    `EBADF'
          The FILEDES argument is not a valid file descriptor.

    `ENOSYS'
          The system doesn't support job control.

    `ENOTTY'
          The terminal file associated with the FILEDES argument isn't
          the controlling terminal of the calling process.

 - Function: int tcsetpgrp (int FILEDES, pid_t PGID)
     This function is used to set a terminal's foreground process group
     ID.  The argument FILEDES is a descriptor which specifies the
     terminal; PGID specifies the process group.  The calling process
     must be a member of the same session as PGID and must have the same
     controlling terminal.

     For terminal access purposes, this function is treated as output.
     If it is called from a background process on its controlling
     terminal, normally all processes in the process group are sent a
     `SIGTTOU' signal.  The exception is if the calling process itself
     is ignoring or blocking `SIGTTOU' signals, in which case the
     operation is performed and no signal is sent.

     If successful, `tcsetpgrp' returns `0'.  A return value of `-1'
     indicates an error.  The following `errno' error conditions are
     defined for this function:

    `EBADF'
          The FILEDES argument is not a valid file descriptor.

    `EINVAL'
          The PGID argument is not valid.

    `ENOSYS'
          The system doesn't support job control.

    `ENOTTY'
          The FILEDES isn't the controlling terminal of the calling
          process.

    `EPERM'
          The PGID isn't a process group in the same session as the
          calling process.


File: libc.info,  Node: Name Service Switch,  Next: Users and Groups,  Prev: Job Control,  Up: Top

System Databases and Name Service Switch
****************************************

   Various functions in the C Library need to be configured to work
correctly in the local environment.  Traditionally, this was done by
using files (e.g., `/etc/passwd'), but other nameservices (line the
Network Information Service (NIS) and the Domain Name Service (DNS))
became popular, and were hacked into the C library, usually with a fixed
search order (*note frobnicate: (jargon)frobnicate.).

   The GNU C Library contains a cleaner solution of this problem.  It is
designed after a method used by Sun Microsystems in the C library of
Solaris 2.  GNU C Library follows their name and calls this scheme
"Name Service Switch" (NSS).

   Though the interface might be similar to Sun's version there is no
common code.  We never saw any source code of Sun's implementation and
so the internal interface is incompatible.  This is also manifests in
the file names we use as we will see later.

* Menu:

* NSS Basics::                  What is this NSS good for.
* NSS Configuration File::      Configuring NSS.
* NSS Module Internals::        How does it work internally.
* Extending NSS::               What to do to add services or databases.


File: libc.info,  Node: NSS Basics,  Next: NSS Configuration File,  Prev: Name Service Switch,  Up: Name Service Switch

NSS Basics
==========

   The basic idea is to put the implementation of the different services
offered to access the databases in separate modules.  This has some
advantages:

  1. Contributors can add new services without adding them to GNU C
     Library.

  2. The modules can be updated separately.

  3. The C library image is smaller.

   To fulfill the first goal above the ABI of the modules will be
described below.  For getting the implementation of a new service right
it is important to understand how the functions in the modules get
called.  They are in no way designed to be used by the programmer
directly.  Instead the programmer should only use the documented and
standardized functions to access the databases.

The databases available in the NSS are

`ethers'
     Ethernet numbers,

`group'
     Groups of users, *note Group Database::..

`hosts'
     Host names and numbers, *note Host Names::..

`netgroup'
     Network wide list of host and users, *note Netgroup Database::..

`network'
     Network names and numbers, *note Networks Database::..

`protocols'
     Network protocols, *note Protocols Database::..

`passwd'
     User passwords, *note User Database::..

`rpc'
     Remote procedure call names and numbers,

`services'
     Network services, *note Services Database::..

`shadow'
     Shadow user passwords,

There will be some more added later (`aliases', `automount',
`bootparams', `netmasks', and `publickey').


File: libc.info,  Node: NSS Configuration File,  Next: NSS Module Internals,  Prev: NSS Basics,  Up: Name Service Switch

The NSS Configuration File
==========================

   Somehow the NSS code must be told about the wishes of the user.  For
this reason there is the file `/etc/nsswitch.conf'.  For each database
this file contain a specification how the lookup process should work.
The file could look like this:

     # /etc/nsswitch.conf
     #
     # Name Service Switch configuration file.
     #
     
     passwd:     db files nis
     shadow:     files
     group:      db files nis
     
     hosts:      files nisplus nis dns
     networks:   nisplus [NOTFOUND=return] files
     
     ethers:     nisplus [NOTFOUND=return] db files
     protocols:  nisplus [NOTFOUND=return] db files
     rpc:        nisplus [NOTFOUND=return] db files
     services:   nisplus [NOTFOUND=return] db files

   The first column is the database as you can guess from the table
above.  The rest of the line specifies how the lookup process works.
Please note that you specify the way it works for each database
individually.  This cannot be done with the old way of a monolithic
implementation.

   The configuration specification for each database can contain two
different items:

   * the service specification like `files', `db', or `nis'.

   * the reaction on lookup result line `[NOTFOUND=return]'.

* Menu:

* Services in the NSS configuration::  Service names in the NSS configuration.
* Actions in the NSS configuration::  React appropriately to the lookup result.
* Notes on NSS Configuration File::  Things to take care about while
                                     configuring NSS.


File: libc.info,  Node: Services in the NSS configuration,  Next: Actions in the NSS configuration,  Prev: NSS Configuration File,  Up: NSS Configuration File

Services in the NSS configuration File
--------------------------------------

   The above example file mentions four different services: `files',
`db', `nis', and `nisplus'.  This does not mean these services are
available on all sites and it does also not mean these are all the
services which will ever be available.

   In fact, these names are simply strings which the NSS code uses to
find the implicitly addressed functions.  The internal interface will be
described later.  Visible to the user are the modules which implement an
individual service.

   Assume the service NAME shall be used for a lookup.  The code for
this service is implemented in a module called `libnss_NAME'.  On a
system supporting shared libraries this is in fact a shared library
with the name (for example) `libnss_NAME.so.1'.  The number at the end
is the currently used version of the interface which will not change
frequently.  Normally the user should not have to be cognizant of these
files since they should be placed in a directory where they are found
automatically.  Only the names of all available services are important.


File: libc.info,  Node: Actions in the NSS configuration,  Next: Notes on NSS Configuration File,  Prev: Services in the NSS configuration,  Up: NSS Configuration File

Actions in the NSS configuration
--------------------------------

   The second item in the specification gives the user much finer
control on the lookup process.  Action items are placed between two
service names and are written within brackets.  The general form is

     `[' ( `!'? STATUS `=' ACTION )+ `]'

where

     STATUS => success | notfound | unavail | tryagain
     ACTION => return | continue

   The case of the keywords is insignificant.  The STATUS values are
the results of a call to a lookup function of a specific service.  They
mean

`success'
     No error occurred and the wanted entry is returned.  The default
     action for this is `return'.

`notfound'
     The lookup process works ok but the needed value was not found.
     The default action is `continue'.

`unavail'
     The service is permanently unavailable.  This can either mean the
     needed file is not available, or, for DNS, the server is not
     available or does not allow queries.  The default action is
     `continue'.

`tryagain'
     The service is temporarily unavailable.  This could mean a file is
     locked or a server currently cannot accept more connections.  The
     default action is `continue'.

If we have a line like

     ethers: nisplus [NOTFOUND=return] db files

this is equivalent to

     ethers: nisplus [SUCCESS=return NOTFOUND=return UNAVAIL=continue
                      TRYAGAIN=continue]
             db      [SUCCESS=return NOTFOUND=continue UNAVAIL=continue
                      TRYAGAIN=continue]
             files

(except that it would have to be written on one line).  The default
value for the actions are normally what you want, and only need to be
changed in exceptional cases.

   If the optional `!' is placed before the STATUS this means the
following action is used for all statii but STATUS itself.  I.e., `!'
is negation as in the C language (and others).

   Before we explain the exception which makes this action item
necessary one more remark: obviously it makes no sense to add another
action item after the `files' service.  Since there is no other service
following the action *always* is `return'.

   Now, why is this `[NOTFOUND=return]' action useful?  To understand
this we should know that the `nisplus' service is often complete; i.e.,
if an entry is not available in the NIS+ tables it is not available
anywhere else.  This is what is expressed by this action item: it is
useless to examine further services since they will not give us a
result.

   The situation would be different if the NIS+ service is not available
because the machine is booting.  In this case the return value of the
lookup function is not `notfound' but instead `unavail'.  And as you
can see in the complete form above: in this situation the `db' and
`files' services are used.  Neat, isn't it?  The system administrator
need not pay special care for the time the system is not completely
ready to work (while booting or shutdown or network problems).


File: libc.info,  Node: Notes on NSS Configuration File,  Prev: Actions in the NSS configuration,  Up: NSS Configuration File

Notes on the NSS Configuration File
-----------------------------------

   Finally a few more hints.  The NSS implementation is not completely
helpless if `/etc/nsswitch.conf' does not exist.  For all supported
databases there is a default value so it should normally be possible to
get the system running even if the file is corrupted or missing.

   For the `hosts' and `network' databases the default value is `dns
[!UNAVAIL=return] files'.  I.e., the system is prepared for the DNS
service not to be available but if it is available the answer it
returns is ultimative.

   The `passwd', `group', and `shadow' databases are traditionally
handled in a special way.  The appropriate files in the `/etc'
directory are read but if an entry with a name starting with a `+'
character is found NIS is used.  This kind of lookup remains possible
by using the special lookup service `compat' and the default value for
the three databases above is `compat [NOTFOUND=return] files'.

   For all other databases the default value is `nis [NOTFOUND=return]
files'.  This solution give the best chance to be correct since NIS and
file based lookup is used.

   A second point is that the user should try to optimize the lookup
process.  The different service have different response times.  A
simple file look up on a local file could be fast, but if the file is
long and the needed entry is near the end of the file this may take
quite some time.  In this case it might be better to use the `db'
service which allows fast local access to large data sets.

   Often the situation is that some global information like NIS must be
used.  So it is unavoidable to use service entries like `nis' etc.  But
one should avoid slow services like this if possible.


File: libc.info,  Node: NSS Module Internals,  Next: Extending NSS,  Prev: NSS Configuration File,  Up: Name Service Switch

NSS Module Internals
====================

   Now it is time to described how the modules look like.  The functions
contained in a module are identified by their names.  I.e., there is no
jump table or the like.  How this is done is of no interest here; those
interested in this topic should read about Dynamic Linking.

* Menu:

* NSS Module Names::            Construction of the interface function of
                                the NSS modules.
* NSS Modules Interface::       Programming interface in the NSS module
                                functions.


File: libc.info,  Node: NSS Module Names,  Next: NSS Modules Interface,  Prev: NSS Module Internals,  Up: NSS Module Internals

The Naming Scheme of the NSS Modules
------------------------------------

The name of each function consist of various parts:

            _nss_SERVICE_FUNCTION

   SERVICE of course corresponds to the name of the module this
function is found in.(1)  The FUNCTION part is derived from the
interface function in the C library itself.  If the user calls the
function `gethostbyname' and the service used is `files' the function

            _nss_files_gethostbyname_r

in the module

            libnss_files.so.1

is used.  You see, what is explained above in not the whole truth.  In
fact the NSS modules only contain reentrant versions of the lookup
functions.  I.e., if the user would call the `gethostbyname_r' function
this also would end in the above function.  For all user interface
functions the C library maps this call to a call to the reentrant
function.  For reentrant functions this is trivial since the interface
is (nearly) the same.  For the non-reentrant version pointers to static
buffers are used to replace the user supplied buffers.

   I.e., the reentrant functions *can* have counterparts.  No service
module is forced to have functions for all databases and all kinds to
access them.  If a function is not available it is simply treated as if
the function would return `unavail' (*note Actions in the NSS
configuration::.).

   The file name `libnss_files.so.1' would be on a Solaris 2 system
`nss_files.so.1'.  This is the difference mentioned above.  Sun's NSS
modules are usable as modules which get indirectly loaded only.

   The NSS modules in the GNU C Library are prepared to be used as
normal libraries itself.  This is *not* true in the moment, though.
But the different organization of the name space in the modules does
not make it impossible like it is for Solaris.  Now you can see why the
modules are still libraries.(2)

   ---------- Footnotes ----------

   (1)  Now you might ask why to duplicate this information.  The
answer is that we want to keep the possibility to link directly with
these shared objects.

   (2)  There is a second explanation: we were too lazy to change the
Makefiles to allow the generation of shared objects not starting with
`lib' but do not tell this anybody.

