c - 进程的二叉树

标签 c recursion process fork binary-tree

我正在尝试创建一个递归函数,在给定树的级别数的情况下,使用 fork() 创建父子进程的二叉树结构。到目前为止我已经:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>


void createTree(int level){

    pid_t leftson;
    pid_t rightson;

    if (level > 1){


        if ((leftson = fork()) < 0) {
             perror("fork:");
             exit(1);
        }   // Create the first son

        if (leftson == 0){
            createTree(level--);
        } // If I'm the left son, continue biulding the structure

        else { // I'm father

            if ((rightson = fork()) < 0) {
                 perror("fork:");
                 exit(1);
            } // Create right son

            if (rightson == 0){
                createTree(level--);
            } // I'm right, continue building

            else printf("created my 2 sons"); // I'm the father

        } 




    }
    else if (level == 1){
        printf("end of tree");
    }   




}


void main(){

    createTree(3);

}

问题是程序进入了创建进程的无限循环,因为级别变量永远不会减少,我正在考虑使用管道,但我不知道当进程太多时如何使用它们。

另外,有没有办法像我在 bash 中那样给出新进程的参数?而不是使用管道?

最佳答案

尝试使用createTree(level-1);而不是createTree(level--);,因为有时这可能会导致递归调用中的无限循环。

关于c - 进程的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319803/

相关文章:

c++ - 递归回溯数独求解器问题,C++

python - 创建未知数量的以编程方式定义的变量

c# - 在 C# 中运行程序时,所有消息都转到标准输出,但标准错误不包含任何内容

Android 应用程序到 Linux 的流程映射

c - 如何知道 scanf() 的分界线

c++ - Cython VS C++ 性能比较?

c++ - 重载==递归比较两个链表

firefox - 如何处理 Selenium 崩溃

c - 面向 C/C++ 开发人员的 Eclipse IDE : breakpoints not working

c - 根据规则对从文件中读取的文本进行标记