linux下C++获取各种系统信息

本文档介绍如何在Linux环境下使用C++编程获取系统信息,包括CPU、内存、磁盘等详细信息。代码示例来源于开源项目mooon,具体实现可查看该项目的info.cpp源文件。
摘要由CSDN通过智能技术生成

下面是头文件内容,代码是mooon的一部分,对应的CPP文件请直接浏览:http://code.google.com/p/mooon/source/browse/trunk/common_library/src/sys/info.cpp


/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: JianYi, eyjian@qq.com or eyjian@gmail.com
 */
#include <sys/times.h>
#include <sys/sysinfo.h>
#include <sys/resource.h>
#include "sys/info.h"
#include "sys/close_helper.h"
#include "util/string_util.h"
SYS_NAMESPACE_BEGIN

bool CInfo::get_sys_info(sys_info_t& sys_info)
{
    struct sysinfo info;
    if (-1 == sysinfo(&info)) return false;

    sys_info.uptime_second   = info.uptime;
    sys_info.average_load[0] = info.loads[0];
    sys_info.average_load[1] = info.loads[1];
    sys_info.average_load[2] = info.loads[2];
    sys_info.ram_total       = info.totalram;
    sys_info.ram_free        = info.freeram;
    sys_info.ram_shared      = info.sharedram;
    sys_info.ram_buffer      = info.bufferram;
    sys_info.swap_total      = info.totalswap;
    sys_info.swap_free       = info.freeswap;
    sys_info.process_number  = info.procs;
    return true;
}

bool CInfo::get_mem_info(mem_info_t& mem_info)
{
    FILE* fp = fopen("/proc/meminfo", "r");
    if (NULL == fp) return false;
    sys::CloseHelper<FILE*> ch(fp);

    int i = 0;
    int value;
    char name[LINE_MAX];
    char line[LINE_MAX];
        int filed_number = 2;
        int member_number = 7;

    while (fgets(line, sizeof(line)-1, fp))
    {
        if (sscanf(line, "%s%u", name, &value) != filed_number)
            continue;

        if (0 == strcmp(name
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值