overcomit_memory :
0 :用户申请内存的时候,系统会判断剩余的内存多少,如果不够的话那么就会失败。
1: 用户申请内存的时候,系统不进行任何检查任务内存足够用,直到使用内存超过可用内存。
2: 用户一次申请的内存大小不允许超过可用内存的大小。
overcommit_ratio:
当 overcomot_memory = 2
时,该参数有效,这个参数决定了系统可用内存的大小。
计算公式: (Physical-RAM-Size)*ratio / 100 +(Swap-Size)
;
本机当前内存使用情况
[[email protected] /]# free -m (M为 单位)
total used free shared buffers cached
Mem: 5792 513 5279 0 40 158
-/+ buffers/cache: 314 5478
Swap: 1983 0 1983
[[email protected] /]#
测试代码:
#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