http://blog.csdn.net/wangjiannuaa/article/details/6585136
#include <stdio.h>#include <stdlib.h>#include <sys/time.h>#include <unistd.h>#include <sys/vfs.h>#include <error.h>#define Gsize (1024.00 * 1024.00 * 1024.00)#define Msize (1024.00 * 1024.00)#ifndef EXT2_SUPER_MAGIC#define EXT2_SUPER_MAGIC 0xef53#endifdouble time_so_far(){struct timeval tp;if (gettimeofday(&tp, (struct timezone*)NULL) == -1)perror("gettimeofday");return ((double)(tp.tv_sec)) + (((double)tp.tv_usec) * 0.000001);}int main(int argc, char **argv){FILE *f1;double ti, tf;char c[10], d[10];int i1, i2, i3, i4, i5, i6;/*cpu information*/ ti = time_so_far();f1 = fopen("/proc/stat", "r");fscanf(f1, "%s\t%d\t%d\t%d\n", c, &i1, &i2, &i3);printf("i1=%d, i2=%d, i3=%d\n", i1, i2, i3);fclose(f1);usleep(1000000);tf = time_so_far();f1 = fopen("/proc/stat", "r");fscanf(f1, "%s\t%d\t%d\t%d\n", c, &i4, &i5, &i6);printf("i4=%d, i5=%d, i6=%d\n", i4, i5, i6);fclose(f1);int t = (i4 + i5 + i6) - (i1 + i2 + i3);printf("cpu usage: %.1f%%\n", (t / ((tf - ti) * 100)) * 100);/*memory information*/f1 = fopen("/proc/meminfo", "r");fscanf(f1, "%s\t%d\t%s", c, &i1, d);printf("mem total: %d\n", i1);fscanf(f1, "%s\t%d\t%s", c, &i1, d);printf("mem free: %d\n", i1);fclose(f1);/*disk information*/long long blocks, bfree;struct statfs fs;if (statfs("/", &fs) < 0){perror("statfs");exit(0);}blocks = fs.f_blocks;bfree = fs.f_bfree;if (fs.f_type == EXT2_SUPER_MAGIC){printf("Total size of / is %f G\n", blocks * fs.f_bsize / Gsize);printf("Free size of / is %f G\n", bfree * fs.f_bsize / Gsize);}return 0;}
結果如下: