Eric Brotto
Eric Brotto

Reputation: 54281

Getting CPU info from Process ID

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!

Upvotes: 4

Views: 2120

Answers (1)

epatel
epatel

Reputation: 46051

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;
}

Upvotes: 1

Related Questions