fork创建多个子进程方法

第一种方法:验证通过 

特点:同时创建多个子进程,每个子进程可以执行不同的任务,程序 可读性较好,便于分析,易扩展为多个子进程 

int main(void){           
 printf("before fork(), pid = %d\n", getpid());        
   pid_t p1 = fork();          
   if( p1 == 0 ){               
    printf("in child 1, pid = %d\n", getpid());              
    return 0;
   }           
   pid_t p2 = fork();
   if( p2 == 0 ){               
    printf("in child 2, pid = %d\n", getpid());             
    return 0;       //子程结束,跳回父进程     
    printf(“Hello world\n”); //没有打印           
   }            int st1, st2;          
   waitpid( p1, &st1, 0);          
   waitpid( p2, &st2, 0);           
   printf("in parent, child 1 pid = %d\n", p1);          
   printf("in parent, child 2 pid = %d\n", p2);          
   printf("in parent, pid = %d\n", getpid());          
   printf("in parent, child 1 exited with %d\n", st1);          
   printf("in parent, child 2 exited with %d\n", st2);          
   return 0;      
   }
   

第二种方法: 验证通过 

 

特点:同时创建两个子进程,结构比较繁琐,程序可读性不好,不易扩展

int main(){
 printf("This?is?parent?process%d\n",getpid());
 pid_t p1,p2;
 if((p1=fork())==0){
  printf("This is child_1 process%d\n",getpid());
 }else{
  if((p2=fork())==0){
   printf("This is child_2 process%d\n",getpid());
  }else{
   wait(p1,NULL,0);
   wait(p2,NULL,0);
   printf("This is parent process%d\n",getpid());
  }
 }
}

 

第三种方法:for 循环方法 

 

特点:其实每次循环只是创建了单个进程,并没有同时创建多个进程

 

#include<stdio.h> 

 

#include<unistd.h> 

 

#include<sys/types.h> 

 

main() 

 

{

 

printf("This is parent process%d\n",getpid()); 

 

pid_t p1,p2; 

 

int i; 

 

for(i=0;i<=2;i++)

 

 

if((p1=fork())==0)

 

 

printf("This is child_1 process%d\n",getpid()); 

 

return 0;//这个地方非常关键 

 

 

wait(p1,NULL,0); //父进程等待p1子进程执行后才能继续fork其他子进程

 

printf("This is parent process%d\n",getpid()); 

 

}

 

 

注意:标注的 return 0 对程序结果影响很大 

没有return 0 ;的情况下:父进程会生成 n(n+1)/2+1个子进程,为循环次数,本例中共有 个子进程, 但实际上只有 个是父进程产生的,其余都为子进程 fork()出来的。父进程fork3个进程,第一个子进程执行完之后又fork2个进程,第2个子进程fork1个进程。

正确的使用Linux中的用fork()由一个父进程创建同时多个子进程 的格式如下:

 

int status,i;

 

for (i = 0; i < 10; i++)

 

{

 

  status = fork();

 

  if (status == 0 || status == -1) break;//每次循环时,如果发现是子进程就直接从创建子进程的循环中跳出来,不让你进入循环,这样就保证了每次只有父进程来做循环创建子进程的工作

 

}

 

if (status == -1)

 

{

 

  //error

 

}

 

else if (status == 0) //每个子进程都会执行的代码

 

{

 

  //sub process

 

}

 

else

 

{

 

  //parent process

 

}

 

 


   

posted on 2014-01-17 10:17  yuanqing  阅读(1141)  评论(0)    收藏  举报

导航