程序中獲取linux系統(tǒng)啟動時間方法
1、前言
時間對操作系統(tǒng)來說非常重要,從內(nèi)核級到應(yīng)用層,時間的表達方式及精度各部相同。linux內(nèi)核里面用一個名為jiffes的常量來計算時間戳。應(yīng)用層有time、getdaytime等函數(shù)。今天需要在應(yīng)用程序獲取系統(tǒng)的啟動時間,通過sysinfo中的uptime可以計算出系統(tǒng)的啟動時間。
2、sysinfo結(jié)構(gòu)
sysinfo結(jié)構(gòu)保持了系統(tǒng)啟動后的信息,主要包括啟動到現(xiàn)在的時間,可用內(nèi)存空間、共享內(nèi)存空間、進程的數(shù)目等。man sysinfo得到結(jié)果如下所示:
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)啟動到現(xiàn)在的秒數(shù),用當前時間減去這個秒數(shù)即系統(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;
}
測試結(jié)果如下所:
![]() |
相關(guān)文章
shell編程基礎(chǔ)之認識與學(xué)習(xí)BASH
本文介紹下,shell基礎(chǔ)編程中有關(guān)bash的相關(guān)知識,有需要的朋友參考學(xué)習(xí)下2013-11-11Linux 怎么實現(xiàn)添加FTP用戶并設(shè)置權(quán)限的方法
這篇文章主要介紹了Linux 怎么實現(xiàn)添加FTP用戶并設(shè)置權(quán)限的方法的相關(guān)資料,這里對添加FTP用戶進行了步驟詳解,需要的朋友可以參考下2017-01-01利用Shell腳本循環(huán)讀取文件中每一行的方法詳解
讀取文件是我們在日常工作中經(jīng)常遇到的一個需求,下面這篇文章主要給大家介紹了關(guān)于利用Shell腳本循環(huán)讀取文件中每一行的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)下吧。2017-09-09Shell執(zhí)行/調(diào)用Java/Jar程序例子的實例詳解
這篇文章主要介紹了Shell執(zhí)行/調(diào)用Java/Jar程序例子的實例詳解的相關(guān)資料,這里提供實例幫助大家實現(xiàn)這樣的功能,需要的朋友可以參考下2017-08-08學(xué)習(xí)shell腳本之前的基礎(chǔ)知識[圖文]
在學(xué)習(xí)shell腳本之前,需要你了解很多關(guān)于shell的知識,這些知識是編寫shell腳本的基礎(chǔ),所以希望你能夠熟練的掌握2013-03-03