[英]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.