获取当前进程的CPU使用率

时间:2018-06-17 22:15:56

标签: c cpu-usage pid

我正在尝试根据PID读取当前进程的CPU使用情况。我使用以下代码来获取CPU使用情况:

#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <listdir.h>
struct pstat {
    long unsigned int utime_ticks;
    long int cutime_ticks;
    long unsigned int stime_ticks;
    long int cstime_ticks;
    long unsigned int vsize; // virtual memory size in bytes
    long unsigned int rss; //Resident  Set  Size in bytes

    long unsigned int cpu_total_time;
};

/*
 * read /proc data into the passed struct pstat
 * returns 0 on success, -1 on error
*/
int get_usage(const pid_t pid, struct pstat* result) {
    //convert  pid to string
    char pid_s[20];
    snprintf(pid_s, sizeof(pid_s), "%d", pid);
    char stat_filepath[30] = "/proc/"; strncat(stat_filepath, pid_s,
            sizeof(stat_filepath) - strlen(stat_filepath) -1);
    strncat(stat_filepath, "/stat", sizeof(stat_filepath) -
            strlen(stat_filepath) -1);

    FILE *fpstat = fopen(stat_filepath, "r");
    if (fpstat == NULL) {
        perror("FOPEN ERROR ");
        return -1;
    }

    FILE *fstat = fopen("/proc/stat", "r");
    if (fstat == NULL) {
        perror("FOPEN ERROR ");
        fclose(fstat);
        return -1;
    }

    //read values from /proc/pid/stat
    bzero(result, sizeof(struct pstat));
    long int rss;
    if (fscanf(fpstat, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"
                "%lu %ld %ld %*d %*d %*d %*d %*u %lu %ld",
                &result->utime_ticks, &result->stime_ticks,
                &result->cutime_ticks, &result->cstime_ticks, &result->vsize,
                &rss) == EOF) {
        fclose(fpstat);
        return -1;
    }
    fclose(fpstat);
    result->rss = rss * getpagesize();

    //read+calc cpu total time from /proc/stat
    long unsigned int cpu_time[10];
    bzero(cpu_time, sizeof(cpu_time));
    if (fscanf(fstat, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
                &cpu_time[0], &cpu_time[1], &cpu_time[2], &cpu_time[3],
                &cpu_time[4], &cpu_time[5], &cpu_time[6], &cpu_time[7],
                &cpu_time[8], &cpu_time[9]) == EOF) {
        fclose(fstat);
        return -1;
    }

    fclose(fstat);

    for(int i=0; i < 10;i++)
        result->cpu_total_time += cpu_time[i];

    return 0;
}

从这个github项目获得上述代码:https://github.com/fho/code_snippets/blob/master/c/getusage.c并且是这个问题的答案:https://stackoverflow.com/a/4410209/9951420

现在,当我尝试在我的函数中调用get_usage()时,如下所示:

int my_cpu_usage_func(int pid){
  struct pstat* result;
  double cpu = 0.0;
  int success = get_usage(pid, result);
  if(success == 0) printf("CPU usage read successfully\n");
  if(success == -1) printf("Couldn't read CPU usage\n");
  cpu = result->cpu_total_time;
  printf("CPU usage of %i %f", pid, cpu);
}

当我编译my_cpu_usage_func(int)时,我首先收到以下警告:

  

extmodule.c:131:23:注意:初始化变量&#39;结果&#39;沉默   这个警告结构pstat *结果;                         ^                          = NULL

然后当我执行相同的功能时,我收到以下错误:

  

FOPEN ERROR:没有这样的文件或目录

有人可以帮忙吗? 注:我是C编程的新手,所以任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

程序中有一些微不足道的错误;我用// <<--注释了修正 [我添加了一个main()函数]

#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#pragma include <listdir.h> // <<-- non-existent header

struct pstat {
    long unsigned int utime_ticks;
    long int cutime_ticks;
    long unsigned int stime_ticks;
    long int cstime_ticks;
    long unsigned int vsize; // virtual memory size in bytes
    long unsigned int rss; //Resident  Set  Size in bytes

    long unsigned int cpu_total_time;
};

/*
 * read /proc data into the passed struct pstat
 * returns 0 on success, -1 on error
*/
int get_usage(const pid_t pid, struct pstat* result) {
    char stat_filepath[80] ;
    int ii;
        // use snprintf() , not str[n]cat() to compose strings
    ii = snprintf(stat_filepath, sizeof stat_filepath, "/proc/%d/stat", pid );
    if (ii >= sizeof stat_filepath) return -1;

    FILE *fpstat = fopen(stat_filepath, "r");
    if (fpstat == NULL) {
        perror("FOPEN ERROR "); // <<-- should be printed by caller
        return -1;
    }

    FILE *fstat = fopen("/proc/stat", "r");
    if (fstat == NULL) {
        perror("FOPEN ERROR "); // <<-- could be printed by caller
        fclose(fstat);
        return -1;
    }

    //read values from /proc/pid/stat
    memset(result, 0 , sizeof *result ); // bzero is a BSD-ism
    long int rss;
    if (fscanf(fpstat, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"
                "%lu %ld %ld %*d %*d %*d %*d %*u %lu %ld",
                &result->utime_ticks, &result->stime_ticks,
                &result->cutime_ticks, &result->cstime_ticks, &result->vsize,
                &rss) == EOF) {
        fclose(fpstat);
        return -1;
    }
    fclose(fpstat);
    result->rss = rss * getpagesize();

    //read+calc cpu total time from /proc/stat
    long unsigned int cpu_time[10];
    memset(cpu_time,0, sizeof cpu_time);
    if (fscanf(fstat, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
                &cpu_time[0], &cpu_time[1], &cpu_time[2], &cpu_time[3],
                &cpu_time[4], &cpu_time[5], &cpu_time[6], &cpu_time[7],
                &cpu_time[8], &cpu_time[9]) == EOF) {
        fclose(fstat);
        return -1;
    }

    fclose(fstat);

    for(ii=0; ii < 10;ii++)
        result->cpu_total_time += cpu_time[ii];

    return 0;
}
int my_cpu_usage_func(int pid){
  struct pstat result; // <<-- this is a structure, not a pointer
  double cpu = 0.0;
  int success ;

  success = get_usage(pid, &result); // <<-- but the function expects a pointer, so give it one
  if (success == -1) printf("Couldn't read CPU usage\n");
  else if(success == 0) {
        printf("CPU usage read successfully\n");
        cpu = result.cpu_total_time;
        printf("CPU usage of %d %f\n", pid, cpu);
        }
  return success;
}

int main(void)
{
my_cpu_usage_func(getpid());

return 0;
}