从进程ID获取CPU信息 [英] Getting CPU info from Process ID

查看:208
本文介绍了从进程ID获取CPU信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人可以帮助我,那将是很棒的:)

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

这似乎很难.从进程ID开始,我需要能够抓取:

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

  1. 该进程占用了多少CPU(百分比)
  2. 该进程使用CPU多长时间了

这需要用Cocoa/Objective-C或C编写.还需要通过Snow Leopard在Tiger上工作.

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

谢谢!

推荐答案

一种粗略的方法是产生popen命令并从ps获取一些输出.

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

就是这样:

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

这篇关于从进程ID获取CPU信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆