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

It would be nice to get:

  • Process id for each
  • How much processor time is used by the process

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

+4
source share
3 answers

The usual way to do this is to switch to C and list the serial numbers of the process on the system (return to files before Mac OS X). NSWorkspace has an API, but they do not always work as you expect.

Note that classic processes (on PowerPC systems) will be listed with this code (with different process serial numbers), although they all have the same process identifier.

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 this function and pass in a block that will do what you want with the PID.


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); } } } 
+4
source

You can use the BSD sysctl procedure or the ps command to get a list of all BSD processes. Take a look at fooobar.com/questions/1316886 / ...

+3
source

Hey, you can make a system call like:

 ps -eo pid,pcpu 

and analyze the results.

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

+1
source

All Articles