【问题标题】:Find out which processes use the most memory and kill them找出哪些进程使用最多的内存并杀死它们
【发布时间】:2017-07-12 13:05:20
【问题描述】:

我目前有一个 bash 脚本,它检查我的机器内存状态,并在其内存超过某个阈值时向我发送电子邮件警报,我的问题是:

  • 有没有办法找出哪些进程在机器上消耗的内存最多,并在脚本中杀死它们?

这是我的脚本,现在是这样:

#!/bin/bash

############################################################
#                  Memory usage function                   #
#           Captures memory usage in percentage            #
#  Sends an email alert if memory usage exceeds threshold  #
############################################################

memory_check() {
    total_ram=`cat /proc/meminfo | grep 'MemTotal' | awk '{print $2}'`;
    free_ram=`cat /proc/meminfo | grep 'MemFree' | awk '{print $2}'`;
    used_ram=$(($total_ram - $free_ram))
    mem_percent=$(($used_ram * 100 / $total_ram))
    machine_name=`hostname`
    threshold=95
    if [ $mem_percent -gt $threshold ]; then
        echo "Memory usage has exceeded $threshold% threshold and was at $mem_percent%." > memory_alert_report
        mailx -s "Memory resource alarm on $machine_name !" my@adress.com < memory_alert_report
    else
        exit;
    fi
    exit;
}

【问题讨论】:

  • 是的,有办法。但是你为什么要开始不分青红皂白地杀死进程呢?到目前为止,您实际上尝试过什么?这看起来像家庭作业......
  • @arco444 问题是,当内存超过 95% 的使用率时,我需要终止进程,因为它不应该达到那个点,如果它达到了那意味着我的程序已经疯了,我需要杀死在它达到 100% 之前,就像不久前一样,它会破坏我的生产环境......到目前为止,我已经做了一些研究,但没有找到任何答案。
  • 我知道我的程序将是使用最多内存的程序,如果这种情况发生在夜间,我希望尽快将其杀死。
  • 更好的办法是让您的程序监控其内存使用情况,如果使用过多则自行退出。
  • 只需在你的程序上设置一个 ulimit。

标签: bash unix memory-management


【解决方案1】:

为什么不在批处理模式下使用 top ?例如

$ top -b -n 1

会将进程信息(包括内存信息)转储到标准输出。然后,您可以重定向到 sort(在适当的列上排序)并提取最高内存使用者的 pid。

【讨论】:

    【解决方案2】:

    这并没有解决您的问题,但我希望它有助于简化您的 shell 脚本。

    从 /proc/meminfo 捕获 MemTotal 时,您的原始行是:

    cat /proc/meminfo | grep 'MemTotal' | awk '{print $2}'
    

    您无需使用cat 将文件输入grep。只需这样做:

    grep MemTotal /proc/meminfo | awk '{print $2}'
    

    更好的是,awk 是隐式的 greplike,所以你可以用这个替换你的整个管道:

    awk '/MemTotal/ {print $2}' /proc/meminfo
    

    这意味着“如果我的行匹配/MemTotal/,则执行print $2

    【讨论】:

      【解决方案3】:

      正如@chepner 建议的那样,我现在通过我的程序监控内存,这要归功于一个 Java 套接字,如果内存变高,它将接收一个信号,然后很好地关闭进程。

      【讨论】:

        【解决方案4】:

        我会回答最初的问题,即使 OP 找到了解决他问题的更好方法,因为出于其他原因我想要这样的脚本:

        #! /usr/bin/env sh
        # kills the process using the most memory
        
        # -A: list all processes
        # sort in reverse order of resident set size
        pid=`ps -A --sort -rss --format pid --no-headers | head -n1`
        
        kill $pid
        sleep 15 # give it a chance to exit gracefully
        kill -9 $pid # otherwise, kill forcefully
        

        感谢 Alex D 的 his answer on Unix Stack Exchange 为我提供了基本的 ps 语法,感谢 Jon Jensen 的 his article 让我有了在等待后强行杀死的想法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 1970-01-01
          • 1970-01-01
          • 2017-10-26
          相关资源
          最近更新 更多