【问题标题】:problems with the output of multiple forks多叉输出的问题
【发布时间】:2014-11-25 15:02:48
【问题描述】:

大家好,我有这个示例代码,但我不明白它的输出是什么,你们谁能帮我解释一下。

tnx 提前

int main(){

 int i, j;
 i = j = 0;
 fork();
 j++;
 printf("i = %d, j = %d \n", i, j);
 if(fork())
 {
    i += 5;
    fork();

    j *= 3;
    printf("i = %d, j = %d \n", i, j);
}
else
{
    i = j;
    printf("i = %d, j = %d \n", i, j);
    i--;
    if(fork() == 0)
        printf("i = %d, j = %d \n", i, j);  
}}

【问题讨论】:

  • 我看不出如何使用该代码获得该输出,j 在第一行不能为 0。你的意思是这就是你期望得到的输出吗?
  • @Joni 看来我输入的输出有误(我现在才编辑它),问题是当我检查解决方案密钥时,我得到了一个不同的,那么你能解释一下这段代码的输出是什么
  • 问题是什么?
  • @user3344003 我只是解释一下这段代码是如何工作的,我还是 C OS 新手

标签: operating-system fork


【解决方案1】:

每次代码调用 fork() 函数时,它都会创建一个与其自身重复的进程。

fork() 将子进程的进程ID返回给父进程,返回零给子进程。

 if (fork ())
 {
     // Code executes in the parent process but not the child process.

  }
 else
 {
     // Code executes in the child process but not in the parent process.
 }


if (fork () == 0)
 // Code executes in the child process

然后您可以画出一棵小树,显示新进程的创建以及得到的输出。

【讨论】:

    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2021-12-08
    • 2011-06-30
    • 2014-08-16
    相关资源
    最近更新 更多