我写了一个简单的应用程序来测试内存消耗。在这个测试应用程序中,我创建了四个进程来持续消耗内存,除非进程退出,否则这些进程不会释放内存。
我预计这个测试应用程序会消耗最多的 RAM 内存并导致其他应用程序变慢或崩溃。但是结果和预想的不一样。下面是代码:
#include <stdio.h>
#include <unistd.h>
#include <list>
#include <vector>
using namespace std;
unsigned short calcrc(unsigned char *ptr, int count)
{
unsigned short crc;
unsigned char i;
//high cpu-consumption code
//implements the CRC algorithm
//CRC is Cyclic Redundancy Code
}
void* ForkChild(void* param){
vector<unsigned char*> MemoryVector;
pid_t PID = fork();
if (PID > 0){
const int TEN_MEGA = 10 * 10 * 1024 * 1024;
unsigned char* buffer = NULL;
while(1){
buffer = NULL;
buffer = new unsigned char [TEN_MEGA];
if (buffer){
try{
calcrc(buffer, TEN_MEGA);
MemoryVector.push_back(buffer);
} catch(...){
printf("An error was throwed, but caught by our app!\n");
delete [] buffer;
buffer = NULL;
}
}
else{
printf("no memory to allocate!\n");
try{
if (MemoryVector.size()){
buffer = MemoryVector[0];
calcrc(buffer, TEN_MEGA);
buffer = NULL;
} else {
printf("no memory ever allocated for this Process!\n");
continue;
}
} catch(...){
printf("An error was throwed -- branch 2,"
"but caught by our app!\n");
buffer = NULL;
}
}
} //while(1)
} else if (PID == 0){
} else {
perror("fork error");
}
return NULL;
}
int main(){
int children = 4;
while(--children >= 0){
ForkChild(NULL);
};
while(1) sleep(1);
printf("exiting main process\n");
return 0;
}
顶部命令
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 2775 steve 20 0 1503m 508 312 R 99.5 0.0 1:00.46 test 2777 steve 20 0 1503m 508 312 R 96.9 0.0 1:00.54 test 2774 steve 20 0 1503m 904 708 R 96.6 0.0 0:59.92 test 2776 steve 20 0 1503m 508 312 R 96.2 0.0 1:00.57 test
虽然 CPU 很高,但内存百分比仍然为 0.0。怎么可能??
自由命令
free shared buffers cached Mem: 3083796 0 55996 428296
可用内存超过 4G RAM 中的 3G。
有谁知道为什么这个测试应用程序不能按预期工作?