linux獲取系統(tǒng)啟動(dòng)時(shí)間示例詳解
1、前言
時(shí)間對(duì)操作系統(tǒng)來說非常重要,從內(nèi)核級(jí)到應(yīng)用層,時(shí)間的表達(dá)方式及精度各部相同。linux內(nèi)核里面用一個(gè)名為jiffes的常量來計(jì)算時(shí)間戳。應(yīng)用層有time、getdaytime等函數(shù)。今天需要在應(yīng)用程序獲取系統(tǒng)的啟動(dòng)時(shí)間,百度了一下,通過sysinfo中的uptime可以計(jì)算出系統(tǒng)的啟動(dòng)時(shí)間。
2、sysinfo結(jié)構(gòu)
sysinfo結(jié)構(gòu)保持了系統(tǒng)啟動(dòng)后的信息,主要包括啟動(dòng)到現(xiàn)在的時(shí)間,可用內(nèi)存空間、共享內(nèi)存空間、進(jìn)程的數(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)啟動(dòng)時(shí)間
通過sysinfo獲取系統(tǒng)啟動(dòng)到現(xiàn)在的秒數(shù),用當(dāng)前時(shí)間減去這個(gè)秒數(shù)即系統(tǒng)的啟動(dòng)時(shí)間。程序如下所示:
#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;
}
測(cè)試結(jié)果如下所:
相關(guān)文章
查看某時(shí)間段到現(xiàn)在的系統(tǒng)日志的sed命令
查看某時(shí)間段到現(xiàn)在的系統(tǒng)日志的sed命令,需要的朋友可以參考下2013-02-02查看linux中某個(gè)端口(port)是否被占用的方法
下面小編就為大家?guī)硪黄榭磍inux中某個(gè)端口(port)是否被占用的方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05rhel5.7下安裝gearmand及啟動(dòng)的方法
這篇文章主要介紹了rhel5.7下安裝gearmand及啟動(dòng)的方法,需要的朋友可以參考下2014-07-07詳解shell 遍歷文件夾內(nèi)所有文件并打印絕對(duì)路徑
本篇文章主要介紹了shell 遍歷文件夾內(nèi)所有文件并打印絕對(duì)路徑,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01Linux環(huán)境下tcpdump網(wǎng)絡(luò)協(xié)議抓包與解析
這篇文章主要為大家介紹了Linux環(huán)境下tcpdump網(wǎng)絡(luò)協(xié)議抓包與解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09