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


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

有帮助吗?

解决方案

流程信息来自 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 load来自 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

有关详细信息,请查看 top lsof 的来源,它们是开源的(您需要注册为Apple开发人员,但这是免费的):

https://opensource.apple的.com /源极/顶/顶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.
 */

其他提示

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

您可以使用getrusage()获得CPU时间,这可以为您的流程提供用户和系统CPU时间总量。要获得CPU百分比,您需要每秒对getrusage值进行一次快照(或者无论您想要的是多少)。

#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发布。

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

您可以在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结构包含有关进程的所有信息,例如进程标识符(pid),  流程组,流程状态等。

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

顺便说一句,为什么虚函数方法会返回返回整个流程范围的函数?

这只是 CARBON ,不适用于cocoa

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top