overcomit_memory :
0 :用户申请内存的时候,系统会判断剩余的内存多少,如果不够的话那么就会失败。
1: 用户申请内存的时候,系统不进行任何检查任务内存足够用,直到使用内存超过可用内存。
2: 用户一次申请的内存大小不允许超过可用内存的大小。
overcommit_ratio:
当 overcomit_memory= 2时,该参数有效,这个参数决定了系统可用内存的大小。
计算公式: (Physical-RAM-Size)*ratio / 100 +(Swap-Size) ;
(Physical-RAM-Size)= Men 行的 total :5792
ratiao = 99 (仅当 overcomit_memory =2)
(Swap-Size) = Swap 行的 total : 1983
得: (5792*99/100)+ 1983 = 7123M
本机当前内存使用情况
[root@localhost /]# free -m (M为 单位)
total used free shared buffers cached
Mem: 5792 513 5279 0 40 158
-/+ buffers/cache: 314 5478
Swap: 1983 0 1983
[root@localhost /]#
测试代码:
#include<stdio.h>
#include<stdlib.h>
size_t max_num = 0;
int main(int argc, char **argv)
{
void *block;
void *tmp_block;
size_t block_size[] = {1024*1024, 1024, 1};
int i=0;
int count;
for(i=0; i<3; i++)
{
for(count = 1; ;count ++)
{
block = malloc(max_num + block_size[i]*count);
if(block)
{
tmp_block = block;
max_num += block_size[i]*count;
printf("max_num current malloc size =%lf GB\n",max_num*1.0/1024.0/1024.0/1024.0);
free(block);
}
else
{
break;
}
}
}
printf("max_num malloc size = %lf GB\n", max_num*1.0/1024.0/1024.0/1024.0);
printf("the address is %x \n",tmp_block);
printf("the address end is %x\n", tmp_block + max_num);
while(1);
}
情况 ①
overcomot_memory = 0,vm.overcommit_ratio = 50 =》max_num malloc size = 7.137890GB
情况②
overcomot_memory = 2 ,vm.overcommit_ratio = 50 =》max_num malloc size = 3.958923GB
情况③
overcomot_memory = 2 ,vm.overcommit_ratio = 99 =》 max_nummalloc size = 6.722099 GB