views:

72

answers:

3

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!

+1  A: 

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.

Guillaume Lebourgeois
+3  A: 

There is a nice Q&A note with source code on Apple developers site.

Diederik Hoogenboom
Yes, I saw this already, but I'm having trouble implementing it as I'm not super familiar with C. Any advice or sample code?
Eric Brotto
+1  A: 

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.

Jonathan Grynspan