Home > Backend Development > PHP Problem > What should I do if the cpu is 100% due to php reasons?

What should I do if the cpu is 100% due to php reasons?

藏色散人
Release: 2023-03-17 13:10:01
Original
4399 people have browsed it

php原因导致cpu100%的解决办法:1、找出CPU使用率高的进程PID;2、跟踪进程并修改有可疑的PHP代码;3、配置“PHP-CGI”的进程数;4、通过监控与自动恢复的脚本保证服务的正常运转即可。

What should I do if the cpu is 100% due to php reasons?

本教程操作环境:windows7系统、PHP8.1版、Dell G3电脑。

php原因导致cpu100%怎么办?

PHP-FPM进程CPU 100%的原因及解决方案

近有服务器不时出现的CPU使用率超高,内存几乎被吃光,系统甚至自动kill掉一些进程,如sshd,vsftpd等。用top查看,PHP-CGI进程高挂不下,如下是解决方案:

一、进程跟踪

# top //找出CPU使用率高的进程PID
# strace -p PID //跟踪进程
# ll /proc/PID/fd //查看该进程在处理哪些文件
Copy after login

将有可疑的PHP代码修改之,如:file_get_contents没有设置超时时间。

二、内存分配

如果进程跟踪无法找到问题所在,再从系统方面找原因,会不会有可能内存不够用?据说一个较为干净的PHP-CGI打开大概20M-30M左右的内存,决定于PHP模块开启多少。

通过pmap指令查看PHP-CGI进程的内存使用情况

# pmap $(pgrep php-cgi |head -1)
Copy after login

按输出的结果,结合系统的内存大小,配置PHP-CGI的进程数(max_children)。

三、监控

最后,还可以通过监控与自动恢复的脚本保证服务的正常运转。下面是我用到的一些脚本:

只要一个php-cgi进程占用的内存超过 %1 就把它kill掉

#!/bin/sh
PIDS=`ps aux|grep php-cgi|grep -v grep|awk’{if($4>=1)print $2}’`
for PID in $PIDS
do
echo `date +%F….%T`>>/data/logs/phpkill.log
echo $PID >> /data/logs/phpkill.log
kill -9 $PID
done
Copy after login

检测php-fpm进程

#!/bin/bash
netstat -tnlp | grep “php-cgi” >> /dev/null #2&> /data/logs/php_fasle.log
if [ "$?" -eq "1" ];then #&& [ `netstat -tnlp | grep 9000 | awk '{ print $4}' | awk -F ":" '{print $2}'` -eq "1" ];then
/usr/local/webserver/php/sbin/php-fpm start
echo `date +%F….%T` “System memory OOM.Kill php-cgi. php-fpm service start. ” >> /data/logs/php_monitor.log
fi
Copy after login

通过http检测php执行

#!/bin/bash
status=`curl -s –head “http://127.0.0.1:8080/chk.php” | awk ‘/HTTP/ {print $2}’`
if [ $status != "200" -a $status != "304" ]; then
/usr/local/webserver/php/sbin/php-fpm restart
echo `date +%F….%T` “php-fpm service restart” >> /data/logs/php_monitor.log
fi
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of What should I do if the cpu is 100% due to php reasons?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template