在子进程中使用 fork() 的斐波那契数列
我出于家庭作业目的编写了下面的代码。当我在 OSX 中的 XCode 上运行它时,在“输入斐波那契数列的数字:”这句话之后,我输入了数字 2 次。为什么有 2 个且只有 1 个 scanf
。
代码:
#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;
}
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
.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
scanf 中的
%d
之后有一个空格。尝试scanf("%d", &i);
。You have a space after
%d
in your scanf. Tryscanf("%d", &i);
.当您调用
fork()
时,两个进程都会获取自己的stdout
副本,并且缓冲区中的消息会被复制。因此,为了解决这个问题,您必须在分叉之前刷新标准输出。
解决方案:
在
printf("Enter the number of a Fibonacci Sequence:\n")
之后写入fflush(stdout)
When you call
fork()
, both processes get their own copies ofstdout
and the message in the buffer gets duplicated.So in order to solve this problem you will have to flush stdout just before forking.
Solution:
Write
fflush(stdout)
just afterprintf("Enter the number of a Fibonacci Sequence:\n")