Bash script to kill a process if process count is over X amount
So, I was wondering if there was a way to see if one could use bash to kill a PID of a process if more than X amount spawned. For example:
Let's say we have 10 php processes running with separate PIDs all with the command /usr/bin/php. If it hit 10 processes, would there be a way to kill it with a bash script? (I'll be having this script run full time in the foreground with a terminal)
IMHO, you're solving the wrong problem. I'd rather make sure that the process in itself couldn't have more than one instance (here's an implementation checklist), and give instructions by some sort of instruction stack.
Not a good idea to kill stuff this way, but this is what you asked. Try with this one (all on one single line):
j=0; for i in `ps fax | grep '/usr/bin/php' | grep -v grep | awk '{print $1}'`; do let j=j+1; if [ $j -ge 10 ]; then echo "Killing process $i"; kill $i; fi done
Pay attention to what you are doing. HTH.
这对我有效:
#!/bin/bash
#PROGRAM_NAME=/usr/bin/php
PROGRAM_NAME="gedit"
MAX_INSTANCES=2
CURRENT_INSTANCES=0
while true
do
sleep 1
let CURRENT_INSTANCES=`ps aux | grep -c $PROGRAM_NAME`
if [ "$CURRENT_INSTANCES" -ge "$MAX_INSTANCES" ];then
killall $PROGRAM_NAME
echo "killing program!"
exit 0;
fi
done
链接地址: http://www.djcxy.com/p/46410.html
上一篇: #!/ usr / bin / python和#!/ usr / bin / env python,哪些支持?