views:

59

answers:

1

If anyone could please help me out, that would be great :)

This seems to be a tough one. Starting from the process ID, I need to be able to grab:

  1. How much CPU the process is taking up in %
  2. How long the process has been using the CPU

This needs to be written in Cocoa/ Objective-C or C. It also needs to work on Tiger through Snow Leopard.

Thanks!

+1  A: 

A crude way would be to spawn of a popen command and grab some output from ps.

Ie like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void get_process_info(int pid) {
  char ps_cmd[256];
  sprintf(ps_cmd, "ps -O %%cpu -p %d", pid); // see man page for ps
  FILE *fp = popen(ps_cmd, "r"); 
  if (fp) {
    char line[4096];
    while (line == fgets(line, 4096, fp)) {
      if (atoi(line) == pid) {
        char dummy[256];
        char cpu[256];
        char time[256];

        //   PID  %CPU   TT  STAT      TIME COMMAND
        // 32324   0,0 s001  S+     0:00.00 bc

        sscanf(line, "%s %s %s %s %s", dummy, cpu, dummy, dummy, time);
        printf("%s %s\n", cpu, time); // you will need to parse these strings

        pclose(fp);
        return;
      }
    }
    pclose(fp);
  }
}

int main() {
  get_process_info(32324);
  return 0;
}
epatel
This seems to compute a little slow. I'm going to be running this against all processes currently on the machine every second and this may not be efficient enough. I gave you a vote for effort though. At least you gave me something :)
Eric Brotto
@Eric If you want to get that data for all processes it can be easily optimized. Let the `ps` command output all and parse them all at the same time. This will only be one `popen` call each second.
epatel
At the moment I'm calling the above method for just the Focus App every second, but sometimes a couple of seconds go by with no returned value. Does this make sense? How could I optimise the code so that it runs quickly on at least one process?Thanks so much. Btw great portfolio!
Eric Brotto
Thanks. I also see some hints for other solutions in the answers in this question http://stackoverflow.com/questions/220323/determine-process-info-programmatically-in-darwin-osx
epatel