问题描述:
The Fibonacci sequence is the series of numbers 0
,
1
,
1
,
2
,
3
,
5
,
8
, ...
. For
mally, it can be expressed as:
fib
0
=
0
fib
1
= 1
fib
n
= fibn
−
1
+
fib
n
−
2
Write a C program using the
fork()
system call that that generates the
Fibonacci sequence in the child process. The number of the sequence
will be provided in the command line. For example, if 5 is provided, the
fifirst fifive numbers in the Fibonacci sequence will be output by the child
process. Because the parent and child processes have their own copies
of the data, it will be necessary for the child to output the sequence.
Have the parent invoke the
wait()
call to wait for the child process to
complete before exiting the program. Perform necessary error checking
to ensure that a non-negative number is passed on the command line.
简单翻译下: 使用c语言,通过调用fork语句,使子进程生成一个斐波那契数列。
例如,如果输入5,则子进程应输出斐波那契数列的前五个数。
下面是我的一些思路,我仍存在一些问题。
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<iostream>
using namespace std;
int main()
{
int n;
pid_t pid; //pid_t是一个typedef定义类型。 用它来表示进程id类型
cout<<"请输入n,n>2"<<endl;
cin>>n;
int *fib=new int [n];
int i=0;
while(i<n){ //!!!!!!!!!!!!
pid = fork(); //创建子进程
if (pid < 0) //创建失败
{
printf("Fork Failed");
}
else if (pid == 0) //创建成功,此时在子进程中
{
if(i==0){fib[i]=0;}
else if(i==1){fib[i]=1;}
else {fib[i]=fib[i-1]+fib[i-2];}
printf("儿子!的id:%d\n", getpid()); //用来检查生成了多少个孩子进程
for (int w=0;w<i;w++){
cout<<fib[w]<<" ";
}
cout<<endl;
}
else //创建成功,此时在父进程中
{
wait(NULL); //清除子进程,
}
i++;
}
return 0;
}
通过while循环来不停的进行fork(),创建子进程。这种方法确实能实现效果,但同时使我产生了更多疑惑。
我输入5,一共创造了31个孩子进程,加上父进程,等于一共有2的5次方的进程被创造。指数增长,这是很可怕的。
问: 1.有没有线性增长的方法来实现
2. 具体的创建流程如何?没有搞太清楚。
恳请大佬解答!!!