本文介绍了如何在 Linux 上使用 C 检查堆栈和堆的使用情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法可以在 Linux 上用 C 检索堆栈和堆的使用情况?

Is there any way to retrieve the stack and heap usage in C on Linux?

我想知道堆栈/堆专门占用的内存量.

I want to know the amount of memory taken specifically by stack/heap.

推荐答案

如果你知道进程的 pid(例如 1234),你可以使用 pmap 1234 命令,它打印内存映射.您还可以读取 /proc/1234/maps 文件(实际上是一个文本伪文件,因为它不存在于磁盘上;它的内容由内核懒惰地合成).阅读 proc(5) 手册页.它是 Linux 特有的,但受到 /proc 文件系统的启发其他 Unix 系统.

If you know the pid (e.g. 1234) of the process, you could use the pmap 1234 command, which print the memory map. You can also read the /proc/1234/maps file (actually, a textual pseudo-file because it does not exist on disk; its content is lazily synthesized by the kernel). Read proc(5) man page. It is Linux specific, but inspired by /proc file systems on other Unix systems.

从你的程序内部,你可以读取 /proc/self/maps 文件.在终端中尝试
cat/proc/self/maps 命令以查看 虚拟地址空间 运行它的进程的映射cat 命令和 cat/proc/$$/maps 查看当前 shell 的映射.

And from inside your program, you could read the /proc/self/maps file. Try the
cat /proc/self/maps command in a terminal to see the virtual address space map of the process running that cat command, and cat /proc/$$/maps to see the map of your current shell.

所有这些都为您提供了一个进程的内存映射,它包含它使用的各种内存段(特别是用于堆栈、堆和各种动态库的空间).

All this give you the memory map of a process, and it contains the various memory segments used by it (notably space for stack, for heap, and for various dynamic libraries).

您也可以使用 getrusage 系统调用.

You can also use the getrusage system call.

另请注意,对于多线程,进程的每个线程有自己的调用堆栈.

Notice also that with multi-threading, each thread of a process has its own call stack.

您还可以解析 /proc/$pid/statm/proc/self/statm 伪文件,或 /proc/$pid/status/proc/self/status 一.

You could also parse the /proc/$pid/statm or /proc/self/statm pseudo-file, or the /proc/$pid/status or /proc/self/status one.

但另请参阅 Linux 吃了我的 RAM 以获得一些提示.

But see also Linux Ate my RAM for some hints.

考虑使用 valgrind(至少在 Linux 上)来调试 内存泄漏.

Consider using valgrind (at least on Linux) to debug memory leaks.

这篇关于如何在 Linux 上使用 C 检查堆栈和堆的使用情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 11:26