top如何能够看到内存使用情况

How is top able to see memory usage

本文关键字:用情 情况 内存 何能够 top      更新时间:2023-10-16

top是用什么语言写的?我想写一个c++程序,可以看到OSX中单个进程使用了多少内存。我不能使用/proc,因为它不在OSX上。Top能够发现进程正在使用多少内存,因此它也不使用内存。我想知道它是怎么发现的

需要对源代码进行一些挖掘才能弄清楚,但是Top使用task_info()调用与Mach内核接口并收集内存统计信息。您可以在http://www.gnu.org/software/hurd/gnumach-doc/Task-Information.html上阅读一些大多数关于task_info()的正确信息。我说大部分是正确的,因为我发现在OS X实现中至少有一个不同:内存大小以字节报告,而不是页。

作为一个总结,你传递给task_info()一个"目标任务"(mach_task_self()如果你想要关于你的程序本身的信息,否则使用task_for_pid()或processor_set_tasks()),并告诉它你想要"基本信息",虚拟和常驻内存大小属于这个类别。然后task_info()用你想要的信息填充task_basic_info结构体。

这是我写的一个类来获取驻留内存大小。它还展示了如何使用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;
        }
};

可能比你想要的更多,但是OS X中的top是在开源许可下发布的:

http://opensource.apple.com/source/top/top-67/

相关文章: