为什么 PHP 脚本运行的内存限制最小是 2M 呢? memory_limit 参数已经设置为 1M

2020-05-11 10:51:39 +08:00
 ligthdawn

附上脚本

<?php

ini_set('memory_limit', '1M');
file_get_contents("/data/www/elasticsearch-7.4.2-linux-x86_64.tar.gz");

读取的文件 elasticsearch-7.4.2-linux-x86_64.tar.gz 200 多 M

报错信息如下 PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 288783720 bytes)

疑问,为什么设置了脚本运行的内存限制为 1M,但是报错信息是显示 2M 呢

1037 次点击
所在节点    问与答
4 条回复
CodeCodeStudy
2020-05-11 17:34:47 +08:00
PHP 采取“预分配方案”,提前向操作系统申请一个 chunk ( 2M,利用到 hugepage 特性),并且将这 2M 内存切割为不同规格(大小)的若干内存块,当程序申请内存时,直接查找现有的空闲内存块即可

https://segmentfault.com/a/1190000014764790
CodeCodeStudy
2020-05-11 18:18:00 +08:00
https://github.com/php/php-src/blob/master/Zend/zend_alloc.c#L2660

ZEND_API int zend_set_memory_limit(size_t memory_limit)
{
#if ZEND_MM_LIMIT
AG(mm_heap)->limit = (memory_limit >= ZEND_MM_CHUNK_SIZE) ? memory_limit : ZEND_MM_CHUNK_SIZE;
#endif
return SUCCESS;
}

说明 memory_limit 是有最小值限制的
CodeCodeStudy
2020-05-11 18:24:23 +08:00
https://github.com/php/php-src/blob/master/Zend/zend_alloc_sizes.h#L22

#define ZEND_MM_CHUNK_SIZE (2 * 1024 * 1024) /* 2 MB */
ligthdawn
2020-05-12 10:14:48 +08:00
@CodeCodeStudy 谢谢老哥,今天早上刚刚找到类似的文章 https://blog.csdn.net/IT_10/article/details/94768679

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/670454

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX