结合top命令来监测CPU占用情况并记录占用CPU较多的线程
#!/bin/bash
threshold=80
current_pid=$$
while true; do
top -b -n 1 -o %CPU | tail -n +8 > cpu_usage.txt
high_cpu_threads=$(awk -v th="$threshold" '$9 > th {print $0}' cpu_usage.txt)
if [[ -n "$high_cpu_threads" ]]; then
echo "CPU usage is above $threshold%:"
echo "$high_cpu_threads"
echo "----------------------------------------"
high_cpu_processes=$(echo "$high_cpu_threads" | awk '{print $NF}' | sort | uniq)
for process in $high_cpu_processes; do
if [[ "$(pgrep -f "$process" | grep -v $$)" ]]; then
echo "Process with high CPU usage: $process"
pid=$(pgrep -f "$process" | grep -v $$)
ps -p $pid -o user,pid,ppid,%cpu,%mem,cmd
echo "----------------------------------------"
fi
done
fi
rm cpu_usage.txt
sleep 5
done