Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

请帮我写一个服务器内存满了能够自动释放内存的脚本

  1. User

    请帮我写一个服务器内存满了能够自动释放内存的脚本

  2. Assistant

    以下是一个基本的服务器内存自动释放脚本,当内存使用量达到特定阈值时,脚本将杀死最大的进程,以释放内存。

    #!/bin/bash
    
    # 设定 内存使用百分比 阈值
    threshold=90
    
    # 获取当前内存使用百分比
    memory_usage=$(free | awk 'NR==2{printf "%.1f\n", $3/$2*100}')
    
    # 如果内存使用百分比高于阈值
    if (( $(echo "$memory_usage > $threshold" | bc -l) )); then
        # 获取占用内存最大的进程
        max_mem_process=$(ps -eo pmem,pcpu,pid,args | sort -k 1 -r | grep -v "grep" | head -n 1)
        # 杀死占用内存最大的进程
        echo "Mem usage at ${memory_usage}%. Killing process: ${max_mem_process}"
        pid=$(echo $max_mem_process | awk '{printf $4}')
        kill -9 $pid
    else
        echo "Mem usage at ${memory_usage}%. No action needed."
    fi
    

    这个脚本可以使用 cron 定时执行,例如每分钟执行一次:

    * * * * * /path/to/memory_cleanup.sh >> /var/log/memory_cleanup.log 2>&1
    

    在此例中,脚本的输出将被写入 /var/log/memory_cleanup.log。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.