Linux 在子进程中使用 fork() 的斐波那契数列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4246335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:03:18  来源:igfitidea点击:

fibonacci using fork() in the child process

clinuxsystemfork

提问by Bobj-C

I wrote the code below for homework purposes. When I run it on XCode in OSX, after the sentence "Enter the number of a Fibonacci Sequence:", I enter the number 2 times. Why 2 and only 1 scanf.

我写了下面的代码用于家庭作业。当我在 OSX 中的 XCode 上运行它时,在“输入斐波那契数列的数字:”这句话之后,我输入了 2 次数字。为什么 2 而只有 1 scanf

The code :

编码 :

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

int main()

{



int a=0, b=1, n=a+b,i;


printf("Enter the number of a Fibonacci Sequence:\n");
scanf("%d ", &i);

pid_t pid = fork();
if (pid == 0)
{
    printf("Child is make the Fibonacci\n");
    printf("0 %d ",n);
    while (i>0) {
        n=a+b;
        printf("%d ", n);
        a=b;
        b=n;
        i--;
        if (i == 0) {
            printf("\nChild ends\n");
        }
    }
}
    else 
    {
        printf("Parent is waiting for child to complete...\n");
        waitpid(pid, NULL, 0);
        printf("Parent ends\n");
    }
    return 0;
}

采纳答案by Chris

You have a space after %din your scanf. Try scanf("%d", &i);.

%d的 scanf后面有一个空格。试试scanf("%d", &i);

回答by Sid

When you call fork(), both processes get their own copies of stdoutand the message in the buffer gets duplicated. So in order to solve this problem you will have to flush stdout just before forking.

当您调用 时fork(),两个进程都会获得它们自己的副本,stdout并且缓冲区中的消息会被复制。因此,为了解决这个问题,您必须在分叉之前刷新标准输出。

Solution: Write fflush(stdout)just after printf("Enter the number of a Fibonacci Sequence:\n")

解决方法:写fflush(stdout)在后面printf("Enter the number of a Fibonacci Sequence:\n")