linux C获取进程的CPU和内存

来源:互联网 发布:mac ppt演讲者模式 编辑:程序博客网 时间:2024/06/04 05:38

获取内存开始尝试用getrusage,发现数值一直是0的,,,后面查资料,该函数内存相关的字段还没实现(unmaintained)

使用statm的,发现rss和data位即使top时看到的内存已经下降了但是数值仍然不变,只能通过resident字段来获取当前进程所占用的内

size       (1) total program size
                             (same as VmSize in /proc/[pid]/status)
                  resident   (2) resident set size
                             (same as VmRSS in /proc/[pid]/status)
                  share      (3) shared pages (i.e., backed by a file)
                  text       (4) text (code)
                  lib        (5) library (unused in Linux 2.6)
                  data       (6) data + stack
                  dt         (7) dirty pages (unused in Linux 2.6)



            FILE *f = fopen("/proc/self/statm","r");        if(f){             i = fscanf(f,"%u%u%u%u%u%u%u",            &n_rss,&n_resident,&n_share,&n_text,&n_lib,&n_data,&n_dt);                         fclose(f);        }        else        {            IMIO::instance()->log(INFO, "open /proc/self/statm fail");        }        n_rss = n_resident * 4 / 1024;        if (n_rss < 1024*1.5 && s_freereq.size() > s_threadnum/3)        {            return ;        }        static unsigned int s_CLOCKS_PER_SEC_100 = CLOCKS_PER_SEC / 100;        clock_t ct0, ct1;         ct0 = clock ();        sleep(1);        ct1 = clock ();            char buf[256];        sprintf(buf, "rss=%u,mshare=%u;freereq=%ld;cpu=%ld;", n_rss, n_share/1024, s_freereq.size(), (ct1 - ct0) /s_CLOCKS_PER_SEC_100);


0 0
原创粉丝点击