您的位置:首页 > 运维架构 > Linux

如何获取linux下的进程pid列表

2013-02-01 15:30 615 查看
有时候,我们需要在移植后的系统上监视linux的进程,有时候需要在新的软件上面进行进程的管理,如何仅仅用system(ps)将会多一个进程并且分析并不是很高效。在proc文件目录下,我们可以看到所有进程的文件(文件名为数字都是对应的pid进程,里面含有对应的进程信息。),在此之前查看比较官方文档会比较清楚。

---------------------------------------------------------

由此,我们可以简单的发现有两个方法能监测到进程的状态,一个经过system的调用,第二经过读取proc目录下的对应文件。

我就可以选择第二种来获取进程的pid列表。

------------------------------------------------------------

函数

功能:获取进程的pid列表和pid总数

输入参数:无

输出参数:进程pid列表指针,pid总数的指针,由上层分配

返回值:0 成功 -1 为失败

-------------------------------------------------------------

#include <dirent.h> //struct DIR
int get_process_IDs (unsigned int* uPid,unsigned int* count)
{
#define READ_BUF_SIZE 1024
DIR* dir;
struct dirent *next;
long pidList;
FILE* status;
char filename[READ_BUF_SIZE];
int i =0;

if(count == NULL || uPid == NULL)
{
//DBGPrint(DBG_DEBUG_OS,DBG_API,"error happened in LINE=%d,FUN=%s\n",__LINE__,__FUNCTION__);
return -1;
}
dir = opendir("/proc");
if(!dir)
{
printf("Cannot open /proc\n");
return -1;
}
//遍历/proc 目录下所有文件,找到数字文件名并记录
while((next = readdir(dir)) != NULL)
{
if(strcmp( next->d_name,".") == 0)
{
continue;
}

if(!isdigit(next->d_name[0]))
{
continue;
}
sprintf(filename,"/proc/%s/status",next->d_name);
if(!(status = fopen(filename,"r")))
{
continue;
}
//找到一个进程,记录pid
pidList = strtol(next->d_name,NULL,0);
uPid[i++] = (CMW_U32)pidList;
if(i >= *count)
{
break;
}
}
closedir(dir);
*count = i;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: