热门关键字:  ubuntu  分区  函数  linux系统进程  Fedora

Linux下如何查看某一进程的CPU占用率

来源: 作者: 时间:2007-04-25 Tag: 点击:

/proc下每个进程有一个目录,目录下的stat文件可以得到关于该进程的信息,比如:

# cat /proc/2122/stat

2122 (sshd) S 6599 2122 2122 0 -1 8448 1110 217 0 1 20 3 12 0 15 0 1 0 242306177 8482816 592 4294967295 134512640 134795532 3221224656 3221220240 4294960144 0 0 4096 73728 0 0 0 17 0 0 0

具体每一项的内容可以看man:

man 5 proc

cpu的占用率似乎并不能直接得到,你需要自己去计算,我猜想ps的做法是从/proc得到所有进程的信息,通过每个进程的运行时间,可以计算出某个进程的占用率

正好做过点这个,给你参考一下,恕未整理:

char buf[64];
    sprintf(buf,"/proc/%d/stat",pid);
    FILE* fid = fopen(buf,"r");
    if(fid){
    fscanf(fid,"%d %s %c %d %d %d %d %d %lu %lu "
    "%lu %lu %lu %lu %lu %ld %ld %ld %ld %ld "
    "%ld %ld %lu %lu %ld %lu %lu %lu %lu %lu",
     &pstat[0],buf,&pstat[2],&pstat[3],&pstat[4],&pstat[5],&pstat[6],&pstat[7],
    &pstat[8],&pstat[9],&pstat[10],&pstat[11],&pstat[12],&pstat[13],&pstat[14],&pstat[15],
     &pstat[16],&pstat[17],&pstat[18],&pstat[19],&pstat[20],&pstat[21],&pstat[22],&pstat[23],
     &pstat[24],&pstat[25],&pstat[26],&pstat[27],&pstat[28],&pstat[29],&pstat[30]);
     fclose(fid);
。。。。。
    ut = pstat[13];
    st = pstat[14];
    cut = pstat[15];
    cst = pstat[16];
。。。。。
   ts = time(NULL) - lasttime;
   百分比=(ut+st-sut-sst)/ts

最新评论共有 4 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册