今天在在学习过程中遇到一个结构体timeval,不是很了解它用法,现在简单的总结一下:
struct timeval
{
time_t tv_sec; /*seconds, 秒*/
SUSEconds tv_usec; /*microseconds, 微秒*/
}
其实从结构体的定义不难看出,这个结构体定义了一个时间的表示方法,这个结构体最为重要的作用就是在套接字选项接口setsockopt(int sockfd, int level, int option, const void *val, socklen_t len)控制中的使用当需要控制利用套接字进行收发数据的时间延迟时,传递的一个参数!
struct timeval tv = {1, 0};
setsockopt(int sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
setsockopt(int sockfd,SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
这样就把我们用recieve和send函数进行数据通信时,时间延迟定义为了1s!
在debian linux的man页中对gettimeofday函数的说明中,有这样一个说明:
DESCRIPTION
The functions gettimeofday and settimeofday can get and set the time as
well as a timezone. The tv argument is a timeval struct, as specified
in <sys/time.h>:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
microsecond 是微秒的意思,简写为usec
毫秒的英语单词是millisecond,简写为msec
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int main(int argc,char * argv[])
{
struct timeval tv;
while(1)
{
gettimeofday(&tv,NULL);
printf("time %u:%u\n",tv.tv_sec,tv.tv_usec);
sleep(2);
}
return 0;
}