进程内存打印

221 阅读1分钟

1 shell脚本

使用方式

sh monitor.sh [pid]

monitor.sh

#!/bin/bash
pid=$1  #获取进程pid
echo $pid
interval=1  #设置采集间隔
while true
do
    echo $(date +"%y-%m-%d %H:%M:%S") >> proc_memlog.txt
    cat  /proc/$pid/status|grep -e VmRSS >> proc_memlog.txt    #获取内存占用
    cpu=`top -n 1 -p $pid|tail -2|head -1|awk '{ssd=NF-4} {print $ssd}'`    #获取cpu占用
    echo "Cpu: " $cpu >> proc_memlog.txt
    echo $blank >> proc_memlog.txt
    sleep $interval
done

或者简短命令:

while true;do cat /proc/9781/status | grep VmRSS | awk '{print $2}' ;sleep 1s;done

2 C++代码

#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>

static int GetRamPss() {
    int pid = getpid();  // 获取当前进程 ID
    int pss = 0;  // 单位为 KB

    std::string filename = "/proc/" + std::to_string(pid) + "/smaps";  //读取 smaps

    std::ifstream ifs(filename);
    std::string line;

    while (getline(ifs, line)) {
        if (line.substr(0, 4) == "Pss:") {  // 查找以 Pss 开头的行
            pss += std::stoi(line.substr(6));  //计算 Pss 的值
        }
    }
    return pss;
}

内存指标:

  • VSS Virtual Set Size 虚拟耗用内存(包含共享库占用的全部内存,以及分配但未使用内存),很少被用于判断一个进程的真实内存使用量

  • RSS Resident Set Size 实际使用物理内存(包含共享库占用的全部内存)。可用于判断内存使用量。

  • PSS Proportional Set Size 实际使用的物理内存(共享库占用内存,按照进程等比例划分)。可用于判断内存使用量。

  • USS Unique Set Size
    进程独自占用的物理内存(不包含共享库占用内存)。当进程存在可疑内存泄漏,USS是最佳观察数据。

参考: 内存耗用:VSS/RSS/PSS/USS 的介绍