#include<stdio.h>
#include<dirent.h>
#include<string.h>
typedef struct pro_info
{
int pid;
int ppid;
char name[100];
int flag;
int rec;
}info;
int filter(const struct dirent *dir){ //select number folder
int i;
int n = strlen(dir->d_name);//
for(i = 0;i<n;i++)
{
if(!isdigit(dir->d_name[i]))
return 0;
}
return 1;
}
int my_getpid(char * str)
{
int length=strlen(str);
char num[10];
int i,j,ret;
if(strncmp(str,"Pid",3)==0)
{
for(i=0;i<length;i++)
{
if(str[i]>='0'&&str[i]<='9')
break;
}
for(j=0;j<length-i;j++)
num[j]=str[i+j];
num[j]='\0';
ret=atoi(num);
}
else ret=-1;
return ret;
}
int my_getppid(char *str){
int len=strlen(str);
char num[10];
int i,j,ret;
if(strncmp(str,"PPid",4)==0){
//printf("%s",str);
for(i=0;i<len;i++){
if(str[i]>='0'&&str[i]<='9')
break;
}
//printf("len=%d,i=%d\n",len,i);
for(j=0;j<len-i+1;j++){
num[j]=str[i+j];
}
num[j]='\0';
ret=atoi(num);
//printf("ret=%d\n",ret);
}
else ret=-1;
return ret;
}
void print_tree(info *proc,int total,int ppid,int rec)
{
int i,j,k;
for(i=0;i<total;i++)
{
if(proc[i].flag==0&&proc[i].ppid==ppid)
{
proc[i].rec=rec+1;
proc[i].flag=1;
for(k=0;k<rec;k++)
printf(" ");
if(proc[i].pid>0)
printf("├——%s(%d)\n",proc[i].name,proc[i].pid);
print_tree(proc,total,proc[i].pid,proc[i].rec);
}
}
}
//main
int main()
{
struct dirent **namelist;
int k,ppid,pid,s1,s2,j;
char pid_path[20],str[100],name[100];
info proc[1024];
int i=0;//,t=0;
FILE *fp;
int total=scandir("/proc",&namelist,filter,alphasort);
if(total<0)
{
printf("scandir erorr !!!");
}
else printf("共有进程:%d\n",total);
printf("===================================\n");
for(i=0;i<total;i++)
{
strcpy(pid_path,"/proc/");
strcat(pid_path,namelist[i]->d_name);
strcat(pid_path,"/status");
fp=fopen(pid_path,"r");
while(!feof(fp))
{
fgets(str,1024,fp);
if((s1=my_getpid(str))!=-1)
pid=s1;
if((s2=my_getppid(str))!=-1)
ppid=s2;
if(strncmp(str,"Name",4)==0)
{
for(j=4;j<strlen(str);j++)
{
if(str[j]>='a'&&str[j]<='z')
break;
}
for(k=j;k<strlen(str);k++)
{
name[k-j]=str[k];
}
name[k-j]='\0';
}
proc[i].pid=pid;
proc[i].ppid=ppid;
strcpy(proc[i].name,name);
}
fclose(fp);
proc[i].flag=0;
proc[i].rec=0;
}
print_tree(proc,total,0,0);
}