我正在使用以下代码来确定我的iOS设备上次重启的时间:
int mib[MIB_SIZE];
size_t size;
struct timeval boottime;
mib[0] = CTL_KERN;
mib[1] = KERN_BOOTTIME;
size = sizeof(boottime);
if (sysctl(mib, MIB_SIZE, &boottime, &size, NULL, 0) != -1) {
return boottime.tv_sec;
}
return 0;
这次我看到一些异常。特别是,我保存了long以及几天和几周后,检查保存的long agains以上代码返回的值。
我不确定,但我想我会看到一些变化。这对我来说没有任何意义。我不会转换为NSDate来防止漂移。我认为启动时间是由内核在启动时记录的,不再进行计算,而是存储起来的。但是,iOS是否可以将启动时间保存为NSDate,从而避免任何固有的漂移问题?
虽然iOS内核是开源的,但可以合理地假设大多数与OSX内核相同,后者是开源的。
内部osfmk/kern/clock.c
有函数:
/*
* clock_get_boottime_nanotime:
*
* Return the boottime, used by sysctl.
*/
void
clock_get_boottime_nanotime(
clock_sec_t *secs,
clock_nsec_t *nanosecs)
{
spl_t s;
s = splclock();
clock_lock();
*secs = (clock_sec_t)clock_boottime;
*nanosecs = 0;
clock_unlock();
splx(s);
}
并clock_boottime
声明为:
static uint64_t clock_boottime; /* Seconds boottime epoch */
最后对该函数的注释表明它确实可以更改:
/*
* clock_set_calendar_microtime:
*
* Sets the current calendar value by
* recalculating the epoch and offset
* from the system clock.
*
* Also adjusts the boottime to keep the
* value consistent, writes the new
* calendar value to the platform clock,
* and sends calendar change notifications.
*/
void
clock_set_calendar_microtime(
clock_sec_t secs,
clock_usec_t microsecs)
{
...
更新以回答来自OP的查询
我不确定clock_set_calendar_microtime()
调用频率,因为我不熟悉内核的内部工作原理。但是,它会调整clock_boottime
值并在clock_bootime
中初始化值clock_initialize_calendar()
,因此我想可以多次调用它。我一直无法找到使用它的任何呼叫:
$ find . -type f -exec grep -l clock_set_calendar_microtime {} \;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句