尝试了多种方法, 取得的系统的内存使用量总是和 windows 任务管理器 底部显示的 内存使用有较大差距.
用以下方法可以很接近任务管理器中的值.
由 wmic OS 中取得 FreeSpaceInPagingFiles, SizeStoredInPagingFiles
已用内存即为 SizeStoredInPagingFiles - FreeSpaceInPagingFiles
以下为程序实现
/*
* Author: xiaomu
* Date: 2012/04/11
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *free, *total;
int free_size, total_size;
char *cmd_free = "wmic OS get freespaceinpagingfiles|findstr /v /i \"freespaceinpagingfiles\"|more > free";
char *cmd_total = "wmic OS get SizeStoredInPagingFiles|findstr /v /i \"SizeStoredInPagingFiles\"|more >total";
system(cmd_free);
system(cmd_total);
total = fopen("total", "r");
if(total == NULL)
{
perror("fopen failed");
return -1;
}
free = fopen("free", "r");
if(free == NULL)
{
perror("fopen failed");
return -1;
}
fscanf(free, "%d", &free_size);
fscanf(total, "%d", &total_size);
printf("total: %dm ", total_size/1024);
printf("used: %dm\n", (total_size-free_size)/1024);
fclose(free);
fclose(total);
while(1)
{
system(cmd_free);
free = fopen("free", "r");
if(free == NULL)
{
perror("fopen failed");
return -1;
}
fscanf(free, "%d", &free_size);
printf("total: %dm ", total_size/1024);
printf("used: %dm\n", (total_size-free_size)/1024);
fclose(free);
}
return 0;
}