linux获取系统启动时间

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:%d\n",
        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:%d\n", 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;
}

测试结果如下所:

文章来源:http://www.cnblogs.com/Anker/p/3527609.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值