关于fork的理解

头文件:
 
    #include <unistd.h>
    #include <stdio.h>
 
返回值:

  负数:如果出错,则fork()返回-1,此时没有创建新的进程。最初的进程仍然运行。

  零:在子进程中,fork()返回0

  正数:在负进程中,fork()返回正的子进程的PID

 
用个例子说明下:

#include <unistd.h>

  #include <stdio.h>

  int main()

  {

  pid_t pid;

  int count=0;

  pid = fork();

//父进程和子进程都从此处开始执行 ,所以可以看到打印结果中This is first time,This is second time 会被打印两次,

  printf( "This is first time, pid = %d\n", pid );

  printf( "This is second time, pid = %d\n", pid );

  count++;

  printf( "count = %d\n", count ); //那么count++ 应该执行两次,为什么两次打印都是1呢?那是因为fork之后,子进程和父进程的数据什么的,都分开了,

                                                      //各是各的,互不相干。

  if ( pid>0 )

  {

  printf( "This is the parent process,the child has the pid:%d\n", pid );

  }

  else if ( !pid )

  {

  printf( "This is the child Process.\n")

      //如果在此处处上    _exit(0);    那么 子进程将在此处结束, 不会继续往下执行

  }

  else

  {

  printf( "fork failed.\n" );

  }

  printf( "This is third time, pid = %d\n", pid );

  printf( "This is fouth time, pid = %d\n", pid );

  return 0;

  }

打印结果:  




父进程执行路径如下:

    printf( "This is first time, pid = %d\n", pid );

       printf( "This is secONd time, pid = %d\n", pid );

  count++;

  printf( "count = %d\n", count );


 |

 |

  父进程 pid>0

if ( pid>0 )

  {

  printf( "This is the parent process,the child has the pid:%d\n", pid );

  }

 |

 |

printf( "This is third time, pid = %d\n", pid );

printf( "This is fouth time, pid = %d\n", pid );

return 0;

 

子进程执行路径如下:

       printf( "This is first time, pid = %d\n", pid );

  printf( "This is secONd time, pid = %d\n", pid );

  count++;

  printf( "count = %d\n", count );

 

 |
 |

 

子进程 pid==0

  else if ( !pid )

  {

  printf( "This is the child Process.\n")

     //如果在此处处上    _exit(0);    那么 子进程将在此处结束, 不会继续往下执行,也就是说,以下红色部分将不执行了,同理在父进程中也是如此

  }

 

 |
 |

 

printf( "This is third time, pid = %d\n", pid );

printf( "This is fouth time, pid = %d\n", pid );

return 0;



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值