首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Darwin/OSX中以编程方式确定进程信息

在Darwin/OSX中以编程方式确定进程信息
EN

Stack Overflow用户
提问于 2008-10-20 23:38:55
回答 5查看 21K关注 0票数 15

我有一个包含以下成员函数的类:

代码语言:javascript
复制
/// caller pid
virtual pid_t Pid() const = 0; 

/// physical memory size in KB
virtual uint64_t Size() const = 0;  

/// resident memory for this process
virtual uint64_t Rss() const = 0; 

/// cpu used by this process
virtual double PercentCpu() const = 0; 

/// memory used by this process
virtual double PercentMemory() const = 0; 

/// number of threads in this process
virtual int32_t Lwps() const = 0; 

这个类的职责是返回关于调用者的进程信息。物理内存大小可以很容易地通过sysctl调用来确定,pid是微不足道的,但是除了在ps或top上调用popen并解析输出之外,其余的调用我都无法理解-这是不可接受的。任何帮助都将不胜感激。

要求:

在g++ 4.0上编译

无obj-c

OSX 10.5

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2008-10-21 06:00:16

进程信息来自pidinfo

代码语言:javascript
复制
cristi:~ diciu$ grep proc_pidinfo /usr/include/libproc.h

int proc_pidinfo(int pid, int flavor, uint64_t arg,  void *buffer, int buffersize);

cpu负载来自host_statistics

代码语言:javascript
复制
cristi:~ diciu$ grep -r host_statistics /usr/include/

/usr/include/mach/host_info.h:/* host_statistics() */

/usr/include/mach/mach_host.defs:routine host_statistics(

/usr/include/mach/mach_host.h:/* Routine host_statistics */

/usr/include/mach/mach_host.h:kern_return_t host_statistics

有关更多详细信息,请查看toplsof的源代码,它们是开源的(您需要注册为苹果开发人员,但这是免费的):

https://opensource.apple.com/source/top/top-111.20.1/libtop.c.auto.html

稍后编辑:所有这些接口都是特定于版本的,所以在编写生产代码(libproc.h)时需要考虑到这一点:

代码语言:javascript
复制
/*
 * This header file contains private interfaces to obtain process information.
 * These interfaces are subject to change in future releases.
 */
票数 14
EN

Stack Overflow用户

发布于 2008-10-21 02:11:57

既然您说没有Objective-C,我们将排除大多数MacOS框架。

您可以使用getrusage()获取CPU时间,它给出了向您的进程收费的用户和系统CPU时间总量。要获得CPU百分比,您需要每秒拍摄一次getrusage值的快照(或者您希望的粒度)。

代码语言:javascript
复制
#include <sys/resource.h>

struct rusage r_usage;

if (getrusage(RUSAGE_SELF, &r_usage)) {
    /* ... error handling ... */
}

printf("Total User CPU = %ld.%ld\n",
        r_usage.ru_utime.tv_sec,
        r_usage.ru_utime.tv_usec);
printf("Total System CPU = %ld.%ld\n",
        r_usage.ru_stime.tv_sec,
        r_usage.ru_stime.tv_usec);

在getrusage结构中有一个RSS字段,但在MacOS X 10.5中似乎始终为零。几年前,Michael Knight写了一篇关于如何确定RSS的博客文章。

票数 7
EN

Stack Overflow用户

发布于 2008-10-20 23:51:59

我认为这些值中的大多数都可以在Mach API中找到,但我已经有一段时间没有研究过它了。或者,您可以只查看"ps“或"top”命令的源代码,看看它们是如何做到这一点的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/220323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档