硬盤
#include <sys/vfs.h> /* 或者 <sys/statfs.h> */
int statfs(const char *path, struct statfs *buf);
int fstatfs(int fd, struct statfs *buf);
參數:
path: 位於需要查詢信息的文件系統的文件路徑名(不是設備名,是掛載點名稱)。
fd: 位於需要查詢信息的文件系統的文件描述詞。
buf:以下結構體的指針變量,用於儲存文件系統相關的信息
struct statfs
{
long f_type; /* 文件系統類型 */
long f_bsize; /* 經過優化的傳輸塊大小 */
long f_blocks; /* 文件系統數據塊總數 */
long f_bfree; /* 可用塊數 */
long f_bavail; /* 非超級用戶可獲取的塊數 */
long f_files; /* 文件結點總數 */
long f_ffree; /* 可用文件結點數 */
fsid_t f_fsid; /* 文件系統標識 */
long f_namelen; /* 文件名的最大長度 */
};
返回說明:
成功執行時,返回0。失敗返回-1,errno被設爲以下的某個值
參考代碼如下:
#include <stdio.h>
#include <sys/vfs.h>
int main()
{
struct statfs sfs;
int i = statfs("/", &sfs);
int percent = (sfs.f_blocks - sfs.f_bfree ) * 100 / (sfs.f_blocks - sfs.f_bfree + sfs.f_bavail) + 1;
printf("/ %ld %ld %ld %d%% /home\n", 4*sfs.f_blocks, 4*(sfs.f_blocks - sfs.f_bfree), 4*sfs.f_bavail, percent);
system("df /");
printf("\n%d\n",percent);
return 0;
}
CPU
這條shell命令下去
top | head -3 | tail -1
%Cpu(s): 3.2 us, 0.0 sy, 0.0 ni, 90.3 id, 6.5 wa, 0.0 hi, 0.0 si, 0.0 st
us | 用戶空間佔用CPU百分比 |
sy | 內核空間佔用CPU百分比 |
ni | 用戶進程空間內改變過優先級的進程佔用CPU百分比 |
id | 空閒CPU百分比 |
wa | 等待輸入輸出的CPU時間百分比 |
hi | 硬中斷(Hardware IRQ)佔用CPU的百分比 |
si | 軟中斷(Software Interrupts)佔用CPU的百分比 |
st | 在虛擬環境中運行時在其他操作系統上花費的時間 |
內存
free -m
源碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/vfs.h>
int main()
{
// memory
double memory_have = 0;
system("sudo free -m | grep Mem > memory.txt");
system("sudo chmod 777 memory.txt");
FILE * fp;
fp = fopen ("memory.txt", "r");
if(fp == NULL)
{
printf("<p>open file:memory.txt error</p>");
return 0;
}
char s1[20] = {};
double total = 0;
double used = 0;
fscanf(fp, "%s %f %f", s1, &total, &used);
fclose(fp);
fp = NULL;
memory_have = 100 - ((100 * used) / total);
// disk
int disk_have = 0;
struct statfs sfs;
int ret = statfs("/", &sfs);
disk_have = (sfs.f_blocks - sfs.f_bfree ) * 100 / (sfs.f_blocks - sfs.f_bfree + sfs.f_bavail) + 1;
// cpu
system("sudo cat /proc/stat | head -1 > cpu.txt");
system("sudo chmod 777 cpu.txt");
fp = fopen ("cpu.txt", "r");
if(fp == NULL)
{
printf("<p>open file:cpu.txt error</p>");
return 0;
}
char str1[20] = {};
int user, nice, system, idle;
fscanf(fp, "%s %d %d %d %d", str1, &user, &nice, &system, &idle);
fclose(fp);
fp = NULL;
double cpu_have = 100 * (user + nice + system) / (user + nice + system + idle);
printf("cpu:%.1f,disk:%d,memory:%.1f", cpu_have, disk_have, memory_have);
return 0;
}