#### 22.5.2 Setting and Adjusting the Time ¶

The clock hardware inside a modern computer is quite reliable, but it can still be wrong. The functions in this section allow one to set the system’s idea of the current calendar time, and to adjust the rate at which the system counts seconds, so that the calendar time will both be accurate, and remain accurate.

The functions in this section require special privileges to use. See Users and Groups.

Function: `int` clock_settime `(clockid_t clock, const struct timespec *ts)` ¶

  Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

  Change the current calendar time, according to the clock identified by clock, to be the simple calendar time in `*ts`.

  Not all of the system’s clocks can be changed. For instance, the `CLOCK_REALTIME` clock can be changed (with the appropriate privileges), but the `CLOCK_MONOTONIC` clock cannot.

  Because simple calendar times are independent of time zone, this function should not be used when the time zone changes (e.g. if the computer is physically moved from one zone to another). Instead, use the facilities described in State Variables for Time Zones.

  `clock_settime` causes the clock to jump forwards or backwards, which can cause a variety of problems. Changing the `CLOCK_REALTIME` clock with `clock_settime` does not affect when timers expire (see Setting an Alarm) or when sleeping processes wake up (see Sleeping), which avoids some of the problems. Still, for small changes made while the system is running, it is better to use `ntp_adjtime` (below) to make a smooth transition from one time to another.

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

  `EINVAL`

    The clock identified by clock is not supported or cannot be set at all, or the simple calendar time in `*ts` is invalid (for instance, `ts->tv_nsec` is negative or greater than 999,999,999).

  `EPERM`

    This process does not have the privileges required to set the clock identified by clock.

  Portability Note: On some systems, including systems that use older versions of the GNU C Library, programs that use `clock_settime` must be linked with the `-lrt` library. This has not been necessary with the GNU C Library since version 2.17.

For systems that remain up and running for long periods, it is not enough to set the time once; one should also discipline the clock so that it does not drift away from the true calendar time.

The `ntp_gettime` and `ntp_adjtime` functions provide an interface to monitor and discipline the system clock. For example, you can fine-tune the rate at which the clock “ticks,” and make small adjustments to the current reported calendar time smoothly, by temporarily speeding up or slowing down the clock.

These functions’ names begin with ‘`ntp_`’ because they were designed for use by programs implementing the Network Time Protocol to synchronize a system’s clock with other systems’ clocks and/or with external high-precision clock hardware.

These functions, and the constants and structures they use, are declared in `sys/timex.h`.

Data Type: struct ntptimeval ¶

  This structure is used to report information about the system clock. It contains the following members:

  `struct timeval time`

    The current calendar time, as if retrieved by `gettimeofday`. The `struct timeval` data type is described in Time Types.

  `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 system clock from the true calendar time.

Function: `int` ntp_gettime `(struct ntptimeval *tptr)` ¶

  Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

  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, an `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 the system clock. 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 system clock from the true calendar 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 calendar time and the system clock. The value is expressed as scaled PPM (parts per million, 0.0001%). The scaling is `1 << SHIFT_USEC`. The value can be set with bit `MOD_FREQUENCY`, but the absolute value must not exceed `MAXFREQ`.

  `long int maxerror`

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

  `long int esterror`

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

  `int status`

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

  `long int constant`

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

  `long int precision`

    This value represents the accuracy or the maximum error when reading the system clock. The value is expressed in microseconds.

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

  `struct timeval time`

    The current calendar time.

  `long int tick`

    The elapsed time between clock ticks in microseconds. A clock tick is a periodic timer interrupt on which the system clock is based.

  `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 system clock. The value is expressed in scaled PPM and it denotes the difference in frequency between the system clock and the PPS signal.

  `long int jitter`

    This value expresses a median filtered average of the PPS signal’s dispersion in microseconds.

  `int shift`

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

  `long int stabil`

    This value represents the median filtered dispersion of the PPS frequency in scaled PPM.

  `long int jitcnt`

    This counter represents the number of pulses where the jitter exceeded the allowed maximum `MAXTIME`.

  `long int calcnt`

    This counter reflects the number of successful calibration intervals.

  `long int errcnt`

    This counter represents the number of calibration errors (caused by large offsets or jitter).

  `long int stbcnt`

    This counter denotes the number of calibrations where the stability exceeded the threshold.

Function: `int` ntp_adjtime `(struct timex *tptr)` ¶

  Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

  The `ntp_adjtime` function sets the structure specified by tptr to current values.

  In addition, `ntp_adjtime` updates some settings to match what you pass to it in `*tptr`. Use the `modes` element of `*tptr` to select what settings to update. You can set `offset`, `freq`, `maxerror`, `esterror`, `status`, `constant`, and `tick`.

  `modes` = zero means set nothing.

  Only the superuser can update settings.

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

  `EPERM`

    The process specified a settings update, but is not superuser.

  For more details see RFC 5905 (Network Time Protocol, Version 4) and related documents.

  Portability note: Early versions of the GNU C Library did not have this function, but did have the synonymous `adjtimex`.

Function: `int` adjtime `(const struct timeval *delta, struct timeval *olddelta)` ¶

  Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

  This simpler version of `ntp_adjtime` speeds up or slows down the system clock for a short time, in order to correct it by a small amount. This avoids a discontinuous change in the calendar time reported by the `CLOCK_REALTIME` clock, at the price of having to wait longer for the time to become correct.

  The delta argument specifies a relative adjustment to be made to the clock time. If negative, the system clock is slowed down for a while until it has lost this much elapsed time. If positive, the system clock is sped 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.

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

  `EPERM`

    This process does not have the privileges required to adjust the `CLOCK_REALTIME` clock.

For compatibility, the GNU C Library also provides several older functions for controlling the system time. New programs should prefer to use the functions above.

Function: `int` stime `(const time_t *newtime)` ¶

  Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

  Change the `CLOCK_REALTIME` calendar time to be the simple calendar time in `*newtime`. Calling this function is exactly the same as calling ‘`clock_settime (CLOCK_REALTIME)`’, except that the new time can only be set to a precision of one second.

  This function is no longer available on GNU systems, but it may be the only way to set the time on very old Unix systems, so we continue to document it. If it is available, it is declared in `time.h`.

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

  `EPERM`

    This process does not have the privileges required to adjust the `CLOCK_REALTIME` clock.

Function: `int` adjtimex `(struct timex *timex)` ¶

  Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

  `adjtimex` is an older name for `ntp_adjtime`. This function is only available on GNU/Linux systems. It is declared in `sys/timex.h`.

Function: `int` settimeofday `(const struct timeval *tp, const void *tzp)` ¶

  Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

  Change the `CLOCK_REALTIME` calendar time to be the simple calendar time in `*newtime`. This function is declared in `sys/time.h`.

  When tzp is a null pointer, calling this function is exactly the same as calling ‘`clock_settime (CLOCK_REALTIME)`’, except that the new time can only be set to a precision of one microsecond.

  When tzp is not a null pointer, the data it points to may be used to set a system-wide idea of the current time zone. This feature is obsolete and not supported on GNU systems. Instead, use the facilities described in State Variables for Time Zones and in Broken-down Time for working with time zones.

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

  `EPERM`

    This process does not have the privileges required to set the `CLOCK_REALTIME` clock.

  `EINVAL`

    Neither tp nor tzp is a null pointer. (For historical reasons, it is not possible to set the current time and the current time zone in the same call.)

  `ENOSYS`

    The operating system does not support setting time zone information, and tzp is not a null pointer.