[英]How is top able to see memory usage
top 是用什么语言写的? 我想编写一个 c++ 程序,可以查看在 OSX 中使用了多少 memory 各个进程。 我不能使用 /proc,因为那不在 OSX 上。 top 能够找出 memory 进程正在使用多少,因此它也不使用它。 我想知道它是如何发现的。
可能比您要查找的信息更多,但 OS X 中的 top 是在开源许可下发布的:
需要对源代码进行一些挖掘才能弄清楚,但 Top 使用 task_info() 调用与 Mach kernel 接口并收集 memory 统计信息。 您可以在http://www.gnu.org/software/hurd/gnumach-doc/Task-Information.html阅读有关 task_info() 的一些大部分正确信息。 我说大部分是正确的,因为我在 OS X 实现中发现了至少一个差异:memory 大小以字节而不是页面报告。
作为总结,你传递 task_info() 一个“目标任务”(mach_task_self() 如果你想要关于你的程序本身的信息,否则使用 task_for_pid() 或 processor_set_tasks())并告诉它你想要“基本信息”,下面的类别其中虚拟和常驻 memory 大小下降。 然后 task_info() 用你想要的信息填充一个 task_basic_info 结构。
这是我写的 class 以获得常驻 memory 大小。 它还显示了如何使用 sysctl 获取有关系统的信息(在本例中,您拥有多少物理内存):
#include <sys/sysctl.h>
#include <mach/mach.h>
#include <cstdio>
#include <stdint.h>
#include <unistd.h>
////////////////////////////////////////////////////////////////////////////////
/*! Class for retrieving memory usage and system memory statistics on Mac OS X.
// (Or probably any system using the MACH kernel.)
*///////////////////////////////////////////////////////////////////////////////
class MemoryInfo
{
public:
/** Total amount of physical memory (bytes) */
uint64_t physicalMem;
////////////////////////////////////////////////////////////////////////
/*! Constructor queries various memory properties of the system
*///////////////////////////////////////////////////////////////////////
MemoryInfo()
{
int mib[2];
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
size_t returnSize = sizeof(physicalMem);
if (sysctl(mib, 2, &physicalMem, &returnSize, NULL, 0) == -1)
perror("Error in sysctl call");
}
////////////////////////////////////////////////////////////////////////
/*! Queries the kernel for the amount of resident memory in bytes.
// @return amount of resident memory (bytes)
*///////////////////////////////////////////////////////////////////////
static size_t Usage(void)
{
task_t targetTask = mach_task_self();
struct task_basic_info ti;
mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;
kern_return_t kr = task_info(targetTask, TASK_BASIC_INFO_64,
(task_info_t) &ti, &count);
if (kr != KERN_SUCCESS) {
printf("Kernel returned error during memory usage query");
return -1;
}
// On Mac OS X, the resident_size is in bytes, not pages!
// (This differs from the GNU Mach kernel)
return ti.resident_size;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.