Linux内核时钟-2-用户空间接口
一、精度秒级别的函数
1. time()
#include <time.h> time_t time(time_t *tloc); //time_t=long
返回自 Epoch 1970-01-01 00:00:00 +0000 (UTC) 以来的秒数。精度秒,如果参数 tloc 不是NULL,返回值也会存到这个参数中。若失败返回((time_t) -1)并设置errno。
time() 和 stime() 应该属于比较老的系统调用,需要定义 __ARCH_WANT_SYS_TIME 其对应的系统调用才会存在。
2. stime()
#include <time.h> int stime(const time_t *t);
stime() 设置系统对时间和日期的概念。 t 指向的时间以秒为单位,从纪元 1970-01-01 00:00:00 +0000 (UTC) 开始计算的时间。 stime() 只能由超级用户执行,必须要有 CAP_SYS_TIME 权限才能执行成功。
3. sys_gettimeofday()
二、时间转换
1. 相关函数
#include <time.h> char *asctime(const struct tm *tm); char *asctime_r(const struct tm *tm, char *buf); char *ctime(const time_t *timep); char *ctime_r(const time_t *timep, char *buf); struct tm *gmtime(const time_t *timep); struct tm *gmtime_r(const time_t *timep, struct tm *result); struct tm *localtime(const time_t *timep); struct tm *localtime_r(const time_t *timep, struct tm *result); time_t mktime(struct tm *tm);
这些函数主要用来进行时间格式转换。比如 asctime()/asctime_r() 这对函数将 struct tm 格式的时间转换为字符串格式,前者使用函数内的静态buffer,可能随时被后续任何日期相关的函数覆盖。后者需要自己传传入的buffer.
调用 ctime(t) 相当于 asctime(localtime(t)), 它将日历时间 t 转换为字符串如 “Wed Jun 30 21:49:08 1993”.
成功时,gmtime_r() 和 localtime_r() 返回 result 指向的结构的地址。出错时,mktime() 返回值 (time_t) -1。其余函数出错时返回 NULL。并设置设置 errno。
2. 相关结构
struct tm { int tm_sec; /* Seconds (0-60) */ int tm_min; /* Minutes (0-59) */ int tm_hour; /* Hours (0-23) */ int tm_mday; /* Day of the month (1-31) */ int tm_mon; /* Month (0-11) */ int tm_year; /* Year - 1900 */ int tm_wday; /* Day of the week (0-6, Sunday = 0) */ int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */ int tm_isdst; /* Daylight saving time */ };
部分成员简介:
tm_wday: 缩写 Sun、Mon、Tue、Wed、Thu、Fri、Sat。
tm_mon: 缩写 Jan、Feb、Mar、Apr、May、Jun、Jul、Aug、Sep、Oct、Nov、Dec。
tm_isdst: 指示所述时间是否实施夏令时标志。如果夏令时有效,则值为正,如果夏令时无效,则值为零,如果信息不可用,则值为负。
参考:
Linux时间子系统之(三):用户空间接口函数: http://www.wowotech.net/timer_subsystem/timer_subsystem_userspace.html
Linux时间子系统系列文章之目录: http://www.wowotech.net/timer_subsystem/time_subsystem_index.html
posted on 2025-03-22 17:16 Hello-World3 阅读(42) 评论(0) 收藏 举报