Bash脚本开发:如何监控CPU使用率以利用空闲时间
Hey there! Since you're new to shell scripting, let's build this CPU monitoring script together—super practical and easy to follow. I get that most online examples only print CPU usage percentages, so we'll focus on the trigger logic you need: firing up a CPU-heavy process when the system is idle.
First, let's break this down into simple, manageable parts:
1. Get Accurate CPU Idle Percentage
We'll use mpstat (part of the sysstat package) because it's far more reliable for scripting than interactive tools like top. If you don't have it installed yet:
- Debian/Ubuntu:
sudo apt install sysstat - RHEL/CentOS:
sudo yum install sysstat
This command grabs the average CPU idle percentage over 1 second, rounded to an integer for easy comparison:
IDLE_PERCENT=$(mpstat 1 1 | awk '/Average/ {print int($12)}')
2. A Simple CPU-Intensive Process
For testing, a basic infinite empty loop works perfectly—it will hog one full CPU core. If you need to load multiple cores, we'll cover that later. Here's the loop:
while true; do :; done
The : is a no-op (no operation) command, so the loop runs nonstop without doing anything else.
3. Full Working Script
This script will monitor CPU idle time, start the CPU-hog process when idle, and kill it once the system is busy again. Tweak the threshold to match your needs!
#!/bin/bash # Set your CPU idle threshold (percent) - adjust this as needed IDLE_THRESHOLD=80 # Infinite loop to keep monitoring while true; do # Get current CPU idle percentage (integer) CURRENT_IDLE=$(mpstat 1 1 | awk '/Average/ {print int($12)}') echo "Current CPU idle: ${CURRENT_IDLE}%" # Check if CPU is idle enough to trigger our process if [ "$CURRENT_IDLE" -gt "$IDLE_THRESHOLD" ]; then echo "CPU is idle - starting CPU load process..." # Start the CPU-hog loop in the background while true; do :; done & # Save the process ID to kill it later LOAD_PID=$! echo "Load process started with PID: $LOAD_PID" # Wait until CPU is no longer idle, then kill the load process while true; do CHECK_IDLE=$(mpstat 1 1 | awk '/Average/ {print int($12)}') if [ "$CHECK_IDLE" -le "$IDLE_THRESHOLD" ]; then echo "CPU is busy again - stopping load process..." kill $LOAD_PID break fi sleep 5 # Check every 5 seconds while waiting done fi # Wait 10 seconds before checking again (adjust this interval if needed) sleep 10 done
4. Customization Tips
- Load multiple CPU cores: If you want to use more than one core, replace the single background loop with a loop that starts multiple processes:
# Start 4 load processes (adjust the number as needed) PIDS=() for i in {1..4}; do while true; do :; done & PIDS+=($!) done # Then kill all of them later: kill "${PIDS[@]}" - Adjust thresholds/check intervals: Tweak
IDLE_THRESHOLD,sleep 10, orsleep 5to match your system's behavior. - Verify column number first: Run
mpstat 1 1manually to confirm the idle percentage column (some systems might use column 13 instead of 12—just adjust theawkcommand if needed).
Save this script as cpu_monitor.sh, make it executable with chmod +x cpu_monitor.sh, and run it with ./cpu_monitor.sh. You can also set it to run at startup if you need it to run continuously!
内容的提问来源于stack exchange,提问作者gizmo

