The use of settimeofday function and gettimeofday function in C language

  • 2020-04-02 03:16:22
  • OfStack

C settimeofday() function: sets the current timestamp
The header file:


#include <sys/time.h>  #include <unistd.h>

Definition function:


int settimeofday(const struct timeval *tv, const struct timezone *tz);

Settimeofday () sets the current time to the structure information referred to by TV, and the local time zone information to the structure referred to by tz. Refer to gettimeofday() for detailed instructions.

Note that under Linux, only root permission can use this function to change the time.

Return value: 0 on success, -1 on failure, error code in errno.

Error code:
EPERM   Not called settimeofday() by root, not enough.
EINVAL   The time zone or certain data is incorrect and the time cannot be set correctly.

C gettimeofday() function: gets the current time
The header file:


#include <sys/time.h>  #include <unistd.h>

Function: int gettimeofday (struct timeval * TV, struct timezone * tz);

Gettimeofday () returns the current time to the tv-referential structure, and the local time zone information to the tz referential structure.

The timeval structure is defined as:


struct timeval{
  long tv_sec; //seconds
  long tv_usec; // micro seconds
};

Timezone structure is defined as:


struct timezone
{
  int tz_minuteswest; //How many minutes is the Greenwich time
  int tz_dsttime; //The state of daylight saving time
};

Both structures are defined in /usr/include/sys/time.h. tz_dsttime as follows


  DST_NONE //Do not use
  DST_USA //The United States
  DST_AUST //Australia
  DST_WET //In Western Europe
  DST_MET //China and the eu
  DST_EET //Eastern Europe,
  DST_CAN //Canada
  DST_GB //Great Britain
  DST_RUM //Romania
  DST_TUR //Turkey
  DST_AUSTALT //Australia(1986  Years later )

Return value: 0 on success, -1 on failure, error code in errno.

Note: EFAULT pointer TV and tz refer to memory space that exceeds access.

sample


#include <sys/time.h>
#include <unistd.h>
main(){
  struct timeval tv;
  struct timezone tz;
  gettimeofday (&tv, &tz);
  printf("tv_sec; %dn", tv.tv_sec);
  printf("tv_usec; %dn", tv.tv_usec);
  printf("tz_minuteswest; %dn", tz.tz_minuteswest);
  printf("tz_dsttime, %dn", tz.tz_dsttime);
}

Execution results:


tv_sec: 974857339
tv_usec:136996
tz_minuteswest:-540
tz_dsttime:0


Related articles: