MST
星途 面试题库

面试题:Bash环境下复杂条件判断与进程控制

假设有多个服务进程(通过进程名识别),编写一个Bash脚本,当系统内存使用率超过80%时,停止其中不重要的两个服务进程,并在内存使用率降到60%以下时重新启动这两个服务进程。
43.3万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/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
  1. 脚本说明

    • 定义了内存使用率的高低阈值 high_thresholdlow_threshold
    • 定义了两个不重要的服务进程名 service1service2
    • 在无限循环中,获取当前内存使用率,并与阈值比较。
    • 当内存使用率超过高阈值时,停止两个服务进程;当内存使用率降到低阈值以下时,启动两个服务进程。
    • 每5秒检查一次内存使用率。
  2. 注意事项

    • 请将 "service1_process_name""service2_process_name" 替换为实际的服务进程名,并且要确保系统使用 systemctl 来管理这些服务(如果是其他系统,如SysV init,需要替换为相应的启动/停止命令)。
    • 脚本中的 free -h 命令获取的内存信息格式在不同系统可能略有差异,如果出现获取内存使用率不准确的情况,需要根据实际系统进行调整。