获取linux的CPU,内存,磁盘

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
#endif

double 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;
}


结果如下:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值