Issue
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)?
Solution
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;
}
Answered By - sundq Answer Checked By - Timothy Miller (WPSolving Admin)