【问题标题】:add pid value to /proc/"pid"/stat将 pid 值添加到 /proc/"pid"/stat
【发布时间】:2021-05-14 20:04:46
【问题描述】:

您好,我需要将 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];

【问题讨论】:

    标签: c cpu-usage pid


    【解决方案1】:

    显然,要将%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个系统时间。

    【讨论】:

    • 哦,谢谢先生的解决方案,我只是看到 /proc/stat 上的信息与 /proc/self/stat 上的信息不一样,如何获得 self 进程的 cpu 使用率!?跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多