How to avoid memory leaks when writing timers in PHP

(*-*)浩
Release: 2023-02-27 20:00:01
Original
3146 people have browsed it

对于PHP-FPM多进程的模式,想要避免内存泄漏问题很简单,就是要让PHP-CGI在处理一定数量进程后退出即可。

How to avoid memory leaks when writing timers in PHP

否则PHP程序或第三方模块(如Imagemagick扩展)导致的内存泄漏问题会导致内存耗尽或不足。

php-fpm.conf中有相关配置:  (推荐学习:PHP视频教程

#请自行按需求配置
pm.max_requests = 1024
Copy after login

实际上还有另一个跟它有关联的值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
Copy after login

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
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!