您好,我需要将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];发布于 2021-05-15 04:18:20
显然,要将%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个系统时间。
https://stackoverflow.com/questions/67540379
复制相似问题