在fork()之后,父进程仍然可以改变变量值?

时间:2013-05-03 12:06:18

标签: c linux fork

    #include<stdio.h>
    #include <stdlib.h>
    int main()
    {
            int i=1;
            pid_t j=fork();
            i=4;
            if(j==0)
            {
                    printf("%d\n",i);
            }
            i=5;    // will this line runs in both parent and child?

    }

我认为在fork()之后 在子进程中,无论父进程如何更改它,我都是1 但结果是4 为什么不1?

2 个答案:

答案 0 :(得分:2)

您更改了子级中父级i的值。 fork()之后的所有代码都在两个进程中运行。

pid_t j=fork();
i=4;              // <- this runs in both parent and child
if(j==0) {
   ...            // <- this runs only in child because of the if
}
i=5;              // <- this runs in both parent and child

子进程中的执行从fork之后的行开始,然后正常运行。作为一个“孩子”,孩子的执行没有什么特别之处 - 正常的代码流就像父母一样。

如果您想清楚地区分孩子中发生的事情以及父母发生的事情,请在您的代码中明确说明:

pid_t j = fork();
if (j < 0) {
  // fork failed, no child created at all
  // handle error
} else if (j == 0) {
  /* In child process */
  ...
} else {
  /* In parent process */
  ...
}

答案 1 :(得分:1)

以下代码fork同时在parentchild中运行..