Reputation: 54251
It would all be good to get:
and can we do this for Mac in C or Objective C? Some example code would be awesome!
Upvotes: 7
Views: 10217
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
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
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