Chinaunix首页 | 论坛 | 博客
  • 博客访问: 312255
  • 博文数量: 45
  • 博客积分: 2079
  • 博客等级: 上尉
  • 技术积分: 464
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-03 16:57
文章分类

全部博文(45)

文章存档

2015年(1)

2013年(1)

2012年(9)

2011年(2)

2010年(32)

分类: LINUX

2012-03-08 17:31:35

    前一段时间做的一个小demo,可用于获取当前进程内存使用情况。守护进程可以用这种方式根据自己的内存使用情况,做相应的处理。闲言少叙,直接上代码吧。

#include
#include
#include
int main(void)
{
    unsigned long rss_value = 0;
    FILE *fp;
    char buf[32];
    char line[256];
    memset(buf,0,sizeof(buf));
    memset(line,0,sizeof(line));
    pid_t pid;
    pid = getpid();
    printf("The pid is: %d\n", pid);
    sprintf(buf, "/proc/%d/status", pid);
    printf("The buf is: %s\n", buf);
    if ((fp = fopen(buf, "r")) == NULL)
    {
        return -1;
    }
    while(line == fgets(line, sizeof(line), fp)){
    if(strstr(line,"VmRSS:"))
    {
        printf("%s\n",line);
        sscanf(line,"VmRSS:\t%8lu kB\n",&rss_value);
        printf("value is %lu\n",rss_value);
    }
    memset(line,0,sizeof(line));
    }       
    fclose(fp);
    return 0;
}

[root@localhost test]# gcc self_test_mem.c
[root@localhost test]# ./a.out 
The pid is: 6666
The buf is: /proc/6666/status
VmRSS:       396 kB

value is 396


阅读(3397) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~