为什么hello world只打印两次为什么a的最大值是2

Why does hello world print twice only and why is a's largest value 2

#include <stdio.h>
#include <unistd.h>

int main() {
    int a=0;
    int rc=fork();
    a++;
    if(rc=0)
    {
        rc=fork();

        a++;
    }
    else
    {
       a++;
    }
    printf("Hello World");
    printf("%d",a);

    return 0;
}
      int a=0; //a=0
      int rc=fork();
        a++;//a=1
      printf("A before the if else");
      printf("%d",a);// a=1

      if(rc==0)// this was rc=0 it should have been rc==0
        {
            rc=fork();
            a++;//a=2
            printf("A inside the if");
            printf("%d",a);// a=2

        }
        else
        {        
            a++;//a=2
            printf("A inside the else");
            printf("%d",a);// a=2

        }
        printf("Hello World");// "Hello World"
        printf("%d",a);// a=2

        return 0;// always returns 0

至于为什么它打印两次 Hello world 我不能从给定的代码中说出来,但你必须调用 main 两次。如果你的语言有能力,我会使用堆栈跟踪()(不是 c 开发人员)

Why does hello world print twice only and why is a's largest value 2

为了回答您的问题(在更正您的 (rc = 0)(rc == 0) 问题之后),它可能有助于绘制代码中发生的事情。例如:

    parent
      |
      a = 1
      if (rc == 0)
      +--------------- child 1
      |                   |
      else                +--------------- child 2
        a++               a++              a++
      a = 2               a = 2            a = 2
      Hello World2        Hello World2     Hello World2

在 parent 过程中,您 fork 然后在测试 if (rc == 0) 之前将 a 增加 a++ 以指示 child 过程。原来的parent因为else又看到了a++,结果是"Hello World2"

在 first-child 中,您再次分叉,但是 child-1(如 parent)和 child-2 都递增 a++;退出条件 "Hello World2" 两者的结果。

您似乎在尝试类似的操作:

#include <stdio.h>
#include <unistd.h>

int main (void) {

    int a = 1,
        rc = fork();

    if (rc == 0) {
        a++;
        rc = fork();

        if (rc == 0)
            a++;
    }

    printf ("Hello World %d\n", a);
}

例子Use/Output

$ ./bin/forkcount
Hello World 1
Hello World 2
Hello World 3

有时候铅笔和纸和键盘一样有用。如果您还有其他问题,请告诉我。