在我正在开发的基于Linux的项目中,我需要能够找到所有子进程。每次开始记录都是不可行的 - 它们需要在事后发现。这需要是纯C,我想在没有读/ proc的情况下这样做。有谁知道如何做到这一点?
我发现你的评论认为将进程的创建记录为奇数是不可行的,但是如果你真的不能(可能是因为你不知道将创建多少进程并且不想保持realloc
ing内存),然后我可能打开所有匹配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 *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; }
你可以试试这个
#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()
执行的完整命令。
您可以解析包含父进程ID的进程列表(ps -ax?)。这可能是通过一个简单的shell脚本完成的。
如果要跟踪fork事件并提取子pid以进行调试,有很多方法可以做到这一点,包括:
如果您尝试将所有子进程用于等待它们退出的特定目的,则可以使用waitpid(-1,...):
while (true) {
// Wait for any child exiting
int child_status;
const int child_pid = waitpid(-1, &child_status, 0);
// check child_status
}