linux擷取系統啟動時間樣本詳解_linux shell

來源:互聯網
上載者:User

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

測試結果如下所:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.