Linux C獲取系統開機的運行時間(秒數)

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; 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章