欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

linux獲取系統(tǒng)啟動時間示例詳解

 更新時間:2014年02月10日 09:56:12   作者:  
這篇文章主要介紹了linux獲取系統(tǒng)啟動時間的示例,需要的朋友可以參考下

1、前言

時間對操作系統(tǒng)來說非常重要,從內核級到應用層,時間的表達方式及精度各部相同。linux內核里面用一個名為jiffes的常量來計算時間戳。應用層有time、getdaytime等函數。今天需要在應用程序獲取系統(tǒng)的啟動時間,百度了一下,通過sysinfo中的uptime可以計算出系統(tǒng)的啟動時間。

2、sysinfo結構

sysinfo結構保持了系統(tǒng)啟動后的信息,主要包括啟動到現在的時間,可用內存空間、共享內存空間、進程的數目等。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、獲取系統(tǒng)啟動時間

通過sysinfo獲取系統(tǒng)啟動到現在的秒數,用當前時間減去這個秒數即系統(tǒng)的啟動時間。程序如下所示:

復制代碼 代碼如下:

#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:%s\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;
}

測試結果如下所:

相關文章

最新評論