Eric Brotto
Eric Brotto

Reputation: 54251

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!

Upvotes: 7

Views: 10217

Answers (3)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

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

Upvotes: 7

Parag Bafna
Parag Bafna

Reputation: 22930

You can use BSD sysctl routine or ps command to get a list of all BSD processes.Have a look at https://stackoverflow.com/a/18821357/944634

Upvotes: 4

Guillaume Lebourgeois
Guillaume Lebourgeois

Reputation: 3873

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.

Upvotes: 0

Related Questions