Linux下用C语言获取IO信息 只获取iostat的CPU信息
代码如下
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <errno.h> #include <sys/param.h> #include <linux/major.h> struct cpu_info { unsigned long long user; unsigned long long system; unsigned long long idle; unsigned long long iowait; }; void mini_iostat() { int linux_ver = 6; FILE* fp=NULL; const char* scan_fmt = NULL; struct cpu_info info; double total; char buffer[1024]; fp = fopen("/proc/diskstats", "r"); if (fp) { linux_ver = 6; } else { fp = fopen("/proc/partitions", "r"); if (fp) linux_ver = 4; } if (fp)fclose(fp); switch (linux_ver) { case 4: scan_fmt = "%4d %4d %*d %*s %u %u %llu %u %u %u %llu %u %*u %u %u"; break; case 6: scan_fmt = "%4d %4d %*s %u %u %llu %u %u %u %llu %u %*u %u %u"; break; } fp = fopen("/proc/stat", "r"); while (fgets(buffer, sizeof(buffer), fp)) { if (!strncmp(buffer, "cpu ", 4)) { int items; unsigned long long nice, irq, softirq; items = sscanf(buffer, "cpu %llu %llu %llu %llu %llu %llu %llu", &info.user, &nice, &info.system, &info.idle, &info.iowait, &irq, &softirq); info.user += nice; if (items == 4) info.iowait = 0; if (items == 7) info.system += irq + softirq; } } fclose(fp); total = (info.user + info.system + info.idle + info.iowait) / 100.0; printf("user=%3.0f system=%3.0f ", info.user / total, info.system / total); if (linux_ver == 6) printf("iowait=%3.0f ", info.iowait / total); printf("idle=%3.0f\n", info.idle / total); } int main(int argc, char** argv) { mini_iostat(); return 0; }
标签:info,fp,iostat,long,简易版,llu,linux,include From: https://www.cnblogs.com/yuandaozhe/p/17028051.html