How to get all child process's PIDs when given the parent PID in C

你。 提交于 2020-01-05 13:07:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!