Linux 获取内存和CPU使用率

#ifndef _SYS_FUNC_H_
#define _SYS_FUNC_H_

int GetMemInfo(int *pTotal, int *pUsed);

int GetCpuUsedRate(int *pValue);

#endif
#include "sys_func.h"
#include <stdio.h>
#include<unistd.h>
#include <string.h>
#include <stdlib.h>

typedef struct //定义一个cpu occupy的结构体
{
    char name[20];       //定义一个char类型的数组名name有20个元素
    unsigned int user;   //定义一个无符号的int类型的user
    unsigned int nice;   //定义一个无符号的int类型的nice
    unsigned int system; //定义一个无符号的int类型的system
    unsigned int idle;   //定义一个无符号的int类型的idle
} CPU_OCCUPY;

typedef struct //定义一个mem occupy的结构体
{
    char name[20]; //定义一个char类型的数组名name有20个元素
    unsigned long total;
    char name2[20];
    unsigned long free;
} MEM_OCCUPY;


int cal_cpuoccupy (CPU_OCCUPY *o, CPU_OCCUPY *n) 
{   
    unsigned long od, nd;    
    unsigned long id, sd;
    int cpu_use = 0;   
    
    od = (unsigned long) (o->user + o->nice + o->system +o->idle);//第一次(用户+优先级+系统+空闲)的时间再赋给od
    nd = (unsigned long) (n->user + n->nice + n->system +n->idle);//第二次(用户+优先级+系统+空闲)的时间再赋给od
      
    id = (unsigned long) (n->user - o->user);    //用户第一次和第二次的时间之差再赋给id
    sd = (unsigned long) (n->system - o->system);//系统第一次和第二次的时间之差再赋给sd
    if((nd-od) != 0)
    cpu_use = (int)((sd+id)*10000)/(nd-od); //((用户+系统)乖100)除(第一次和第二次的时间差)再赋给g_cpu_used
    else cpu_use = 0;
    //printf("cpu: %u\n",cpu_use);
    return cpu_use;
}

void get_cpuoccupy (CPU_OCCUPY *cpust) //对无类型get函数含有一个形参结构体类弄的指针O
{   
    FILE *fd;         
    int n;            
    char buff[256]; 
    CPU_OCCUPY *cpu_occupy;
    cpu_occupy=cpust;
                                                                                                              
    fd = fopen ("/proc/stat", "r"); 
    fgets (buff, sizeof(buff), fd);
    
    sscanf (buff, "%s %u %u %u %u", cpu_occupy->name, &cpu_occupy->user, &cpu_occupy->nice,&cpu_occupy->system, &cpu_occupy->idle);
    
    fclose(fd);     
}

int GetCpuUsedRate(int *pValue)
{
    if (NULL == pValue)
    {
        return -1;
    }
    CPU_OCCUPY cpu_stat1;
    CPU_OCCUPY cpu_stat2;
    //第一次获取cpu使用情况
    get_cpuoccupy((CPU_OCCUPY *)&cpu_stat1);
    usleep(100*1000);
    //第二次获取cpu使用情况
    get_cpuoccupy((CPU_OCCUPY *)&cpu_stat2);
    //计算cpu使用率
    int cpu = cal_cpuoccupy ((CPU_OCCUPY *)&cpu_stat1, (CPU_OCCUPY *)&cpu_stat2);
    *pValue = cpu;

    printf("===========CPU RATE:%d====\n", *pValue);

    return 0;
}
    
int GetMemInfo(int *pTotal, int *pUsed)
{
    if (NULL == pTotal || NULL == pUsed)
    {
        return -1;
    }
    char str[81] = {0};
    FILE *fp;
    memset(str, 0, sizeof(str));
    fp = popen("cat /proc/meminfo | grep MemTotal | awk '{print $2}'", "r");
    if (fp == NULL)
    {
        printf("获取系统mem信息失败!\n");
        return -1;
    }
    fgets(str, 80, fp);
    fclose(fp);
    printf("GetMemorySize str = %s\n", str);
    int nTotalSize = atoi(str)/1024;
    printf("mem size = %d MByte\n", nTotalSize);
    *pTotal = nTotalSize;

    memset(str, 0, sizeof(str));
    fp = popen("cat /proc/meminfo | grep MemAvailable | awk '{print $2}'", "r");
    if (fp == NULL)
    {
        printf("获取系统mem信息失败!\n");
        return -1;
    }
    fgets(str, 80, fp);
    fclose(fp);
    int nAvailbleSize = atoi(str)/1024;
    printf("mem nAvailbleSize size = %d MByte\n", nAvailbleSize);
    *pTotal = nTotalSize;
    *pUsed = nTotalSize - nAvailbleSize;

    printf("====pTotal:%d pFree:%d====\n", *pTotal, *pUsed);
    return 0;
}
   

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用Java的Runtime类和Process类来获取Linux服务器的CPU内存使用率。具体实现方法如下: 1. 获取CPU使用率: ```java public static double getCpuUsage() { try { Process process = Runtime.getRuntime().exec("top -b -n1"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); while (line != null) { if (line.startsWith("Cpu(s)")) { String[] cpuInfo = line.split("\\s+"); double idleCpuUsage = Double.parseDouble(cpuInfo[4]); double totalCpuUsage = 100 - idleCpuUsage; return totalCpuUsage; } line = reader.readLine(); } } catch (IOException e) { e.printStackTrace(); } return 0; } ``` 2. 获取内存使用率: ```java public static double getMemoryUsage() { try { Process process = Runtime.getRuntime().exec("free -m"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); if (line != null) { String[] memoryInfo = line.split("\\s+"); double totalMemory = Double.parseDouble(memoryInfo[1]); double usedMemory = Double.parseDouble(memoryInfo[2]); double memoryUsage = usedMemory / totalMemory * 100; return memoryUsage; } } catch (IOException e) { e.printStackTrace(); } return 0; } ``` 以上代码通过执行Linux命令获取CPU内存使用率,并返回一个double类型的数值,表示使用率的百分比。需要注意的是,这些命令的输出格式可能会因Linux版本而异,需要根据实际情况进行调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值