且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取Mac上所有正在运行的进程的列表?

更新时间:2023-09-11 07:57:22

通常的方法是放入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);
        }
    }
}