自上电以来,Linux获得系统时间 [英] Linux get system time since power on

查看:91
本文介绍了自上电以来,Linux获得系统时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要查找系统时间,因为在我的C代码中,在Linux机器上加电了.诸如"time()"和gettimeofday()之类的函数返回自纪元开始的时间,而不是自上电以来的时间.我如何找到自开机以来的时间或时钟滴答数?

I need to find the system time since power is applied on a linux machine in my c code. Functions like 'time()' and gettimeofday() return the time since epoch and not since power on. How do I find the time or number of clock ticks since power on?

提前谢谢!

推荐答案

此信息是通过/proc 文件系统API提供的.具体来说,/proc/uptime.在C语言中,只需将其作为普通文件打开,然后从中读取一个浮点数即可.这是自开机以来的秒数.如果您读取另一个FP值,则将是系统总共花费了几秒钟的空闲时间.不过,您只对第一个数字感兴趣.

This information is provided through the /proc filesystem API. Specifically, /proc/uptime. In C, just open it as a normal file and read one floating point number from it. It will be the amount of seconds since power on. If you read another FP value, it will be how many seconds the system has spent in total being idle. You're only interested in the first number though.

示例:

float uptime;
FILE* proc_uptime_file = fopen("/proc/uptime", "r");
fscanf(proc_uptime_file, "%f", &uptime);

此值以秒为单位,浮点数.

This value is in seconds, floating point.

您可以将其转换回时钟滴答声:

You can convert it back to clock ticks:

uptime * sysconfig(_SC_CLK_TCK);

这篇关于自上电以来,Linux获得系统时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆