Apache High CPU Usage/Load, Kill the process via Cron script – Linux

For seemingly “unknown” causes, or a bug script, it may happen that the Apache web server it remains somehow “stuck” in an infinite execution loop, while the blocked process can occupy over 90% of the core / processor, which can practically lead to server crashes if all cores have a process locked in a loop where the cores is 100% loaded!

The first solution until finding the cause of these problems is relatively simple and within the reach of anyone, you only have to periodically check the apache processes, and when one of them exceeds 90% load, it will be “killed”!

For linux operating system, here is the solution:

1. Create a killhicpu.sh file in the /home/cfg/ folder (or any other folder you want) with the following content:

top -b -s -n 1 | grep apache2 | awk '{if ($9 > 90) print $1}' | while read line; do sudo kill -9 "$line"; date; echo "-"; done | tee -a /home/cfg/kill.log

In order for the file to be executable, be sure to set its executable attribute:

sudo chmod +x /home/cfg/killhicpu.sh

2. Open linux crontab

sudo crontab -e

3. and add the following command:

*/5 * * * * /home/cfg/killhicpu.sh

4. Resload crontab so that the current command is executed without restarting the system

sudo service cron reload

That was all !

Linux CommandFrom now on, every time an apache process exceeds 90% load, the resource PID is destroyed, and this aspect is checked every 5 minutes.

It is not recommended a too small check interval, because sometimes these processes may have short loading times and it is not advisable to “kill” them prematurely. For those who want, in the killhicpu.sh file you can also check how long the process has been blocked for more precise control!

You can check in log file how many times these processes have been blocked and destroyed by the script, by viewing the contents of the logs in the file: /home/cfg/kill.log

* Attention, this solution only kill the blocked processes based on the PID, not the whole apache process, for this, there is another solution!

byrev Written by:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *