将 pid 值添加到 /proc/"pid"/stat

时间:2021-05-14 20:04:46

标签: c cpu-usage pid

嗨,我需要将pid号添加到/proc/%d/stat

我该怎么做? 这是我的完整代码,有了这个,我就有了总的 CPU 使用率:

unsigned sleep(unsigned sec);    
struct cpustat {
    unsigned long t_user;
    unsigned long t_nice;
    unsigned long t_system;
    unsigned long t_idle;
    unsigned long t_iowait;
    unsigned long t_irq;
    unsigned long t_softirq;
};


void skip_lines(FILE *fp, int numlines)
{
    int cnt = 0;
    char ch;
    while((cnt < numlines) && ((ch = getc(fp)) != EOF))
    {
        if (ch == '\n')
            cnt++;
    }
    return;
}


void get_stats(struct cpustat *st, int cpunum)
{
    FILE *fp = fopen("/proc/stat", "r");
    int lskip = cpunum+1;
     skip_lines(fp, lskip);
    char cpun[255];

1 个答案:

答案 0 :(得分:0)

显然,要将 %d 替换为整数,您需要像在第二个示例中一样将 sprintf 用于缓冲区。您也可以只使用 /proc/self/stat 来获取当前进程的统计信息,而不是 getpid+sprintf。

您的主要问题似乎与您希望看到的内容/格式有关。 stat 包含有关进程的单行信息,如 proc(5) 中所述。例如:

$ cat /proc/self/stat
27646 (cat) R 3284 27646 3284 34835 27646 4194304 86 0 1 0 0 0 0 0 20 0 1 0 163223159 7618560 210 18446744073709551615 4194304 4240236 140730092885472 0 0 0 0 0 0 0 0 0 17 1 0 0 2 0 0 6340112 6341364 37523456 140730092888335 140730092888355 140730092888355 140730092892143 0

您似乎跳过了一些初始行,然后尝试阅读不同格式的内容。


在 proc(5) 手册页中,/proc/self/stat 中的一些数字与 CPU 时间有关:

          (14) utime  %lu
                    Amount of time that this process has been scheduled in  user  mode,  mea‐
                    sured  in  clock  ticks  (divide by sysconf(_SC_CLK_TCK)).  This includes
                    guest time, guest_time (time spent running a virtual CPU, see below),  so
                    that  applications that are not aware of the guest time field do not lose
                    that time from their calculations.

          (15) stime  %lu
                    Amount of time that this process has been scheduled in kernel mode,  mea‐
                    sured in clock ticks (divide by sysconf(_SC_CLK_TCK)).

它为您提供了自此过程开始以来在此过程中的总 CPU 时间。使用上面的 cat 程序,这些数字都是 0(它运行得太快,无法累积任何滴答声),但如果我这样做了

$ cat /proc/$$/stat
3284 (bash) S 2979 3284 3284 34835 12764 4194304 71122 947545 36 4525 104 66 1930 916 20 0 1 0 6160 24752128 1448 18446744073709551615 4194304 5192964 140726761267456 0 0 0 65536 3670020 1266777851 1 0 0 17 1 0 0 68 0 0 7290352 7326856 30253056 140726761273517 140726761273522 140726761273522 140726761275374 0

你可以看到我的shell有104个用户时间和66个系统时间。