问题
I know that this can be done in bash by: pstree parent-pid
. But how can I do this in C
? Is there any method that doesn't have to iterating the whole /proc file system (e.g. system call/library function)?
回答1:
you can use popen
to read the output of the command ps -ef
,then look for the all the child process of a specified PID
int getAllChildProcess(pid_t ppid)
{
char *buff = NULL;
size_t len = 255;
char command[256] = {0};
sprintf(command,"ps -ef|awk '$3==%u {print $2}'",ppid);
FILE *fp = (FILE*)popen(command,"r");
while(getline(&buff,&len,fp) >= 0)
{
printf("%s\n",buff);
}
free(buff);
fclose(fp);
return 0;
}
来源:https://stackoverflow.com/questions/20393397/how-to-get-all-child-processs-pids-when-given-the-parent-pid-in-c