如何获取Mac上所有正在运行的进程的列表?
获得所有好处:
- 每个进程的进程ID
- 该进程占用了多少CPU时间
我们可以在C或Objective C的Mac中做到这一点吗?一些示例代码会很棒!
and can we do this for Mac in C or Objective C? Some example code would be awesome!
通常的方法是放入C并枚举系统上的进程序列号(回溯到Mac OS X之前的日子). NSWorkspace有API,但是它们并不总是按您期望的方式工作.
The usual way to do it is to drop into C and enumerate through the process serial numbers on the system (a throwback to pre-Mac OS X days.) NSWorkspace has APIs but they don't always work the way you expect.
请注意,即使经典进程(在PowerPC系统上)都共享一个进程ID,也会使用此代码(具有不同的进程序列号)进行枚举.
Note that Classic processes (on PowerPC systems) will be enumerated with this code (having distinct process serial numbers), even though they all share a single process ID.
void DoWithProcesses(void (^ callback)(pid_t)) {
ProcessSerialNumber psn = { 0, kNoProcess };
while (noErr == GetNextProcess(&psn)) {
pid_t pid;
if (noErr == GetProcessPID(&psn, &pid)) {
callback(pid);
}
}
}
然后您可以调用该函数并传递一个将使用PID进行所需操作的块.
You can then call that function and pass a block that will do what you want with the PIDs.
使用NSRunningApplication
和NSWorkspace
:
void DoWithProcesses(void (^ callback)(pid_t)) {
NSArray *runningApplications = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication *app in runningApplications) {
pid_t pid = [app processIdentifier];
if (pid != ((pid_t)-1)) {
callback(pid);
}
}
}