Linux C中当前进程的内存使用情况

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1558402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:46:19  来源:igfitidea点击:

Memory usage of current process in C

clinuxmemorymemory-managementphp-extension

提问by scotts

I need to get the memory usage of the current process in C. Can someone offer a code sample of how to do this on a Linux platform?

我需要在 C 中获取当前进程的内存使用情况。有人可以提供如何在 Linux 平台上执行此操作的代码示例吗?

I'm aware of the cat /proc/<your pid>/statusmethod of getting memory usage, but I have no idea how to capture that in C.

我知道cat /proc/<your pid>/status获取内存使用情况的方法,但我不知道如何在 C 中捕获它。

BTW, it's for a PHP extension I'm modifying (granted, I'm a C newbie). If there are shortcuts available within the PHP extension API, that would be even more helpful.

顺便说一句,它用于我正在修改的 PHP 扩展(当然,我是 C 新手)。如果 PHP 扩展 API 中有可用的快捷方式,那会更有帮助。

采纳答案by CB Bailey

You can always just open the 'files' in the /procsystem as you would a regular file (using the 'self' symlink so you don't have to look up your own pid):

您始终可以像打开/proc常规文件一样打开系统中的“文件” (使用“self”符号链接,因此您不必查找自己的 pid):

FILE* status = fopen( "/proc/self/status", "r" );

Of course, you now have to parse the file to pick out the information you need.

当然,您现在必须解析文件以挑选出您需要的信息。

回答by caf

The getrusagelibrary function returns a structure containing a whole lot of data about the current process, including these:

getrusage库函数返回包含一大堆有关当前进程,包括这些数据的结构:

long   ru_ixrss;         /* integral shared memory size */
long   ru_idrss;         /* integral unshared data size */
long   ru_isrss;         /* integral unshared stack size */

However, the most up-to-date linux documentation says about these 3 fields

但是,最新的 linux 文档说明了这 3 个字段

(unmaintained) This field is currently unused on Linux

which the manual then defines as:

然后手册将其定义为:

Not all fields are completed; unmaintained fields are set to zero by the kernel. (The unmaintained fields are provided for compatibility with other systems, and because they may one day be supported on Linux.)

并非所有字段都已完成;内核将未维护的字段设置为零。(提供未维护的字段是为了与其他系统兼容,因为它们可能有一天会在 Linux 上得到支持。)

See getrusage(2)

getrusage(2)

回答by Jeff

#include <sys/resource.h>
#include <errno.h>

errno = 0;
struct rusage* memory = malloc(sizeof(struct rusage));
getrusage(RUSAGE_SELF, memory);
if(errno == EFAULT)
    printf("Error: EFAULT\n");
else if(errno == EINVAL)
    printf("Error: EINVAL\n");
printf("Usage: %ld\n", memory->ru_ixrss);
printf("Usage: %ld\n", memory->ru_isrss);
printf("Usage: %ld\n", memory->ru_idrss);
printf("Max: %ld\n", memory->ru_maxrss);

I used this code but for some reason I get 0 all the time for all 4 printf()

我使用了这段代码,但出于某种原因,所有 4 个 printf() 始终为 0

回答by mellthy

The above struct was taken from 4.3BSD Reno. Not all fields are mean- ingful under Linux. In linux 2.4 only the fields ru_utime, ru_stime, ru_minflt, and ru_majflt are maintained. Since Linux 2.6, ru_nvcsw and ru_nivcsw are also maintained.

上述结构取自 4.3BSD Reno。并非所有字段在 Linux 下都有意义。在 linux 2.4 中只保留了字段 ru_utime、ru_stime、ru_minflt 和 ru_majflt。从 Linux 2.6 开始,还维护了 ru_nvcsw 和 ru_nivcsw。

http://www.atarininja.org/index.py/tags/code

http://www.atarininja.org/index.py/tags/code

回答by James

This is a terribly ugly and non-portable way of getting the memory usage, but since getrusage()'s memory tracking is essentially useless on Linux, reading /proc//statm is the only way I know of to get the information on Linux.

这是一种非常丑陋且不可移植的获取内存使用情况的方法,但是由于 getrusage() 的内存跟踪在 Linux 上基本上没有用,因此读取 /proc//statm 是我所知道的在 Linux 上获取信息的唯一方法.

If anyone know of cleaner, or preferably more cross-Unix ways of tracking memory usage, I would be very interested in learning how.

如果有人知道更干净的,或者最好是更多跨 Unix 跟踪内存使用情况的方法,我将非常有兴趣学习如何使用。

typedef struct {
    unsigned long size,resident,share,text,lib,data,dt;
} statm_t;

void read_off_memory_status(statm_t& result)
{
  unsigned long dummy;
  const char* statm_path = "/proc/self/statm";

  FILE *f = fopen(statm_path,"r");
  if(!f){
    perror(statm_path);
    abort();
  }
  if(7 != fscanf(f,"%ld %ld %ld %ld %ld %ld %ld",
    &result.size,&result.resident,&result.share,&result.text,&result.lib,&result.data,&result.dt))
  {
    perror(statm_path);
    abort();
  }
  fclose(f);
}

From the proc(5) man-page:

从 proc(5) 手册页:

   /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)

回答by lepe

I came across this post: http://appcrawler.com/wordpress/2013/05/13/simple-example-of-tracking-memory-using-getrusage/

我遇到了这篇文章:http: //appcrawler.com/wordpress/2013/05/13/simple-example-of-tracking-memory-using-getrusage/

Simplified version:

简化版:

#include <sys/resource.h>
#include <stdio.h>

int main() {
  struct rusage r_usage;
  getrusage(RUSAGE_SELF,&r_usage);
  // Print the maximum resident set size used (in kilobytes).
  printf("Memory usage: %ld kilobytes\n",r_usage.ru_maxrss);
  return 0;
}

(tested in Linux 3.13)

(在 Linux 3.13 中测试)

回答by Anti Earth

I'm late to the party, but this might be helpful for anyone else looking for the resident and virtual (and their peak values so far) memories on linux.

我参加聚会迟到了,但这可能对其他人在 linux 上寻找常驻和虚拟(以及他们目前的峰值)内存有所帮助。

It's probably pretty terrible, but it gets the job done.

这可能很糟糕,但它完成了工作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/*
 * Measures the current (and peak) resident and virtual memories
 * usage of your linux C process, in kB
 */
void getMemory(
    int* currRealMem, int* peakRealMem,
    int* currVirtMem, int* peakVirtMem) {

    // stores each word in status file
    char buffer[1024] = "";

    // linux file contains this-process info
    FILE* file = fopen("/proc/self/status", "r");

    // read the entire file
    while (fscanf(file, " %1023s", buffer) == 1) {

        if (strcmp(buffer, "VmRSS:") == 0) {
            fscanf(file, " %d", currRealMem);
        }
        if (strcmp(buffer, "VmHWM:") == 0) {
            fscanf(file, " %d", peakRealMem);
        }
        if (strcmp(buffer, "VmSize:") == 0) {
            fscanf(file, " %d", currVirtMem);
        }
        if (strcmp(buffer, "VmPeak:") == 0) {
            fscanf(file, " %d", peakVirtMem);
        }
    }
    fclose(file);
}