c++ - 在 Darwin/OSX 中以编程方式确定进程信息

标签 c++ c macos operating-system darwin

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


/// 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 并解析输出之外,其余的调用让我望而却步——这是 Not Acceptable 。任何帮助将不胜感激。

要求:
在 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负载来自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

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

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

关于c++ - 在 Darwin/OSX 中以编程方式确定进程信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/220323/

相关文章:

c++ - QT信号槽如何使用模板?

c++ - 避免转换容器的元素指针类型

C 编程,从重复的代码中创建循环

macos -/usr/local/bin没有这样的文件或目录

macos - OS X 上的自动布局 - 让 NSTextField 填充 super View

c++ - 更改关联性时的答案略有不同

c++ - 有没有办法在 Catalina 上安装 Valgrind?

c - 关于代码时间复杂度计算的问题

c# - 使用 C# 和 C 语言进行 USB 转串口(来回)通信

c++ - 如何在 OS X 10.9 上编译 C++ 程序并在以前的 OS X 版本上使用?