Understanding priority
- Nice values: -20 (highest) to 19 (lowest)
- Default: 0
- Root only: Can set negative values
- Higher nice = Lower priority = Less CPU time
Check current nice value
nice
ps -l -p PID
ps -eo pid,ni,comm | grep process-name
Start with nice
nice command
nice -n 10 command
nice --adjustment=10 command
sudo nice -n -20 command
nice -n 19 command
Renice running process
renice -n 10 -p 1234
sudo renice -n 5 -u username
sudo renice -n 5 -g groupname
Common use cases
Background jobs
nice -n 19 ./heavy-computation.sh &
nice -n 15 tar -czf backup.tar.gz /data
Increase priority
sudo renice -n -10 -p $(pgrep important-app)
Batch processing
nice -n 19 for file in *.mp4; do
ffmpeg -i "$file" "converted_$file"
done
Find processes by priority
ps -eo pid,ni,comm --sort=-ni
ps -eo pid,ni,comm | awk '$2 < 0'
ps -eo pid,ni,comm | awk '$2 > 10'
Script with nice
#!/bin/bash
if [ "$(nice)" != "10" ]; then
exec nice -n 10 "$0" "$@"
fi
echo "Running at nice level: $(nice)"
Ionice (I/O priority)
which ionice
ionice -c 3 cp large-file.iso /backup/
nice -n 19 ionice -c 3 dd if=/dev/zero of=test bs=1M count=1000
Priority classes
ionice -c 2 -n 7 command
ionice -c 3 command
sudo ionice -c 1 -n 0 command
Check ionice
ionice -p PID
ps -eo pid,class,ni,comm
Monitoring
watch -n 1 'ps -eo pid,ni,comm --sort=-ni | head -20'
htop
Permanent nice values
Using systemd
[Service]
Nice=10
IOSchedulingClass=idle
Using /etc/security/limits.conf
username hard priority 10
username soft priority 5
CPU affinity (taskset)
taskset -c 0,1 command
taskset -p -c 0,1 PID
taskset -p PID
Combine techniques
nice -n 19 ionice -c 3 taskset -c 0 ./backup.sh
Cgroups (advanced)
sudo cgcreate -g cpu:/lowpri
echo 256 | sudo tee /sys/fs/cgroup/cpu/lowpri/cpu.shares
sudo cgexec -g cpu:lowpri nice -n 19 command
Best practices
nice -n 15 gzip large-file.txt
nice -n 19 ionice -c 3 rsync -av /data /backup
nice -n 10 make -j$(nproc)
sudo renice -n -5 -p $(pgrep postgres)
sudo renice -n -2 -p $(pgrep nginx)
Monitoring script
#!/bin/bash
echo "Top 10 processes by nice value:"
ps -eo pid,ni,pmem,pcpu,comm --sort=-ni | head -11
echo -e "\nHigh priority (nice < 0):"
ps -eo pid,ni,comm | awk '$2 < 0 {print}'
echo -e "\nLow priority (nice > 15):"
ps -eo pid,ni,comm | awk '$2 > 15 {print}'
Permissions
Real-world examples
Video encoding
nice -n 19 ionice -c 3 ffmpeg -i input.mp4 output.mp4
Database vacuum
nice -n 10 ionice -c 2 -n 7 vacuumdb -a
Log rotation
nice -n 15 logrotate /etc/logrotate.conf
Scientific computing
sudo nice -n -10 taskset -c 0-3 ./simulation
Troubleshooting
top -p PID
chrt (Real-time priority)
chrt -p PID
sudo chrt -f -p 50 PID