如何找到所有子进程?

问题描述 投票:14回答:7

在我正在开发的基于Linux的项目中,我需要能够找到所有子进程。每次开始记录都是不可行的 - 它们需要在事后发现。这需要是纯C,我想在没有读/ proc的情况下这样做。有谁知道如何做到这一点?

c linux process
7个回答
4
投票

我发现你的评论认为将进程的创建记录为奇数是不可行的,但是如果你真的不能(可能是因为你不知道将创建多少进程并且不想保持reallocing内存),然后我可能打开所有匹配glob /proc/[1-9]*/status的文件,并寻找说PPid: <num>的行,其中<num>是我的进程ID。


5
投票

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

正如手册页所说:

pid_t fork(void);

如果您能告诉我们您认为不可行的原因,将会有所帮助。


5
投票

你可以使用popen

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

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

int main(int argc, char *argv[])
{
    FILE *fp = popen("ps -C *YOUR PROGRAM NAME HERE* --format '%P %p'" , "r");
    if (fp == NULL)
    {
        printf("ERROR!\n");
    }

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

         // Check the parentID to see if it that of your process
    }

    pclose(fp);

    return 1;
}



4
投票

你可以试试这个

#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 <parent_id>的所有子进程的pid。现在,我们可以使用getpid()获取父进程的PID,它返回pid_t并隐式转换为整数。 sprintf()将其转换为字符串,我们将结果与str连接起来,以获得由system()执行的完整命令。


1
投票

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


0
投票

如果要跟踪fork事件并提取子pid以进行调试,有很多方法可以做到这一点,包括:

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

0
投票

如果您尝试将所有子进程用于等待它们退出的特定目的,则可以使用waitpid(-1,...):

while (true) {
  // Wait for any child exiting
  int child_status;
  const int child_pid = waitpid(-1, &child_status, 0);
  // check child_status
}
© www.soinside.com 2019 - 2024. All rights reserved.