Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 377
Eric Brotto Avatar asked Jul 26 '10 12:07

Eric Brotto


People also ask

How do I list all processes on a Mac?

Launch Terminal (Finder > Applications > Utilities). When Terminal is running, type top and hit Return. This will pull up a list of all your currently running processes.

How do I see all Applications running on my Mac?

Open a Finder window and navigate to Applications>Utilities. Double-click Activity Monitor. In the main window, you will see a list of processes with strange names. This is everything running on your Mac right now.

How do I find unnecessary background processes on my Mac?

The easiest way to view all active processes running on your Mac is to launch Activity Monitor from your Applications folder. In the default CPU tab, you can see how much processing power every process takes, ranked by the most consuming.

Why do I have so many processes running Mac?

MacOS launches many processes to do all the jobs that it needs to do. The number of process "triggered by you" is a small proportion of the total. In general, if there isn't a "problem" -- such as one process using up all your memory or CPU resources, or a general sluggishness -- then I would assume all is well.


2 Answers

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);
        }
    }
}
like image 120
Jonathan Grynspan Avatar answered Sep 22 '22 23:09

Jonathan Grynspan


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

like image 42
Parag Bafna Avatar answered Sep 21 '22 23:09

Parag Bafna