我需要找到系统时间,因为在我的 c 代码中对 linux 机器施加了电源。'time()' 和 gettimeofday() 之类的函数返回自纪元以来的时间,而不是自开机以来的时间。如何找到开机后的时间或时钟滴答数?
提前致谢!
此信息通过/proc
文件系统 API 提供。具体来说,/proc/uptime
。在 C 语言中,只需将其作为普通文件打开并从中读取一个浮点数。这将是自开机以来的秒数。如果您读取另一个 FP 值,它将是系统总共花费了多少秒处于空闲状态。不过,您只对第一个数字感兴趣。
例子:
float uptime;
FILE* proc_uptime_file = fopen("/proc/uptime", "r");
fscanf(proc_uptime_file, "%f", &uptime);
该值以秒为单位,浮点数。
您可以将其转换回时钟刻度:
uptime * sysconfig(_SC_CLK_TCK);
请参阅 sysinfo()
系统/系统信息.h
struct sysinfo {
long uptime; /* Seconds since boot */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
unsigned long totalram; /* Total usable main memory size */
unsigned long freeram; /* Available memory size */
unsigned long sharedram; /* Amount of shared memory */
unsigned long bufferram; /* Memory used by buffers */
unsigned long totalswap; /* Total swap space size */
unsigned long freeswap; /* swap space still available */
unsigned short procs; /* Number of current processes */
unsigned long totalhigh; /* Total high memory size */
unsigned long freehigh; /* Available high memory size */
unsigned int mem_unit; /* Memory unit size in bytes */
char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};
如果你想了解 C API,
这个问题可能与What API do I call to get the system uptime 的重复?
如果您想通过 shell 了解正常运行时间,请使用 uptime 命令。
$uptime