Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1048786
  • 博文数量: 297
  • 博客积分: 11721
  • 博客等级: 上将
  • 技术积分: 3431
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-25 10:21
文章分类

全部博文(297)

文章存档

2016年(9)

2011年(71)

2010年(137)

2009年(80)

分类: LINUX

2010-12-29 13:42:54

#include
#include
#include
#include
#include
#include
#include

#define READ_BUF_SIZE 1024

int find_pids_by_name(char *pidName, int *pids, int size)
{
    DIR *dir;
    struct dirent *next;
    int i=0;

    dir = opendir("/proc");
    if (!dir)
    {
        fprintf(stderr, "Cannot open /proc\n");
        exit(1);
    }

    while((next = readdir(dir)) != NULL)
    {
        FILE *status;
        char filename[READ_BUF_SIZE];
        char buffer[READ_BUF_SIZE];
        char name[READ_BUF_SIZE];

        // Must skip ".." since that is outside /proc
        if (strcmp(next->d_name, "..") == 0)
            continue;

        // If it isn't a number, we don't want it
        if (!isdigit(*next->d_name))
            continue;

        sprintf(filename, "/proc/%s/status", next->d_name);
        if (! (status = fopen(filename, "r")))
            continue;

        // Read first line in /proc/?pid?/status
        if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL)
        {
            fclose(status);
            continue;
        }
        fclose(status);

        // Buffer should contain a string like "Name:   binary_name"
        sscanf(buffer, "%*s %s", name);
        if (!strcmp(name, pidName))
        {
                        *(pids+i) = strtol(next->d_name, NULL, 0);
                        i++;
        }
    }

    return i;
}
int main()
{
        int pids[10];
        memset(pids, 0, sizeof(int)*10);
        int ret, i;
        ret=find_pids_by_name( "Parse", pids, 10);
        printf("ncount->[%d]\n", ret);
        for(i=0; i< ret; i++)
                printf("pid[%d]->[%d]\n", i, pids[i]);

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