【发布时间】: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