This is libc.info, produced by makeinfo version 4.0 from libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.09 DRAFT, last updated 28 Aug 1999, of `The GNU C
Library Reference Manual', for Version 2.2 Beta.

   Copyright (C) 1993, '94, '95, '96, '97, '98, '99 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: BSD Handler,  Next: Blocking in BSD,  Up: BSD Signal Handling

BSD Function to Establish a Handler
-----------------------------------

 - Data Type: struct sigvec
     This data type is the BSD equivalent of `struct sigaction' (*note
     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.  *Note
     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' (*note 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'.  *Note Interrupted Primitives::.


File: libc.info,  Node: Blocking in BSD,  Prev: BSD Handler,  Up: BSD Signal Handling

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 equivalent to `sigprocmask' (*note Process Signal
     Mask::) with a HOW argument of `SIG_BLOCK': it adds the signals
     specified by MASK to the calling process's set of blocked signals.
     The return value is the previous set of blocked signals.

 - Function: int sigsetmask (int MASK)
     This function equivalent to `sigprocmask' (*note 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' (*note 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.


File: libc.info,  Node: Program Basics,  Next: Processes,  Prev: Signal Handling,  Up: Top

The Basic Program/System Interface
**********************************

   "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.  Though it may have multiple threads
of control within the same program and a program may be composed of
multiple logically separate modules, a process always executes exactly
one program.

   Note that we are using a specific definition of "program" for the
purposes of this manual, which corresponds to a common definition in the
context of Unix system.  In popular usage, "program" enjoys a much
broader definition; it can refer for example to a system's kernel, an
editor macro, a complex package of software, or a discrete section of
code executing within a process.

   Writing the program is what this manual is all about.  This chapter
explains the most basic interface between your program and the system
that runs, or calls, it.  This includes passing of parameters (arguments
and environment) from the system, requesting basic services from the
system, and telling the system the program is done.

   A program starts another program with the `exec' family of system
calls.  This chapter looks at program startup from the execee's point
of view.  To see the event from the execor's point of view, *Note
Executing a File::.

* Menu:

* Program Arguments::           Parsing your program's command-line arguments.
* Environment Variables::       Less direct parameters affecting your program
* System Calls::                Requesting service from the system
* Program Termination::         Telling the system you're done; return status


File: libc.info,  Node: Program Arguments,  Next: Environment Variables,  Up: Program Basics

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.

   In ISO C 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"'.

   In Unix systems you can define `main' a third way, using three
arguments:

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

   The first two arguments are just the same.  The third argument ENVP
gives the program's environment; it is the same as the value of
`environ'.  *Note Environment Variables::.  POSIX.1 does not allow this
three-argument form, so to be portable it is best to write `main' to
take two arguments, and use the value of `environ'.

* Menu:

* Argument Syntax::             By convention, options start with a hyphen.
* Parsing Program Arguments::   Ways to parse program options and arguments.


File: libc.info,  Node: Argument Syntax,  Next: Parsing Program Arguments,  Up: Program Arguments

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

   POSIX recommends these conventions for command line arguments.
`getopt' (*note Getopt::) and `argp_parse' (*note Argp::) make 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';
     *note 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 implementations of `getopt' and `argp_parse' in the GNU C
     library normally make 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.  They do 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.
     *Note 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.


File: libc.info,  Node: Parsing Program Arguments,  Prev: Argument Syntax,  Up: Program Arguments

Parsing Program Arguments
-------------------------

   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' (*note Getopt::) or
`argp_parse' (*note Argp::) to do the parsing.

   `getopt' is more standard (the short-option only version of it is a
part of the POSIX standard), but using `argp_parse' is often easier,
both for very simple and very complex option structures, because it
does more of the dirty work for you.

* Menu:

* Getopt::                      Parsing program options using `getopt'.
* Argp::                        Parsing program options using `argp_parse'.
* Suboptions::                  Some programs need more detailed options.
* Suboptions Example::          This shows how it could be done for `mount'.


File: libc.info,  Node: Getopt,  Next: Argp,  Up: Parsing Program Arguments

Parsing program options using `getopt'
======================================

   The `getopt' and `getopt_long' functions automate some of the chore
involved in parsing typical unix command line options.

* Menu:

* Using Getopt::                Using the `getopt' function.
* Example of Getopt::           An example of parsing options with `getopt'.
* Getopt Long Options::         GNU suggests utilities accept long-named
                                 options; here is one way to do.
* Getopt Long Option Example::  An example of using `getopt_long'.


File: libc.info,  Node: Using Getopt,  Next: Example of Getopt,  Up: Getopt

Using the `getopt' function
---------------------------

   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 an option character is followed
     by two colons (`::'), its argument is optional; this is a GNU
     extension.

     `getopt' has three ways to deal with options that follow
     non-options ARGV elements.  The special argument `--' forces in
     all cases the end of option scanning.

        * The default is to permute the contents of ARGV while scanning
          it so that eventually all the non-options are at the end.
          This allows options to be given in any order, even with
          programs that were not written to expect this.

        * 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 `\1'.

        * POSIX demands the following behaviour: The first non-option
          stops option processing.  This mode is selected by either
          setting the environment variable `POSIXLY_CORRECT' or
          beginning the OPTIONS argument string with a plus sign (`+').

     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 variable 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.


File: libc.info,  Node: Example of Getopt,  Next: Getopt Long Options,  Prev: Using Getopt,  Up: Getopt

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 -


File: libc.info,  Node: Getopt Long Options,  Next: Getopt Long Option Example,  Prev: Example of Getopt,  Up: Getopt

Parsing Long Options with `getopt_long'
---------------------------------------

   To accept GNU-style long options as well as single-character options,
use `getopt_long' instead of `getopt'.  This function is declared in
`getopt.h', not `unistd.h'.  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 *const *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.

   Since long option names were used before before the `getopt_long'
options was invented there are program interfaces which require programs
to recognize options like `-option value' instead of `--option value'.
To enable these programs to use the GNU getopt functionality there is
one more function available.

 - Function: int getopt_long_only (int ARGC, char *const *ARGV, const
          char *SHORTOPTS, struct option *LONGOPTS, int *INDEXPTR)
     The `getopt_long_only' function is equivalent to the `getopt_long'
     function but it allows to specify the user of the application to
     pass long options with only `-' instead of `--'.  The `--' prefix
     is still recognized but instead of looking through the short
     options if a `-' is seen it is first tried whether this parameter
     names a long option.  If not, it is parsed as a short option.

     Assuming `getopt_long_only' is used starting an application with

            app -foo

     the `getopt_long_only' will first look for a long option named
     `foo'.  If this is not found, the short options `f', `o', and
     again `o' are recognized.


File: libc.info,  Node: Getopt Long Option Example,  Prev: Getopt Long Options,  Up: Getopt

Example of Parsing Long Options with `getopt_long'
--------------------------------------------------

     #include <stdio.h>
     #include <stdlib.h>
     #include <getopt.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", no_argument,       &verbose_flag, 1},
               {"brief",   no_argument,       &verbose_flag, 0},
               /* These options don't set a flag.
                  We distinguish them by their indices. */
               {"add",     required_argument, 0, 'a'},
               {"append",  no_argument,       0, 'b'},
               {"delete",  required_argument, 0, 'd'},
               {"create",  no_argument,       0, 'c'},
               {"file",    required_argument, 0, 'f'},
               {0, 0, 0, 0}
             };
           /* `getopt_long' stores the option index here. */
           int option_index = 0;
     
           c = getopt_long (argc, argv, "abc:d:f:",
                            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 'f':
               printf ("option -f 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);
     }


File: libc.info,  Node: Argp,  Next: Suboptions,  Prev: Getopt,  Up: Parsing Program Arguments

Parsing Program Options with Argp
=================================

   "Argp" is an interface for parsing unix-style argument vectors
(*note Program Arguments::).

   Unlike the more common `getopt' interface, it provides many related
convenience features in addition to parsing options, such as
automatically producing output in response to `--help' and `--version'
options (as defined by the GNU coding standards).  Doing these things
in argp results in a more consistent look for programs that use it, and
makes less likely that implementors will neglect to implement them or
keep them up-to-date.

   Argp also provides the ability to merge several independently defined
option parsers into one, mediating conflicts between them, and making
the result appear seamless.  A library can export an argp option parser,
which programs can easily use in conjunction with their own option
parser.  This results in less work for user programs (indeed, some may
use only argument parsers exported by libraries, and have no options of
their own), and more consistent option-parsing for the abstractions
implemented by the library.

   The header file `<argp.h>' should be included to use argp.

The `argp_parse' Function
-------------------------

   The main interface to argp is the `argp_parse' function; often, a
call to `argp_parse' is the only argument-parsing code needed in `main'
(*note Program Arguments::).

 - Function: error_t argp_parse (const struct argp *ARGP, int ARGC,
          char **ARGV, unsigned FLAGS, int *ARG_INDEX, void *INPUT)
     The `argp_parse' function parses the arguments in ARGV, of length
     ARGC, using the argp parser ARGP (*note Argp Parsers::); a value
     of zero is the same as a `struct argp' containing all zeros.
     FLAGS is a set of flag bits that modify the parsing behavior
     (*note Argp Flags::).  INPUT is passed through to the argp parser
     ARGP, and has meaning defined by it; a typical usage is to pass a
     pointer to a structure which can be used for specifying parameters
     to the parser and passing back results from it.

     Unless the `ARGP_NO_EXIT' or `ARGP_NO_HELP' flags are included in
     FLAGS, calling `argp_parse' may result in the program exiting--for
     instance when an unknown option is encountered.  *Note Program
     Termination::.

     If ARG_INDEX is non-null, the index of the first unparsed option
     in ARGV is returned in it.

     The return value is zero for successful parsing, or an error code
     (*note Error Codes::) if an error was detected.  Different argp
     parsers may return arbitrary error codes, but standard ones are
     `ENOMEM' if a memory allocation error occurred, or `EINVAL' if an
     unknown option or option argument was encountered.

* Menu:

* Globals: Argp Global Variables.  Global argp parameters.
* Parsers: Argp Parsers.        Defining parsers for use with `argp_parse'.
* Flags: Argp Flags.            Flags that modify the behavior of `argp_parse'.
* Help: Argp Help.              Printing help messages when not parsing.
* Examples: Argp Examples.      Simple examples of programs using argp.
* Customization: Argp User Customization.
                                Users may control the `--help' output format.


File: libc.info,  Node: Argp Global Variables,  Next: Argp Parsers,  Up: Argp

Argp Global Variables
---------------------

   These variables make it very easy for every user program to implement
the `--version' option and provide a bug-reporting address in the
`--help' output (which is implemented by argp regardless).

 - Variable: const char * argp_program_version
     If defined or set by the user program to a non-zero value, then a
     `--version' option is added when parsing with `argp_parse' (unless
     the `ARGP_NO_HELP' flag is used), which will print this string
     followed by a newline and exit (unless the `ARGP_NO_EXIT' flag is
     used).

 - Variable: const char * argp_program_bug_address
     If defined or set by the user program to a non-zero value,
     `argp_program_bug_address' should point to a string that is the
     bug-reporting address for the program.  It will be printed at the
     end of the standard output for the `--help' option, embedded in a
     sentence that says something like `Report bugs to ADDRESS.'.

 - Variable: argp_program_version_hook
     If defined or set by the user program to a non-zero value, then a
     `--version' option is added when parsing with `argp_parse' (unless
     the `ARGP_NO_HELP' flag is used), which calls this function to
     print the version, and then exits with a status of 0 (unless the
     `ARGP_NO_EXIT' flag is used).  It should point to a function with
     the following type signature:

          void PRINT-VERSION (FILE *STREAM, struct argp_state *STATE)

     *Note Argp Parsing State::, for an explanation of STATE.

     This variable takes precedent over `argp_program_version', and is
     useful if a program has version information that cannot be easily
     specified as a simple string.

 - Variable: error_t argp_err_exit_status
     The exit status that argp will use when exiting due to a parsing
     error.  If not defined or set by the user program, this defaults to
     `EX_USAGE' from `<sysexits.h>'.


File: libc.info,  Node: Argp Parsers,  Next: Argp Flags,  Prev: Argp Global Variables,  Up: Argp

Specifying Argp Parsers
-----------------------

   The first argument to the `argp_parse' function is a pointer to a
`struct argp', which known as an "argp parser":

 - Data Type: struct argp
     This structure specifies how to parse a given set of options and
     arguments, perhaps in conjunction with other argp parsers.  It has
     the following fields:

    `const struct argp_option *options'
          A pointer to a vector of `argp_option' structures specifying
          which options this argp parser understands; it may be zero if
          there are no options at all.  *Note Argp Option Vectors::.

    `argp_parser_t parser'
          A pointer to a function that defines actions for this parser;
          it is called for each option parsed, and at other
          well-defined points in the parsing process.  A value of zero
          is the same as a pointer to a function that always returns
          `ARGP_ERR_UNKNOWN'.  *Note Argp Parser Functions::.

    `const char *args_doc'
          If non-zero, a string describing what non-option arguments
          are wanted by this parser; it is only used to print the
          `Usage:' message.  If it contains newlines, the strings
          separated by them are considered alternative usage patterns,
          and printed on separate lines (lines after the first are
          prefixed by ` or: ' instead of `Usage:').

    `const char *doc'
          If non-zero, a string containing extra text to be printed
          before and after the options in a long help message, with the
          two sections separated by a vertical tab (`'\v'', `'\013'')
          character.  By convention, the documentation before the
          options is just a short string saying what the program does,
          and that afterwards is longer, describing the behavior in
          more detail.

    `const struct argp_child *children'
          A pointer to a vector of `argp_children' structures specifying
          additional argp parsers that should be combined with this one.
          *Note Argp Children::.

    `char *(*help_filter)(int KEY, const char *TEXT, void *INPUT)'
          If non-zero, a pointer to a function to filter the output of
          help messages.  *Note Argp Help Filtering::.

    `const char *argp_domain'
          If non-zero, the strings used in the argp library are
          translated using the domain described by this string.
          Otherwise the currently installed default domain is used.


   The `options', `parser', `args_doc', and `doc' fields are usually
all that are needed.  If an argp parser is defined as an initialized C
variable, only the used fields need be specified in the
initializer--the rest will default to zero due to the way C structure
initialization works (this fact is exploited for most argp structures,
grouping the most-used fields near the beginning, so that unused fields
can simply be left unspecified).

* Menu:

* Options: Argp Option Vectors.   Specifying options in an argp parser.
* Argp Parser Functions::         Defining actions for an argp parser.
* Children: Argp Children.        Combining multiple argp parsers.
* Help Filtering: Argp Help Filtering.  Customizing help output for an argp parser.


File: libc.info,  Node: Argp Option Vectors,  Next: Argp Parser Functions,  Prev: Argp Parsers,  Up: Argp Parsers

Specifying Options in an Argp Parser
------------------------------------

   The `options' field in a `struct argp' points to a vector of `struct
argp_option' structures, each of which specifies an option that argp
parser supports (actually, sometimes multiple entries may used for a
single option if it has many names).  It should be terminated by an
entry with zero in all fields (note that when using an initialized C
array for options, writing `{ 0 }' is enough to achieve this).

 - Data Type: struct argp_option
     This structure specifies a single option that an argp parser
     understands, and how to parse and document it.  It has the
     following fields:

    `const char *name'
          The long name for this option, corresponding to the long
          option `--NAME'; this field can be zero if this option only
          has a short name.  To specify multiple names for an option,
          additional entries may follow this one, with the
          `OPTION_ALIAS' flag set (*note Argp Option Flags::).

    `int key'
          The integer key that is provided to the argp parser's parsing
          function when this option is being parsed.  Also, if KEY has
          a value that is a printable ASCII character (i.e., `isascii
          (KEY)' is true), it _also_ specifies a short option `-CHAR',
          where CHAR is the ASCII character with the code KEY.

    `const char *arg'
          If non-zero, this is the name of an argument associated with
          this option, which must be provided (e.g., with the
          `--NAME=VALUE' or `-CHAR VALUE' syntaxes) unless the
          `OPTION_ARG_OPTIONAL' flag (*note Argp Option Flags::) is
          set, in which case it _may_ be provided.

    `int flags'
          Flags associated with this option (some of which are referred
          to above).  *Note Argp Option Flags::.

    `const char *doc'
          A documentation string for this option, for printing in help
          messages.

          If both the `name' and `key' fields are zero, this string
          will be printed out-dented from the normal option column,
          making it useful as a group header (it will be the first
          thing printed in its group); in this usage, it's conventional
          to end the string with a `:' character.

    `int group'
          The group this option is in.

          In a long help message, options are sorted alphabetically
          within each group, and the groups presented in the order 0,
          1, 2, ..., N, -M, ..., -2, -1.  Every entry in an options
          array with this field 0 will inherit the group number of the
          previous entry, or zero if it's the first one, unless its a
          group header (`name' and `key' fields both zero), in which
          case, the previous entry + 1 is the default.  Automagic
          options such as `--help' are put into group -1.

          Note that because of C structure initialization rules, this
          field often need not be specified, because 0 is the right
          value.

* Menu:

* Flags: Argp Option Flags.     Flags for options.


File: libc.info,  Node: Argp Option Flags,  Up: Argp Option Vectors

Flags for Argp Options
......................

   The following flags may be or'd together in the `flags' field of a
`struct argp_option', and control various aspects of how that option is
parsed or displayed in help messages:

`OPTION_ARG_OPTIONAL'
     The argument associated with this option is optional.

`OPTION_HIDDEN'
     This option isn't displayed in any help messages.

`OPTION_ALIAS'
     This option is an alias for the closest previous non-alias option.
     This means that it will be displayed in the same help entry, and
     will inherit fields other than `name' and `key' from the aliased
     option.

`OPTION_DOC'
     This option isn't actually an option (and so should be ignored by
     the actual option parser), but rather an arbitrary piece of
     documentation that should be displayed in much the same manner as
     the options (known as a "documentation option").

     If this flag is set, then the option `name' field is displayed
     unmodified (e.g., no `--' prefix is added) at the left-margin
     (where a _short_ option would normally be displayed), and the
     documentation string in the normal place.  For purposes of
     sorting, any leading whitespace and punctuation is ignored, except
     that if the first non-whitespace character is not `-', this entry
     is displayed after all options (and `OPTION_DOC' entries with a
     leading `-') in the same group.

`OPTION_NO_USAGE'
     This option shouldn't be included in `long' usage messages (but is
     still included in help messages).  This is mainly intended for
     options that are completely documented in an argp's `args_doc'
     field (*note Argp Parsers::), in which case including the option
     in the generic usage list would be redundant.

     For instance, if `args_doc' is `"FOO BAR\n-x BLAH"', and the `-x'
     option's purpose is to distinguish these two cases, `-x' should
     probably be marked `OPTION_NO_USAGE'.


File: libc.info,  Node: Argp Parser Functions,  Next: Argp Children,  Prev: Argp Option Vectors,  Up: Argp Parsers

Argp Parser Functions
---------------------

   The function pointed to by the `parser' field in a `struct argp'
(*note Argp Parsers::) defines what actions take place in response to
each option or argument that is parsed, and is also used as a hook, to
allow a parser to do something at certain other points during parsing.

   Argp parser functions have the following type signature:

     error_t PARSER (int KEY, char *ARG, struct argp_state *STATE)

where the arguments are as follows:

KEY
     For each option that is parsed, PARSER is called with a value of
     KEY from that option's `key' field in the option vector (*note
     Argp Option Vectors::).  PARSER is also called at other times with
     special reserved keys, such as `ARGP_KEY_ARG' for non-option
     arguments.  *Note Argp Special Keys::.

ARG
     If KEY is an option, ARG is the value given for it, or zero if no
     value was specified.  Only options that have a non-zero `arg'
     field can ever have a value, and those must _always_ have a value,
     unless the `OPTION_ARG_OPTIONAL' flag was specified (if the input
     being parsed specifies a value for an option that doesn't allow
     one, an error results before PARSER ever gets called).

     If KEY is `ARGP_KEY_ARG', ARG is a non-option argument; other
     special keys always have a zero ARG.

STATE
     STATE points to a `struct argp_state', containing useful
     information about the current parsing state for use by PARSER.
     *Note Argp Parsing State::.

   When PARSER is called, it should perform whatever action is
appropriate for KEY, and return either `0' for success,
`ARGP_ERR_UNKNOWN', if the value of KEY is not handled by this parser
function, or a unix error code if a real error occurred (*note Error
Codes::).

 - Macro: int ARGP_ERR_UNKNOWN
     Argp parser functions should return `ARGP_ERR_UNKNOWN' for any KEY
     value they do not recognize, or for non-option arguments (`KEY ==
     ARGP_KEY_ARG') that they do not wish to handle.

   A typical parser function uses a switch statement on KEY:

     error_t
     parse_opt (int key, char *arg, struct argp_state *state)
     {
       switch (key)
         {
         case OPTION_KEY:
           ACTION
           break;
         ...
         default:
           return ARGP_ERR_UNKNOWN;
         }
       return 0;
     }

* Menu:

* Keys: Argp Special Keys.           Special values for the KEY argument.
* State: Argp Parsing State.         What the STATE argument refers to.
* Functions: Argp Helper Functions.  Functions to help during argp parsing.


File: libc.info,  Node: Argp Special Keys,  Next: Argp Parsing State,  Up: Argp Parser Functions

Special Keys for Argp Parser Functions
......................................

   In addition to key values corresponding to user options, the KEY
argument to argp parser functions may have a number of other special
values (ARG and STATE refer to parser function arguments; *note Argp
Parser Functions::):

`ARGP_KEY_ARG'
     This is not an option at all, but rather a command line argument,
     whose value is pointed to by ARG.

     When there are multiple parser functions (due to argp parsers being
     combined), it's impossible to know which one wants to handle an
     argument, so each is called in turn, until one returns 0 or an
     error other than `ARGP_ERR_UNKNOWN'; if an argument is handled by
     no one, `argp_parse' immediately returns success, without parsing
     any more arguments.

     Once a parser function returns success for this key, that fact is
     recorded, and the `ARGP_KEY_NO_ARGS' case won't be used.
     _However_, if while processing the argument, a parser function
     decrements the `next' field of its STATE argument, the option
     won't be considered processed; this is to allow you to actually
     modify the argument (perhaps into an option), and have it
     processed again.

`ARGP_KEY_ARGS'
     If a parser function returns `ARGP_ERR_UNKNOWN' for
     `ARGP_KEY_ARG', it is immediately called again with the key
     `ARGP_KEY_ARGS', which has a similar meaning, but is slightly more
     convenient for consuming all remaining arguments.  ARG is 0, and
     the tail of the argument vector may be found at `STATE->argv +
     STATE->next'.  If success is returned for this key, and
     `STATE->next' is unchanged, then all remaining arguments are
     considered to have been consumed, otherwise, the amount by which
     `STATE->next' has been adjust indicates how many were used.  For
     instance, here's an example that uses both, for different args:

          ...
          case ARGP_KEY_ARG:
            if (STATE->arg_num == 0)
              /* First argument */
              first_arg = ARG;
            else
              /* Let the next case parse it.  */
              return ARGP_KEY_UNKNOWN;
            break;
          case ARGP_KEY_ARGS:
            remaining_args = STATE->argv + STATE->next;
            num_remaining_args = STATE->argc - STATE->next;
            break;

`ARGP_KEY_END'
     There are no more command line arguments at all.  The parser
     functions are called in different order (means children first) for
     this value which allows each parser to clean up its state for the
     parent.

`ARGP_KEY_NO_ARGS'
     Because it's common to want to do some special processing if there
     aren't any non-option args, parser functions are called with this
     key if they didn't successfully process any non-option arguments.
     Called just before `ARGP_KEY_END' (where more general validity
     checks on previously parsed arguments can take place).

`ARGP_KEY_INIT'
     Passed in before any parsing is done.  Afterwards, the values of
     each element of the `child_input' field of STATE, if any, are
     copied to each child's state to be the initial value of the `input'
     when _their_ parsers are called.

`ARGP_KEY_SUCCESS'
     Passed in when parsing has successfully been completed (even if
     there are still arguments remaining).

`ARGP_KEY_ERROR'
     Passed in if an error has occurred, and parsing terminated (in
     which case a call with a key of `ARGP_KEY_SUCCESS' is never made).

`ARGP_KEY_FINI'
     The final key ever seen by any parser (even after
     `ARGP_KEY_SUCCESS' and `ARGP_KEY_ERROR').  Any resources allocated
     by `ARGP_KEY_INIT' may be freed here (although sometimes certain
     resources allocated there are to be returned to the caller after a
     successful parse; in that case, those particular resources can be
     freed in the `ARGP_KEY_ERROR' case).

   In all cases, `ARGP_KEY_INIT' is the first key seen by parser
functions, and `ARGP_KEY_FINI' the last (unless an error was returned
by the parser for `ARGP_KEY_INIT').  Other keys can occur in one the
following orders (OPT refers to an arbitrary option key):

OPT... `ARGP_KEY_NO_ARGS' `ARGP_KEY_END' `ARGP_KEY_SUCCESS'
     The arguments being parsed contained no non-option arguments at
     all.

( OPT | `ARGP_KEY_ARG' )... `ARGP_KEY_END' `ARGP_KEY_SUCCESS'
     All non-option arguments were successfully handled by a parser
     function (there may be multiple parser functions if multiple argp
     parsers were combined).

( OPT | `ARGP_KEY_ARG' )... `ARGP_KEY_SUCCESS'
     Some non-option argument was unrecognized.

     This occurs when every parser function returns `ARGP_KEY_UNKNOWN'
     for an argument, in which case parsing stops at that argument.  If
     ARG_INDEX is a null pointer otherwise an error occurs.

   In all cases, if a non-null value for ARG_INDEX was passed to
`argp_parse', the index of the first unparsed command-line argument is
passed back in it.

   If an error occurs (either detected by argp, or because a parser
function returned an error value), then each parser is called with
`ARGP_KEY_ERROR', and no further calls are made except the final call
with `ARGP_KEY_FINI'.

