手机
当前位置:查字典教程网 >脚本专栏 >linuxshell >linux获取系统启动时间示例详解
linux获取系统启动时间示例详解
摘要:1、前言时间对操作系统来说非常重要,从内核级到应用层,时间的表达方式及精度各部相同。linux内核里面用一个名为jiffes的常量来计算时间...

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>

static int print_system_boot_time()

{

struct sysinfo info;

time_t cur_time = 0;

time_t boot_time = 0;

struct tm *ptm = NULL;

if (sysinfo(&info)) {

fprintf(stderr, "Failed to get sysinfo, errno:%u, reason:%sn",

errno, strerror(errno));

return -1;

}

time(&cur_time);

if (cur_time > info.uptime) {

boot_time = cur_time - info.uptime;

}

else {

boot_time = info.uptime - cur_time;

}

ptm = gmtime(&boot_time);

printf("System boot time: %d-%-d-%d %d:%d:%dn", ptm->tm_year + 1900,

ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);

return 0;

}

int main()

{

if (print_system_boot_time() != 0) {

return -1;

}

return 0;

}

测试结果如下所:

linux获取系统启动时间示例详解1

【linux获取系统启动时间示例详解】相关文章:

linux系统中的列出敏感用户的脚本代码

linux下保留文件系统下剩余指定数目文件的shell脚本

linux shell命令快捷获得系统帮助(一)[man-pages定义规范]

linux链接编译详解

linux系统下hosts文件详解及配置

一天一个shell命令 linux文件操作系列-ln命令详解

linux rsync安装 配置 实例详解

linux shell 字符串操作(长度,查找,替换)详解

Linux下启动tomcat的方法

linux shell命令行选项与参数用法详解

精品推荐
分类导航