如何获取Mac上所有正在运行的进程的列表? [英] How to get a list of all running processes on a Mac?

查看:1274
本文介绍了如何获取Mac上所有正在运行的进程的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获得所有好处:

  1. 每个进程的进程ID
  2. 该进程占用了多少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.

使用NSRunningApplicationNSWorkspace:

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);
        }
    }
}

这篇关于如何获取Mac上所有正在运行的进程的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆