通过实例体会 fork()同时创建多个子进程


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

#include 
#include 
int main()
{
    pid_t p1,p2;
    printf("before fork(),pid=%d\n",getpid());
p1=fork();
if(p1==0)
{
printf("in child 1, pid = %d\n", getpid());
return 0;
}
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;
}

执行结果:

before fork(),pid=2381
in child 1, pid = 2382
in child 2, pid = 2383

第二种方法

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

#include 
#include //查查在windows下能编译吗?Linux函数。
#include //这个头文件不能少,否则pid_t没有定义
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());
 }
}
执行结果:
This is parent process3553
This is child_1 process3554
This is child_2 process3555
This is parent process3553

注意:if .......else if .........else........语句只执行一次。

            当执行完if语句的时候子进程结束if...else if...else语句,父进程并没有结束。

第三种方法:for循环方法

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

#include
#include
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);
printf("This is parent process  %d\n",getpid());/
}

执行结果:

This is parent process2655
This is child_1 process2656
This is child_1 process2657
This is child_1 process2658

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

return 0 情况

#include 
#include 
#include 
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);
   printf("This is parent process  %d\n",getpid());*/
  }
}

执行结果:

This is parent process2620
This is child_1 process  2621
This is child_1 process  2622
This is child_1 process  2625
This is child_1 process  2626
This is child_1 process  2624
This is child_1 process  2623
This is child_1 process  2627

结论:父进程会生成2N-1个子进程,N为循环次数,本例中共有7个子进程,但实际上只有3个是父进程产生的,其余都为子进程fork()出来的

你可能感兴趣的:(c/c++语言编程,linux内核之旅)