admin管理员组文章数量:1539849
1、前言
时间对操作系统来说非常重要,从内核级到应用层,时间的表达方式及精度各部相同。linux内核里面用一个名为jiffes的常量来计算时间戳。应用层有time、getdaytime等函数。今天需要在应用程序获取系统的启动时间,百度了一下,通过sysinfo中的uptime可以计算出系统的启动时间。
2、sysinfo结构
sysinfo结构保持了系统启动后的信息,主要包括启动到现在的时间,可用内存空间、共享内存空间、进程的数目等。man sysinfo得到结果如下所示:
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 */
char _f[22]; /* Pads structure to 64 bytes */
};
3、获取系统启动时间
通过sysinfo获取系统启动到现在的秒数;
#include <stdio.h>
#include <sys/sysinfo.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
struct sysinfo info;
char run_time[128];
if (sysinfo(&info)) {
fprintf(stderr, "Failed to get sysinfo, errno:%u, reason:%s\n",errno, strerror(errno));
return -1;
}
long timenum=info.uptime;
int runday=timenum/86400;
int runhour=(timenum%86400)/3600;
int runmin=(timenum%3600)/60;
int runsec=timenum%60;
bzero(run_time, 128);
sprintf(run_time,"系统开机已运行:%d天%d时%d分%d秒",runday,runhour,runmin,runsec);
printf("--->%s\n",run_time);
return 0;
}
版权声明:本文标题:Linux C获取系统开机的运行时间(秒数) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1725680800a1036268.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论