[英]Linux process tree using fork()
您可能希望將任務分解為原始步驟:
例:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int level = 1;
char const offsets[] = "\t\t\t\t\t\t\t\t";
pid_t create_child_process(int(*child_fn)()) {
// Flush the output buffers to avoid duplicate output from the child process.
fflush(stdout);
fflush(stderr);
pid_t child_pid = fork();
switch(child_pid) {
case 0: // Child process.
++level;
exit(child_fn());
case -1: // fork() failed.
abort();
default: // Parent process.
printf("%.*s %u spawned %u\n", level, offsets, (unsigned)getpid(), (unsigned)child_pid);
return child_pid;
}
}
void wait_for_any_child() {
int wstatus;
pid_t child_pid = wait(&wstatus);
if(child_pid == -1)
abort();
printf("%.*s %u terminated\n", level, offsets, (unsigned)child_pid);
}
int p2() { return 0; }
int p5() { return 0; }
int p6() { return 0; }
int p7() { return 0; }
int p4() {
create_child_process(p5);
create_child_process(p6);
create_child_process(p7);
wait_for_any_child();
wait_for_any_child();
wait_for_any_child();
return 0;
}
int p3() {
create_child_process(p4);
wait_for_any_child();
return 0;
}
int p1() {
printf("%u started\n", (unsigned)getpid());
create_child_process(p2);
create_child_process(p3);
wait_for_any_child();
wait_for_any_child();
printf("%u terminated\n", (unsigned)getpid());
return 0;
}
int main() {
return p1();
}
輸出:
5962 started
5962 spawned 5963
5962 spawned 5964
5963 terminated
5964 spawned 5965
5965 spawned 5966
5965 spawned 5967
5965 spawned 5968
5966 terminated
5967 terminated
5968 terminated
5965 terminated
5964 terminated
5962 terminated
如果你為每個pid使用自己的pid變量(例如p1,p2 ......),它可能會變得不那么混亂。 也許它有幫助,如果你評論哪個進程正在運行分支:
pid_t p1, p2, p3, p4, p5, p6, p7;
p1 = getpid();
p2 = fork();
if (p2 != 0)
{
// P1 runs this branch
p3 = fork();
if (p3 == 0)
{
// P3 runs this branch
p4 = fork();
if (p4 == 0)
{
// P4 runs this branch
p5 = fork();
if (p5 != 0)
{
// P4 runs this branch
p6 = fork();
if (p6 != 0)
{
// P4 runs this branch
p7 = fork();
}
}
}
}
}
您的代碼中可能還有其他問題。 但是例如:
// create child#1
fork();
// create child#2
fork();
// create child#3
fork();
...將產生7個孩子的樹。
如果你正在創建一個嚴肅的程序(不僅僅是使用fork
),那么你需要更好地檢查fork()
結果,因為它也可能失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.