fork 创建进程

问题描述:

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. 具体的创建流程如何?没有搞太清楚。

恳请大佬解答!!!

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mu Haitian

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值