《Linux时间》--------------获取系统时间、设置系统时间、定时器
2016-09-27 23:54
316 查看
一、获取系统时间
函数: time 头文件: time.h 函数原型: time_t time(time_t *timer) |
tm类型,该类型的各数据成员分别表示年月日时分秒。
struct tm *localtime(const time_t *clock); |
struct tm { int tm_sec; /* 秒 – 取值区间为[0,59] */ int tm_min; /* 分 - 取值区间为[0,59] */ int tm_hour; /* 时 - 取值区间为[0,23] */ int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */ int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */ int tm_year; /* 年份,其值等于实际年份减去1900 */ int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */ int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */ int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时, } |
#include<stdio.h> #include<stdlib.h> #include<time.h> int main() { time_t cur_time; struct tm *local_time; //get current time; cur_time = time(NULL); local_time = localtime(&cur_time); printf("current time: Hour = %d Min = %d Sec = %d\n",local_time->tm_hour,local_time->tm_min,local_time->tm_sec); exit(0); }
二、设置系统时间
Linux下通过gettimeofday()获取系统当前的时间及地区信息,其中时间可以达到微秒级;头文件:#include<sys/time.h> 函数原型:int gettimeofday(struct timeval*tv,struct timezone *tz ) |
struct timeval{ long tv_sec; long tv_usec; } struct timezone{ int tz_minuteswest; //和greenwich时间差了多少分钟 int tz_dsttime; } |
头文件:#include<sys/time.h> 函数原型:int settimeofday(struct timeval *tv,struct timezone *tz) |
#include<stdlib.h>
#include<stdio.h>
#include<sys/time.h>
int main()
{
struct timeval curtime;
struct timezone curzone;
gettimeofday(&curtime,&curzone);
printf("current time of sec is %ld, usec is %ld\n",curtime.tv_sec,curtime.tv_usec);
printf("current zone is %d, dsttime is %d\n",curzone.tz_minuteswest,curzone.tz_dsttime);
//settimeofday
curtime.tv_sec +=60;
settimeofday(&curtime,&curzone);
printf("after settimeofday\n");
printf("current time of sec is %ld, usec is %ld\n",curtime.tv_sec,curtime.tv_usec);
printf("current zone is %d, dsttime is %d\n",curzone.tz_minuteswest,curzone.tz_dsttime);
return 0;
}
三、定时器
(1)通过select设置定时器#include <sys/time.h>
#include <sys/select.h>
#include <time.h>
#include <stdio.h>
void setTimer(int seconds, int mseconds)
{
struct timeval temp;
temp.tv_sec = seconds;
temp.tv_usec = mseconds;
select(0, NULL, NULL, NULL, &temp);
printf("Hello World\n");
return ;
}
int main()
{
int i;
for(i = 0 ; i < 100; i++)
setTimer(10, 0);
return 0;
} (2)通过SIGALRM+alarm设置定时器,然而其只能达到秒级别
#include<stdio.h>
#include<signal.h>
void timer(int signal)
{
if(signal == SIGALRM)
{
printf("HelloWorld\n");
alarm(1);
}
return ;
}
int main()
{
signal(SIGALRM,timer);
alarm(1);
getchar();
return 0;
}
相关文章推荐
- Linux 获取系统时间、设置系统时间、定时器
- 【转载】Delphi获取与设置系统时间格式(长日期与短日期)
- 菜鸟自学ARM:linux下编程获取系统时间和设置时间
- 获取设置时间系统调用
- Android TextClock获取系统时间,格式跟随设置改变
- QT获取系统时间,以及设置日期格式
- 菜鸟自学ARM:linux下编程获取系统时间和设置时间
- QT修改、获取系统时间,以及设置日…
- PHP获取系统时间和设置所在时区
- Linux下用C语言设置和获取系统时间
- C#获取北京时间与设置系统时间
- PHP获取系统时间,时区设置问题
- Linux下用C语言设置和获取系统时间
- Delphi获取与设置系统时间格式,即GetLocaleInfo和SetLocaleInfo
- 获取和设置系统时间
- MFC 获取系统时间 和设置时间
- QT获取系统时间以及设置日期格式
- Linux C++ 获取和设置系统时间
- 获取/设置时间的系统调用的几个思考
- 定时器;如何获取系统时间