   This file documents the GNU C library.

   This is Edition 0.03, last updated 19 May 1993, of
`The GNU C Library Reference Manual', for Version 1.06 Beta.

   Copyright (C) 1993 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 translations of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.

Blocking Signals for a Handler
------------------------------

   When a signal handler is invoked, you usually want it to be able to
finish without being interrupted by another signal.  From the moment the
handler starts until the moment it finishes, you must block signals that
might confuse it or corrupt its data.

   When a handler function is invoked on a signal, that signal is
automatically blocked (in addition to any other signals that are already
in the process's signal mask) during the time the handler is running.
If you set up a handler for `SIGTSTP', for instance, then the arrival
of that signal forces further `SIGTSTP' signals to wait during the
execution of the handler.

   However, by default, other kinds of signals are not blocked; they can
arrive during handler execution.

   The reliable way to block other kinds of signals during the
execution of the handler is to use the `sa_mask' member of the
`sigaction' structure.

   Here is an example:

     #include <signal.h>
     #include <stddef.h>

     void catch_stop ();

     void
     install_handler (void)
     {
       struct sigaction setup_action;
       sigset_t block_mask;

       sigemptyset (&block_mask);
       /* Block other terminal-generated signals while handler runs. */
       sigaddset (&block_mask, SIGINT);
       sigaddset (&block_mask, SIGQUIT);
       setup_action.sa_handler = catch_stop;
       setup_action.sa_mask = block_mask;
       setup_action.sa_flags = 0;
       sigaction (SIGTSTP, &setup_action, NULL);
     }

   This is more reliable than blocking the other signals explicitly in
the code for the handler.  If you block signals explicity in the
handler, you can't avoid at least a short interval at the beginning of
the handler where they are not yet blocked.

   You cannot remove signals from the process's current mask using this
mechanism.  However, you can make calls to `sigprocmask' within your
handler to block or unblock signals as you wish.

   In any case, when the handler returns, the system restores the mask
that was in place before the handler was entered.

Checking for Pending Signals
----------------------------

   You can find out which signals are pending at any time by calling
`sigpending'.  This function is declared in `signal.h'.

 -- Function: int sigpending (sigset_t *SET)
     The `sigpending' function stores information about pending signals
     in SET.  If there is a pending signal that is blocked from
     delivery, then that signal is a member of the returned set.  (You
     can test whether a particular signal is a member of this set using
     `sigismember'; see Signal Sets.)

     The return value is `0' if successful, and `-1' on failure.

   Testing whether a signal is pending is not often useful.  Testing
when that signal is not blocked is almost certainly bad design.

   Here is an example.

     #include <signal.h>
     #include <stddef.h>

     sigset_t base_mask, waiting_mask;

     sigemptyset (&base_mask);
     sigaddset (&base_mask, SIGINT);
     sigaddset (&base_mask, SIGTSTP);

     /* Block user interrupts while doing other processing. */
     sigprocmask (SIG_SETMASK, &base_mask, NULL);
     ...

     /* After a while, check to see whether any signals are pending. */
     sigpending (&waiting_mask);
     if (sigismember (&waiting_mask, SIGINT)) {
       /* User has tried to kill the process. */
     }
     else if (sigismember (&waiting_mask, SIGTSTP)) {
       /* User has tried to stop the process. */
     }

   Remember that if there is a particular signal pending for your
process, additional signals of that same type that arrive in the
meantime might be discarded.  For example, if a `SIGINT' signal is
pending when another `SIGINT' signal arrives, your program will
probably only see one of them when you unblock this signal.

   *Portability Note:* The `sigpending' function is new in POSIX.1.
Older systems have no equivalent facility.

Remembering a Signal to Act On Later
------------------------------------

   Instead of blocking a signal using the library facilities, you can
get almost the same results by making the handler set a flag to be
tested later, when you "unblock".  Here is an example:

     /* If this flag is nonzero, don't handle the signal right away. */
     volatile sig_atomic_t signal_pending;

     /* This is nonzero if a signal arrived and was not handled. */
     volatile sig_atomic_t defer_signal;

     void
     handler (int signum)
     {
       if (defer_signal)
         signal_pending = signum;
       else
         ... /* ``Really'' handle the signal. */
     }

     ...

     void
     update_mumble (int frob)
     {
       /* Prevent signals from having immediate effect. */
       defer_signal++;
       /* Now update `mumble', without worrying about interruption. */
       mumble.a = 1;
       mumble.b = hack ();
       mumble.c = frob;
       /* We have updated `mumble'.  Handle any signal that came in. */
       defer_signal--;
       if (defer_signal == 0 && signal_pending != 0)
         raise (signal_pending);
     }

   Note how the particular signal that arrives is stored in
`signal_pending'.  That way, we can handle several types of
inconvenient signals with the same mechanism.

   We increment and decrement `defer_signal' so that nested critical
sections will work properly; thus, if `update_mumble' were called with
`signal_pending' already nonzero, signals would be deferred not only
within `update_mumble', but also within the caller.  This is also why
we do not check `signal_pending' if `defer_signal' is still nonzero.

   The incrementing and decrementing of `defer_signal' require more
than one instruction; it is possible for a signal to happen in the
middle.  But that does not cause any problem.  If the signal happens
early enough to see the value from before the increment or decrement,
that is equivalent to a signal which came before the beginning of the
increment or decrement, which is a case that works properly.

   It is absolutely vital to decrement `defer_signal' before testing
`signal_pending', because this avoids a subtle bug.  If we did these
things in the other order, like this,

       if (defer_signal == 1 && signal_pending != 0)
         raise (signal_pending);
       defer_signal--;

then a signal arriving in between the `if' statement and the decrement
would be effetively "lost" for an indefinite amount of time.  The
handler would merely set `defer_signal', but the program having already
tested this variable, it would not test the variable again.

   Bugs like these are called "timing errors".  They are especially bad
because they happen only rarely and are nearly impossible to reproduce.
You can't expect to find them with a debugger as you would find a
reproducible bug.  So it is worth being especially careful to avoid
them.

   (You would not be tempted to write the code in this order, given the
use of `defer_signal' as a counter which must be tested along with
`signal_pending'.  After all, testing for zero is cleaner than testing
for one.  But if you did not use `defer_signal' as a counter, and gave
it values of zero and one only, then either order might seem equally
simple.  This is a further advantage of using a counter for
`defer_signal': it will reduce the chance you will write the code in
the wrong order and create a subtle bug.)

Waiting for a Signal
====================

   If your program is driven by external events, or uses signals for
synchronization, then when it has nothing to do it should probably wait
until a signal arrives.

Using `pause'
-------------

   The simple way to wait until a signal arrives is to call `pause'.
Please read about its disadvantages, in the following section, before
you use it.

 -- Function: int pause ()
     The `pause' function suspends program execution until a signal
     arrives whose action is either to execute a handler function, or to
     terminate the process.

     If the signal causes a handler function to be executed, then
     `pause' returns.  This is considered an unsuccessful return (since
     "successful" behavior would be to suspend the program forever), so
     the return value is `-1'.  Even if you specify that other
     primitives should resume when a system handler returns (see
     Interrupted Primitives.), this has no effect on `pause'; it
     always fails when a signal is handled.

     The following `errno' error conditions are defined for this
     function:

    `EINTR'
          The function was interrupted by delivery of a signal.

     If the signal causes program termination, `pause' doesn't return
     (obviously).

     The `pause' function is declared in  `unistd.h'.

Problems with `pause'
---------------------

   The simplicity of `pause' can conceal serious timing errors that can
make a program hang mysteriously.

   It is safe to use `pause' if the real work of your program is done
by the signal handlers themselves, and the "main program" does nothing
but call `pause'.  Each time a signal is delivered, the handler will do
the next batch of work that is to be done, and then return, so that the
main loop of the program can call `pause' again.

   You can't safely use `pause' to wait until one more signal arrives,
and then resume real work.  Even if you arrange for the signal handler
to cooperate by setting a flag, you still can't use `pause' reliably.
Here is an example of this problem:

     /* `usr_interrupt' is set by the signal handler.  */
     if (!usr_interrupt)
       pause ();

     /* Do work once the signal arrives.  */
     ...

This has a bug: the signal could arrive after the variable
`usr_interrupt' is checked, but before the call to `pause'. If no
further signals arrive, the process would never wake up again.

   You can put an upper limit on the excess waiting by using `sleep' in
a loop, instead of using `pause'.  (see Sleeping, for more about
`sleep'.)  Here is what this looks like:

     /* `usr_interrupt' is set by the signal handler.
     while (!usr_interrupt)
       sleep (1);

     /* Do work once the signal arrives.  */
     ...

   For some purposes, that is good enough.  But with a little more
complexity, you can wait reliably until a particular signal handler is
run, using `sigsuspend'. See Sigsuspend.

Using `sigsuspend'
------------------

   The clean and reliable way to wait for a signal to arrive is to
block it and then use `sigsuspend'.  By using `sigsuspend' in a loop,
you can wait for certain kinds of signals, while letting other kinds of
signals be handled by their handlers.

 -- Function: int sigsuspend (const sigset_t *SET)
     This function replaces the process's signal mask with SET and then
     suspends the process until a signal is delivered whose action is
     either to terminate the process or invoke a signal handling
     function.  In other words, the program is effectively suspended
     until one of the signals that is not a member of SET arrives.

     If the process is woken up by deliver of a signal that invokes a
     handler function, and the handler function returns, then
     `sigsuspend' also returns.

     The mask remains SET only as long as `sigsuspend' is waiting. The
     function `sigsuspend' always restores the previous signal mask
     when it returns.

     The return value and error conditions are the same as for `pause'.

   With `sigsuspend', you can replace the `pause' or `sleep' loop in
the previous section with something completely reliable:

     sigset_t mask, oldmask;

     ...

     /* Set up the mask of signals to temporarily block. */
     sigemptyset (&mask);
     sigaddset (&mask, SIGUSR1);

     ...

     /* Wait for a signal to arrive. */
     sigprocmask (SIG_BLOCK, &mask, &oldmask);
     while (!usr_interrupt)
       sigsuspend (&oldmask);
     sigprocmask (SIG_UNBLOCK, &mask, NULL);

   This last piece of code is a little tricky.  The key point to
remember here is that when `sigsuspend' returns, it resets the process's
signal mask to the original value, the value from before the call to
`sigsuspend'--in this case, the `SIGUSR1' signal is once again blocked.
 The second call to `sigprocmask' is necessary to explicitly unblock
this signal.

   One other point: you may be wondering why the `while' loop is
necessary at all, since the program is apparently only waiting for one
`SIGUSR1' signal.  The answer is that the mask passed to `sigsuspend'
permits the process to be woken up by the delivery of other kinds of
signals, as well--for example, job control signals.  If the process is
woken up by a signal that doesn't set `usr_interrupt', it just suspends
itself again until the "right" kind of signal eventually arrives.

   This technique takes a few more lines of preparation, but that is
needed just once for each kind of wait criterion you want to use.  The
code that actually waits is just four lines.

BSD Signal Handling
===================

   This section describes alternative signal handling functions derived
from BSD Unix.  These facilities were an advance, in their time; today,
they are mostly obsolete, and supported mainly for compatibility with
BSD Unix.

   They do provide one feature that is not available through the POSIX
functions: You can specify a separate stack for use in certain signal
handlers.  Using a signal stack is the only way you can handle a signal
caused by stack overflow.

POSIX and BSD Signal Facilities
-------------------------------

   There are many similarities between the BSD and POSIX signal handling
facilities, because the POSIX facilities were inspired by the BSD
facilities.  Besides having different names for all the functions to
avoid conflicts, the main differences between the two are:

   * BSD Unix represents signal masks as an `int' bit mask, rather than
     as a `sigset_t' object.

   * The BSD facilities use a different default for whether an
     interrupted primitive should fail or resume.  The POSIX facilities
     make system calls fail unless you specify that they should resume.
      With the BSD facility, the default is to make system calls resume
     unless you say they should fail.  See Interrupted Primitives.

   * BSD Unix has a concept of a "signal stack".  This is an alternate
     stack that is used during the execution of signal handler
     functions, instead of its normal execution stack.

   The BSD facilities are declared in `signal.h'.

BSD Function to Establish a Handler
===================================

 -- Data Type: struct sigvec
     This data type is the BSD equivalent of `struct sigaction' (see
     Advanced Signal Handling.); it is used to specify signal actions
     to the `sigvec' function.  It contains the following members:

    `sighandler_t sv_handler'
          This is the handler function.

    `int sv_mask'
          This is the mask of additional signals to be blocked while
          the handler function is being called.

    `int sv_flags'
          This is a bit mask used to specify various flags which affect
          the behavior of the signal.  You can also refer to this field
          as `sv_onstack'.

   These symbolic constants can be used to provide values for the
`sv_flags' field of a `sigvec' structure.  This field is a bit mask
value, so you bitwise-OR the flags of interest to you together.

 -- Macro: int SV_ONSTACK
     If this bit is set in the `sv_flags' field of a `sigvec'
     structure, it means to use the signal stack when delivering the
     signal.

 -- Macro: int SV_INTERRUPT
     If this bit is set in the `sv_flags' field of a `sigvec'
     structure, it means that system calls interrupted by this kind of
     signal should not be restarted if the handler returns; instead,
     the system calls should return with a `EINTR' error status.  See
     Interrupted Primitives.

 -- Macro: int SV_RESETHAND
     If this bit is set in the `sv_flags' field of a `sigvec'
     structure, it means to reset the action for the signal back to
     `SIG_DFL' when the signal is received.

 -- Function: int sigvec (int SIGNUM, const struct sigvec
          *ACTION,struct sigvec *OLD_ACTION)
     This function is the equivalent of `sigaction' (see Advanced Signal Handling.);
     it installs the action ACTION for the signal
     SIGNUM, returning information about the previous action in effect
     for that signal in OLD_ACTION.

 -- Function: int siginterrupt (int SIGNUM, int FAILFLAG)
     This function specifies which approach to use when certain
     primitives are interrupted by handling signal SIGNUM.  If FAILFLAG
     is false, signal SIGNUM restarts primitives.  If FAILFLAG is true,
     handling SIGNUM causes these primitives to fail with error code
     `EINTR'.  See Interrupted Primitives.

BSD Functions for Blocking Signals
----------------------------------

 -- Macro: int sigmask (int SIGNUM)
     This macro returns a signal mask that has the bit for signal SIGNUM
     set.  You can bitwise-OR the results of several calls to `sigmask'
     together to specify more than one signal.  For example,

          (sigmask (SIGTSTP) | sigmask (SIGSTOP)
           | sigmask (SIGTTIN) | sigmask (SIGTTOU))

     specifies a mask that includes all the job-control stop signals.

 -- Function: int sigblock (int MASK)
     This function is the equivalent of `sigprocmask' (see Process Signal Mask.)
     with a HOW argument of `SIG_BLOCK': it adds the
     signals specified by MASK to the calling process's signal mask.
     The return value is the previous set of blocked signals.

 -- Function: int sigsetmask (int MASK)
     This function is the equivalent of `sigprocmask' (see Process Signal Mask.)
     with a HOW argument of `SIG_SETMASK': it sets the
     calling process's signal mask to MASK.  The return value is the
     previous set of blocked signals.

 -- Function: int sigpause (int MASK)
     This function is the equivalent of `sigsuspend' (see Waiting for a Signal.):
     it sets the calling process's signal mask to MASK,
     and waits for a signal to arrive.  On return the previous set of
     blocked signals is restored.

Using a Separate Signal Stack
-----------------------------

   A signal stack is a special area of memory to be used as the
execution stack during signal handlers.  It should be fairly large, to
avoid any danger that it will overflow in turn--we recommend at least
16,000 bytes.  You can use `malloc' to allocate the space for the stack.
Then call `sigstack' to tell the system to use that space for the
signal stack.

   You don't need to write signal handlers differently in order to use a
signal stack.  Switching from one stack to the other happens
automatically.  However, some debuggers on some machines may get
confused if you examine a stack trace while a handler that uses the
signal stack is running.

 -- Data Type: struct sigstack
     This structure describes a signal stack.  It contains the
     following members:

    `void *ss_sp'
          This is the stack pointer.

    `int ss_onstack'
          This field is true if the process is currently using this
          stack.

 -- Function: int sigstack (const struct sigstack *STACK, struct
          sigstack *OLDSTACK)
     The `sigstack' function specifies an alternate stack for use during
     signal handling.  When a signal is received by the process and its
     action indicates that the signal stack is used, the system
     arranges a switch to the currently installed signal stack while
     the handler for that signal is executed.

     If OLDSTACK is not a null pointer, information about the currently
     installed signal stack is returned in the location it points to.
     If STACK is not a null pointer, then this is installed as the new
     stack for use by signal handlers.

     The return value is `0' on success and `1' on failure.

Process Startup and Termination
*******************************

   "Processes" are the primitive units for allocation of system
resources.  Each process has its own address space and (usually) one
thread of control.  A process executes a program; you can have multiple
processes executing the same program, but each process has its own copy
of the program within its own address space and executes it
independently of the other copies.

   This chapter explains what your program should do to handle the
startup of a process, to terminate its process, and to receive
information (arguments and the environment) from the parent process.

Program Arguments
=================

   The system starts a C program by calling the function `main'.  It is
up to you to write a function named `main'--otherwise, you won't even
be able to link your program without errors.

   You can define `main' either to take no arguments, or to take two
arguments that represent the command line arguments to the program, like
this:

     int main (int ARGC, char *ARGV[])

   The command line arguments are the whitespace-separated tokens given
in the shell command used to invoke the program; thus, in `cat foo
bar', the arguments are `foo' and `bar'.  The only way a program can
look at its command line arguments is via the arguments of `main'.  If
`main' doesn't take arguments, then you cannot get at the command line.

   The value of the ARGC argument is the number of command line
arguments.  The ARGV argument is a vector of C strings; its elements
are the individual command line argument strings.  The file name of the
program being run is also included in the vector as the first element;
the value of ARGC counts this element.  A null pointer always follows
the last element: `ARGV[ARGC]' is this null pointer.

   For the command `cat foo bar', ARGC is 3 and ARGV has three
elements, `"cat"', `"foo"' and `"bar"'.

   If the syntax for the command line arguments to your program is
simple enough, you can simply pick the arguments off from ARGV by hand.
But unless your program takes a fixed number of arguments, or all of the
arguments are interpreted in the same way (as file names, for example),
you are usually better off using `getopt' to do the parsing.

Program Argument Syntax Conventions
-----------------------------------

   POSIX recommends these conventions for command line arguments.
`getopt' (see Parsing Options.) makes it easy to implement them.

   * Arguments are options if they begin with a hyphen delimiter (`-').

   * Multiple options may follow a hyphen delimiter in a single token if
     the options do not take arguments.  Thus, `-abc' is equivalent to
     `-a -b -c'.

   * Option names are single alphanumeric characters (as for `isalnum';
     see Classification of Characters).

   * Certain options require an argument.  For example, the `-o' command
     of the `ld' command requires an argument--an output file name.

   * An option and its argument may or may not appear as separate
     tokens.  (In other words, the whitespace separating them is
     optional.)  Thus, `-o foo' and `-ofoo' are equivalent.

   * Options typically precede other non-option arguments.

     The implementation of `getopt' in the GNU C library normally makes
     it appear as if all the option arguments were specified before all
     the non-option arguments for the purposes of parsing, even if the
     user of your program intermixed option and non-option arguments.
     It does this by reordering the elements of the ARGV array.  This
     behavior is nonstandard; if you want to suppress it, define the
     `_POSIX_OPTION_ORDER' environment variable.  See Standard Environment.

   * The argument `--' terminates all options; any following arguments
     are treated as non-option arguments, even if they begin with a
     hyphen.

   * A token consisting of a single hyphen character is interpreted as
     an ordinary non-option argument.  By convention, it is used to
     specify input from or output to the standard input and output
     streams.

   * Options may be supplied in any order, or appear multiple times.
     The interpretation is left up to the particular application
     program.

   GNU adds "long options" to these conventions.  Long options consist
of `--' followed by a name made of alphanumeric characters and dashes.
Option names are typically one to three words long, with hyphens to
separate words.  Users can abbreviate the option names as long as the
abbreviations are unique.

   To specify an argument for a long option, write `--NAME=VALUE'.
This syntax enables a long option to accept an argument that is itself
optional.

   Eventually, the GNU system will provide completion for long option
names in the shell.

Parsing Program Options
-----------------------

   Here are the details about how to call the `getopt' function.  To
use this facility, your program must include the header file `unistd.h'.

 -- Variable: int opterr
     If the value of this variable is nonzero, then `getopt' prints an
     error message to the standard error stream if it encounters an
     unknown option character or an option with a missing required
     argument.  This is the default behavior.  If you set this variable
     to zero, `getopt' does not print any messages, but it still
     returns the character `?' to indicate an error.

 -- Variable: int optopt
     When `getopt' encounters an unknown option character or an option
     with a missing required argument, it stores that option character
     in this variable.  You can use this for providing your own
     diagnostic messages.

 -- Variable: int optind
     This variable is set by `getopt' to the index of the next element
     of the ARGV array to be processed.  Once `getopt' has found all of
     the option arguments, you can use this variable to determine where
     the remaining non-option arguments begin.  The initial value of
     this variable is `1'.

 -- Variable: char * optarg
     This variable is set by `getopt' to point at the value of the
     option argument, for those options that accept arguments.

 -- Function: int getopt (int ARGC, char **ARGV, const char *OPTIONS)
     The `getopt' function gets the next option argument from the
     argument list specified by the ARGV and ARGC arguments. Normally
     these values come directly from the arguments received by `main'.

     The OPTIONS argument is a string that specifies the option
     characters that are valid for this program.  An option character
     in this string can be followed by a colon (`:') to indicate that
     it takes a required argument.

     If the OPTIONS argument string begins with a hyphen (`-'), this is
     treated specially.  It permits arguments that are not options to be
     returned as if they were associated with option character `\0'.

     The `getopt' function returns the option character for the next
     command line option.  When no more option arguments are available,
     it returns `-1'.  There may still be more non-option arguments; you
     must compare the external variable `optind' against the ARGC
     parameter to check this.

     If the option has an argument, `getopt' returns the argument by
     storing it in the varables OPTARG.  You don't ordinarily need to
     copy the `optarg' string, since it is a pointer into the original
     ARGV array, not into a static area that might be overwritten.

     If `getopt' finds an option character in ARGV that was not
     included in OPTIONS, or a missing option argument, it returns `?'
     and sets the external variable `optopt' to the actual option
     character.  If the first character of OPTIONS is a colon (`:'),
     then `getopt' returns `:' instead of `?' to indicate a missing
     option argument.  In addition, if the external variable `opterr'
     is nonzero (which is the default), `getopt' prints an error
     message.

Example of Parsing Arguments with `getopt'
------------------------------------------

   Here is an example showing how `getopt' is typically used.  The key
points to notice are:

   * Normally, `getopt' is called in a loop.  When `getopt' returns
     `-1', indicating no more options are present, the loop terminates.

   * A `switch' statement is used to dispatch on the return value from
     `getopt'.  In typical use, each case just sets a variable that is
     used later in the program.

   * A second loop is used to process the remaining non-option
     arguments.

     #include <unistd.h>
     #include <stdio.h>

     int
     main (int argc, char **argv)
     {
       int aflag = 0;
       int bflag = 0;
       char *cvalue = NULL;
       int index;
       int c;

       opterr = 0;

       while ((c = getopt (argc, argv, "abc:")) != -1)
         switch (c)
           {
           case 'a':
             aflag = 1;
             break;
           case 'b':
             bflag = 1;
             break;
           case 'c':
             cvalue = optarg;
             break;
           case '?':
             if (isprint (optopt))
               fprintf (stderr, "Unknown option `-%c'.\n", optopt);
             else
               fprintf (stderr,
                        "Unknown option character `\\x%x'.\n",
                        optopt);
             return 1;
           default:
             abort ();
           }

       printf ("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue);

       for (index = optind; index < argc; index++)
         printf ("Non-option argument %s\n", argv[index]);
       return 0;
     }

   Here are some examples showing what this program prints with
different combinations of arguments:

     % testopt
     aflag = 0, bflag = 0, cvalue = (null)

     % testopt -a -b
     aflag = 1, bflag = 1, cvalue = (null)

     % testopt -ab
     aflag = 1, bflag = 1, cvalue = (null)

     % testopt -c foo
     aflag = 0, bflag = 0, cvalue = foo

     % testopt -cfoo
     aflag = 0, bflag = 0, cvalue = foo

     % testopt arg1
     aflag = 0, bflag = 0, cvalue = (null)
     Non-option argument arg1

     % testopt -a arg1
     aflag = 1, bflag = 0, cvalue = (null)
     Non-option argument arg1

     % testopt -c foo arg1
     aflag = 0, bflag = 0, cvalue = foo
     Non-option argument arg1

     % testopt -a -- -b
     aflag = 1, bflag = 0, cvalue = (null)
     Non-option argument -b

     % testopt -a -
     aflag = 1, bflag = 0, cvalue = (null)
     Non-option argument -

Parsing Long Options
--------------------

   To accept GNU-style long options as well as single-character options,
use `getopt_long' instead of `getopt'.  You should make every program
accept long options if it uses any options, for this takes little extra
work and helps beginners remember how to use the program.

 -- Data Type: struct option
     This structure describes a single long option name for the sake of
     `getopt_long'.  The argument LONGOPTS must be an array of these
     structures, one for each long option.  Terminate the array with an
     element containing all zeros.

     The `struct option' structure has these fields:

    `const char *name'
          This field is the name of the option.  It is a string.

    `int has_arg'
          This field says whether the option takes an argument.  It is
          an integer, and there are three legitimate values:
          `no_argument', `required_argument' and `optional_argument'.

    `int *flag'
    `int val'
          These fields control how to report or act on the option when
          it occurs.

          If `flag' is a null pointer, then the `val' is a value which
          identifies this option.  Often these values are chosen to
          uniquely identify particular long options.

          If `flag' is not a null pointer, it should be the address of
          an `int' variable which is the flag for this option.  The
          value in `val' is the value to store in the flag to indicate
          that the option was seen.

 -- Function: int getopt_long (int ARGC, char **ARGV, const char
          *SHORTOPTS, struct option *LONGOPTS, int *INDEXPTR)
     Decode options from the vector ARGV (whose length is ARGC). The
     argument SHORTOPTS describes the short options to accept, just as
     it does in `getopt'.  The argument LONGOPTS describes the long
     options to accept (see above).

     When `getopt_long' encounters a short option, it does the same
     thing that `getopt' would do: it returns the character code for the
     option, and stores the options argument (if it has one) in
     `optarg'.

     When `getopt_long' encounters a long option, it takes actions based
     on the `flag' and `val' fields of the definition of that option.

     If `flag' is a null pointer, then `getopt_long' returns the
     contents of `val' to indicate which option it found.  You should
     arrange distinct values in the `val' field for options with
     different meanings, so you can decode these values after
     `getopt_long' returns.  If the long option is equivalent to a short
     option, you can use the short option's character code in `val'.

     If `flag' is not a null pointer, that means this option should just
     set a flag in the program.  The flag is a variable of type `int'
     that you define.  Put the address of the flag in the `flag' field.
     Put in the `val' field the value you would like this option to
     store in the flag.  In this case, `getopt_long' returns `0'.

     For any long option, `getopt_long' tells you the index in the array
     LONGOPTS of the options definition, by storing it into
     `*INDEXPTR'.  You can get the name of the option with
     `LONGOPTS[*INDEXPTR].name'.  So you can distinguish among long
     options either by the values in their `val' fields or by their
     indices.  You can also distinguish in this way among long options
     that set flags.

     When a long option has an argument, `getopt_long' puts the argument
     value in the variable `optarg' before returning.  When the option
     has no argument, the value in `optarg' is a null pointer.  This is
     how you can tell whether an optional argument was supplied.

     When `getopt_long' has no more options to handle, it returns `-1',
     and leaves in the variable `optind' the index in ARGV of the next
     remaining argument.

Example of Parsing Long Options
-------------------------------

     #include <stdio.h>

     /* Flag set by `--verbose'.   */
     static int verbose_flag;

     int
     main (argc, argv)
          int argc;
          char **argv;
     {
       int c;

       while (1)
         {
           static struct option long_options[] =
     	{
     	  /* These options set a flag.   */
     	  {"verbose", 0, &verbose_flag, 1},
     	  {"brief", 0, &verbose_flag, 0},
     	  /* These options don't set a flag.
     	     We distinguish them by their indices.  */
     	  {"add", 1, 0, 0},
     	  {"append", 0, 0, 0},
     	  {"delete", 1, 0, 0},
     	  {"create", 0, 0, 0},
     	  {"file", 1, 0, 0},
     	  {0, 0, 0, 0}
     	};
           /* `getopt_long' stores the option index here.   */
           int option_index = 0;

           c = getopt_long (argc, argv, "abc:d:",
     		       long_options, &option_index);

           /* Detect the end of the options.   */
           if (c == -1)
     	break;

           switch (c)
     	{
     	case 0:
     	  /* If this option set a flag, do nothing else now.   */
     	  if (long_options[option_index].flag != 0)
     	    break;
     	  printf ("option %s", long_options[option_index].name);
     	  if (optarg)
     	    printf (" with arg %s", optarg);
     	  printf ("\n");
     	  break;

     	case 'a':
     	  puts ("option -a\n");
     	  break;

     	case 'b':
     	  puts ("option -b\n");
     	  break;

     	case 'c':
     	  printf ("option -c with value `%s'\n", optarg);
     	  break;

     	case 'd':
     	  printf ("option -d with value `%s'\n", optarg);
     	  break;

     	case '?':
     	  /* `getopt_long' already printed an error message.   */
     	  break;

     	default:
     	  abort ();
     	}
         }

       /* Instead of reporting `--verbose'
          and `--brief' as they are encountered,
          we report the final status resulting from them.  */
       if (verbose_flag)
         puts ("verbose flag is set");

       /* Print any remaining command line arguments (not options).   */
       if (optind < argc)
         {
           printf ("non-option ARGV-elements: ");
           while (optind < argc)
     	printf ("%s ", argv[optind++]);
           putchar ('\n');
         }

       exit (0);
     }

Environment Variables
=====================

   When a program is executed, it receives information about the
context in which it was invoked in two ways.  The first mechanism uses
the ARGV and ARGC arguments to its `main' function, and is discussed in
Program Arguments.  The second mechanism uses "environment
variables" and is discussed in this section.

   The ARGV mechanism is typically used to pass command-line arguments
specific to the particular program being invoked.  The environment, on
the other hand, keeps track of information that is shared by many
programs, changes infrequently, and that is less frequently accessed.

   The environment variables discussed in this section are the same
environment variables that you set using assignments and the `export'
command in the shell.  Programs executed from the shell inherit all of
the environment variables from the shell.

   Standard environment variables are used for information about the
user's home directory, terminal type, current locale, and so on; you
can define additional variables for other purposes.  The set of all
environment variables that have values is collectively known as the
"environment".

   Names of environment variables are case-sensitive and must not
contain the character `='.  System-defined environment variables are
invariably uppercase.

   The values of environment variables can be anything that can be
represented as a string.  A value must not contain an embedded null
character, since this is assumed to terminate the string.

Environment Access
------------------

   The value of an environment variable can be accessed with the
`getenv' function.  This is declared in the header file `stdlib.h'.

 -- Function: char * getenv (const char *NAME)
     This function returns a string that is the value of the environment
     variable NAME.  You must not modify this string.  In some systems
     not using the GNU library, it might be overwritten by subsequent
     calls to `getenv' (but not by any other library function). If the
     environment variable NAME is not defined, the value is a null
     pointer.

 -- Function: int putenv (const char *STRING)
     The `putenv' function adds or removes definitions from the
     environment. If the STRING is of the form `NAME=VALUE', the
     definition is added to the environment.  Otherwise, the STRING is
     interpreted as the name of an environment variable, and any
     definition for this variable in the environment is removed.

     The GNU library provides this function for compatibility with
     SVID; it may not be available in other systems.

   You can deal directly with the underlying representation of
environment objects to add more variables to the environment (for
example, to communicate with another program you are about to execute;
see Executing a File).

 -- Variable: char ** environ
     The environment is represented as an array of strings.  Each
     string is of the format `NAME=VALUE'.  The order in which strings
     appear in the environment is not significant, but the same NAME
     must not appear more than once.  The last element of the array is
     a null pointer.

     This variable is declared in the header file `unistd.h'.

     If you just want to get the value of an environment variable, use
     `getenv'.

Standard Environment Variables
------------------------------

   These environment variables have standard meanings.  This doesn't
mean that they are always present in the environment; but if these
variables *are* present, they have these meanings, and that you
shouldn't try to use these environment variable names for some other
purpose.

`HOME'
     This is a string representing the user's "home directory", or
     initial default working directory.

     The user can set `HOME' to any value. If you need to make sure to
     obtain the proper home directory for a particular user, you should
     not use `HOME'; instead, look up the user's name in the user
     database (see User Database.).

     For most purposes, it is better to use `HOME', precisely because
     this lets the user specify the value.

`LOGNAME'
     This is the name that the user used to log in.  Since the value in
     the environment can be tweaked arbitrarily, this is not a reliable
     way to identify the user who is running a process; a function like
     `getlogin' (see Who Logged In.) is better for that purpose.

     For most purposes, it is better to use `LOGNAME', precisely because
     this lets the user specify the value.

`PATH'
     A "path" is a sequence of directory names which is used for
     searching for a file.  The variable `PATH' holds a path used for
     searching for programs to be run.

     The `execlp' and `execvp' functions (see Executing a File.)
     use this environment variable, as do many shells and other
     utilities which are implemented in terms of those functions.

     The syntax of a path is a sequence of directory names separated by
     colons.  An empty string instead of a directory name stands for the
     current directory (see Working Directory.).

     A typical value for this environment variable might be a string
     like:

          :/bin:/etc:/usr/bin:/usr/new/X11:/usr/new:/usr/local:/usr/local/bin

     This means that if the user tries to execute a program named `foo',
     the system will look for files named `foo', `/bin/foo',
     `/etc/foo', and so on.  The first of these files that exists is
     the one that is executed.

`TERM'
     This specifies the kind of terminal that is receiving program
     output. Some programs can make use of this information to take
     advantage of special escape sequences or terminal modes supported
     by particular kinds of terminals.  Many programs which use the
     termcap library (see Find (termcap))
     use the `TERM' environment variable, for example.

`TZ'
     This specifies the time zone.  See TZ Variable, for
     information about the format of this string and how it is used.

`LANG'
     This specifies the default locale to use for attribute categories
     where neither `LC_ALL' nor the specific environment variable for
     that category is set.  See Locales, for more information about
     locales.

`LC_COLLATE'
     This specifies what locale to use for string sorting.

`LC_CTYPE'
     This specifies what locale to use for character sets and character
     classification.

`LC_MONETARY'
     This specifies what locale to use for formatting monetary values.

`LC_NUMERIC'
     This specifies what locale to use for formatting numbers.

`LC_TIME'
     This specifies what locale to use for formatting date/time values.

`_POSIX_OPTION_ORDER'
     If this environment variable is defined, it suppresses the usual
     reordering of command line arguments by `getopt'.  See Argument Syntax.

Program Termination
===================

   The usual way for a program to terminate is simply for its `main'
function to return.  The "exit status value" returned from the `main'
function is used to report information back to the process's parent
process or shell.

   A program can also terminate normally by calling the `exit' function.

   In addition, programs can be terminated by signals; this is
discussed in more detail in Signal Handling.  The `abort'
function causes a signal that kills the program.

Normal Termination
------------------

   A process terminates normally when the program calls `exit'.
Returning from `main' is equivalent to calling `exit', and the value
that `main' returns is used as the argument to `exit'.

 -- Function: void exit (int STATUS)
     The `exit' function terminates the process with status STATUS.
     This function does not return.

   Normal termination causes the following actions:

  1. Functions that were registered with the `atexit' or `on_exit'
     functions are called in the reverse order of their registration.
     This mechanism allows your application to specify its own
     "cleanup" actions to be performed at program termination.
     Typically, this is used to do things like saving program state
     information in a file, or unlocking locks in shared data bases.

  2. All open streams are closed, writing out any buffered output data.
      See Closing Streams.  In addition, temporary files opened
     with the `tmpfile' function are removed; see Temporary Files.

  3. `_exit' is called, terminating the program.  See Termination Internals.