在 Darwin/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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
进程信息来自
pidinfo
:CPU 负载来自
host_statistics
:有关更多详细信息,请查看
top
和lsof
的来源>,它们是开源的(您需要注册为 Apple 开发人员,但这是免费的):https://opensource.apple.com/source/top/top-111.20.1/libtop.c.auto.html
稍后编辑:< /strong> 所有这些接口都是特定于版本的,因此在编写生产代码(libproc.h)时需要考虑到这一点:
Process info comes from
pidinfo
:cpu load comes from
host_statistics
:For more details, check out sources for
top
andlsof
, they are open source (you need to register as an Apple developer but that's free of charge):https://opensource.apple.com/source/top/top-111.20.1/libtop.c.auto.html
Later edit: All these interfaces are version specific, so you need to take that into account when writing production code (libproc.h):
既然你说不支持 Objective-C,我们就排除大部分 MacOS 框架。
您可以使用 getrusage() 获取 CPU 时间,它给出进程占用的用户和系统 CPU 时间总量。 要获取 CPU 百分比,您需要每秒快照一次 getrusage 值(或者您想要的粒度)。
getrusage 结构中有一个 RSS 字段,但在 MacOS X 10.5 中似乎始终为零。 Michael Knight 写了一个博客几年前关于如何确定 RSS 的帖子。
Since you say no Objective-C we'll rule out most of the MacOS frameworks.
You can get CPU time using getrusage(), which gives the total amount of User and System CPU time charged to your process. To get a CPU percentage you'd need to snapshot the getrusage values once per second (or however granular you want to be).
There is an RSS field in the getrusage structure, but is appears to always be zero in MacOS X 10.5. Michael Knight wrote a blog post several years ago about how to determine the RSS.
您可以使用下面的代码来获取 mac OS 中的进程信息:
kinfo_proc 结构体包含有关进程的所有信息。例如进程标识符 (pid)、
进程组、进程状态等
You can use below code for process info in mac OS:
kinfo_proc struct contains all the information about a process.such as Process identifier (pid),
process group, process status and etc.
我认为大多数这些值都可以在 Mach API 中找到,但我已经有一段时间没有在那里研究了。 或者,您可以只查看“ps”或“top”命令的源代码,看看它们是如何做到的。
I think most of these values are available in the Mach API, but it's been a while since I've poked around in there. Alternatively, you could just look at the source code for the "ps" or "top" commands, and see how they do it.
大多数信息可以从 GetProcessInformation()。
顺便说一句,为什么函数的虚拟方法返回进程范围的信息?
这仅限于碳,不适用于可可
Most of this info can be gotten from GetProcessInformation().
By the way, why virtual methods for functions that return processwide info?
This is CARBON only, and won't work with cocoa