简体   繁体   English

获取当前进程的CPU使用率

[英]Get CPU usage of current process

I am trying to read the CPU usage of a current process based on PID. 我试图读取基于PID的当前进程的CPU使用率。 I am using the following code to fetch CPU usage: 我正在使用以下代码来获取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;
}

Got the above code from this github project: https://github.com/fho/code_snippets/blob/master/c/getusage.c and is an answer of this question: https://stackoverflow.com/a/4410209/9951420 从这个github项目中获得了上面的代码: https : //github.com/fho/code_snippets/blob/master/c/getusage.c ,是这个问题的答案: https : //stackoverflow.com/a/4410209/ 9951420

Now when I am trying to call the get_usage() in my function as follows: 现在,当我尝试按以下方式在函数中调用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);
}

When I am compiling my_cpu_usage_func(int) I am first getting the following warning: 当我编译my_cpu_usage_func(int)时,我首先收到以下警告:

extmodule.c:131:23: note: initialize the variable 'result' to silence this warning struct pstat* result; extmodule.c:131:23:注意:初始化变量“结果”以使此警告结构pstat *结果静音; ^ = NULL ^ =空

And then when I am executing the same function I am getting the following error: 然后,当我执行相同的功能时,出现以下错误:

FOPEN ERROR : No such file or directory FOPEN ERROR:没有这样的文件或目录

Can anyone help in this? 有人可以帮忙吗? NB I am new to C programming, so any help will be awesome. 注意:我是C编程的新手,所以任何帮助都很棒。

There are a few trivial errors in the program; 程序中有一些琐碎的错误; I Annotated the fixes with // <<-- [And I added a main() function] 我注释的修复与// <<-- [和我加入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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM