如何在不调用外部程序的情况下测量进程的内存使用情况

Ale*_*rev 3 c unix memory process linux-kernel

运行以下内容可以显示进程的内存使用情况:

$ ps -C processname -o size
 SIZE
 3808
Run Code Online (Sandbox Code Playgroud)

有没有办法在不执行ps(或任何外部程序)或阅读的情况下检索此信息/proc

Arj*_*kar 7

在Linux系统上,可以通过读取查询进程的内存使用情况/proc/[pid]/statm.[pid]过程的PID 在哪里.如果进程想要查询自己的数据,则可以通过读取/proc/self/statm来执行此操作.man 5 proc说:

的/ proc/[PID]/statm

          Provides information about memory usage, measured in pages.  The
          columns are:

              size       total program size
                         (same as VmSize in /proc/[pid]/status)
              resident   resident set size
                         (same as VmRSS in /proc/[pid]/status)
              share      shared pages (from shared mappings)
              text       text (code)
              lib        library (unused in Linux 2.6)
              data       data + stack
              dt         dirty pages (unused in Linux 2.6)
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令打开文件:fopen("/proc/self/statm", "r")并阅读内容.

由于文件在"页面"中返回结果,因此您还需要查找页面大小.getpagesize ()返回页面的大小,以字节为单位.