gpt4 book ai didi

获取 PID 及其所有子项的 CPU 使用率的 C 程序

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:27 37 4
gpt4 key购买 nike

我有一个 C 程序可以解析/proc//stat 目录以计算 5 秒内的平均 CPU 使用率:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define ITERATIONS 5

int main(int argc, char *argv[])
{
if (argc != 2) {
printf( "usage: %s <PID>\n", argv[0] );
return(-1);
}

long double a[4], b[4];
long double pidTime = 0.0;
long int clk;
int i;
FILE *fp;
char stat[1024];

clk = sysconf(_SC_CLK_TCK);

if (clk == -1) {
printf("Could not determine clock ticks per second");
return(-1);
}

char *pidPath = malloc(strlen("/proc/stat/")+strlen(argv[1])+1);
if (pidPath == NULL) {
printf("Could not allocate memory for str\n");
return(-1);
} else {
strcpy(pidPath, "/proc/");
strcat(pidPath, argv[1]);
strcat(pidPath, "/stat");
}

for(i = 0; i < ITERATIONS; i++)
{
fp = fopen(pidPath,"r");
if (fp == NULL) {
perror(pidPath);
return(-1);
} else {
fgets(stat, sizeof(stat), fp);
sscanf(stat,"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %Lf %Lf %Lf %Lf %*ld %*ld %*ld %*ld %*llu",&a[0],&a[1],&a[2],&a[3]);
fclose(fp);
sleep(1);
}

fp = fopen(pidPath,"r");
if (fp == NULL) {
perror(pidPath);
return(-1);
} else {
fgets(stat, sizeof(stat), fp);
sscanf(stat,"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %Lf %Lf %Lf %Lf %*ld %*ld %*ld %*ld %*llu",&b[0],&b[1],&b[2],&b[3]);
fclose(fp);
}

pidTime += (((b[0]+b[1]+b[2]+b[3]) - (a[0]+a[1]+a[2]+a[3])));
}

pidTime = (pidTime / (clk * ITERATIONS));
printf("pidCPU=%Lf\n", pidTime);
printf("%ld", clk);
free(pidPath);
return(0);
}

据我了解,stat 中的相关字段是:

  • 时间;/** 用户模式 ​​jiffies **/

  • 时间;/** 内核模式 jiffies **/

  • int cutime;/** 用户模式 ​​jiffies with childs **/

  • int 时间;/** 内核模式 jiffies with childs **/

对于单个进程,这很好用,但是当我有一个 fork 或多线程的进程时,它就会崩溃。 cutime 和 cstime 计数器是否仅在父进程等待子进程时才工作?如何计算以 PID 为根的进程树的总使用量?

最佳答案

是的,父级需要等待子级的 CPU 时间被添加进来(参见 getrusage 的手册条目 link )。另见 this answer了解更多详情。

关于获取 PID 及其所有子项的 CPU 使用率的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839560/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com