   This file documents the GNU C library.

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

   Copyright (C) 1993 Free Software Foundation, Inc.

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

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

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

High-Resolution Calendar
------------------------

   The `time_t' data type used to represent calendar times has a
resolution of only one second.  Some applications need more precision.

   So, the GNU C library also contains functions which are capable of
representing calendar times to a higher resolution than one second.  The
functions and the associated data types described in this section are
declared in `sys/time.h'.

 -- Data Type: struct timeval
     The `struct timeval' structure represents a calendar time.  It has
     the following members:

    `long int tv_sec'
          This represents the number of seconds since the epoch.  It is
          equivalent to a normal `time_t' value.

    `long int tv_usec'
          This is the fractional second value, represented as the
          number of microseconds.

          Some times struct timeval values are user for time intervals.
           Then the `tv_sec' member is the number of seconds in the
          interval, and `tv_usec' is the number of addictional
          microseconds.

 -- Data Type: struct timezone
     The `struct timezone' structure is used to hold minimal information
     about the local time zone.  It has the following members:

    `int tz_minuteswest'
          This is the number of minutes west of GMT.

    `int tz_dsttime'
          If nonzero, daylight savings time applies during some part of
          the year.

   It is often necessary to subtract two values of type
`struct timeval'.  Here is the best way to do this.  It works even on
some peculiar operating systems where the `tv_sec' member has an
unsigned type.

     /* Subtract the `struct timeval' values X and Y,
        storing the result in RESULT.
        Return 1 if the difference is negative, otherwise 0.  */

     int
     timeval_subtract (result, x, y)
          struct timeval *result, *x, *y;
     {
       /* Perform the carry for the later subtraction by updating y. */
       if (x->tv_usec < y->tv_usec) {
         int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
         y->tv_usec -= 1000000 * nsec;
         y->tv_sec += nsec;
       }
       if (x->tv_usec - y->tv_usec > 1000000) {
         int nsec = (y->tv_usec - x->tv_usec) / 1000000;
         y->tv_usec += 1000000 * nsec;
         y->tv_sec -= nsec;
       }

       /* Compute the time remaining to wait.
          `tv_usec' is certainly positive. */
       result->tv_sec = x->tv_sec - y->tv_sec;
       result->tv_usec = x->tv_usec - y->tv_usec;

       /* Return 1 if result is negative. */
       return x->tv_sec < y->tv_sec;
     }

 -- Function: int gettimeofday (struct timeval *TP, struct timezone
          *TZP)
     The `gettimeofday' function returns the current date and time in
     the `struct timeval' structure indicated by TP.  Information about
     the time zone is returned in the structure pointed at TZP.  If the
     TZP argument is a null pointer, time zone information is ignored.

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

    `ENOSYS'
          The operating system does not support getting time zone
          information, and TZP is not a null pointer.  The GNU
          operating system does not support using `struct timezone' to
          represent time zone information.  Use `tzname' et al instead.
           *Say something more helpful here.*

 -- Function: int settimeofday (const struct timeval *TP, const struct
          timezone *TZP)
     The `settimeofday' function sets the current date and time
     according to the arguments.  As for `gettimeofday', time zone
     information is ignored if TZP is a null pointer.

     You must be a privileged user in order to use `settimeofday'.

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

    `EPERM'
          This process cannot set the time because it is not privileged.

    `ENOSYS'
          The operating system does not support setting time zone
          information, and TZP is not a null pointer.

 -- Function: int adjtime (const struct timeval *DELTA, struct timeval
          *OLDDELTA)
     This function speeds up or slows down the system clock in order to
     make gradual adjustments in the current time.  This ensures that
     the time reported by the system clock is always monotonically
     increasing, which might not happen if you simply set the current
     time.

     The DELTA argument specifies a relative adjustment to be made to
     the current time.  If negative, the system clock is slowed down
     for a while until it has lost this much time.  If positive, the
     system clock is speeded up for a while.

     If the OLDDELTA argument is not a null pointer, the `adjtime'
     function returns information about any previous time adjustment
     that has not yet completed.

     This function is typically used to synchronize the clocks of
     computers in a local network.  You must be a privileged user to
     use it. The return value is `0' on success and `-1' on failure.
     The following `errno' error condition is defined for this function:

    `EPERM'
          You do not have privilege to set the time.

   *Portability Note:*  The `gettimeofday', `settimeofday', and
`adjtime' functions are derived from BSD.

Broken-down Time
----------------

   Calender time is represented as a number of seconds.  This is
convenient for calculation, but has no resemblance to the way people
normally represent dates and times.  By contrast, "broken-down time" is
a binary representation separated into year, month, day, and so on.
Broken down time values are not useful for calculations, but they are
useful for printing human readable time.

   A broken-down time value is always relative to a choice of local time
zone, and it also indicates which time zone was used.

   The symbols in this section are declared in the header file `time.h'.

 -- Data Type: struct tm
     This is the data type used to represent a broken-down time.  The
     structure contains at least the following members, which can
     appear in any order:

    `int tm_sec'
          This is the number of seconds after the minute, normally in
          the range `0' to `59'.  (The actual upper limit is `61', to
          allow for "leap seconds".)

    `int tm_min'
          This is the number of minutes after the hour, in the range
          `0' to `59'.

    `int tm_hour'
          This is the number of hours past midnight, in the range `0' to
          `23'.

    `int tm_mday'
          This is the day of the month, in the range `1' to `31'.

    `int tm_mon'
          This is the number of months since January, in the range `0'
          to `11'.

    `int tm_year'
          This is the number of years since `1900'.

    `int tm_wday'
          This is the number of days since Sunday, in the range `0' to
          `6'.

    `int tm_yday'
          This is the number of days since January 1, in the range `0'
          to `365'.

    `int tm_isdst'
          This is a flag that indicates whether Daylight Saving Time is
          (or was, or will be) in effect at the time described.  The
          value is positive if Daylight Saving Time is in effect, zero
          if it is not, and negative if the information is not
          available.

    `long int tm_gmtoff'
          This field describes the time zone that was used to compute
          this broken-down time value; it is the amount you must add to
          the local time in that zone to get GMT, in units of seconds.
          The value is like that of the variable `timezone' (see Time Zone Functions.).
          You can also think of this as the
          "number of seconds west" of GMT.  The `tm_gmtoff' field is a
          GNU library extension.

    `const char *tm_zone'
          This field is the three-letter name for the time zone that
          was used to compute this broken-down time value.  It is a GNU
          library extension.

 -- Function: struct tm * localtime (const time_t *TIME)
     The `localtime' function converts the calendar time pointed to by
     TIME to broken-down time representation, expressed relative to the
     user's specified time zone.

     The return value is a pointer to a static broken-down time
     structure, which might be overwritten by subsequent calls to any
     of the date and time functions.  (But no other library function
     overwrites the contents of this object.)

     Calling `localtime' has one other effect: it sets the variable
     `tzname' with information about the current time zone.  See Time Zone Functions.

 -- Function: struct tm * gmtime (const time_t *TIME)
     This function is similar to `localtime', except that the
     broken-down time is expressed as Coordinated Universal Time
     (UTC)--that is, as Greenwich Mean Time (GMT) rather than relative
     to the local time zone.

     Recall that calendar times are *always* expressed in coordinated
     universal time.

 -- Function: time_t mktime (struct tm *BROKENTIME)
     The `mktime' function is used to convert a broken-down time
     structure to a calendar time representation.  It also "normalizes"
     the contents of the broken-down time structure, by filling in the
     day of week and day of year based on the other date and time
     components.

     The `mktime' function ignores the specified contents of the
     `tm_wday' and `tm_yday' members of the broken-down time structure.
      It uses the values of the other components to compute the
     calendar time; it's permissible for these components to have
     unnormalized values outside of their normal ranges.  The last
     thing that `mktime' does is adjust the components of the BROKENTIME
     structure (including the `tm_wday' and `tm_yday').

     If the specified broken-down time cannot be represented as a
     calendar time, `mktime' returns a value of `(time_t)(-1)' and does
     not modify the contents of BROKENTIME.

     Calling `mktime' also sets the variable `tzname' with information
     about the current time zone.  See Time Zone Functions.

Formatting Date and Time
------------------------

   The functions described in this section format time values as
strings. These functions are declared in the header file `time.h'.

 -- Function: char * asctime (const struct tm *BROKENTIME)
     The `asctime' function writes the broken-down time value pointed
     at by BROKENTIME into a string in a standard format:

          "Tue May 21 13:46:22 1991\n"

     The abbreviations for the days of week are: `Sun', `Mon', `Tue',
     `Wed', `Thu', `Fri', and `Sat'.

     The abbreviations for the months are: `Jan', `Feb', `Mar', `Apr',
     `May', `Jun', `Jul', `Aug', `Sep', `Oct', `Nov', and `Dec'.

     The return value points to a statically allocated string, which
     might be overwritten by subsequent calls to any of the date and
     time functions. (But no other library function overwrites the
     contents of this string.)

 -- Function: char * ctime (const time_t *TIME)
     The `ctime' function is similar to `asctime', except that the time
     value is specified in calendar time (rather than local time)
     format.  It is equivalent to

          asctime (localtime (TIME))

     `ctime' sets the variable `tzname', because `localtime' does so.
     See Time Zone Functions.

 -- Function: size_t strftime (char *S, size_t SIZE, const char
          *TEMPLATE, const struct tm *BROKENTIME)
     This function is similar to the `sprintf' function (see
     Formatted Input.), but the conversion specifications that can
     appear in the format template TEMPLATE are specialized for
     printing components of the date and time BROKENTIME according to
     the locale currently specified for time conversion (see
     Locales.).

     Ordinary characters appearing in the TEMPLATE are copied to the
     output string S; this can include multibyte character sequences.
     Conversion specifiers are introduced by a `%' character, and are
     replaced in the output string as follows:

    `%a'
          The abbreviated weekday name according to the current locale.

    `%A'
          The full weekday name according to the current locale.

    `%b'
          The abbreviated month name according to the current locale.

    `%B'
          The full month name according to the current locale.

    `%c'
          The preferred date and time representation for the current
          locale.

    `%d'
          The day of the month as a decimal number (range `01' to `31').

    `%H'
          The hour as a decimal number, using a 24-hour clock (range
          `00' to `23').

    `%I'
          The hour as a decimal number, using a 12-hour clock (range
          `01' to `12').

    `%j'
          The day of the year as a decimal number (range `001' to
          `366').

    `%m'
          The month as a decimal number (range `01' to `12').

    `%M'
          The minute as a decimal number.

    `%p'
          Either `am' or `pm', according to the given time value; or the
          corresponding strings for the current locale.

    `%S'
          The second as a decimal number.

    `%U'
          The week number of the current year as a decimal number,
          starting with the first Sunday as the first day of the first
          week.

    `%W'
          The week number of the current year as a decimal number,
          starting with the first Monday as the first day of the first
          week.

    `%w'
          The day of the week as a decimal number, Sunday being `0'.

    `%x'
          The preferred date representation for the current locale, but
          without the time.

    `%X'
          The preferred time representation for the current locale, but
          with no date.

    `%y'
          The year as a decimal number, but without a century (range
          `00' to `99').

    `%Y'
          The year as a decimal number, including the century.

    `%Z'
          The time zone or name or abbreviation (empty if the time zone
          can't be determined).

    `%%'
          A literal `%' character.

     The SIZE parameter can be used to specify the maximum number of
     characters to be stored in the array S, including the terminating
     null character.  If the formatted time requires more than SIZE
     characters, the excess characters are discarded.  The return value
     from `strftime' is the number of characters placed in the array S,
     not including the terminating null character.  If the value equals
     SIZE, it means that the array S was too small; you should repeat
     the call, providing a bigger array.

     For an example of `strftime', see Time Functions Example.

Specifying the Time Zone with `TZ'
----------------------------------

   In the GNU system, a user can specify the time zone by means of the
`TZ' environment variable.  For information about how to set
environment variables, see Environment Variables.  The
functions for accessing the time zone are declared in `time.h'.

   The value of the `TZ' variable can be of one of three formats.  The
first format is used when there is no Daylight Saving Time (or summer
time) in the local time zone:

     STD OFFSET

   The STD string specifies the name of the time zone.  It must be
three or more characters long and must not contain a leading colon or
embedded digits, commas, or plus or minus signs.  There is no space
character separating the time zone name from the OFFSET, so these
restrictions are necessary to parse the specification correctly.

   The OFFSET specifies the time value one must add to the local time
to get a Coordinated Universal Time value.  It has syntax like
[`+'|`-']HH[`:'MM[`:'SS]].  This is positive if the local time zone is
west of the Prime Meridian and negative if it is east.  The hour must
be between `0' and `24', and the minute and seconds between `0' and
`59'.

   For example, here is how we would specify Eastern Standard Time, but
without any daylight savings time alternative:

     EST+5

   The second format is used when there is Daylight Saving Time:

     STD OFFSET DST [OFFSET]`,'START[`/'TIME]`,'END[`/'TIME]

   The initial STD and OFFSET specify the standard time zone, as
described above.  The DST string and OFFSET specify the name and offset
for the corresponding daylight savings time time zone; if the OFFSET is
omitted, it defaults to one hour ahead of standard time.

   The remainder of the specification describes when daylight savings
time is in effect.  The START field is when daylight savings time goes
into effect and the END field is when the change is made back to
standard time.  The following formats are recognized for these fields:

`JN'
     This specifies the Julian day, with N between `1' and `365'.
     February 29 is never counted, even in leap years.

`N'
     This specifies the Julian day, with N between `0' and `365'.
     February 29 is counted in leap years.

`MM.W.D'
     This specifies day D of week W of month M.  The day D must be
     between `0' (Sunday) and `6'.  The week W must be between `1' and
     `5'; week `1' is the first week in which day D occurs, and week
     `5' specifies the *last* D day in the month.  The month M should be
     between `1' and `12'.

   The TIME fields specify when, in the local time currently in effect,
the change to the other time occurs.  If omitted, the default is
`02:00:00'.

   For example, here is how one would specify the Eastern time zone in
the United States, including the appropriate daylight saving time and
its dates of applicability.  The normal offset from GMT is 5 hours;
since this is west of the prime meridian, the sign is positive.  Summer
time begins on the first Sunday in April at 2:00am, and ends on the
last Sunday in October at 2:00am.

     EST+5EDT,M4.1.0/M10.5.0

   The schedule of daylight savings time in any particular jurisdiction
has changed over the years.  To be strictly correct, the conversion of
dates and times in the past should be based on the schedule that was in
effect then.  However, the system has no facilities to let you specify
how the schedule has changed from year to year.  The most you can do is
specify one particular schedule--usually the present day schedule--and
this is used to convert any date, no matter when.

   The third format looks like this:

     :CHARACTERS

   Each operating system interprets this format differently; in the GNU
C library, CHARACTERS is the name of a file which describes the time
zone.

   If the `TZ' environment variable does not have a value, the
operation chooses a time zone by default.  Each operating system has its
own rules for choosing the default time zone, so there is little we can
say about them.

Functions and Variables for Time Zones
--------------------------------------

 -- Variable: char *tzname
     The array `tzname' contains two strings, which are the standard
     three-letter names of the pair of time zones (standard and daylight
     savings) that the user has selected.  `tzname[0]' is the name of
     the standard time zone (for example, `"EST"'), and `tzname[1]' is
     the name for the time zone when daylight savings time is in use
     (for example, `"EDT"').  These correspond to the STD and DST
     strings (respectively) from the `TZ' environment variable.

     The `tzname' array is initialized from the `TZ' environment
     variable whenever `tzset', `ctime', `strftime', `mktime', or
     `localtime' is called.

 -- Function: void tzset (void)
     The `tzset' function initializes the `tzname' variable from the
     value of the `TZ' environment variable.  It is not usually
     necessary for your program to call this function, because it is
     called automatically when you use the other time conversion
     functions that depend on the time zone.

   The following variables are defined for compatibility with System V
Unix.  These variables are set by calling `localtime'.

 -- Variable: long int timezone
     This contains the difference between GMT and local standard time,
     in seconds.  For example, in the U.S. Eastern time zone, the value
     is `5*60*60'.

 -- Variable: int daylight
     This variable has a nonzero value if the standard U.S. daylight
     savings time rules apply.

Time Functions Example
----------------------

   Here is an example program showing the use of some of the local time
and calendar time functions.

     #include <time.h>
     #include <stdio.h>

     #define SIZE 256

     int
     main (void)
     {
       char buffer[SIZE];
       time_t curtime;
       struct tm *loctime;

       /* Get the current time.  */
       curtime = time (NULL);

       /* Convert it to local time representation.  */
       loctime = localtime (&curtime);

       /* Print out the date and time in the standard format.  */
       fputs (asctime (loctime), stdout);

       /* Print it out in a nice format.  */
       strftime (buffer, SIZE, "Today is %A, %B %d.\n", loctime);
       fputs (buffer, stdout);
       strftime (buffer, SIZE, "The time is %I:%M %p.\n", loctime);
       fputs (buffer, stdout);

       return 0;
     }

   It produces output like this:

     Wed Jul 31 13:02:36 1991
     Today is Wednesday, July 31.
     The time is 01:02 PM.

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

   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 *OLD, struct
          itimerval *NEW)
     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'.

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'
          User time used.

    `struct timeval ru_stime'
          System time used.

    `long ru_majflt'
          Number of page faults.

    `long ru_inblock'
          Number of block input operations.

    `long ru_oublock'
          Number of block output operations.

    `long ru_msgsnd'
          Number of messages sent.

    `long ru_msgrcv'
          Number of messages received.

    `long ru_nsignals'
          Number of signals received.

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

 -- Function: int setrlimit (int RESOURCE, 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.

 -- 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_cur'
          The current value of the limit in question.

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

     In `getrlimit', the structure is an output; it receives the current
     values.  In `setrlimit', 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 Nonstandard Signals.

`RLIMIT_FSIZE'
     The maximum size of file the process can create.  Trying to write a
     larger file causes a signal: `SIGXFSZ'.  See Nonstandard 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 a core file is made, and this maximum size
     is not enough, the core file is truncated.

`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_OPEN_FILES'
     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.

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

 -- Constant: int
     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 smallest 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).

     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)
     Read the priority of a class of processes; 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 not meaningful.

     Here is an equivalent definition for `nice':

          int
          nice (int increment)
          {
            int old = getpriority (PRIO_PROCESS, 0);
            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' 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 `sigsetjmp') 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.