How to get all child process's PIDs when given

2019-08-10 08:01发布

问题:

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;
}