0

I need this because my shared hosting plan has a process limit of 25. Whenever there is above 25 process limit, my site gives an error 500.

What I want to do is build a script that would kill all instances of the process /opt/php56/bin/php-cgi if the number of the running process exceeds 20. I build a cron job to run this script every 5 mins.

1 Answer 1

0

As a small shell script:

#!/bin/sh

if [ $(pgrep -cf /opt/php56/bin/php-cgi) -gt 20 ]
then
  pkill -f ./opt/php56/bin/php-cgi
fi

pgrep -c says to count the matching instances; -f says to match the full process name. If there are strictly greater than 20 (adjust that number to taste), then run the corresponding pkill command.

To kill them if the total number of processes is more than 20:

if [ $(ps -e -o pid= | wc -l) -gt 20 ]
then
  pkill -f ./opt/php56/bin/php-cgi
fi

That ps line says to gather all (-e) of the processes, print only the pid field, and use (nothing) as the renamed header for the pid column -- meaning, don't display the "PID" header -- and then count the number of resulting lines (wc -l).

3
  • Thanks, Jeff. But I don't want to count just the process /opt/php56/bin/php-cgi. What I want is if all processes in total exceed 20, the kill all processes named /opt/php56/bin/php-cgi. Commented Aug 10, 2017 at 8:57
  • Hey Jeff, I just used your idea to come up with this. How can you improve it please? if [ $(ps -ef|grep -v grep |awk '{print $2}'|) -gt 20 ] then ps -ef|grep /opt/php56/bin/php-cgi|grep -v grep |awk '{print $2}'|xargs -exec kill fi (The 2nd column has the PID) Commented Aug 10, 2017 at 10:20
  • That's a long way of getting the process listing; consider my edit above.
    – Jeff Schaller
    Commented Aug 10, 2017 at 10:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .