本文目录导读:

在Linux和macOS系统中,可以通过nice和renice命令来控制进程的优先级,以下是几种常见的方法来通过脚本控制进程优先级:
使用 nice 启动新进程
#!/bin/bash # 以较低优先级运行程序(优先级+10) nice -n 10 ./your_program # 以较高优先级运行程序(优先级-5,需要root权限) nice -n -5 ./your_program
优先级范围:-20(最高)到 19(最低)
使用 renice 调整正在运行的进程
#!/bin/bash
# 通过PID调整优先级
renice -n 10 -p 1234 # 降低PID为1234的进程优先级
# 通过进程名称调整
renice -n 5 -p $(pgrep -f "process_name")
# 批量调整多个进程
for pid in $(pgrep -f "python3 my_script"); do
renice -n 10 -p $pid
done
完整的脚本示例
#!/bin/bash
# 控制进程优先级的脚本
set_priority() {
local process_name="$1"
local priority="$2"
echo "正在设置 $process_name 的优先级为 $priority"
# 查找匹配的进程
pids=$(pgrep -f "$process_name" 2>/dev/null)
if [ -z "$pids" ]; then
echo "未找到进程: $process_name"
return 1
fi
# 调整每个找到的进程
for pid in $pids; do
echo "调整 PID $pid 的优先级"
renice -n "$priority" -p "$pid" 2>/dev/null
if [ $? -eq 0 ]; then
echo "成功调整 PID $pid 的优先级"
else
echo "调整 PID $pid 失败(可能需要root权限)"
fi
done
}
# 使用示例
# 降低所有firefox进程的优先级
set_priority "firefox" 10
# 提高数据库服务优先级(需要root)
set_priority "mysql" -5
# 启动程序并设置优先级
start_with_priority() {
local priority="$1"
shift
nice -n "$priority" "$@"
}
# 示例:以较低优先级运行备份脚本
start_with_priority 10 ./backup_script.sh
监控和管理脚本
#!/bin/bash
# 监控并自动调整高资源消耗进程的优先级
auto_manage_processes() {
local cpu_threshold=50.0 # CPU使用率阈值
while true; do
# 获取CPU使用率最高的进程
top -b -n 1 | awk -v threshold="$cpu_threshold" '
NR>7 && $9>threshold {
system("renice -n 15 -p " $1 " 2>/dev/null")
print "降低优先级: PID " $1 " (" $12 ") 使用CPU: " $9 "%"
}'
sleep 10 # 每10秒检查一次
done
}
# 启动监控(在后台运行)
auto_manage_processes &
系统服务优先级设置
对于需要持久化设置的系统服务,可以创建systemd服务文件:
# /etc/systemd/system/myapp.service [Service] Nice=-5 ExecStart=/path/to/your/app
常用的优先级设置场景
#!/bin/bash # 低优先级任务(后台下载、备份等) nice -n 19 tar -czf backup.tar.gz /data/ # 普通优先级 nice -n 0 ./normal_app # 高优先级任务(交互式应用、实时处理等,需要root) nice -n -10 ./critical_app # 实时优先级(慎用,可能影响系统稳定性) # chrt -r 99 ./real_time_app
注意事项
- 权限要求:提高优先级(负值)通常需要root权限
- 系统影响:设置过高优先级可能影响其他系统进程
- 持久性:
renice设置只对当前运行的进程有效,重启后丢失 - 调度策略:可以使用
chrt命令设置实时调度策略
通过合理使用这些命令和脚本,可以有效管理系统的进程优先级,确保关键任务获得足够的CPU资源。