linux fork与vfork简要分析理解

一.先来看下思维导图,以快速认知。
   

 二.实例讲解  
实例一.

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{

  pid_t pid;
  pid = fork();
  if(pid<0){
    printf("error in fork");
  }else if(pid == 0){ 
    printf("This is child process, pid is %d\n", getpid());
  }else{
    printf("This is parent process, pid is %d\n", getpid());
  }
  printf("父子进程都会执行\n");
  return 0;
}

[fl@linux1 c]$ ./fork
This is child process, pid is 992
父子进程都会执行
This is parent process, pid is 991
父子进程都会执行
[fl@linux1 c]$

说明:

1.实际上父子进程的执行顺序是不固定的,认为子进程结束后,父进程才会运行那你的理解就错了

2.父进程执行所有程序,而子进程只会执行fork之后的程序,这是因为子进程继承的父进程的程序计数器(program counter, pc)-即指出当前占用 CPU的进程要执行的下一条指令的位置
3.对子进程来说fork()返回的0,0只是代表创建子进程成功,如果需要得到子进程的pid可以使用getpid()

实例二.

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{

  pid_t pid;
  int count = 0;

  pid = vfork();

  if(pid < 0){ 
    printf("fork error");
  }

  if(pid == 0){ 
    count ++; 
    _exit(0);
  }else{
    count ++; 
  }
    printf("count is %d\n", count);
   return 0;
}
[fl@linux1 c]$ ./vfork
count is 2

程序说明:
1.vfork()使父子进程共享数据段,并保证了子进程的先运行
2.vfork()创建的子进程结束后需要运行exit()父进程才会运行

原文地址:https://www.cnblogs.com/fanglin/p/2506099.html