使用fork()的Linux进程树 [英] Linux process tree using fork()

查看:59
本文介绍了使用fork()的Linux进程树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create the following process tree using the fork() function:

我知道代码有点杂乱无章,但是我是一个初学者,尽管我尝试过,但我不了解有关流程的许多内容.我正在等待有关该代码的建议,以及该代码是否正确的意见.预先谢谢你.

I am aware that the code is kind of messy but I'm a begginer and can't understand many things about processes although I tried to. I am waiting for some advice for the code and what an opinion whether this code is correct or not. Thank you in advance.

推荐答案

您可能希望将任务分解为原始步骤:

You may like to break down the task into primitive steps:

  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

这篇关于使用fork()的Linux进程树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆