统计Linux系统的内存和CPU使用信息

#include

#include

#include

#include

#include

#include

#include

#include

#include

void get_memory_info(char *buf, long long int *total, long long int *free) {

char path[64] = "/proc/meminfo";

FILE *fp = fopen(path, "r");

if (fp == NULL) {

perror("fopen");

return;

}

 

char line[256];

while (fgets(line, sizeof(line), fp)) {

if (strncmp(line, "MemTotal:", 8) == 0) {

*total = atoll(line + 8);

} else if (strncmp(line, "MemFree:", 7) == 0) {

*free = atoll(line + 7);

} else if (strncmp(line, "Buffers:", 7) == 0) {

*total += atoll(line + 7);

} else if (strncmp(line, "Cached:", 6) == 0) {

*total += atoll(line + 6);

}

}

fclose(fp);

}

void get_cpu_info(char *buf, double *user, double *system, double *idle) {

char path[64] = "/proc/stat";

FILE *fp = fopen(path, "r");

if (fp == NULL) {

perror("fopen");

return;

}

char line[256];

while (fgets(line, sizeof(line), fp)) {

if (strncmp(line, "cpu ", 4) == 0) {

sscanf(line, "cpu %lf %lf %lf", user, system, idle);

break;

}

}

fclose(fp);

}

 

int main() {

long long int total_memory, free_memory;

double user_cpu, system_cpu, idle_cpu;

time_t now;

struct tm *ltm;

char time_buf[32];

char mem_info[128], cpu_info[128];

get_memory_info(mem_info, &total_memory, &free_memory);

get_cpu_info(cpu_info, &user_cpu, &system_cpu, &idle_cpu);

now = time(NULL);

ltm = localtime(&now);

strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", ltm);

printf("Memory usage: %lld MB total / %lld MB free

", total_memory / 1024 / 1024, free_memory / 1024 / 1024);

printf("CPU usage: %.2lf%% user / %.2lf%% system / %.2lf%% idle

", user_cpu * 100, system_cpu * 100, idle_cpu * 100);

printf("Time: %s

", time_buf);

printf("Memory info:%s", mem_info);

printf("CPU info:%s", cpu_info);

return 0;

}

这段代码定义了两个函数get_memory_info和get_cpu_info,分别用于获取内存和CPU使用信息。

 

 

你可能感兴趣的:(Linux,linux)