在某些情况下,你可能需要限制系统上的CPU性能,以确保系统资源的平衡使用。本文介绍如何在CentOS 7上使用systemd服务来实现这一目的。
准备工作
在开始之前,请确保你的系统已经安装了 `cpulimit` 工具。你可以通过以下命令来安装:
sudo yum install cpulimit
编写Shell脚本
首先,创建一个Shell脚本来监视CPU使用情况并限制性能。在root根目录下创建一个名为 `cpu_limit_start.sh` 的文件,并将以下内容复制到文件中:
每分钟检测一次ffmpeg是否在运行,在运行的话就限制cpu性能为300%(3核心)运行,结果会写入当前目录下cpu_limit_log文件夹
#!/bin/bash
# 创建日志文件夹
mkdir -p cpu_limit_log
while true; do
# 获取当前日期
current_date=$(date +"%Y-%m-%d")
# 获取 ffmpeg 进程的 PID
ffmpeg_pid=$(pgrep -f ffmpeg)
# 如果找到了 ffmpeg 进程的 PID
if [ -n "$ffmpeg_pid" ]; then
echo "Found ffmpeg process with PID: $ffmpeg_pid" >> "cpu_limit_log/cpu_limit_$current_date.log"
# 使用 cpulimit 来限制 CPU 使用率
sudo cpulimit -l 300 -p "$ffmpeg_pid" >> "cpu_limit_log/cpu_limit_$current_date.log" 2>&1
else
echo "ffmpeg process not found." >> "cpu_limit_log/cpu_limit_$current_date.log"
fi
# 等待一分钟
sleep 1m
done &
cpu_limit_stop.sh
#!/bin/bash
# 确定要结束的脚本名称
script_name="cpu_limit_start.sh"
# 提示用户输入
read -p "是否要结束 $script_name 脚本?(y/n): " choice
# 检查用户选择
if [ "$choice" = "y" ] || [ "$choice" = "Y" ]; then
# 结束脚本
echo "结束 $script_name 脚本。"
pkill -f "$script_name"
else
echo "未结束 $script_name 脚本。"
fi
确保你的脚本具有执行权限:
chmod +x cpu_limit_start.sh
chmod +x cpu_limit_stop.sh
创建systemd服务单元
创建一个systemd服务单元,让它在系统启动时自动运行 `cpu_limit.sh` 脚本。在 `/etc/systemd/system/` 目录下创建一个名为 `cpu_limit.service` 的文件,并将以下内容复制到文件中:
[Unit]
Description=CPU Limit Service
After=network.target
[Service]
ExecStart=/root/cpu_limit_start.sh
Restart=always
[Install]
WantedBy=multi-user.target
启用并启动服务
启用并启动这个新创建的服务:
sudo systemctl enable cpu_limit.service
sudo systemctl start cpu_limit.service
查看脚本是否运行中
ps aux | grep /root/cpu_limit_start.sh
停止脚本
/root/cpu_limit_stop.sh
现在,你的系统将会自动启动该服务,并在启动后,根据需要限制CPU性能。
通过这种方式,你可以有效地控制系统上的CPU资源使用,确保系统的稳定性和性能平衡。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容