shell脚本:实现监控进程内存


# 根据进程名获取进程PID
function get_process_id() {
    local p_name=$1
    local cmd=`ps -ef | grep ${p_name} |grep -v "grep" | awk '{print $2}'`
    echo ${cmd}
}


# 获取进程占用内存大小(即:top命令的RES,单位KB)
function get_process_RmRSS() {
    local p_name=$1
    local the_pid=$(get_process_id ${p_name})
    local cmd=`cat /proc/${the_pid}/status | grep VmRSS | sed 's/VmRSS: / /g' | awk '{print $2}'`
    echo ${cmd}
}


function get_time_tag() {
    local cmd=`date +%Y%m%d-%H%M%S`
    echo ${cmd}
}

# echo $(get_time_tag)

# 输出lite上所有进程的内存占用信息
function get_lite_all_prcess_RmRSS() {
    local array_process_name=("process_1" "process_2" "process_3")
    local result_txt=""
    for(( i=0;i<${#array_process_name[@]};i++ ))
    do
        the_pname=${array_process_name[i]}
        the_rss=$(get_process_RmRSS ${the_pname})
        result_txt=${result_txt}"${i}:"${the_rss}" "
    done;
    echo ${result_txt}
}

function main() {
    while true; do
        echo $(get_time_tag)" "$(get_lite_all_prcess_RmRSS) >> monitor_process_memory.txt
        sleep 1
    done;
}

main

你可能感兴趣的:(linux,bash)