{/n/'title/': /'C语言获取CPU和内存使用率的函数 - get_cpu_mem_from_top()/',/n/'description/': /'本文详细解析了一个C语言函数get_cpu_mem_from_top(),该函数通过执行top命令并解析输出结果来获取系统CPU和内存使用率。/',/n/'keywords/': /'C语言, CPU使用率, 内存使用率, top命令, 函数, get_cpu_mem_from_top, 代码解析/',/n/'content/': /'///'int get_cpu_mem_from_top()//n{//n//tchar cmdbuf[1024];//n//tchar linebuf[1024];//n//tFILE *fp = NULL;//n//tchar dummy[64], user_str[64], sys_str[64];//n//tchar total_str[64], occupy_str[64], free_str[64];//n//tint i;//n//tchar *p = NULL;//n//tu_int8_t mem_used_percent = 0, cpu_used_percent = 0;//n//n//tsprintf(cmdbuf, ///'top b C n 1|head -8 >%s///', TOP_DAT);//n//tsystem(cmdbuf);//n//n//tfp = fopen(TOP_DAT, ///'r///');//n//tif (fp == NULL)//n//t/tgoto err;//n//n//tfor (i = 0; i < 8; i++) //n//t{//n//t/tif (!fgets(linebuf, sizeof(linebuf), fp))//n//t/t/tbreak;//n//t/t//n//t/tif (strstr(linebuf, ///'CPU///')) //n//t/t{//n//t/t/tif (strstr(linebuf, ///'%///')) //n//t/t/t{//n//t/t/t/t// cpu data is in the same line//n//t/t/t/tsscanf(linebuf, ///'%s %s %s %s %s///', dummy, dummy, user_str, dummy, sys_str);//n//t/t/t}//n//t/t/telse //n//t/t/t{//n//t/t/t/t// cpu data is in a new line//n//t/t/t/tif (!fgets(linebuf, sizeof(linebuf), fp))//n//t/t/t/t/tbreak;//n//t/t/t/t//n//t/t/t/tif (strstr(linebuf, ///'total///')) //n//t/t/t/t/tsscanf(linebuf, ///'%s %s %s %s///', dummy, user_str, dummy, sys_str);//n//t/t/t/telse // error//n//t/t/t/t/tbreak;//n//t/t/t}//n//t/t/t//n//t/t/tp = strchr(user_str, '.');//n//t/t/tif (p) *p = 0;//n//t/t/tp = strchr(sys_str, '.');//n//t/t/tif (p) *p = 0;//n//t/t//n//t/t/tcpu_used_percent = atoi(user_str) + atoi(sys_str);//n//t/t}//n//n//t/tif (strstr(linebuf, ///'Mem///')) //n//t/t{//n//t/t/tsscanf(linebuf, ///'%s %s %s %s %s %s//n///', dummy, total_str, dummy, occupy_str, dummy, free_str);//n//t/t/tp = strchr(total_str, 'k');//n//n//t/t/tif (p) *p = 0;//n//n//t/t/tp = strchr(occupy_str, 'k');//n//t/t/tif (p) *p = 0;//n//n//t/t/tmem_used_percent = atoi(occupy_str)*100/atoi(total_str);//n//t/t}//n//t}//n//t//n//tprintf(///'mem:%d, cpu:%d//n///', mem_used_percent, cpu_used_percent);//n//n//tfclose(fp);//n//n//treturn 0;//nerr://n/treturn -1;//n}//n//n解释代码内容:这段代码是用来从top命令中获取CPU和内存使用情况的函数。具体步骤如下://n//n1. 定义了一些用于存储命令和读取数据的变量,包括cmdbuf、linebuf、fp、dummy、user_str、sys_str、total_str、occupy_str和free_str等。//n2. 使用sprintf函数将top命令输出到一个临时文件中(TOP_DAT)。//n3. 使用system函数执行上述命令。//n4. 使用fopen函数打开临时文件,如果打开失败则跳转到err标签处。//n5. 使用fgets函数逐行读取文件内容,共读取8行。//n6. 查找包含///'CPU///'的行,如果找到了,则根据是否包含///'%///'来判断CPU数据是在同一行还是新的一行。如果是同一行,则使用sscanf函数从该行中解析出用户态和系统态的CPU使用百分比;如果是新的一行,则继续使用fgets函数读取下一行,并根据行中是否包含///'total///'来解析出CPU使用百分比。//n7. 查找包含///'Mem///'的行,如果找到了,则使用sscanf函数从该行中解析出总内存和已使用内存的大小(以KB为单位)。//n8. 将已使用内存除以总内存并乘以100,得到内存使用百分比。//n9. 将CPU使用百分比和内存使用百分比打印出来。//n10. 使用fclose函数关闭文件。//n11. 函数返回0表示成功,返回-1表示出错。//n//n总的来说,这段代码的主要功能就是从top命令的输出中提取出CPU和内存的使用情况,并将其打印出来。/

C语言获取CPU和内存使用率的函数 - get_cpu_mem_from_top()

原文地址: https://www.cveoy.top/t/topic/pYeC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录