linux用c语言获取系统启动时长

思路是通过读取/proc/uptime获得系统启动时长。
使用命令cat /proc/uptime
这里写图片描述
通过man proc可以看到如下的信息:
/proc/uptime:This file contains two numbers: the uptime of the system (seconds), and the amount of time spent in idle process (seconds).
第一个是系统的启动时长,第二个是系统的空闲时间。两个的单位都是秒。

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <stdlib.h>

struct timeval timeget(void)
{
    struct timeval now;
    unsigned char  timestr[60] = {0};
    unsigned char  uptimestr[30] = {0};
    unsigned char * dotaddr;
    unsigned long second;
    char error = 0;
    FILE * timefile = NULL;

    timefile = fopen("/proc/uptime", "r");
    if(!timefile)
    {
        printf("[%s:line:%d] error opening '/proc/uptime'",__FILE__,__LINE__);
        error = 1;
        goto out;
    }

    if( (fread(timestr, sizeof(char), 60, timefile)) == 0 )
    {
        printf("[%s:line:%d] read '/proc/uptime' error",__FILE__,__LINE__);
        error = 1;
        goto out;
    }

    dotaddr = strchr(timestr, '.');
    if((dotaddr - timestr + 2) < 30)
        memcpy(uptimestr, timestr, dotaddr - timestr + 2);
    else
    {
        printf("[%s:line:%d] uptime string is too long",__FILE__,__LINE__);
        error = 1;
        goto out;
    }
    uptimestr[dotaddr - timestr + 2] = '\0';

out:
    if(error)
    {
        now.tv_sec  = 0;
        now.tv_usec = 0;
    }
    else
    {
        now.tv_sec  = atol(uptimestr);
        now.tv_usec = 0;
    }

    fclose(timefile);
    return now;
}

int main()
{
    struct timeval uptime;

    uptime = timeget();
    printf("uptime = %lu\n", uptime.tv_sec);
    return 0;
}

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值