面试题答案
一键面试#!/bin/bash
# 定义要监控的内存使用率阈值
high_threshold=80
low_threshold=60
# 定义不重要的两个服务进程名
service1="service1_process_name"
service2="service2_process_name"
while true; do
# 获取当前内存使用率
memory_usage=$(free -h | awk '/Mem:/ {print $3/$2 * 100}' | cut -d '.' -f 1)
if [ "$memory_usage" -ge "$high_threshold" ]; then
# 停止服务进程
echo "内存使用率超过 $high_threshold%,停止服务进程 $service1 和 $service2"
systemctl stop $service1
systemctl stop $service2
elif [ "$memory_usage" -le "$low_threshold" ]; then
# 启动服务进程
echo "内存使用率降到 $low_threshold%以下,启动服务进程 $service1 和 $service2"
systemctl start $service1
systemctl start $service2
fi
# 每5秒检查一次内存使用率
sleep 5
done
-
脚本说明:
- 定义了内存使用率的高低阈值
high_threshold
和low_threshold
。 - 定义了两个不重要的服务进程名
service1
和service2
。 - 在无限循环中,获取当前内存使用率,并与阈值比较。
- 当内存使用率超过高阈值时,停止两个服务进程;当内存使用率降到低阈值以下时,启动两个服务进程。
- 每5秒检查一次内存使用率。
- 定义了内存使用率的高低阈值
-
注意事项:
- 请将
"service1_process_name"
和"service2_process_name"
替换为实际的服务进程名,并且要确保系统使用systemctl
来管理这些服务(如果是其他系统,如SysV init,需要替换为相应的启动/停止命令)。 - 脚本中的
free -h
命令获取的内存信息格式在不同系统可能略有差异,如果出现获取内存使用率不准确的情况,需要根据实际系统进行调整。
- 请将