【问题标题】:Script or command to get a user's memory consumption获取用户内存消耗的脚本或命令
【发布时间】:2011-09-13 15:14:35
【问题描述】:

我的主机为我的网站提供有限数量的 RAM,我想通过在 cron 中运行脚本来监控内存消耗。

我已经编造了这个命令:

ps -u xxxxxx -o rss,command | grep -v peruser | awk '{sum+=$1} END {print sum/1024}'

但是我的主机计算内存的方式有一个特殊性。它会忽略运行时间少于 5 分钟的进程。

你知道一个命令或 Python 脚本可以向我显示忽略短期进程的总使用内存吗?

【问题讨论】:

    标签: python unix memory


    【解决方案1】:

    使用etime 查找进程的已用时间。然后你可以修改你的awk命令来检查这个时间是否大于5分钟。

    ps -u xxxxxx -o rss,etime,command | ...
    

    经过时间的格式为[[dd-]hh:]mm:ss。这意味着时间可能是 00:30、12:57:39 甚至 4-08:27:12。您可以使用awk 来解析这种时间格式并将其转换为秒。以秒为单位,检查是否超过 5 分钟,如果超过,则将其添加到 rss 的运行总数中。

    这是一个执行此操作的示例脚本:

    ps -u xxxxxx -o rss,etime,command | grep -v peruser | grep -v RSS | sed 's/^ *//g' | awk '{
     split($2,arr,":") #split time on :
     len=0
     for(i in arr) len++ 
     secs=arr[len]+60*arr[len-1] #convert to seconds
     if(len>2) secs=secs+substr(arr[len-2],length(arr[len-2])-1)*60*60
    
     if(secs>5*60) { #check if more than 5 minutes
         print $0 #print out the process
         sum+=$1 
     }
    } END{print "SUM:"sum/1024}'
    

    【讨论】:

    • 我真的很讨厌 unix 命令:(你能告诉我如何修改我的 awk 命令并过滤掉 etime 为 5 分钟或更短的进程吗?谢谢!
    • 该死的,我没有收到你回答的通知。我会马上测试你的脚本并在明天发布我的结果。谢谢dogbane!
    猜你喜欢
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多