【问题标题】:What is the process tree of that fork?该分叉的进程树是什么?
【发布时间】:2021-06-22 13:50:49
【问题描述】:

我刚刚开始使用叉子,这让我很困惑。 我这里有脚本:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main () {
    int x=3;
    int i;
    for(i=0; i<=2;i++){
        fork();
        x=x-1;
        printf(“process, %x\n”, x);
    }
    return 0;
} 

和这里的输出: enter image description here

现在,我尝试使用 x 的附加值构建进程树,但感觉并不好。 我以为进程数是 8,但正如输出所示,它们是 14。 有人可以帮我处理流程树吗!? 那是我的:

enter image description here

【问题讨论】:

  • 您不检查 fork 的返回值,因此您的代码在父子节点中执行。这是令人困惑的吗?
  • @Luca Scarpelli - 你使用了错误的引号。
  • 我必须画出进程树。为了做到这一点,我必须知道父母和孩子在这里是如何锻炼的。我以为最后只有 8 个进程,但最后进程是 14 个。他们是怎么冒出来的?他们在做什么?是的,我检查了返回值以帮助我了解有多少进程正在运行。
  • 它不应该让你感觉良好。 fork() 是一个功能失调且效率低下的函数,用途有限。当你可以学习有用的多线程时,思考它的作用可能是浪费时间。如果你学习 fork(),你可能最终会使用它,而你应该使用 pthreads。
  • 这很有趣 - 功能失调

标签: c for-loop process treeview fork


【解决方案1】:

您是绝对正确的,因为有 8 个进程 - 原始父进程和 7 个子进程。您只是忽略了打印输出的数量不等于进程的数量,因为每个父级在 fork 之后继续并多次执行printf:原始父级和第一个子级各 3 次,另外两个子级各 2 次,其余四个孩子只有一次; 3 + 3 + 2 + 2 + 1 + 1 + 1 + 1 = 14。

father x=3 i=0 fork x=2 print i=1 fork x=1 print i=2 fork x=0 print
               ch1                ch2                ch3
child1              x=2 print i=1 fork x=1 print i=2 fork x=0 print
                                  ch4                ch5
child2                                 x=1 print i=2 fork x=0 print
                                                     ch6
child3                                                    x=0 print
child4                                 x=1 print i=2 fork x=0 print
                                                     ch7
child5                                                    x=0 print
child6                                                    x=0 print
child7                                                    x=0 print

【讨论】:

  • 那是我将 printf 放入循环中的错误(哈哈)。非常感谢。
  • @LucaScarpelli 使用getpid() (unistd.h) 打印当前的pid,这将有助于您以后对fork() 的探索。检查getpid 手册页。
猜你喜欢
  • 2013-11-19
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
  • 2020-05-15
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多