linux 下获通过pid获取绝对路径
char * GetFullPath(int pid)
{
char dir[256]={0};
char path[256] = {0};
char link[256] = {0};
char * cmdline=NULL;
char *linkpath=NULL;
char * hmoedir=NULL;
char * ptr = NULL;
FILE * fp = NULL;
struct stat st;
ssize_t ret =0;
sprintf(dir,"/proc/%d/",pid);
sprintf(path,"%sstat",dir);
if(stat(dir,&st)!=0)
{
return NULL;
}
sprintf(link,"%sexe",dir);
linkpath =(char *) calloc(4096,sizeof(char));
if( readlink(link,linkpath,4096)<0)
{
printf("errr1\n"); //链接有问题
free(linkpath);
return NULL;
}
if(strcmp(linkpath,"/bin/bash")!=0) //检查是不是shell脚本
{
return linkpath; //直接找到
}
//是shell脚本
memset(linkpath,0,strlen(linkpath));
sprintf(link,"%scwd",dir);
hmoedir =(char *) calloc(4096,sizeof(char));
if( readlink(link,hmoedir,4096)<0) //获取home目录
{
printf("errr2\n"); //home链接目录不存在
free(linkpath);
free(hmoedir);
return NULL;
}
cmdline = (char *) calloc(8192,sizeof(char));
sprintf(path,"%scmdline",dir);
fp = fopen(path,"rb");
ret += fread(cmdline + ret,1,8192-ret,fp);
fclose(fp);
ptr = cmdline+strlen(cmdline)+1; //过滤shell头 /bin/bash or /bin/sh
if(ptr[0]=='.'&&ptr[1]=='/') //是不是绝对路径运行
{
sprintf(linkpath,"%s%s",hmoedir,ptr+1) ;
}
else
{
sprintf(linkpath,ptr);
}
if(hmoedir)
{
free(hmoedir);
}
if(cmdline)
{
free(cmdline);
}
return linkpath; //返回绝对路径
}