   This file documents the GNU C library.

   This is Edition 0.08 DRAFT, last updated 11 Jan 1999, of `The GNU C
Library Reference Manual', for Version 2.1 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.

Precision Time
==============

   The `net_gettime' and `ntp_adjtime' functions provide an interface
to monitor and manipulate high precision time.  These functions are
declared in `sys/timex.h'.

 - Data Type: struct ntptimeval
     This structure is used to monitor kernel time.  It contains the
     following members:
    `struct timeval time'
          This is the current time.  The `struct timeval' data type is
          described in High-Resolution Calendar.

    `long int maxerror'
          This is the maximum error, measured in microseconds.  Unless
          updated via `ntp_adjtime' periodically, this value will reach
          some platform-specific maximum value.

    `long int esterror'
          This is the estimated error, measured in microseconds.  This
          value can be set by `ntp_adjtime' to indicate the estimated
          offset of the local clock against the true time.

 - Function: int ntp_gettime (struct ntptimeval *TPTR)
     The `ntp_gettime' function sets the structure pointed to by TPTR
     to current values.  The elements of the structure afterwards
     contain the values the timer implementation in the kernel assumes.
     They might or might not be correct.  If they are not a
     `ntp_adjtime' call is necessary.

     The return value is `0' on success and other values on failure.
     The following `errno' error conditions are defined for this
     function:

    `TIME_ERROR'
          The precision clock model is not properly set up at the
          moment, thus the clock must be considered unsynchronized, and
          the values should be treated with care.

 - Data Type: struct timex
     This structure is used to control and monitor kernel time in a
     greater level of detail.  It contains the following members:
    `unsigned int modes'
          This variable controls whether and which values are set.
          Several symbolic constants have to be combined with _binary
          or_ to specify the effective mode.  These constants start
          with `MOD_'.

    `long int offset'
          This value indicates the current offset of the local clock
          from the true time.  The value is given in microseconds.  If
          bit `MOD_OFFSET' is set in `modes', the offset (and possibly
          other dependent values) can be set.  The offset's absolute
          value must not exceed `MAXPHASE'.

    `long int frequency'
          This value indicates the difference in frequency between the
          true time and the local clock.  The value is expressed as
          scaled PPM (parts per million, 0.0001%).  The scaling is `1
          << SHIFT_USEC'.  The value can be set with bit
          `MOD_FREQUENCY', but the absolute value must not exceed
          `MAXFREQ'.

    `long int maxerror'
          This is the maximum error, measured in microseconds.  A new
          value can be set using bit `MOD_MAXERROR'.  Unless updated via
          `ntp_adjtime' periodically, this value will increase steadily
          and reach some platform-specific maximum value.

    `long int esterror'
          This is the estimated error, measured in microseconds.  This
          value can be set using bit `MOD_ESTERROR'.

    `int status'
          This variable reflects the various states of the clock
          machinery.  There are symbolic constants for the significant
          bits, starting with `STA_'.  Some of these flags can be
          updated using the `MOD_STATUS' bit.

    `long int constant'
          This value represents the bandwidth or stiffness of the PLL
          (phase locked loop) implemented in the kernel.  The value can
          be changed using bit `MOD_TIMECONST'.

    `long int precision'
          This value represents the accuracy or the maximum error when
          reading the system clock.  The value is expressed in
          microseconds and can't be changed.

    `long int tolerance'
          This value represents the maximum frequency error of the
          system clock in scaled PPM.  This value is used to increase
          the `maxerror' every second.

    `long int ppsfreq'
          This is the first of a few optional variables that are
          present only if the system clock can use a PPS (pulse per
          second) signal to discipline the local clock.  The value is
          expressed in scaled PPM and it denotes the difference in
          frequency between the local clock and the PPS signal.

    `long int jitter'
          This value expresses a median filtered average of the PPS
          signal's dispersion in microseconds.

    `int int shift'
          This value is a binary exponent for the duration of the PPS
          calibration interval, ranging from `PPS_SHIFT' to
          `PPS_SHIFTMAX'.

    `long int stabil'
          This value represents the median filtered dispersion of the
          PPS frequency in scaled PPM.

    `long int jitcnt'
          This counter represents the number of pulses where the jitter
          exceeded the allowed maximum `MAXTIME'.

    `long int calcnt'
          This counter reflects the number of successful calibration
          intervals.

    `long int errcnt'
          This counter represents the number of calibration errors
          (caused by large offsets or jitter).

    `long int stbcnt'
          This counter denotes the number of of calibrations where the
          stability exceeded the threshold.

 - Function: int ntp_adjtime (struct timex *TPTR)
     The `ntp_adjtime' function sets the structure specified by TPTR to
     current values.  In addition, values passed in TPTR can be used to
     replace existing settings.  To do this the `modes' element of the
     `struct timex' must be set appropriately.  Setting it to zero
     selects reading the current state.

     The return value is `0' on success and other values on failure.
     The following `errno' error conditions are defined for this
     function:

    `TIME_ERROR'
          The precision clock model is not properly set up at the
          moment, thus the clock must be considered unsynchronized, and
          the values should be treated with care.  Another reason could
          be that the specified new values are not allowed.

     For more details see RFC1305 (Network Time Protocol, Version 3) and
     related documents.

Setting an Alarm
================

   The `alarm' and `setitimer' functions provide a mechanism for a
process to interrupt itself at some future time.  They do this by
setting a timer; when the timer expires, the process receives a signal.

   Each process has three independent interval timers available:

   * A real-time timer that counts clock time.  This timer sends a
     `SIGALRM' signal to the process when it expires.

   * A virtual timer that counts CPU time used by the process.  This
     timer sends a `SIGVTALRM' signal to the process when it expires.

   * A profiling timer that counts both CPU time used by the process,
     and CPU time spent in system calls on behalf of the process.  This
     timer sends a `SIGPROF' signal to the process when it expires.

     This timer is useful for profiling in interpreters.  The interval
     timer mechanism does not have the fine granularity necessary for
     profiling native code.

   You can only have one timer of each kind set at any given time.  If
you set a timer that has not yet expired, that timer is simply reset to
the new value.

   You should establish a handler for the appropriate alarm signal using
`signal' or `sigaction' before issuing a call to `setitimer' or
`alarm'.  Otherwise, an unusual chain of events could cause the timer
to expire before your program establishes the handler, and in that case
it would be terminated, since that is the default action for the alarm
signals.  See Signal Handling.

   The `setitimer' function is the primary means for setting an alarm.
This facility is declared in the header file `sys/time.h'.  The `alarm'
function, declared in `unistd.h', provides a somewhat simpler interface
for setting the real-time timer.

 - Data Type: struct itimerval
     This structure is used to specify when a timer should expire.  It
     contains the following members:
    `struct timeval it_interval'
          This is the interval between successive timer interrupts.  If
          zero, the alarm will only be sent once.

    `struct timeval it_value'
          This is the interval to the first timer interrupt.  If zero,
          the alarm is disabled.

     The `struct timeval' data type is described in
     High-Resolution Calendar.

 - Function: int setitimer (int WHICH, struct itimerval *NEW, struct
          itimerval *OLD)
     The `setitimer' function sets the timer specified by WHICH
     according to NEW.  The WHICH argument can have a value of
     `ITIMER_REAL', `ITIMER_VIRTUAL', or `ITIMER_PROF'.

     If OLD is not a null pointer, `setitimer' returns information
     about any previous unexpired timer of the same kind in the
     structure it points to.

     The return value is `0' on success and `-1' on failure.  The
     following `errno' error conditions are defined for this function:

    `EINVAL'
          The timer interval was too large.

 - Function: int getitimer (int WHICH, struct itimerval *OLD)
     The `getitimer' function stores information about the timer
     specified by WHICH in the structure pointed at by OLD.

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

`ITIMER_REAL'
     This constant can be used as the WHICH argument to the `setitimer'
     and `getitimer' functions to specify the real-time timer.

`ITIMER_VIRTUAL'
     This constant can be used as the WHICH argument to the `setitimer'
     and `getitimer' functions to specify the virtual timer.

`ITIMER_PROF'
     This constant can be used as the WHICH argument to the `setitimer'
     and `getitimer' functions to specify the profiling timer.

 - Function: unsigned int alarm (unsigned int SECONDS)
     The `alarm' function sets the real-time timer to expire in SECONDS
     seconds.  If you want to cancel any existing alarm, you can do
     this by calling `alarm' with a SECONDS argument of zero.

     The return value indicates how many seconds remain before the
     previous alarm would have been sent.  If there is no previous
     alarm, `alarm' returns zero.

   The `alarm' function could be defined in terms of `setitimer' like
this:

     unsigned int
     alarm (unsigned int seconds)
     {
       struct itimerval old, new;
       new.it_interval.tv_usec = 0;
       new.it_interval.tv_sec = 0;
       new.it_value.tv_usec = 0;
       new.it_value.tv_sec = (long int) seconds;
       if (setitimer (ITIMER_REAL, &new, &old) < 0)
         return 0;
       else
         return old.it_value.tv_sec;
     }

   There is an example showing the use of the `alarm' function in
Handler Returns.

   If you simply want your process to wait for a given number of
seconds, you should use the `sleep' function.  See Sleeping.

   You shouldn't count on the signal arriving precisely when the timer
expires.  In a multiprocessing environment there is typically some
amount of delay involved.

   *Portability Note:* The `setitimer' and `getitimer' functions are
derived from BSD Unix, while the `alarm' function is specified by the
POSIX.1 standard.  `setitimer' is more powerful than `alarm', but
`alarm' is more widely used.

Sleeping
========

   The function `sleep' gives a simple way to make the program wait for
short periods of time.  If your program doesn't use signals (except to
terminate), then you can expect `sleep' to wait reliably for the
specified amount of time.  Otherwise, `sleep' can return sooner if a
signal arrives; if you want to wait for a given period regardless of
signals, use `select' (see Waiting for I/O) and don't specify any
descriptors to wait for.

 - Function: unsigned int sleep (unsigned int SECONDS)
     The `sleep' function waits for SECONDS or until a signal is
     delivered, whichever happens first.

     If `sleep' function returns because the requested time has
     elapsed, it returns a value of zero.  If it returns because of
     delivery of a signal, its return value is the remaining time in
     the sleep period.

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

   Resist the temptation to implement a sleep for a fixed amount of
time by using the return value of `sleep', when nonzero, to call
`sleep' again.  This will work with a certain amount of accuracy as
long as signals arrive infrequently.  But each signal can cause the
eventual wakeup time to be off by an additional second or so.  Suppose a
few signals happen to arrive in rapid succession by bad luck--there is
no limit on how much this could shorten or lengthen the wait.

   Instead, compute the time at which the program should stop waiting,
and keep trying to wait until that time.  This won't be off by more
than a second.  With just a little more work, you can use `select' and
make the waiting period quite accurate.  (Of course, heavy system load
can cause unavoidable additional delays--unless the machine is
dedicated to one application, there is no way you can avoid this.)

   On some systems, `sleep' can do strange things if your program uses
`SIGALRM' explicitly.  Even if `SIGALRM' signals are being ignored or
blocked when `sleep' is called, `sleep' might return prematurely on
delivery of a `SIGALRM' signal.  If you have established a handler for
`SIGALRM' signals and a `SIGALRM' signal is delivered while the process
is sleeping, the action taken might be just to cause `sleep' to return
instead of invoking your handler.  And, if `sleep' is interrupted by
delivery of a signal whose handler requests an alarm or alters the
handling of `SIGALRM', this handler and `sleep' will interfere.

   On the GNU system, it is safe to use `sleep' and `SIGALRM' in the
same program, because `sleep' does not work by means of `SIGALRM'.

 - Function: int nanosleep (const struct timespec *REQUESTED_TIME,
          struct timespec *REMAINING)
     If the resolution of seconds is not enough the `nanosleep' function
     can be used.  As the name suggests the sleeping period can be
     specified in nanoseconds.  The actual period of waiting time might
     be longer since the requested time in the REQUESTED_TIME parameter
     is rounded up to the next integer multiple of the actual
     resolution of the system.

     If the function returns because the time has elapsed the return
     value is zero.  If the function return -1 the global variable ERRNO
     is set to the following values:

    `EINTR'
          The call was interrupted because a signal was delivered to
          the thread.  If the REMAINING parameter is not the null
          pointer the structure pointed to by REMAINING is updated to
          contain the remaining time.

    `EINVAL'
          The nanosecond value in the REQUESTED_TIME parameter contains
          an illegal value.  Either the value is negative or greater
          than or equal to 1000 million.

     This function is a cancelation point in multi-threaded programs.
     This is a problem if the thread allocates some resources (like
     memory, file descriptors, semaphores or whatever) at the time
     `nanosleep' is called.  If the thread gets canceled these
     resources stay allocated until the program ends.  To avoid this
     calls to `nanosleep' should be protected using cancelation
     handlers.

     The `nanosleep' function is declared in `time.h'.

Resource Usage
==============

   The function `getrusage' and the data type `struct rusage' are used
for examining the usage figures of a process.  They are declared in
`sys/resource.h'.

 - Function: int getrusage (int PROCESSES, struct rusage *RUSAGE)
     This function reports the usage totals for processes specified by
     PROCESSES, storing the information in `*RUSAGE'.

     In most systems, PROCESSES has only two valid values:

    `RUSAGE_SELF'
          Just the current process.

    `RUSAGE_CHILDREN'
          All child processes (direct and indirect) that have
          terminated already.

     In the GNU system, you can also inquire about a particular child
     process by specifying its process ID.

     The return value of `getrusage' is zero for success, and `-1' for
     failure.

    `EINVAL'
          The argument PROCESSES is not valid.

   One way of getting usage figures for a particular child process is
with the function `wait4', which returns totals for a child when it
terminates.  See BSD Wait Functions.

 - Data Type: struct rusage
     This data type records a collection usage amounts for various
     sorts of resources.  It has the following members, and possibly
     others:

    `struct timeval ru_utime'
          Time spent executing user instructions.

    `struct timeval ru_stime'
          Time spent in operating system code on behalf of PROCESSES.

    `long int ru_maxrss'
          The maximum resident set size used, in kilobytes.  That is,
          the maximum number of kilobytes that PROCESSES used in real
          memory simultaneously.

    `long int ru_ixrss'
          An integral value expressed in kilobytes times ticks of
          execution, which indicates the amount of memory used by text
          that was shared with other processes.

    `long int ru_idrss'
          An integral value expressed the same way, which is the amount
          of unshared memory used in data.

    `long int ru_isrss'
          An integral value expressed the same way, which is the amount
          of unshared memory used in stack space.

    `long int ru_minflt'
          The number of page faults which were serviced without
          requiring any I/O.

    `long int ru_majflt'
          The number of page faults which were serviced by doing I/O.

    `long int ru_nswap'
          The number of times PROCESSES was swapped entirely out of
          main memory.

    `long int ru_inblock'
          The number of times the file system had to read from the disk
          on behalf of PROCESSES.

    `long int ru_oublock'
          The number of times the file system had to write to the disk
          on behalf of PROCESSES.

    `long int ru_msgsnd'
          Number of IPC messages sent.

    `long ru_msgrcv'
          Number of IPC messages received.

    `long int ru_nsignals'
          Number of signals received.

    `long int ru_nvcsw'
          The number of times PROCESSES voluntarily invoked a context
          switch (usually to wait for some service).

    `long int ru_nivcsw'
          The number of times an involuntary context switch took place
          (because the time slice expired, or another process of higher
          priority became runnable).

   An additional historical function for examining usage figures,
`vtimes', is supported but not documented here.  It is declared in
`sys/vtimes.h'.

Limiting Resource Usage
=======================

   You can specify limits for the resource usage of a process.  When the
process tries to exceed a limit, it may get a signal, or the system call
by which it tried to do so may fail, depending on the limit.  Each
process initially inherits its limit values from its parent, but it can
subsequently change them.

   The symbols in this section are defined in `sys/resource.h'.

 - Function: int getrlimit (int RESOURCE, struct rlimit *RLP)
     Read the current value and the maximum value of resource RESOURCE
     and store them in `*RLP'.

     The return value is `0' on success and `-1' on failure.  The only
     possible `errno' error condition is `EFAULT'.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' on a
     32 bits system this function is in fact `getrlimit64'.  I.e., the
     LFS interface transparently replaces the old interface.

 - Function: int getrlimit64 (int RESOURCE, struct rlimit64 *RLP)
     This function is similar to the `getrlimit' but its second
     parameter is a pointer to a variable of type `struct rlimit64'
     which allows this function to read values which wouldn't fit in the
     member of a `struct rlimit'.

     If the sources are compiled with `_FILE_OFFSET_BITS == 64' on a 32
     bits machine this function is available under the name `getrlimit'
     and so transparently replaces the old interface.

 - Function: int setrlimit (int RESOURCE, const struct rlimit *RLP)
     Store the current value and the maximum value of resource RESOURCE
     in `*RLP'.

     The return value is `0' on success and `-1' on failure.  The
     following `errno' error condition is possible:

    `EPERM'
          You tried to change the maximum permissible limit value, but
          you don't have privileges to do so.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' on a
     32 bits system this function is in fact `setrlimit64'.  I.e., the
     LFS interface transparently replaces the old interface.

 - Function: int setrlimit64 (int RESOURCE, const struct rlimit64 *RLP)
     This function is similar to the `setrlimit' but its second
     parameter is a pointer to a variable of type `struct rlimit64'
     which allows this function to set values which wouldn't fit in the
     member of a `struct rlimit'.

     If the sources are compiled with `_FILE_OFFSET_BITS == 64' on a 32
     bits machine this function is available under the name `setrlimit'
     and so transparently replaces the old interface.

 - Data Type: struct rlimit
     This structure is used with `getrlimit' to receive limit values,
     and with `setrlimit' to specify limit values.  It has two fields:

    `rlim_t rlim_cur'
          The current value of the limit in question.  This is also
          called the "soft limit".

    `rlim_t rlim_max'
          The maximum permissible value of the limit in question.  You
          cannot set the current value of the limit to a larger number
          than this maximum.  Only the super user can change the
          maximum permissible value.  This is also called the "hard
          limit".

     In `getrlimit', the structure is an output; it receives the current
     values.  In `setrlimit', it specifies the new values.

   For the LFS functions a similar type is defined in `sys/resource.h'.

 - Data Type: struct rlimit64
     This structure is used with `getrlimit64' to receive limit values,
     and with `setrlimit64' to specify limit values.  It has two fields:

    `rlim64_t rlim_cur'
          The current value of the limit in question.  This is also
          called the "soft limit".

    `rlim64_t rlim_max'
          The maximum permissible value of the limit in question.  You
          cannot set the current value of the limit to a larger number
          than this maximum.  Only the super user can change the
          maximum permissible value.  This is also called the "hard
          limit".

     In `getrlimit64', the structure is an output; it receives the
     current values.  In `setrlimit64', it specifies the new values.

   Here is a list of resources that you can specify a limit for.  Those
that are sizes are measured in bytes.

`RLIMIT_CPU'
     The maximum amount of cpu time the process can use.  If it runs for
     longer than this, it gets a signal: `SIGXCPU'.  The value is
     measured in seconds.  See Operation Error Signals.

`RLIMIT_FSIZE'
     The maximum size of file the process can create.  Trying to write a
     larger file causes a signal: `SIGXFSZ'.  See Operation Error Signals.

`RLIMIT_DATA'
     The maximum size of data memory for the process.  If the process
     tries to allocate data memory beyond this amount, the allocation
     function fails.

`RLIMIT_STACK'
     The maximum stack size for the process.  If the process tries to
     extend its stack past this size, it gets a `SIGSEGV' signal.
     See Program Error Signals.

`RLIMIT_CORE'
     The maximum size core file that this process can create.  If the
     process terminates and would dump a core file larger than this
     maximum size, then no core file is created.  So setting this limit
     to zero prevents core files from ever being created.

`RLIMIT_RSS'
     The maximum amount of physical memory that this process should get.
     This parameter is a guide for the system's scheduler and memory
     allocator; the system may give the process more memory when there
     is a surplus.

`RLIMIT_MEMLOCK'
     The maximum amount of memory that can be locked into physical
     memory (so it will never be paged out).

`RLIMIT_NPROC'
     The maximum number of processes that can be created with the same
     user ID.  If you have reached the limit for your user ID, `fork'
     will fail with `EAGAIN'.  See Creating a Process.

`RLIMIT_NOFILE'
`RLIMIT_OFILE'
     The maximum number of files that the process can open.  If it
     tries to open more files than this, it gets error code `EMFILE'.
     See Error Codes.  Not all systems support this limit; GNU
     does, and 4.4 BSD does.

`RLIM_NLIMITS'
     The number of different resource limits.  Any valid RESOURCE
     operand must be less than `RLIM_NLIMITS'.

 - Constant: int RLIM_INFINITY
     This constant stands for a value of "infinity" when supplied as
     the limit value in `setrlimit'.

   Two historical functions for setting resource limits, `ulimit' and
`vlimit', are not documented here.  The latter is declared in
`sys/vlimit.h' and comes from BSD.

Process Priority
================

   When several processes try to run, their respective priorities
determine what share of the CPU each process gets.  This section
describes how you can read and set the priority of a process.  All
these functions and macros are declared in `sys/resource.h'.

   The range of valid priority values depends on the operating system,
but typically it runs from `-20' to `20'.  A lower priority value means
the process runs more often.  These constants describe the range of
priority values:

`PRIO_MIN'
     The smallest valid priority value.

`PRIO_MAX'
     The largest valid priority value.

 - Function: int getpriority (int CLASS, int ID)
     Read the priority of a class of processes; CLASS and ID specify
     which ones (see below).  If the processes specified do not all
     have the same priority, this returns the smallest value that any
     of them has.

     The return value is the priority value on success, and `-1' on
     failure.  The following `errno' error condition are possible for
     this function:

    `ESRCH'
          The combination of CLASS and ID does not match any existing
          process.

    `EINVAL'
          The value of CLASS is not valid.

     When the return value is `-1', it could indicate failure, or it
     could be the priority value.  The only way to make certain is to
     set `errno = 0' before calling `getpriority', then use `errno !=
     0' afterward as the criterion for failure.

 - Function: int setpriority (int CLASS, int ID, int PRIORITY)
     Set the priority of a class of processes to PRIORITY; CLASS and ID
     specify which ones (see below).

     The return value is `0' on success and `-1' on failure.  The
     following `errno' error condition are defined for this function:

    `ESRCH'
          The combination of CLASS and ID does not match any existing
          process.

    `EINVAL'
          The value of CLASS is not valid.

    `EPERM'
          You tried to set the priority of some other user's process,
          and you don't have privileges for that.

    `EACCES'
          You tried to lower the priority of a process, and you don't
          have privileges for that.

   The arguments CLASS and ID together specify a set of processes you
are interested in.  These are the possible values for CLASS:

`PRIO_PROCESS'
     Read or set the priority of one process.  The argument ID is a
     process ID.

`PRIO_PGRP'
     Read or set the priority of one process group.  The argument ID is
     a process group ID.

`PRIO_USER'
     Read or set the priority of one user's processes.  The argument ID
     is a user ID.

   If the argument ID is 0, it stands for the current process, current
process group, or the current user, according to CLASS.

 - Function: int nice (int INCREMENT)
     Increment the priority of the current process by INCREMENT.  The
     return value is the same as for `setpriority'.

     Here is an equivalent definition for `nice':

          int
          nice (int increment)
          {
            int old = getpriority (PRIO_PROCESS, 0);
            return setpriority (PRIO_PROCESS, 0, old + increment);
          }

Non-Local Exits
***************

   Sometimes when your program detects an unusual situation inside a
deeply nested set of function calls, you would like to be able to
immediately return to an outer level of control.  This section
describes how you can do such "non-local exits" using the `setjmp' and
`longjmp' functions.

Introduction to Non-Local Exits
===============================

   As an example of a situation where a non-local exit can be useful,
suppose you have an interactive program that has a "main loop" that
prompts for and executes commands.  Suppose the "read" command reads
input from a file, doing some lexical analysis and parsing of the input
while processing it.  If a low-level input error is detected, it would
be useful to be able to return immediately to the "main loop" instead
of having to make each of the lexical analysis, parsing, and processing
phases all have to explicitly deal with error situations initially
detected by nested calls.

   (On the other hand, if each of these phases has to do a substantial
amount of cleanup when it exits--such as closing files, deallocating
buffers or other data structures, and the like--then it can be more
appropriate to do a normal return and have each phase do its own
cleanup, because a non-local exit would bypass the intervening phases
and their associated cleanup code entirely.  Alternatively, you could
use a non-local exit but do the cleanup explicitly either before or
after returning to the "main loop".)

   In some ways, a non-local exit is similar to using the `return'
statement to return from a function.  But while `return' abandons only
a single function call, transferring control back to the point at which
it was called, a non-local exit can potentially abandon many levels of
nested function calls.

   You identify return points for non-local exits calling the function
`setjmp'.  This function saves information about the execution
environment in which the call to `setjmp' appears in an object of type
`jmp_buf'.  Execution of the program continues normally after the call
to `setjmp', but if a exit is later made to this return point by
calling `longjmp' with the corresponding `jmp_buf' object, control is
transferred back to the point where `setjmp' was called.  The return
value from `setjmp' is used to distinguish between an ordinary return
and a return made by a call to `longjmp', so calls to `setjmp' usually
appear in an `if' statement.

   Here is how the example program described above might be set up:

     #include <setjmp.h>
     #include <stdlib.h>
     #include <stdio.h>

     jmp_buf main_loop;

     void
     abort_to_main_loop (int status)
     {
       longjmp (main_loop, status);
     }

     int
     main (void)
     {
       while (1)
         if (setjmp (main_loop))
           puts ("Back at main loop....");
         else
           do_command ();
     }

     void
     do_command (void)
     {
       char buffer[128];
       if (fgets (buffer, 128, stdin) == NULL)
         abort_to_main_loop (-1);
       else
         exit (EXIT_SUCCESS);
     }

   The function `abort_to_main_loop' causes an immediate transfer of
control back to the main loop of the program, no matter where it is
called from.

   The flow of control inside the `main' function may appear a little
mysterious at first, but it is actually a common idiom with `setjmp'.
A normal call to `setjmp' returns zero, so the "else" clause of the
conditional is executed.  If `abort_to_main_loop' is called somewhere
within the execution of `do_command', then it actually appears as if
the _same_ call to `setjmp' in `main' were returning a second time with
a value of `-1'.

   So, the general pattern for using `setjmp' looks something like:

     if (setjmp (BUFFER))
       /* Code to clean up after premature return. */
       ...
     else
       /* Code to be executed normally after setting up the return point. */
       ...

Details of Non-Local Exits
==========================

   Here are the details on the functions and data structures used for
performing non-local exits.  These facilities are declared in
`setjmp.h'.

 - Data Type: jmp_buf
     Objects of type `jmp_buf' hold the state information to be
     restored by a non-local exit.  The contents of a `jmp_buf'
     identify a specific place to return to.

 - Macro: int setjmp (jmp_buf STATE)
     When called normally, `setjmp' stores information about the
     execution state of the program in STATE and returns zero.  If
     `longjmp' is later used to perform a non-local exit to this STATE,
     `setjmp' returns a nonzero value.

 - Function: void longjmp (jmp_buf STATE, int VALUE)
     This function restores current execution to the state saved in
     STATE, and continues execution from the call to `setjmp' that
     established that return point.  Returning from `setjmp' by means of
     `longjmp' returns the VALUE argument that was passed to `longjmp',
     rather than `0'.  (But if VALUE is given as `0', `setjmp' returns
     `1').

   There are a lot of obscure but important restrictions on the use of
`setjmp' and `longjmp'.  Most of these restrictions are present because
non-local exits require a fair amount of magic on the part of the C
compiler and can interact with other parts of the language in strange
ways.

   The `setjmp' function is actually a macro without an actual function
definition, so you shouldn't try to `#undef' it or take its address.
In addition, calls to `setjmp' are safe in only the following contexts:

   * As the test expression of a selection or iteration statement (such
     as `if', `switch', or `while').

   * As one operand of a equality or comparison operator that appears
     as the test expression of a selection or iteration statement.  The
     other operand must be an integer constant expression.

   * As the operand of a unary `!' operator, that appears as the test
     expression of a selection or iteration statement.

   * By itself as an expression statement.

   Return points are valid only during the dynamic extent of the
function that called `setjmp' to establish them.  If you `longjmp' to a
return point that was established in a function that has already
returned, unpredictable and disastrous things are likely to happen.

   You should use a nonzero VALUE argument to `longjmp'.  While
`longjmp' refuses to pass back a zero argument as the return value from
`setjmp', this is intended as a safety net against accidental misuse
and is not really good programming style.

   When you perform a non-local exit, accessible objects generally
retain whatever values they had at the time `longjmp' was called.  The
exception is that the values of automatic variables local to the
function containing the `setjmp' call that have been changed since the
call to `setjmp' are indeterminate, unless you have declared them
`volatile'.

Non-Local Exits and Signals
===========================

   In BSD Unix systems, `setjmp' and `longjmp' also save and restore
the set of blocked signals; see Blocking Signals.  However, the
POSIX.1 standard requires `setjmp' and `longjmp' not to change the set
of blocked signals, and provides an additional pair of functions
(`sigsetjmp' and `siglongjmp') to get the BSD behavior.

   The behavior of `setjmp' and `longjmp' in the GNU library is
controlled by feature test macros; see Feature Test Macros.  The
default in the GNU system is the POSIX.1 behavior rather than the BSD
behavior.

   The facilities in this section are declared in the header file
`setjmp.h'.

 - Data Type: sigjmp_buf
     This is similar to `jmp_buf', except that it can also store state
     information about the set of blocked signals.

 - Function: int sigsetjmp (sigjmp_buf STATE, int SAVESIGS)
     This is similar to `setjmp'.  If SAVESIGS is nonzero, the set of
     blocked signals is saved in STATE and will be restored if a
     `siglongjmp' is later performed with this STATE.

 - Function: void siglongjmp (sigjmp_buf STATE, int VALUE)
     This is similar to `longjmp' except for the type of its STATE
     argument.  If the `sigsetjmp' call that set this STATE used a
     nonzero SAVESIGS flag, `siglongjmp' also restores the set of
     blocked signals.

Signal Handling
***************

   A "signal" is a software interrupt delivered to a process.  The
operating system uses signals to report exceptional situations to an
executing program.  Some signals report errors such as references to
invalid memory addresses; others report asynchronous events, such as
disconnection of a phone line.

   The GNU C library defines a variety of signal types, each for a
particular kind of event.  Some kinds of events make it inadvisable or
impossible for the program to proceed as usual, and the corresponding
signals normally abort the program.  Other kinds of signals that report
harmless events are ignored by default.

   If you anticipate an event that causes signals, you can define a
handler function and tell the operating system to run it when that
particular type of signal arrives.

   Finally, one process can send a signal to another process; this
allows a parent process to abort a child, or two related processes to
communicate and synchronize.

Basic Concepts of Signals
=========================

   This section explains basic concepts of how signals are generated,
what happens after a signal is delivered, and how programs can handle
signals.

Some Kinds of Signals
---------------------

   A signal reports the occurrence of an exceptional event.  These are
some of the events that can cause (or "generate", or "raise") a signal:

   * A program error such as dividing by zero or issuing an address
     outside the valid range.

   * A user request to interrupt or terminate the program.  Most
     environments are set up to let a user suspend the program by
     typing `C-z', or terminate it with `C-c'.  Whatever key sequence
     is used, the operating system sends the proper signal to interrupt
     the process.

   * The termination of a child process.

   * Expiration of a timer or alarm.

   * A call to `kill' or `raise' by the same process.

   * A call to `kill' from another process.  Signals are a limited but
     useful form of interprocess communication.

   * An attempt to perform an I/O operation that cannot be done.
     Examples are reading from a pipe that has no writer (see Pipes and FIFOs),
     and reading or writing to a terminal in certain
     situations (see Job Control).

   Each of these kinds of events (excepting explicit calls to `kill'
and `raise') generates its own particular kind of signal.  The various
kinds of signals are listed and described in detail in Standard Signals.

Concepts of Signal Generation
-----------------------------

   In general, the events that generate signals fall into three major
categories: errors, external events, and explicit requests.

   An error means that a program has done something invalid and cannot
continue execution.  But not all kinds of errors generate signals--in
fact, most do not.  For example, opening a nonexistent file is an error,
but it does not raise a signal; instead, `open' returns `-1'.  In
general, errors that are necessarily associated with certain library
functions are reported by returning a value that indicates an error.
The errors which raise signals are those which can happen anywhere in
the program, not just in library calls.  These include division by zero
and invalid memory addresses.

   An external event generally has to do with I/O or other processes.
These include the arrival of input, the expiration of a timer, and the
termination of a child process.

   An explicit request means the use of a library function such as
`kill' whose purpose is specifically to generate a signal.

   Signals may be generated "synchronously" or "asynchronously".  A
synchronous signal pertains to a specific action in the program, and is
delivered (unless blocked) during that action.  Most errors generate
signals synchronously, and so do explicit requests by a process to
generate a signal for that same process.  On some machines, certain
kinds of hardware errors (usually floating-point exceptions) are not
reported completely synchronously, but may arrive a few instructions
later.

   Asynchronous signals are generated by events outside the control of
the process that receives them.  These signals arrive at unpredictable
times during execution.  External events generate signals
asynchronously, and so do explicit requests that apply to some other
process.

   A given type of signal is either typically synchronous or typically
asynchronous.  For example, signals for errors are typically synchronous
because errors generate signals synchronously.  But any type of signal
can be generated synchronously or asynchronously with an explicit
request.

How Signals Are Delivered
-------------------------

   When a signal is generated, it becomes "pending".  Normally it
remains pending for just a short period of time and then is "delivered"
to the process that was signaled.  However, if that kind of signal is
currently "blocked", it may remain pending indefinitely--until signals
of that kind are "unblocked".  Once unblocked, it will be delivered
immediately.  See Blocking Signals.

   When the signal is delivered, whether right away or after a long
delay, the "specified action" for that signal is taken.  For certain
signals, such as `SIGKILL' and `SIGSTOP', the action is fixed, but for
most signals, the program has a choice: ignore the signal, specify a
"handler function", or accept the "default action" for that kind of
signal.  The program specifies its choice using functions such as
`signal' or `sigaction' (see Signal Actions).  We sometimes say
that a handler "catches" the signal.  While the handler is running,
that particular signal is normally blocked.

   If the specified action for a kind of signal is to ignore it, then
any such signal which is generated is discarded immediately.  This
happens even if the signal is also blocked at the time.  A signal
discarded in this way will never be delivered, not even if the program
subsequently specifies a different action for that kind of signal and
then unblocks it.

   If a signal arrives which the program has neither handled nor
ignored, its "default action" takes place.  Each kind of signal has its
own default action, documented below (see Standard Signals).  For
most kinds of signals, the default action is to terminate the process.
For certain kinds of signals that represent "harmless" events, the
default action is to do nothing.

   When a signal terminates a process, its parent process can determine
the cause of termination by examining the termination status code
reported by the `wait' or `waitpid' functions.  (This is discussed in
more detail in Process Completion.)  The information it can get
includes the fact that termination was due to a signal, and the kind of
signal involved.  If a program you run from a shell is terminated by a
signal, the shell typically prints some kind of error message.

   The signals that normally represent program errors have a special
property: when one of these signals terminates the process, it also
writes a "core dump file" which records the state of the process at the
time of termination.  You can examine the core dump with a debugger to
investigate what caused the error.

   If you raise a "program error" signal by explicit request, and this
terminates the process, it makes a core dump file just as if the signal
had been due directly to an error.

Standard Signals
================

   This section lists the names for various standard kinds of signals
and describes what kind of event they mean.  Each signal name is a macro
which stands for a positive integer--the "signal number" for that kind
of signal.  Your programs should never make assumptions about the
numeric code for a particular kind of signal, but rather refer to them
always by the names defined here.  This is because the number for a
given kind of signal can vary from system to system, but the meanings of
the names are standardized and fairly uniform.

   The signal names are defined in the header file `signal.h'.

 - Macro: int NSIG
     The value of this symbolic constant is the total number of signals
     defined.  Since the signal numbers are allocated consecutively,
     `NSIG' is also one greater than the largest defined signal number.