如何find所有的subprocess?

在我正在开发的基于Linux的项目中,我需要能够find我所有的subprocess。 每次开始logging都是不可行的 – 事后要find它们。 这需要是纯粹的C,我想这样做没有读/ proc。 有谁知道如何做到这一点?

我发现你的评论认为,把进程的创建记录为奇怪是不可行的,但是如果你真的不能(可能是因为你不知道有多少人会被创建,不想保持重新分配内存),那么我可能会打开所有匹配glob /proc/[1-9]*/status的文件,并找到说PPid: <num>的行,其中<num>是我的进程ID。

每次开始记录子进程通常是完全可行的。 方便地,父进程传递子进程的PID值作为创建它的fork调用的返回值。

正如手册页所述:

 pid_t fork(void); 

如果你能告诉我们为什么你认为这是不可行的,这将有所帮助。

你可以用popen

就像是。 (希望语法足够接近)

 #include <stdio.h>
 #include <unistd.h>
 #include <stdlib.h>

 int main(int argc,char * argv [])
 {
     FILE * fp = popen(“ps -C *您的程序名称在这里*  - 格式'%P%p'”,“r”);
    如果(fp == NULL)
     {
        的printf( “ERROR \ n!”);
     }

     char parentID [256];
     char processID [256];
     while(fscanf(fp,“%s%s”,parentID,processID)!= EOF)
     {
          printf(“PID:%s父:%s \ n”,processID,parentID);

          //检查parentID以查看它是否是你的进程
     }

     pclose函数(FP);

    返回1;
 }


你可以试试这个

  #include<string.h> #include <sys/types.h> #include <unistd.h> char str[50] = "ps -o pid --ppid "; char ppid [7]; sprintf(ppid,"%d",getpid()); strcat(str,ppid); system(str); 

注意:这段代码需要在父进程中

基本上, ps -o pid --ppid <parent_id>给出了父节点具有PID的所有子进程的PID。 现在,我们可以通过使用getpid()来获得父进程的PID,该getpid()返回pid_t并隐式转换为整数..sprintf将其转换为字符串,并将结果与str连接以获得由system()执行的完整命令system()

您可以解析包含父进程ID的进程列表(ps -ax?)。 这可能可以用一个简单的shell脚本完成。

如果您想跟踪fork事件并提取用于调试的子pid,有很多方法可以做到这一点,包括:

  • 使用GDB
  • 使用strace
  • 使用systemtap
  • 使用内核事件连接器(不知道这些是什么)

如果您试图获取所有子进程的等待它们退出的特定目的,则可以使用waitpid(-1,…):

 while (true) { // Wait for any child exiting int child_status; const int child_pid = waitpid(-1, &child_status, 0); // check child_status }