Retrieving CPU Information from a Process ID

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

It seems complicated. Starting with the process id, I need to be able to:

  • How much processor does this process take in%
  • How long does the process use the processor

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

Thanks!

+4
source share
1 answer

A rough way would be to popen and capture some output from ps .

Same:

 #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; } 
+1
source

All Articles