Memory leak refers to the application of memory in the process of running, but after the completion of the use is not released in a timely manner, for ordinary running time of the program may not be so obvious, but for long-running programs, such as Web server, background process is more obvious, As the memory consumed by the system continues to rise, it may crash due to high memory consumption or be killed by the system (OOM).
Memory Leaks in PHP
PHP is a high-level language, language levels do not have the concept of memory, in the use of the process does not need to actively request or release memory, so at the PHP user code level there is no memory leak concept.
If your PHP program memory leaks, or does not release large variables in a timely manner, then the third-party extension itself implementation problems.
Memory leaks caused by php-fpm
Here's a brief talk about how NGINX+PHP-FPM mode works:
Nginx Server fork out N child process (worker), PHP-FPM Manager fork out n child process.
When a user requests, an NGINX worker receives the request and throws the request into the socket.
PHP-FPM The idle child process hears requests in the socket, receives and processes the request.
The third step is to be highlighted here. The third step involves php-fpm the process life cycle. A php-fpm life cycle is roughly like this: module initialization (minit), module activation (rinit), request processing, module deactivation (rshutdown), module activation (rinit), request processing, Module deactivation (rshutdown) .... Module activation (rinit), request processing, module deactivation (rshutdown), modules off (mshutdown). During the life cycle of a php-fpm process, there will be several times the module activation (rinit), request handling, module deactivation (rshutdown) process. This "request processing" The approximate process is this: PHP read the corresponding PHP file, the lexical analysis, generate opcode,zend virtual machine execution opcode.
PHP config file inside the Memory_limit this thing, in fact, it restricts only this "request processing" memory. Therefore, this parameter has nothing to do with the memory that the PHP-FPM process consumes.
So, what is the way to stop this problem?
Php-fpm.conf has a parameter pm.max_requests, equivalent to php_fcgi_max_requests. This value means that an FPM process automatically kills a new process after processing the number of requests.
Debug and tools for memory leaks
Memory leak programs are usually easy to find, because the symptoms are manifested as memory consumption continues to grow, and we need to determine what caused the memory leak when we find that the memory continues to grow, and we often need some tools to help trace, we can use two tools: PHP built-in memory leak detection and Valgrind memory leak analysis.