内核定时机制API之current_kernel_time

本文介绍了如何使用current_kernel_time函数来获取当前内核时间的方法。该函数返回的时间是从1970年开始的秒数和纳秒数,并详细解释了其实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

inline struct timespec current_kernel_time(void) 此函数用于返回当前内核时间。该时间是距离1970开始的秒和纳秒.
static inline struct timespec current_kernel_time(void)
{
	#首先得到时间并存在timespec64 类型的now中
	struct timespec64 now = current_kernel_time64();
	#在通过将timespec64 转成timespec然后返回给用户
	return timespec64_to_timespec(now);
}
其中current_kernel_time64 是通过timekeep得到时间
struct timespec64 current_kernel_time64(void)
{
	#指向timekeep的指针
	struct timekeeper *tk = &tk_core.timekeeper;
	struct timespec64 now;
	unsigned long seq;

	do {
		#顺序锁保护,防止在读取时间的同时时间已经跳变
		seq = read_seqcount_begin(&tk_core.seq);
		#通过timekeep中得到时间
		now = tk_xtime(tk);
	} while (read_seqcount_retry(&tk_core.seq, seq));
	#返回给用户时间,这个时间是保存在timespec64 这个结构体中。
	return now;
}

其中timespec64_to_timespec的实现比较简单,简单的成员变量之间赋值
static inline struct timespec timespec64_to_timespec(const struct timespec64 ts64)
{
	struct timespec ret;

	ret.tv_sec = (time_t)ts64.tv_sec;
	ret.tv_nsec = ts64.tv_nsec;
	return ret;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值