1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Linux下 C语言获取硬盘 CPU 内存使用率

Linux下 C语言获取硬盘 CPU 内存使用率

时间:2021-10-19 03:19:00

相关推荐

Linux下 C语言获取硬盘 CPU 内存使用率

硬盘

#include <sys/vfs.h> /* 或者 <sys/statfs.h> */

int statfs(const char *path, struct statfs *buf);

int fstatfs(int fd, struct statfs *buf);

参数:

path: 位于需要查询信息的文件系统的文件路径名(不是设备名,是挂载点名称)。

fd: 位于需要查询信息的文件系统的文件描述词。

buf:以下结构体的指针变量,用于储存文件系统相关的信息

struct statfs {long f_type;/* 文件系统类型 */ long f_bsize; /* 经过优化的传输块大小 */ long f_blocks; /* 文件系统数据块总数 */ long f_bfree; /* 可用块数 */ long f_bavail; /* 非超级用户可获取的块数 */ long f_files; /* 文件结点总数 */ long f_ffree; /* 可用文件结点数 */ fsid_t f_fsid;/* 文件系统标识 */ long f_namelen; /* 文件名的最大长度 */ };

返回说明:

成功执行时,返回0。失败返回-1,errno被设为以下的某个值

参考代码如下:

#include <stdio.h>#include <sys/vfs.h>int main(){struct statfs sfs;int i = statfs("/", &sfs);int percent = (sfs.f_blocks - sfs.f_bfree ) * 100 / (sfs.f_blocks - sfs.f_bfree + sfs.f_bavail) + 1;printf("/ %ld %ld %ld %d%% /home\n", 4*sfs.f_blocks, 4*(sfs.f_blocks - sfs.f_bfree), 4*sfs.f_bavail, percent);system("df /");printf("\n%d\n",percent);return 0;}

CPU

这条shell命令下去

top | head -3 | tail -1

%Cpu(s): 3.2 us, 0.0 sy, 0.0 ni, 90.3 id, 6.5 wa, 0.0 hi, 0.0 si, 0.0 st

内存

free -m

源码

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/vfs.h>int main(){// memorydouble memory_have = 0;system("sudo free -m | grep Mem > memory.txt");system("sudo chmod 777 memory.txt");FILE * fp;fp = fopen ("memory.txt", "r");if(fp == NULL){printf("<p>open file:memory.txt error</p>");return 0;}char s1[20] = {};double total = 0;double used = 0;fscanf(fp, "%s %f %f", s1, &total, &used);fclose(fp);fp = NULL;memory_have = 100 - ((100 * used) / total);// diskint disk_have = 0;struct statfs sfs;int ret = statfs("/", &sfs);disk_have = (sfs.f_blocks - sfs.f_bfree ) * 100 / (sfs.f_blocks - sfs.f_bfree + sfs.f_bavail) + 1;// cpusystem("sudo cat /proc/stat | head -1 > cpu.txt");system("sudo chmod 777 cpu.txt");fp = fopen ("cpu.txt", "r");if(fp == NULL){printf("<p>open file:cpu.txt error</p>");return 0;}char str1[20] = {};int user, nice, system, idle;fscanf(fp, "%s %d %d %d %d", str1, &user, &nice, &system, &idle);fclose(fp);fp = NULL;double cpu_have = 100 * (user + nice + system) / (user + nice + system + idle);printf("cpu:%.1f,disk:%d,memory:%.1f", cpu_have, disk_have, memory_have);return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。