linux下的路径:
cpu: /proc/stat
mem: /proc/meminfo
#define _ULL unsigned long long
#define SET_IF_DESIRED(x,y) if(x) *(x) = (y)
static int five_cpu_numbers(_ULL* uret, _ULL* nret, _ULL* sret, _ULL* iret,
_ULL* iowait)
{
static _ULL u = 0, m = 0, s = 0, i = 0, iw = 0;
_ULL user_j, nice_j, sys_j, idle_j, iowait_j = 0;
FILE* fp;
uint16_t byte_read;
char buffer[100];
fp = fopen("/proc/stat", "r");
byte_read = fread(buffer, 1, sizeof(buffer) - 1, fp);
fclose(fp);
if (byte_read == 0 || byte_read == sizeof(buffer))
return -1;
buffer[byte_read] = '\0';
sscanf(buffer, "cpu %Lu %Lu %Lu %Lu %Lu", &user_j, &nice_j,
&sys_j, &idle_j, &iowait_j);
SET_IF_DESIRED(uret, user_j - u);
SET_IF_DESIRED(nret, nice_j - m);
SET_IF_DESIRED(sret, sys_j - s);
/* Idle can go backwards one tick due to kernel calculation issues */
SET_IF_DESIRED(iret, (idle_j > i) ? (idle_j - i) : 0);
SET_IF_DESIRED(iowait, iowait_j - iw);
u = user_j;
m = nice_j;
s = sys_j;
i = idle_j;
iw = iowait_j;
return 0;
}
/*
* get the cpu usage
*/
float get_cpu_used()
{
float cpu_usage;
_ULL user_j, nice_j, sys_j, idle_j, iowait_j = 0;
if (five_cpu_numbers(&user_j, &nice_j, &sys_j, &idle_j, &iowait_j) != 0)
return -1;
usleep(500000);
if (five_cpu_numbers(&user_j, &nice_j, &sys_j, &idle_j, &iowait_j) != 0)
return -1;
usleep(500000);
if (five_cpu_numbers(&user_j, &nice_j, &sys_j, &idle_j, &iowait_j) != 0)
return -1;
cpu_usage = (idle_j * 100.0)
/ (user_j + nice_j + sys_j + idle_j + iowait_j);
if (cpu_usage > 100)
cpu_usage = 100.0;
/* change to useage */
cpu_usage = 100.0 - (cpu_usage);
return cpu_usage;
}
uint32_t get_mem_used()
{
FILE* fd;
int n;
unsigned long mem_total, mem_used_rate, mem_fee;
char buff[256], tmp[20];
fd = fopen("/proc/meminfo", "r");
fgets(buff, sizeof(buff), fd);
sscanf(buff, "%s %lu %s\n", tmp, &mem_total, tmp);
fgets(buff, sizeof(buff), fd);
sscanf(buff, "%s %lu %s\n", tmp, &mem_fee, tmp);
mem_used_rate = mem_total - mem_fee;
mem_used_rate = mem_used_rate * 100 / mem_total;
fclose(fd);
return mem_used_rate;
}
void linux_srv_info()
{
float cpu_usage, cpu_used;
cpu_used = get_cpu_used();
printf("cpu:%.f\n", cpu_used);
printf("mem:%d\n", get_mem_used());
char disk_path[3][10] = { "/","/dev","/var" };
for (int i = 0; i < 3; i++)//根据磁盘路径(free -h 最后一列)来查询磁盘信息
{
char cmd[100] = { 0 };
char name[20] = { 0 };
char total[20] = { 0 };
char used[20] = { 0 };
/*sprintf(cmd, "df -h %s| grep %s| awk '{print $1,$2,$3}'", disk_path[i], disk_path[i]);
FILE* fp = popen(cmd, "r");
int ret = fscanf(fp, "%s %s %s", name, total, used);
pclose(fp);
printf("disk:%s %s %s\n", name, total, used);*/
struct statfs sfs = {0};
int ret = statfs(disk_path[i], &sfs);//路径必须为磁盘的路径,不是磁盘名。df -h最后一个参数
int percent = (sfs.f_blocks - sfs.f_bfree) * 100 / (sfs.f_blocks - sfs.f_bfree + sfs.f_bavail + 1);
printf("disk: %ld %ld %ld %d%% /home\n", 4 * sfs.f_blocks, 4 * (sfs.f_blocks - sfs.f_bfree), 4 * sfs.f_bavail, percent);
}
}