Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 6.10 Time and Date Routines 189


There is also ahostname( 1 )command that can fetch or set the host name. (The
host name is set by the superuser using a similar function,sethostname.) The host
name is normally set at bootstrap time from one of the start-up files invoked by
/etc/rcorinit.

6.10 Time and Date Routines


The basic time service provided by the UNIX kernel counts the number of seconds that
have passed since the Epoch: 00:00:00 January 1, 1970, Coordinated Universal Time
(UTC).InSection 1.10, we said that these seconds arerepresented in atime_tdata
type, and we call themcalendar times.These calendar times represent both the time and
the date. The UNIX System has always differed from other operating systems in (a)
keeping time in UTC instead of the local time, (b) automatically handling conversions,
such as daylight saving time, and (c) keeping the time and date as a single quantity.
Thetimefunction returns the current time and date.

#include <time.h>
time_t time(time_t *calptr);
Returns: value of time if OK,−1 on error

The time value is always returned as the value of the function. If the argument is non-
null, the time value is also stored at the location pointed to bycalptr.
The real-time extensions to POSIX.1 added support for multiple system clocks. In
Version 4 of the Single UNIX Specification, the interfaces used to control these clocks
weremoved from an option group to the base.Aclock is identified by theclockid_t
type. Standardvalues aresummarized in Figure6.8.

Identifier Option Description
CLOCK_REALTIME real system time
CLOCK_MONOTONIC _POSIX_MONOTONIC_CLOCK real system time with no negative jumps
CLOCK_PROCESS_CPUTIME_ID _POSIX_CPUTIME CPU time for calling process
CLOCK_THREAD_CPUTIME_ID _POSIX_THREAD_CPUTIME CPU time for calling thread

Figure 6.8Clock type identifiers

Theclock_gettimefunction can be used to get the time of the specified clock.
The time is returned in a timespec structure, introduced in Section 4.2, which
expresses time values in terms of seconds and nanoseconds.

#include <sys/time.h>
int clock_gettime(clockid_tclock_id,struct timespec *tsp);
Returns: 0 if OK,−1 on error
Free download pdf