擷取linux的CPU,記憶體,磁碟

來源:互聯網
上載者:User

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

結果如下:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.