简体   繁体   中英

How to get a list of all running processes on a Mac?

It would all be good to get:

  1. The process ID of each one
  2. How much CPU time gets used by the process

and can we do this for Mac in C or Objective C? Some example code would be awesome!

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.

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

You can then call that function and pass a block that will do what you want with the PIDs.


Using NSRunningApplication and 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);
        }
    }
}

您可以使用BSD sysctl例程或ps命令获取所有BSD进程的列表。看看https://stackoverflow.com/a/18821357/944634

Hey, you can do a system call as :

ps -eo pid,pcpu

and parse the results.

You can make this call using system() in C .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM