2008-10-20 46 views
15

我有以下成员函数的类:确定进程信息编程在达尔文/ OSX


/// 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

+1

请描述你为什么要创建一个这样做的类。大多数运行在Mac OS X上的软件都不需要关心你所描述的任何事情。 此外,在Mac OS X上开发时,“否Objective-C”不是一个合理的策略。 – 2008-10-21 02:54:21

回答

11

过程信息来自pidinfo

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

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,他们都是开源的(你需要注册为Apple开发者,但免费):

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

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

/* 
* This header file contains private interfaces to obtain process information. 
* These interfaces are subject to change in future releases. 
*/ 
2

我觉得这些值都在马赫的API可用,但它已经有一段时间,因为我已经捅在那里。或者,您可以查看“ps”或“top”命令的源代码,并查看它们是如何执行的。

0

大部分信息都可以从GetProcessInformation()得到。

顺便说一句,为什么虚拟方法的函数返回processwide信息?

这是而已,既然你说没有Objective-C中,我们将排除大多数MacOS的框架不会与可可

+0

请注意,GetProcessInformation()是一个Win32 API函数,而不是OP所讨论的Mac OS X. – 2011-12-15 19:44:51

+0

实际上@benhoyt,他在Apple文档中的链接点包含一个名为`GetProcessInformation()`的函数,但它是框架的一部分。 – 2012-07-12 18:39:59

6

工作。

您可以使用getrusage()获得CPU时间,这会给您的进程收取用户和系统CPU时间的总额。要获得CPU百分比,您需要每秒钟对快照值进行一次快照(或者您希望的粒度)。

#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的博客文章。

2

您可以使用下面的代码过程信息MAC OS:

void IsInBSDProcessList(char *name) { 
    assert(name != NULL); 
    kinfo_proc *result; 
    size_t count = 0; 
    result = (kinfo_proc *)malloc(sizeof(kinfo_proc)); 
    if(GetBSDProcessList(&result,&count) == 0) { 
    for (int i = 0; i < count; i++) { 
     kinfo_proc *proc = NULL; 
     proc = &result[i]; 
     } 
    } 
    free(result); 
} 

kinfo_proc增加结构体包含所有关于process.such如进程标识符(PID), 处理组,处理状态等的信息