目录

几种linux获取系统运行时间的方法

几种linux获取系统运行时间的方法

在开发

测试和运维中,获取系统运行时间是一个很重要的参数指标,下面是常用的获取系统时间的方法,以SKYLAB的SKW3000路由模组的运行时间为例进行说明:

一.通过指令获取

获取系统运行时间的指令为uptime,具体操作输出如下:

https://i-blog.csdnimg.cn/direct/9d076ae32e6b4cb2afd7787cc5d2b7a0.png

这个方法在运维中运用,方便直观。但是在开发过程中使用此命令获取系统时间,需要提取字段中的内容,不如通过其他方式获取方便,下面是文件获取的方法。

二.通过文件获取

在linux系统中,文件/proc/time

包含了系统运行总秒数和空闲时间,内容如下图所示,前面为系统运行时间,后面为CPU处于空闲的时间:

https://i-blog.csdnimg.cn/direct/c85b74d80a844f169da99e0d5ffa7055.png

[系统运行总秒数]:系统的运行时间信息,以S为单位,精确到小数点,表示系统从开机到当前时刻所经历的时长,图示为:933370.06;

[空闲时间]:它反映了系统没有进行任何有效工作,CPU处于空闲等待状态的累计时长,图示为:1787850.84。

在开发中,如日志记录等,可以通过读取文件的方式获取系统运行时间。下面是两种通过文件获取系统运行时间的方法。

(1)通过Shell获取系统时间的方法

下面是具体的源码:

#!/bin/sh

uptime_seconds=$(cat /proc/uptime | cut -d. -f1)

days=$((uptime_seconds / (24 * 60 * 60)))
uptime_seconds=$((uptime_seconds % (24 * 60 * 60)))
hours=$((uptime_seconds / (60 * 60)
uptime_seconds=$((uptime_seconds % (60 * 60)))
minutes=$((uptime_seconds / 60))
seconds=$((uptime_seconds % 60))

echo "系统运行时间: $days 天 $hours 小时 $minutes 分钟 $seconds 秒"

运行结果如下:

https://i-blog.csdnimg.cn/direct/e331c1bfc73e43538843d14feba7c804.png

(2)下面是通过C语言获取系统时间的方法

具体源码如下:

#include <stdio.h>
#include <stdlib.h>

void get_run_time(char *time)
{
    FILE *fp;
    double uptime_seconds;
    int days, hours, minutes, seconds;

    // 打开 /proc/uptime 文件
    fp = fopen("/proc/uptime", "r");
    if (fp == NULL) {
        perror("无法打开 /proc/uptime 文件");
        return;
    }

    // 读取系统运行的总秒数
    fscanf(fp, "%lf", &uptime_seconds);
    fclose(fp);

    // 计算天、时、分、秒
    days = (int)uptime_seconds / (24 * 60 * 60);
    uptime_seconds = (int)uptime_seconds % (24 * 60 * 60);
    hours = (int)uptime_seconds / (60 * 60);
    uptime_seconds = (int)uptime_seconds % (60 * 60);
    minutes = (int)uptime_seconds / 60;
    seconds = (int)uptime_seconds % 60;

    if (days > 0) {
        sprintf(time, "%dday%dh%dm%ds", days, hours, minutes, seconds);
    } else if(hours > 0) {
        sprintf(time, "%dh%dm%ds", hours, minutes, seconds);
    } else if(minutes > 0) {
        sprintf(time, "%dm%ds", minutes, seconds);
    } else {
        sprintf(time, "%ds", seconds);
    }
}

int main(void)
{
    char run_time[32] = {0};
    get_run_time(run_time);
    printf("Time:%s\r\n", run_time);
}

运行结果如下:

https://i-blog.csdnimg.cn/direct/15b3f6b87f0346a98d64cf35a367d7db.png