Date and Time
*************

This chapter describes functions for manipulating dates and times, including functions for determining what the current time is and conversion between different time representations.

The time functions fall into three main categories:

  * Functions for measuring elapsed CPU time are discussed in Processor Time.

  * Functions for measuring absolute clock or calendar time are discussed in Calendar Time.

  * Functions for setting alarms and timers are discussed in Setting an Alarm.

Processor Time
==============

If you're trying to optimize your program or measure its efficiency, it's very useful to be able to know how much processor time or CPU time it has used at any given point.  Processor time is different from actual wall clock time because it doesn't include any time spent waiting for I/O or when some other process is running.  Processor time is represented by the data type clock_t, and is given as a number of clock ticks relative to an arbitrary base time marking the beginning of a single program invocation.

Basic CPU Time Inquiry
----------------------

To get the elapsed CPU time used by a process, you can use the clock function.  This facility is declared in the header file time.h.

In typical usage, you call the clock function at the beginning and end of the interval you want to time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second), like this:

     #include <time.h>

     clock_t start, end;
     double elapsed;

     start = clock();
     ... /* Do the work. */
     end = clock();
     elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;

Different computers and operating systems vary wildly in how they keep track of processor time.  It's common for the internal processor clock to have a resolution somewhere between hundredth and millionth of a second.

In the GNU system, clock_t is equivalent to long int and CLOCKS_PER_SEC is an integer value.  But in other systems, both clock_t and the type of the macro CLOCKS_PER_SEC can be either integer or floating-point types.  Casting processor time values to double, as in the example above, makes sure that operations such as arithmetic and printing work properly and consistently no matter what the underlying representation is.

Note that the clock can wrap around.  On a 32bit system with CLOCKS_PER_SEC set to one million a wrap around happens after around 36 minutes.

 -- Macro: int CLOCKS_PER_SEC
     The value of this macro is the number of clock ticks per second measured by the clock function.  POSIX requires that this value is one million independend of the actual resolution.

 -- Macro: int CLK_TCK
     This is an obsolete name for CLOCKS_PER_SEC.

 -- Data Type: clock_t
     This is the type of the value returned by the clock function. Values of type clock_t are in units of clock ticks.

 -- Function: clock_t clock (void)
     This function returns the elapsed processor time.  The base time is arbitrary but doesn't change within a single process.  If the processor time is not available or cannot be represented, clock returns the value (clock_t)(-1).

Detailed Elapsed CPU Time Inquiry
---------------------------------

The times function returns more detailed information about elapsed processor time in a struct tms object.  You should include the header file sys/times.h to use this facility.

 -- Data Type: struct tms
     The tms structure is used to return information about process times.  It contains at least the following members:

     clock_t tms_utime
          This is the CPU time used in executing the instructions of the calling process.

     clock_t tms_stime
          This is the CPU time used by the system on behalf of the calling process.

     clock_t tms_cutime
          This is the sum of the tms_utime values and the tms_cutime values of all terminated child processes of the calling process, whose status has been reported to the parent process by wait or waitpid; see Process Completion.  In other words, it represents the total CPU time used in executing the instructions of all the terminated child processes of the calling process, excluding child processes which have not yet been reported by wait or waitpid.

     clock_t tms_cstime
          This is similar to tms_cutime, but represents the total CPU time used by the system on behalf of all the terminated child processes of the calling process.

     All of the times are given in clock ticks.  These are absolute values; in a newly created process, they are all zero.  See Creating a Process.

 -- Function: clock_t times (struct tms *BUFFER)
     The times function stores the processor time information for the calling process in BUFFER.

     The return value is the same as the value of clock(): the elapsed real time relative to an arbitrary base.  The base is a constant within a particular process, and typically represents the time since system start-up.  A value of (clock_t)(-1) is returned to indicate failure.

Portability Note: The clock function described in Basic CPU Time, is specified by the ISO C standard.  The times function is a feature of POSIX.1.  In the GNU system, the value returned by the clock function is equivalent to the sum of the tms_utime and tms_stime fields returned by times.

Calendar Time
=============

This section describes facilities for keeping track of dates and times according to the Gregorian calendar.

There are three representations for date and time information:

  * Calendar time (the time_t data type) is a compact representation, typically giving the number of seconds elapsed since some implementation-specific base time.

  * There is also a high-resolution time representation (the struct timeval data type) that includes fractions of a second.  Use this time representation instead of ordinary calendar time when you need greater precision.

  * Local time or broken-down time (the struct tm data type) represents the date and time as a set of components specifying the year, month, and so on, for a specific time zone. This time representation is usually used in conjunction with formatting date and time values.

Simple Calendar Time
--------------------

This section describes the time_t data type for representing calendar time, and the functions which operate on calendar time objects. These facilities are declared in the header file time.h.

 -- Data Type: time_t
     This is the data type used to represent calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time.  (This date is sometimes referred to as the epoch.)  POSIX requires that this count ignore leap seconds, but on some hosts this count includes leap seconds if you set TZ to certain values (see TZ Variable).

     In the GNU C library, time_t is equivalent to long int. In other systems, time_t might be either an integer or floating-point type.

 -- Function: double difftime (time_t TIME1, time_t TIME0)
     The difftime function returns the number of seconds elapsed between time TIME1 and time TIME0, as a value of type double.  The difference ignores leap seconds unless leap second support is enabled.

     In the GNU system, you can simply subtract time_t values.  But on other systems, the time_t data type might use some other encoding where subtraction doesn't work directly.

 -- Function: time_t time (time_t *RESULT)
     The time function returns the current time as a value of type time_t.  If the argument RESULT is not a null pointer, the time value is also stored in *RESULT.  If the calendar time is not available, the value (time_t)(-1) is returned.

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 used for time intervals.  Then the tv_sec member is the number of seconds in the interval, and tv_usec is the number of additional 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 UTC.

     int tz_dsttime
          If nonzero, daylight saving time applies during some part of the year.

     The struct timezone type is obsolete and should never be used. Instead, use the facilities described in Time Zone Functions.

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 = (x->tv_usec - y->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; that is an obsolete feature of 4.3 BSD. Instead, use the facilities described in Time Zone Functions.

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

Calendar 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 through 59.  (The actual upper limit is 60, to allow for leap seconds if leap second support is available.)

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

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

     int tm_mday
          This is the day of the month, in the range 1 through 31.

     int tm_mon
          This is the number of months since January, in the range 0 through 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 through 6.

     int tm_yday
          This is the number of days since January 1, in the range 0 through 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, including any adjustment for daylight saving; it is the number of seconds that you must add to UTC to get local time. You can also think of this as the number of seconds east of UTC.  For example, for U.S. Eastern Standard Time, the value is -5*60*60. The tm_gmtoff field is derived from BSD and is a GNU library extension; it is not visible in a strict ISO C environment.

     const char *tm_zone
          This field is the name for the time zone that was used to compute this broken-down time value.  Like tm_gmtoff, this field is a BSD and GNU extension, and is not visible in a strict ISO C environment.

 -- 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 ctime, gmtime, or localtime.  (But no other library function overwrites the contents of this object.)

     The return value is the null pointer if TIME cannot be represented as a broken-down time; typically this is because the year cannot fit into an int.

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

Using the localtime function is a big problem in multi-threaded programs.  The result is returned in a static buffer and this is used in all threads.  POSIX.1c introduced a varient of this function.

 -- Function: struct tm * localtime_r (const time_t *TIME, struct tm *RESULTP)
     The localtime_r function works just like the localtime function.  It takes a pointer to a variable containing the calendar time and converts it to the broken-down time format.

     But the result is not placed in a static buffer.  Instead it is placed in the object of type struct tm to which the parameter RESULTP points.

     If the conversion is successful the function returns a pointer to the object the result was written into, i.e., it returns RESULTP.

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

As for the localtime function we have the problem that the result is placed in a static variable.  POSIX.1c also provides a replacement for gmtime.

 -- Function: struct tm * gmtime_r (const time_t *TIME, struct tm *RESULTP)
     This function is similar to localtime_r, except that it converts just like gmtime the given time as Coordinated Universal Time.

     If the conversion is successful the function returns a pointer to the object the result was written into, i.e., it returns RESULTP.

 -- 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 converts the broken-down time value that BROKENTIME points to 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 asctime or ctime. (But no other library function overwrites the contents of this string.)

 -- Function: char * asctime_r (const struct tm *BROKENTIME, char *BUFFER)
     This function is similar to asctime but instead of placing the result in a static buffer it writes the string in the buffer pointed to by the parameter BUFFER.  This buffer should have at least room for 16 bytes.

     If no error occurred the function returns a pointer to the string the result was written into, i.e., it returns BUFFER.  Otherwise return NULL.

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

          asctime (localtime (TIME))

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

 -- Function: char * ctime_r (const time_t *TIME, char *BUFFER)
     This function is similar to ctime, only that it places the result in the string pointed to by BUFFER.  It is equivalent to (written using gcc extensions, see Statement Exprs (Porting and Using gcc)):

          ({ struct tm tm; asctime_r (localtime_r (time, &tm), buf); })

     If no error occurred the function returns a pointer to the string the result was written into, i.e., it returns BUFFER.  Otherwise return NULL.

 -- 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, followed by an optional flag which can be one of the following.  These flags are all GNU extensions. The first three affect only the output of numbers:

     _
          The number is padded with spaces.

     -
          The number is not padded at all.

     0
          The number is padded with zeros even if the format specifies padding with spaces.

     ^
          The output uses uppercase characters, but only if this is possible (see Case Conversion).

     The default action is to pad the number with zeros to keep it a constant width.  Numbers that do not have a range indicated below are never padded, since there is no natural width for them.

     Following the flag an optional specification of the width is possible. This is specified in decimal notation.  If the natural size of the output is of the field has less than the specified number of characters, the result is written right adjusted and space padded to the given size.

     An optional modifier can follow the optional flag and width specification.  The modifiers, which are POSIX.2 extensions, are:

     E
          Use the locale's alternate representation for date and time.  This modifier applies to the %c, %C, %x, %X, %y and %Y format specifiers.  In a Japanese locale, for example, %Ex might yield a date format based on the Japanese Emperors' reigns.

     O
          Use the locale's alternate numeric symbols for numbers.  This modifier applies only to numeric format specifiers.

     If the format supports the modifier but no alternate representation is available, it is ignored.

     The conversion specifier ends with a format specifier taken from the following list.  The whole % sequence is 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.

     %C
          The century of the year.  This is equivalent to the greatest integer not greater than the year divided by 100.

          This format is a POSIX.2 extension.

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

     %D
          The date using the format %m/%d/%y.

          This format is a POSIX.2 extension.

     %e
          The day of the month like with %d, but padded with blank (range 1 through 31).

          This format is a POSIX.2 extension.

     %F
          The date using the format %Y-%m-%d.  This is the form specified in the ISO 8601 standard and is the preferred form for all uses.

          This format is a ISO C 9X extension.

     %g
          The year corresponding to the ISO week number, but without the century (range 00 through 99).  This has the same format and value as %y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead.

          This format is a GNU extension.

     %G
          The year corresponding to the ISO week number.  This has the same format and value as %Y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead.

          This format is a GNU extension.

     %h
          The abbreviated month name according to the current locale.  The action is the same as for %b.

          This format is a POSIX.2 extension.

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

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

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

     %k
          The hour as a decimal number, using a 24-hour clock like %H, but padded with blank (range  0 through 23).

          This format is a GNU extension.

     %l
          The hour as a decimal number, using a 12-hour clock like %I, but padded with blank (range  1 through 12).

          This format is a GNU extension.

     %m
          The month as a decimal number (range 01 through 12).

     %M
          The minute as a decimal number (range 00 through 59).

     %n
          A single \n (newline) character.

          This format is a POSIX.2 extension.

     %p
          Either AM or PM, according to the given time value; or the corresponding strings for the current locale.  Noon is treated as PM and midnight as AM.

     %P
          Either am or pm, according to the given time value; or the corresponding strings for the current locale, printed in lowercase characters.  Noon is treated as pm and midnight as am.

          This format is a GNU extension.

     %r
          The complete time using the AM/PM format of the current locale.

          This format is a POSIX.2 extension.

     %R
          The hour and minute in decimal numbers using the format %H:%M.

          This format is a GNU extension.

     %s
          The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC. Leap seconds are not counted unless leap second support is available.

          This format is a GNU extension.

     %S
          The seconds as a decimal number (range 00 through 60).

     %t
          A single \t (tabulator) character.

          This format is a POSIX.2 extension.

     %T
          The time using decimal numbers using the format %H:%M:%S.

          This format is a POSIX.2 extension.

     %u
          The day of the week as a decimal number (range 1 through 7), Monday being 1.

          This format is a POSIX.2 extension.

     %U
          The week number of the current year as a decimal number (range 00 through 53), starting with the first Sunday as the first day of the first week.  Days preceding the first Sunday in the year are considered to be in week 00.

     %V
          The ISO 8601:1988 week number as a decimal number (range 01 through 53).  ISO weeks start with Monday and end with Sunday. Week 01 of a year is the first week which has the majority of its days in that year; this is equivalent to the week containing the year's first Thursday, and it is also equivalent to the week containing January 4.  Week 01 of a year can contain days from the previous year. The week before week 01 of a year is the last week (52 or 53) of the previous year even if it contains days from the new year.

          This format is a POSIX.2 extension.

     %w
          The day of the week as a decimal number (range 0 through 6), Sunday being 0.

     %W
          The week number of the current year as a decimal number (range 00 through 53), starting with the first Monday as the first day of the first week.  All days preceding the first Monday in the year are considered to be in week 00.

     %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 without a century as a decimal number (range 00 through 99).  This is equivalent to the year modulo 100.

     %Y
          The year as a decimal number, using the Gregorian calendar.  Years before the year 1 are numbered 0, -1, and so on.

     %z
          RFC 822/ISO 8601:1988 style numeric time zone (e.g., -0600 or +0100), or nothing if no time zone is determinable.

          This format is a GNU extension.

          A full RFC 822 timestamp is generated by the format "%a, %d %b %Y %H:%M:%S %z" (or the equivalent "%a, %d %b %Y %T %z").

     %Z
          The time zone 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, strftime returns zero and the content of the array S is indetermined.  Otherwise the return value indicates the number of characters placed in the array S, not including the terminating null character.

     Warning: This convention for the return value which is prescribed in ISO C can lead to problems in some situations.  For certain format strings and certain locales the output really can be the empty string and this cannot be discovered by testing the return value only. E.g., in most locales the AM/PM time format is not supported (most of the world uses the 24 hour time representation).  In such locales "%p" will return the empty string, i.e., the return value is zero.  To detect situations like this something similar to the following code should be used:

          buf[0] = '\1';
          len = strftime (buf, bufsize, format, tp);
          if (len == 0 && buf[0] != '\0')
            {
              /* Something went wrong in the strftime call.  */
              ...
            }

     If S is a null pointer, strftime does not actually write anything, but instead returns the number of characters it would have written.

     According to POSIX.1 every call to strftime implies a call to tzset.  So the contents of the environment variable TZ is examined before any output is produced.

     For an example of strftime, see Time Functions Example.

Convert textual time and date information back
----------------------------------------------

The ISO C standard does not specify any functions which can convert the output of the strftime function back into a binary format. This lead to variety of more or less successful implementations with different interfaces over the years.  Then the Unix standard got extended by two functions: strptime and getdate.  Both have kind of strange interfaces but at least they are widely available.

Interpret string according to given format
..........................................

The first function is a rather low-level interface.  It is nevertheless frequently used in user programs since it is better known.  Its implementation and the interface though is heavily influenced by the getdate function which is defined and implemented in terms of calls to strptime.

 -- Function: char * strptime (const char *S, const char *FMT, struct tm *TP)
     The strptime function parses the input string S according to the format string FMT and stores the found values in the structure TP.

     The input string can be retrieved in any way.  It does not matter whether it was generated by a strftime call or made up directly by a program.  It is also not necessary that the content is in any human-recognizable format.  I.e., it is OK if a date is written like "02:1999:9" which is not understandable without context.  As long the format string FMT matches the format of the input string everything goes.

     The format string consists of the same components as the format string for the strftime function.  The only difference is that the flags _, -, 0, and ^ are not allowed. Several of the formats which strftime handled differently do the same work in strptime since differences like case of the output do not matter.  For symmetry reasons all formats are supported, though.

     The modifiers E and O are also allowed everywhere the strftime function allows them.

     The formats are:

     %a
     %A
          The weekday name according to the current locale, in abbreviated form or the full name.

     %b
     %B
     %h
          The month name according to the current locale, in abbreviated form or the full name.

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

     %Ec
          Like %c but the locale's alternative date and time format is used.

     %C
          The century of the year.

          It makes sense to use this format only if the format string also contains the %y format.

     %EC
          The locale's representation of the period.

          Unlike %C it makes sometimes sense to use this format since in some cultures it is required to specify years relative to periods instead of using the Gregorian years.

     %d

     %e
          The day of the month as a decimal number (range 1 through 31). Leading zeroes are permitted but not required.

     %Od
     %Oe
          Same as %d but the locale's alternative numeric symbols are used.

          Leading zeroes are permitted but not required.

     %D
          Equivalent to the use of %m/%d/%y in this place.

     %F
          Equivalent to the use of %Y-%m-%d which is the ISO 8601 date format.

          This is a GNU extension following an ISO C 9X extension to strftime.

     %g
          The year corresponding to the ISO week number, but without the century (range 00 through 99).

          Note: This is not really implemented currently.  The format is recognized, input is consumed but no field in TM is set.

          This format is a GNU extension following a GNU extension of strftime.

     %G
          The year corresponding to the ISO week number.

          Note: This is not really implemented currently.  The format is recognized, input is consumed but no field in TM is set.

          This format is a GNU extension following a GNU extension of strftime.

     %H
     %k
          The hour as a decimal number, using a 24-hour clock (range 00 through 23).

          %k is a GNU extension following a GNU extension of strftime.

     %OH
          Same as %H but using the locale's alternative numeric symbols are used.

     %I
     %l
          The hour as a decimal number, using a 12-hour clock (range 01 through 12).

          %l is a GNU extension following a GNU extension of strftime.

     %OI
          Same as %I but using the locale's alternative numeric symbols are used.

     %j
          The day of the year as a decimal number (range 1 through 366).

          Leading zeroes are permitted but not required.

     %m
          The month as a decimal number (range 1 through 12).

          Leading zeroes are permitted but not required.

     %Om
          Same as %m but using the locale's alternative numeric symbols are used.

     %M
          The minute as a decimal number (range 0 through 59).

          Leading zeroes are permitted but not required.

     %OM
          Same as %M but using the locale's alternative numeric symbols are used.

     %n
     %t
          Matches any white space.

     %p

     %P
          The locale-dependent equivalent to AM or PM.

          This format is not useful unless %I or %l is also used. Another complication is that the locale might not define these values at all and therefore the conversion fails.

          %P is a GNU extension following a GNU extension to strftime.

     %r
          The complete time using the AM/PM format of the current locale.

          A complication is that the locale might not define this format at all and therefore the conversion fails.

     %R
          The hour and minute in decimal numbers using the format %H:%M.

          %R is a GNU extension following a GNU extension to strftime.

     %s
          The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC. Leap seconds are not counted unless leap second support is available.

          %s is a GNU extension following a GNU extension to strftime.

     %S
          The seconds as a decimal number (range 0 through 61).

          Leading zeroes are permitted but not required.

          Please note the nonsense with 61 being allowed.  This is what the Unix specification says.  They followed the stupid decision once made to allow double leap seconds.  These do not exist but the myth persists.

     %OS
          Same as %S but using the locale's alternative numeric symbols are used.

     %T
          Equivalent to the use of %H:%M:%S in this place.

     %u
          The day of the week as a decimal number (range 1 through 7), Monday being 1.

          Leading zeroes are permitted but not required.

          Note: This is not really implemented currently.  The format is recognized, input is consumed but no field in TM is set.

     %U
          The week number of the current year as a decimal number (range 0 through 53).

          Leading zeroes are permitted but not required.

     %OU
          Same as %U but using the locale's alternative numeric symbols are used.

     %V
          The ISO 8601:1988 week number as a decimal number (range 1 through 53).

          Leading zeroes are permitted but not required.

          Note: This is not really implemented currently.  The format is recognized, input is consumed but no field in TM is set.

     %w
          The day of the week as a decimal number (range 0 through 6), Sunday being 0.

          Leading zeroes are permitted but not required.

          Note: This is not really implemented currently.  The format is recognized, input is consumed but no field in TM is set.

     %Ow
          Same as %w but using the locale's alternative numeric symbols are used.

     %W
          The week number of the current year as a decimal number (range 0 through 53).

          Leading zeroes are permitted but not required.

          Note: This is not really implemented currently.  The format is recognized, input is consumed but no field in TM is set.

     %OW
          Same as %W but using the locale's alternative numeric symbols are used.

     %x
          The date using the locale's date format.

     %Ex
          Like %x but the locale's alternative data representation is used.

     %X
          The time using the locale's time format.

     %EX
          Like %X but the locale's alternative time representation is used.

     %y
          The year without a century as a decimal number (range 0 through 99).

          Leading zeroes are permitted but not required.

          Please note that it is at least questionable to use this format without the %C format.  The strptime function does regard input values in the range 68 to 99 as the years 1969 to 1999 and the values 0 to 68 as the years 2000 to 2068.  But maybe this heuristic fails for some input data.

          Therefore it is best to avoid %y completely and use %Y instead.

     %Ey
          The offset from %EC in the locale's alternative representation.

     %Oy
          The offset of the year (from %C) using the locale's alternative numeric symbols.

     %Y
          The year as a decimal number, using the Gregorian calendar.

     %EY
          The full alternative year representation.

     %z
          Equivalent to the use of %a, %d %b %Y %H:%M:%S %z in this place. This is the full ISO 8601 date and time format.

     %Z
          The timezone name.

          Note: This is not really implemented currently.  The format is recognized, input is consumed but no field in TM is set.

     %%
          A literal % character.

     All other characters in the format string must have a matching character in the input string.  Exceptions are white spaces in the input string which can match zero or more white space characters in the input string.

     The strptime function processes the input string from right to left.  Each of the three possible input elements (white space, literal, or format) are handled one after the other.  If the input cannot be matched to the format string the function stops.  The remainder of the format and input strings are not processed.

     The return value of the function is a pointer to the first character not processed in this function call.  In case the input string contains more characters than required by the format string the return value points right after the last consumed input character.  In case the whole input string is consumed the return value points to the NUL byte at the end of the string.  If strptime fails to match all of the format string and therefore an error occurred the function returns NULL.

The specification of the function in the XPG standard is rather vague. It leaves out a few important pieces of information.  Most important it does not specify what happens to those elements of TM which are not directly initialized by the different formats.  Various implementations on different Unix systems vary here.

The GNU libc implementation does not touch those fields which are not directly initialized.  Exceptions are the tm_wday and tm_yday elements which are recomputed if any of the year, month, or date elements changed.  This has two implications:

  * Before calling the strptime function for a new input string one has to prepare the structure passed in as the TM.  Normally this will mean that all values are initialized to zero.  Alternatively one can use all fields to values like INT_MAX which allows to determine which elements were set by the function call.  Zero does not work here since it is a valid value for many of the fields.

     Careful initialization is necessary if one wants to find out whether a certain field in TM was initialized by the function call.

  * One can construct a struct tm value in several strptime calls in a row.  A useful application of this is for example the parsing of two separate strings, one containing the date information, the other the time information.  By parsing both one after the other without clearing the structure in between one can construct a complete broken-down time.

The following example shows a function which parses a string which is supposed to contain the date information in either US style or ISO 8601 form.

     const char *
     parse_date (const char *input, struct tm *tm)
     {
       const char *cp;

       /* First clear the result structure.  */
       memset (tm, '\0', sizeof (*tm));

       /* Try the ISO format first.  */
       cp = strptime (input, "%F", tm);
       if (cp == NULL)
         {
           /* Does not match.  Try the US form.  */
           cp = strptime (input, "%D", tm);
         }

       return cp;
     }

A user-friendlier way to parse times and dates
..............................................

The Unix standard defines another function to parse date strings.  The interface is, mildly said, weird.  But if this function fits into the application to be written it is just fine.  It is a problem when using this function in multi-threaded programs or in libraries since it returns a pointer to a static variable, uses a global variable, and a global state (an environment variable).

 -- Variable: getdate_err
     This variable of type int will contain the error code of the last unsuccessful call of the getdate function.  Defined values are:

     1
          The environment variable DATEMSK is not defined or null.

     2
          The template file denoted by the DATEMSK environment variable cannot be opened.

     3
          Information about the template file cannot retrieved.

     4
          The template file is no regular file.

     5
          An I/O error occurred while reading the template file.

     6
          Not enough memory available to execute the function.

     7
          The template file contains no matching template.

     8
          The input string is invalid for a template which would match otherwise. This includes error like February 31st, or return values which can be represented using time_t.

 -- Function: struct tm * getdate (const char *STRING)
     The interface of the getdate function is the simplest possible for a function to parse a string and return the value.  STRING is the input string and the result is passed to the user in a statically allocated variable.

     The details about how the string is processed is hidden from the user. In fact, it can be outside the control of the program.  Which formats are recognized is controlled by the file named by the environment variable DATEMSK.  The content of the named file should contain lines of valid format strings which could be passed to strptime.

     The getdate function reads these format strings one after the other and tries to match the input string.  The first line which completely matches the input string is used.

     Elements which were not initialized through the format string get assigned the values of the time the getdate function is called.

     The format elements recognized by getdate are the same as for strptime.  See above for an explanation.  There are only a few extension to the strptime behavior:

       * If the %Z format is given the broken-down time is based on the current time in the timezone matched, not in the current timezone of the runtime environment.

          Note: This is not implemented (currently).  The problem is that timezone names are not unique.  If a fixed timezone is assumed for a given string (say EST meaning US East Coast time) uses for countries other than the USA will fail.  So far we have found no good solution for this.

       * If only the weekday is specified the selected day depends on the current date.  If the current weekday is greater or equal to the tm_wday value this weeks day is selected.  Otherwise next weeks day.

       * A similar heuristic is used if only the month is given, not the year. For value corresponding to the current or a later month the current year s used.  Otherwise the next year.  The first day of the month is assumed if it is not explicitly specified.

       * The current hour, minute, and second is used if the appropriate value is not set through the format.

       * If no date is given the date for the next day is used if the time is smaller than the current time.  Otherwise it is the same day.

     It should be noted that the format in the template file need not only contain format elements.  The following is a list of possible format strings (taken from the Unix standard):

          %m
          %A %B %d, %Y %H:%M:%S
          %A
          %B
          %m/%d/%y %I %p
          %d,%m,%Y %H:%M
          at %A the %dst of %B in %Y
          run job at %I %p,%B %dnd
          %A den %d. %B %Y %H.%M Uhr

     As one can see the template list can contain very specific strings like run job at %I %p,%B %dnd.  Using the above list of templates and assuming the current time is Mon Sep 22 12:19:47 EDT 1986 we can get the following results for the given input.

     Mon         %a      Mon Sep 22 12:19:47 EDT 1986
     Sun         %a      Sun Sep 28 12:19:47 EDT 1986
     Fri         %a      Fri Sep 26 12:19:47 EDT 1986
     September   %B      Mon Sep 1 12:19:47 EDT 1986
     January     %B      Thu Jan 1 12:19:47 EST 1987
     December    %B      Mon Dec 1 12:19:47 EST 1986
     Sep Mon     %b %a   Mon Sep 1 12:19:47 EDT 1986
     Jan Fri     %b %a   Fri Jan 2 12:19:47 EST 1987
     Dec Mon     %b %a   Mon Dec 1 12:19:47 EST 1986
     Jan Wed 1989    %b %a %Y   Wed Jan 4 12:19:47 EST 1989
     Fri 9       %a %H   Fri Sep 26 09:00:00 EDT 1986
     Feb 10:30   %b %H:%S   Sun Feb 1 10:00:30 EST 1987
     10:30       %H:%M   Tue Sep 23 10:30:00 EDT 1986
     13:30       %H:%M   Mon Sep 22 13:30:00 EDT 1986

     The return value of the function is a pointer to a static variable of type struct tm or a null pointer if an error occurred.  The result in the variable pointed to by the return value is only valid until the next getdate call which makes this function unusable in multi-threaded applications.

     The errno variable is not changed.  Error conditions are signalled using the global variable getdate_err.  See the description above for a list of the possible error values.

     Warning: The getdate function should never be used in SUID-programs.  The reason is obvious: using the DATEMSK environment variable one can get the function to open any arbitrary file and chances are high that with some bogus input (such as a binary file) the program will crash.

 -- Function: int getdate_r (const char *STRING, struct tm *TP)
     The getdate_r function is the reentrant counterpart of getdate.  It does not use the global variable getdate_err to signal the error but instead the return value now is this error code. The same error codes as described in the getdate_err documentation above are used.

     getdate_r also does not store the broken-down time in a static variable.  Instead it takes an second argument which must be a pointer to a variable of type struct tm where the broken-down can be stored.

     This function is not defined in the Unix standard.  Nevertheless it is available on some other Unix systems as well.

     As for getdate the warning for using this function in SUID-programs applies to getdate_r as well.

Specifying the Time Zone with TZ
--------------------------------

In POSIX systems, 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.

You should not normally need to set TZ.  If the system is configured properly, the default time zone will be correct.  You might set TZ if you are using a computer over the network from a different time zone, and would like times reported to you in the time zone that local for you, rather than what is local for the computer.

In POSIX.1 systems the value of the TZ variable can be of one of three formats.  With the GNU C library, the most common format is the last one, which can specify a selection from a large database of time zone information for many regions of the world.  The first two formats are used to describe the time zone information directly, which is both more cumbersome and less precise.  But the POSIX.1 standard only specifies the details of the first two formats, so it is good to be familiar with them in case you come across a POSIX.1 system that doesn't support a time zone information database.

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 23, and the minute and seconds between 0 and 59.

For example, here is how we would specify Eastern Standard Time, but without any daylight saving 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 saving time zone; if the OFFSET is omitted, it defaults to one hour ahead of standard time.

The remainder of the specification describes when daylight saving time is in effect.  The START field is when daylight saving 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 UTC 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/2,M10.5.0/2

The schedule of daylight saving 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, this format 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.  For precise time zone specifications, it is best to use the time zone information database (see below).

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.  In the GNU C library, the default time zone is like the specification TZ=:/etc/localtime (or TZ=:/usr/local/etc/localtime, depending on how GNU C library was configured; see Installation).  Other C libraries use their own rule for choosing the default time zone, so there is little we can say about them.

If CHARACTERS begins with a slash, it is an absolute file name; otherwise the library looks for the file /share/lib/zoneinfo/CHARACTERS.  The zoneinfo directory contains data files describing local time zones in many different parts of the world.  The names represent major cities, with subdirectories for geographical areas; for example, America/New_York, Europe/London, Asia/Hong_Kong. These data files are installed by the system administrator, who also sets /etc/localtime to point to the data file for the local time zone.  The GNU C library comes with a large database of time zone information for most regions of the world, which is maintained by a community of volunteers and put in the public domain.

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

 -- Variable: char * tzname [2]
     The array tzname contains two strings, which are the standard names of the pair of time zones (standard and daylight saving) 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 saving time is in use (for example, "EDT").  These correspond to the STD and DST strings (respectively) from the TZ environment variable.  If daylight saving time is never used, tzname[1] is the empty string.

     The tzname array is initialized from the TZ environment variable whenever tzset, ctime, strftime, mktime, or localtime is called.  If multiple abbreviations have been used (e.g. "EWT" and "EDT" for U.S. Eastern War Time and Eastern Daylight Time), the array contains the most recent abbreviation.

     The tzname array is required for POSIX.1 compatibility, but in GNU programs it is better to use the tm_zone member of the broken-down time structure, since tm_zone reports the correct abbreviation even when it is not the latest one.

     Though the strings are declared as char * the user must stay away from modifying these strings.  Modifying the strings will almost certainly lead to trouble.

 -- 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.  Like tzname, these variables are set by calling tzset or the other time conversion functions.

 -- Variable: long int timezone
     This contains the difference between UTC and the latest local standard time, in seconds west of UTC.  For example, in the U.S. Eastern time zone, the value is 5*60*60.  Unlike the tm_gmtoff member of the broken-down time structure, this value is not adjusted for daylight saving, and its sign is reversed.  In GNU programs it is better to use tm_gmtoff, since it contains the correct offset even when it is not the latest one.

 -- Variable: int daylight
     This variable has a nonzero value if daylight savings time rules apply. A nonzero value does not necessarily mean that daylight savings time is now in effect; it means only that daylight savings time is sometimes in effect.

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

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

          [file strftim.c.texi not included]

It produces output like this:

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

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 valiable 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 numer 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);
          }