用C给出父PID时如何得到所有子进程的PID [英] How to get all child process's PIDs when given the parent PID in C

查看:405
本文介绍了用C给出父PID时如何得到所有子进程的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,这可以在bash这样做: pstree父-PID 。但我怎么能做到这一点用C ?有没有不必遍历整个/ proc文件系统中的任何方法(例如系统调用/库函数)?

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)?

推荐答案

您可以使用的popen 读命令 PS -ef的输出,然后查找所有的子进程指定 PID

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

这篇关于用C给出父PID时如何得到所有子进程的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆