c - 使用 fork() 的 Linux 进程树

标签 c linux fork

我正在尝试使用 fork() 函数创建以下进程树: enter image description here

我知道代码有点乱,但我是初学者,尽管我尝试了,但无法理解很多关于流程的事情。我正在等待对代码的一些建议以及该代码是否正确的意见。提前谢谢你。

最佳答案

您可能喜欢将任务分解为基本步骤:

  1. 编写一个函数来创建一个子进程来执行您提供的函数。
  2. 重复使用该函数来创建所需的流程树。

例子:

#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

关于c - 使用 fork() 的 Linux 进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55971838/

相关文章:

c - 水印图片上C点水印功能

java - 如何启动/停止/重新启动 Linux 服务以及如何从 Java 程序更新它们的配置文件

java - Bouncy CaSTLe 无法在 Linux 机器上运行

c - unlocked_ioctl 与普通 ioctl

linux - 为什么需要僵尸进程?

c - 如何在解析不同流的 block 时保持 Bison 状态?

android - 如何从 unsigned char* 数组中获取 jpeg 图像数组?

c - fork() - 父进程和子进程访问多个文件

ruby - 如何在 Ruby 中控制子进程 stdin、stdout 等?

c - 比较两个数组时如何读取 'zero'?