1:首先介绍下psinfo_t结构体
多种 proc 探测器具有 psinfo_t(proc(4) 中记录的一种结构)类型的参数。DTrace 使用者可以使用的 psinfo_t 结构的定义如下所示
typedef struct psinfo {
int pr_nlwp; /* number of active lwps in the process */
pid_t pr_pid; /* unique process id */
pid_t pr_ppid; /* process id of parent */
pid_t pr_pgid; /* pid of process group leader */
pid_t pr_sid; /* session id */
uid_t pr_uid; /* real user id */
uid_t pr_euid; /* effective user id */
gid_t pr_gid; /* real group id */
gid_t pr_egid; /* effective group id */
uintptr_t pr_addr; /* address of process */
dev_t pr_ttydev; /* controlling tty device (or PRNODEV) */
timestruc_t pr_start; /* process start time, from the epoch */
char pr_fname[PRFNSZ]; /* name of execed file */
char pr_psargs[PRARGSZ]; /* initial characters of arg list */
int pr_argc; /* initial argument count */
uintptr_t pr_argv; /* address of initial argument vector */
uintptr_t pr_envp; /* address of initial environment vector */
char pr_dmodel; /* data model of the process */
taskid_t pr_taskid; /* task id */
projid_t pr_projid; /* project id */
poolid_t pr_poolid; /* pool id */
zoneid_t pr_zoneid; /* zone id */
} psinfo_t;pr_dmodel 字段设置为 PR_MODEL_ILP32(表示 32 位进程)或 PR_MODEL_LP64(表示 64 位进程)。
2:包含的头文件
3:简单的例子
以下是根据进程号获取ID函数:
/**
函数名:nGetNameByPid
功能 :根据进程号得到启动状态
参数 :
pid 进程号
name 进程名
返回值:
0 存在
-1 处理失败
**/
int nGetNameByPid(int pid,char *name)
{
char pcFileName[128];
FILE *fp;
psinfo_t ps;
memset(&ps,'\0',sizeof(ps));
sprintf(pcFileName,"/proc/%d/psinfo",pid);
fp=fopen(pcFileName,"rb");
if(fp==NULL){
sprintf(name,"未启动");
return(-1); /**不存在**/
}else{
int i=0;
fread(&ps,sizeof(psinfo_t),1,fp);
if(ps.pr_fname[0]==' ' ||ps.pr_fname[0]=='\0'){
sprintf(name,"未启动");
}else{
sprintf(name,"启动");
}
fclose(fp);
return(0); /**存在**/
}
return(0);
}
static pid_t getpidbyname (char *name)
{
DIR *dirHandle; /* 目录句柄 */
struct dirent *dirEntry; /* 单个目录项 */
psinfo_t prp;
pid_t pid = -1;
char strPathName[100];
FILE *fp;
memset(strPathName, 0, 100);
if( ( dirHandle = opendir( "/proc" ) ) == NULL )
{
return( -1 );
}
chdir( "/proc" );
/* 下面使用相对路径打开文件,所以必须进入/proc */
while( ( dirEntry = readdir( dirHandle ) ) != NULL )
{
if( dirEntry->;d_name[0] != '.' && strcmp(dirEntry->;d_name,"sys") != 0)
{
/* 拼加路径 */
sprintf(strPathName, "./%s/%s", dirEntry->;d_name, "psinfo");
/* 读取文件 */
if( ( fp = fopen( strPathName, "rb" ) ) == NULL )
{
printf("打开文件[%s]失败!\n", strPathName);
break;
}
/* 读取数据 */
if(fread(&prp, sizeof(psinfo_t), 1, fp) == -1)
{
printf("文件读取失败!\n");
fclose(fp);
break;
}
if ( strcmp( prp.pr_fname, name) == 0 )
{
pid = ( pid_t )atoi( dirEntry->;d_name );
break;
}
fclose( fp );
}
} /* end of while */
closedir( dirHandle );
return( pid );
} /* end of getpidbyname */