对于PHP-FPM多进程的模式,想要避免内存泄漏问题很简单,就是要让PHP-CGI在处理一定数量进程后退出即可。
否则PHP程序或第三方模块(如Imagemagick扩展)导致的内存泄漏问题会导致内存耗尽或不足。
php-fpm.conf中有相关配置: (推荐学习:PHP视频教程)
#请自行按需求配置 pm.max_requests = 1024
实际上还有另一个跟它有关联的值max_children,这个是每次php-fpm会建立多少个进程,这样实际上的内存消耗是max_children*max_requests*每个请求使用内存。
另外一些粗暴的方法包括建立cron kill掉占用内存过多的php-cgi
1.检查php进程的内存占用,杀掉内存使用超额的进程
一般情况下,如果php-cgi进程占用超过1%的内存,就得考虑一下是否要杀掉它了。因为普通情况下,php-cgi进程一般占用0.2%或以下。
这里提供一个脚本供各位使用,就是放在cron任务里,每分钟执行一次。
使用crontab -e 命令,然后添加如下调度任务
* * * * * /bin/bash /usr/local/script/kill_php_cgi.sh
kill_php_cgi.sh脚本如下
* * * * * /bin/bash /usr/local/script/kill_php_cgi.sh kill_php_cgi.sh脚本如下 #!/bin/sh #如果是要杀掉php-fpm的进程,下面的语句中php-cgi请改成php-fpm pids=`ps -ef|grep php-cgi|grep -v "grep"|grep -v "$0"| awk '{print $2}'` if [ "$pids" != "" ];then for pid in $pids; do kill -9 $pid done fi
2.增加内存,将PHP_FCGI_MAX_REQUESTS的值设置成跟你内存总存储量相对应的值
3.优化程序,降低处理每次请求占用的内存大小
如果PHP-FPM能够提供配置子进程内存超过指定大小就被kill,那就省事多了
The above is the detailed content of How to avoid memory leaks when writing timers in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
