linux C 獲取pid終極父程序的PID
阿新 • • 發佈:2019-02-11
int GetFatherPid(int pid)
{
char dir[1024]={0};
char path[1024] = {0};
char buf[1024] = {0};
int rpid = 0;
int fpid=0;
char fpth[1024]={0};
struct stat st;
ssize_t ret =0;
sprintf(dir,"/proc/%d/",pid);
sprintf(path,"%sstat",dir);
if(stat(path,&st)!=0)
{
return -2;
}
memset(buf,0,strlen(buf));
FILE * fp = fopen(path,"r");
ret += fread(buf + ret,1,300-ret,fp);
fclose(fp);
sscanf(buf,"%*d %*c%s %*c %d %*s",fpth,&fpid);
fpth[strlen(fpth)-1]='\0';
if(strcmp(fpth,"bash")!=0 && strcmp(fpth,"sudo")!=0 ) //bash 終端 sudo 終端
{
if(fpid==1)
{
return pid;
}
else if(fpid==2)
{
return -1; //核心執行緒
}
rpid = GetFatherPid(fpid);
if(rpid == 0)
{
rpid = pid;
}
}
return rpid;
}